SWC智能合约漏洞库

SWC-114/交易顺序依赖

以太坊网络以区块为单位处理交易,新区块大约每17秒得到确认。矿工查看他们已收到的交易, 并根据谁支付了足够高的gas价格来选择要包含在区块中的交易。另外,当交易被发送到以太坊 网络时,它们被转发到每个节点进行处理。因此,运行以太坊节点的人可以在最终确定交易之前 就知道将要发生哪些交易。当代码取决于提交给它的交易的顺序时,就会出现竞争条件漏洞。

竞争条件的最简单示例是智能合约为提交信息提供奖励的情况。假设合约将给第一个解决数学问题 的人一个代币。Alice解决了这个问题,并以标准gas价格向网络提交了答案。Eve运行一个以太坊节点, 可以在Alice提交给网络的交易中看到数学问题的答案。因此,Eve以更高的Gas价格向网络提交了答案, 因此在Alice交易之前就得到了处理和承诺。Eve收到了代币,而Alice却一无所获,尽管正是Alice努力 解决了这个问题。

当今网络上最常发生的竞争状况是ERC20代币标准中的竞争状况。ERC20标准包括一个称为“approve”的功能, 该功能允许一个地址批准另一个地址来代表他们花费代币。假设Alice已批准Eve花费其n个代币,则Alice 决定将Eve的批准更改为m个代币。Alice提交一个函数调用以批准Eve的值为n。Eve运行一个以太坊节点, 因此知道Alice会将其批准更改为m。Eve随后提交了tranferFrom请求,向她发送了n个Alice的代币,但是 给它的gas价格比爱丽丝的交易要高得多。transferFrom首先执行,因此给Eve n个令牌并将Eve的批准设置 为零。然后执行Alice的交易并将Eve的批准设置为m。然后,Eve也将这m个代币发送给自己。因此,Eve甚至 认为她应该最多获得max(n,m)个代币,因此获得了n + m个代币。

CWE漏洞分类

CWE-362:并发执行中使用共享资源时未正确同步

整改方案

在提交信息以换取奖励时,可以解决竞争条件漏洞的一种可能方法称为提交显示哈希方案。合约没有存储 提交答案的一方提交hash(salt,address,answer) ——salt是他们选择的数量 —— 而是存储该哈希和发送者的地址。 为了获得奖励,发送者随后提交了带有salt的交易并做出答复。合约计算hash(salt,msg.sender,answer)并针对存储的哈希 检查生成的哈希,如果哈希与合约匹配,则释放奖励。

对于ERC20竞争条件的最佳解决方法是在approve的输入中添加一个字段,该字段是预期的当前值, 如果Eve的当前授权额度不是Alice所期望的,则approve交易回滚。但是,这意味着你的合约不再符合 ERC20标准。如果使合约符合ERC20对你的项目很重要,则可以添加安全批准功能。从用户的角度来看, 可以通过在更改批准前将批准设置为零来调解ERC20竞争条件。

参考文献

关于ERC20的竞争条件

合约示例

ERC20.sol

pragma solidity ^0.4.24;

/** Taken from the OpenZeppelin github
 * @title SafeMath
 * @dev Math operations with safety checks that revert on error
 */
library SafeMath {

  /**
  * @dev Multiplies two numbers, reverts on overflow.
  */
  function mul(uint256 a, uint256 b) internal pure returns (uint256) {
    // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
    // benefit is lost if 'b' is also tested.
    // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
    if (a == 0) {
      return 0;
    }

    uint256 c = a * b;
    require(c / a == b);

    return c;
  }

  /**
  * @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
  */
  function div(uint256 a, uint256 b) internal pure returns (uint256) {
    require(b > 0); // Solidity only automatically asserts when dividing by 0
    uint256 c = a / b;
    // assert(a == b * c + a % b); // There is no case in which this doesn't hold

    return c;
  }

  /**
  * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
  */
  function sub(uint256 a, uint256 b) internal pure returns (uint256) {
    require(b <= a);
    uint256 c = a - b;

    return c;
  }

  /**
  * @dev Adds two numbers, reverts on overflow.
  */
  function add(uint256 a, uint256 b) internal pure returns (uint256) {
    uint256 c = a + b;
    require(c >= a);

    return c;
  }

  /**
  * @dev Divides two numbers and returns the remainder (unsigned integer modulo),
  * reverts when dividing by zero.
  */
  function mod(uint256 a, uint256 b) internal pure returns (uint256) {
    require(b != 0);
    return a % b;
  }
}


contract ERC20 {

  event Transfer( address indexed from, address indexed to, uint256 value );
  event Approval( address indexed owner, address indexed spender, uint256 value);
  using SafeMath for *;

  mapping (address => uint256) private _balances;

  mapping (address => mapping (address => uint256)) private _allowed;

  uint256 private _totalSupply;

  constructor(uint totalSupply){
    _balances[msg.sender] = totalSupply;
  }

  function balanceOf(address owner) public view returns (uint256) {
    return _balances[owner];
  }


  function allowance(address owner, address spender) public view returns (uint256)
  {
    return _allowed[owner][spender];
  }

  function transfer(address to, uint256 value) public returns (bool) {
    require(value <= _balances[msg.sender]);
    require(to != address(0));

    _balances[msg.sender] = _balances[msg.sender].sub(value);
    _balances[to] = _balances[to].add(value);
    emit Transfer(msg.sender, to, value);
    return true;
  }

  function approve(address spender, uint256 value) public returns (bool) {
    require(spender != address(0));

    _allowed[msg.sender][spender] = value;
    emit Approval(msg.sender, spender, value);
    return true;
  }

  function transferFrom(address from, address to, uint256 value) public returns (bool) {
    require(value <= _balances[from]);
    require(value <= _allowed[from][msg.sender]);
    require(to != address(0));

    _balances[from] = _balances[from].sub(value);
    _balances[to] = _balances[to].add(value);
    _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
    emit Transfer(from, to, value);
    return true;
  }
}

ERC20.yaml

description: ERC20 approve() front running
issues:
- id: SWC-114
  count: 1
  locations:
  - bytecode_offsets: {}
    line_numbers:
      ERC20.sol: [104]

eth_tx_order_dependence_minimal.sol

/*
 * @source: https://github.com/ConsenSys/evm-analyzer-benchmark-suite
 * @author: Suhabe Bugrara
 */

pragma solidity ^0.4.16;

contract EthTxOrderDependenceMinimal {
    address public owner;
    bool public claimed;
    uint public reward;

    function EthTxOrderDependenceMinimal() public {
        owner = msg.sender;
    }

    function setReward() public payable {
        require (!claimed);

        require(msg.sender == owner);
        owner.transfer(reward);
        reward = msg.value;
    }

    function claimReward(uint256 submission) {
        require (!claimed);
        require(submission < 10);

        msg.sender.transfer(reward);
        claimed = true;
    }
}

eth_tx_order_dependence_minimal.yaml

description: 'Simple claim/set reward example for front running '
issues:
- id: SWC-114
  count: 1
  locations:
  - bytecode_offsets: {}
    line_numbers:
      eth_tx_order_dependence_minimal.sol: [17]