BEC漏洞分析(2022-11-20)

144 阅读7分钟

BEC合约

2018年4月22日BeautyChain(BEC)的智能合约中一个毁灭性的漏洞。

BeautyChain团队宣布,BEC代币在4月22日出现异常。攻击者通过智能合约漏洞成功转账了10^58 BEC到两个指定的地址。(瑟瑟发抖[^]_[^])

整数溢出攻击原理

  • solidity中,一个 uint8类型 ,只能存储在范围 0到2^8-1,也就是[0,255] 的数字,一个uint256类型 ,只能存储在范围 0到2^256-1的数字
  • 在以太坊虚拟机(EVM)中为整数指定固定大小的数据类型,而且是无符号的,这意味着在以太坊虚拟机中一个整型变量只能有一定范围的数字表示,不能超过这个制定的范围。因此就产生了漏洞危机。 image.png 8 位无符整数 255 在内存中占据了 8bit 位置,若再加上 1 整体会因为进位而导致整体翻转为 0,最后导致原有的 8bit 表示的整数变为 0。

就是说: 定义一个变量uint a,a的取值范围是0到255。

  • 当a=255,我们对a加 1,a会变成 0。
  • 当a=255,我们对a加 2,a会变成 1。
  • 当a=0,我们对a减 1,a会变成 255。
  • 当a=0,我们对a减 2,a会变成 255。 a的值超过了它实际的取值范围,然后会得出后面的值,这种情况叫溢出

变量类型

address
160位的值,且不允许任何算数操作。

uint 8
8位无符号整数,范围是0到2^8-1 (0-255)

uint256
256位无符号整数,范围是0到2^256-1
(0-115792089237316195423570985008687907853269984665640564039457584007913129639935)

合约代码

BEC转账的智能合约代码:

function batchTransfer(address[] _receivers, uint256 _value) public whenNotPaused returns (bool) {
    uint cnt = _receivers.length;
    uint256 amount = uint256(cnt) * _value;//这个位置出现了问题
    require(cnt > 0 && cnt <= 20);
    require(_value > 0 && balances[msg.sender] >= amount);

    balances[msg.sender] = balances[msg.sender].sub(amount);
    for (uint i = 0; i < cnt; i++) {
        balances[_receivers[i]] = balances[_receivers[i]].add(_value);
        Transfer(msg.sender, _receivers[i], _value);
    }
    return true;
 }
 

接下来逐行看代码:

第一行

函数有两个参数:

  1. _receivers ————转账接收人,address类型的变量数组,是一个160位的值。
  2. _value————转账数量,uint256的状态变量,256位的无符号整数。 定义的函数batchTransfer(),功能主要是实现转账,接收两个参数,定义了参数的取值范围。
第二行

uint cnt = _receivers.length;

计算接收人地址对应地址数组的长度,即转账给多少人。因为输入的_receivers是一个地址的数组。

第三行

uint256 amount = uint256(cnt) * _value;

把unit类型的cnt参数值强制转换为uint256然后乘以转账数量_value 并赋值给uint256类型的amount变量。

第四行

require(cnt > 0 && cnt <= 20);

require函数
require的入参判定为 false,则终止函数,恢复所有对状态和以太币账户的变动,并且也不会消耗 gas 。 判断cnt是否大于0且cnt是否小于等于20

第五行

require(_value > 0 && balances[msg.sender] >= amount);

参数解读:

  1. _value————转账数量
  2. balances[msg.sender]————转账人余额
  3. amount————转账总数量

判断_value是否大于0且转账人的余额balances[msg.sender]大于等于转账总金额amount

第六行

balances[msg.sender] = balances[msg.sender].sub(amount);
计算转账人的余额,使用当前余额balances[msg.sender]减去转账总数量

第七行

for (uint i = 0; i < cnt; i++) {
这里是一个循环,循环次数为cnt(遍历转账地址)

第八行

balances[_receivers[i]] = balances[_receivers[i]].add(_value);
当i有具体的值时,balances[_receivers[i]]表示转账接收人,这里是表示转账人给转账接收人_value数量的币。

第九行

Transfer(msg.sender, _receivers[i], _value);
保存转账记录

第十行

return true;
函数返回为True

image.png

转账接收人有两个地址,即balances[_receivers]:

000000000000000000000000b4d30cac5124b46c2df0cf3e3e1be05f42119033
0000000000000000000000000e823ffe018727585eaf5bc769fa80472f76c3d7

转账数量为_value:

8000000000000000000000000000000000000000000000000000000000000000(十六进制)

转10进制为

57896044618658097711785492504343953926634992332820282019728792003956564819968

cnt=2 _value=57896044618658097711785492504343953926634992332820282019728792003956564819968

这两个相乘得到amount,类型为uint256: 即amount=115792089237316195423570985008687907853269984665640564039457584007913129639936

在这一瞬间,amount瞬间从115792089237316195423570985008687907853269984665640564039457584007913129639936变成了0。之后函数继续执行,但amount已经变成了0。攻击者执行完这个操作,转账人的余额根本没变。(就很牛)

这段代码甚至用了SafeMathsub()add(),他真的我哭死[@]_[@]。但凡用了mul()都不至于这样。

 function mul(uint256 a, uint256 b) internal constant returns (uint256) {
    uint256 c = a * b;
    assert(a == 0 || c / a == b);
    return c;
  }

两者相乘得到amount,类型为uint256。由于溢出,amount=0,赋值给mul函数即:

c=amount,而amount=0,则c=0
a=cnt, 而cnt=2,则a=2
b=_value
得出
b=57896044618658097711785492504343953926634992332820282019728792003956564819968

那么c/a==b这个式子不成立,导致assert函数执行会报错,assert报错,那么就不会执行后面的代码,也就不会发生溢出。

知识补充/巩固

以太坊中的gas和ether

gas

  • gas是以太坊中使用的一个特殊单位的名称。虽然gas是可以计量的单位,但没有任何实际的gas代币。也就是说,你不能拥有1000个gas。相反,gas只存在于Ethereum虚拟机中,它是对正在执行的工作量的计数
  • 如果你给出的gas价格很好,但是你的交易的gas成本“超出预算”,交易失败了,但是仍然进入区块链,你不能把钱拿回来,因为你的工作确实被矿工执行了。

ether

  • ether是以太网络内的内置代币,也是用来奖励矿工生产区块的代币。

gas与ether的关系

  • EVM的操作有gas成本,但gas本身也有以ether计量的gas价格。
  • EVM的操作有gas成本,但gas本身也有以ether计量的gas价格。每一笔交易都规定了它愿意以ether支付的每一单位gas的gas价格,从而能够使市场决定ether价格和计算操作成本(以gas计量)之间的关系。
  • 交易的总费用=使用的gas总量*gas价格。

BEC智能合约源码

设计模式:

image.png

pragma solidity ^0.4.16;

/**
 * @title SafeMath
 * @dev Math operations with safety checks that throw on error
 */
library SafeMath {
  function mul(uint256 a, uint256 b) internal constant returns (uint256) {
    uint256 c = a * b;
    assert(a == 0 || c / a == b);
    return c;
  }

  function div(uint256 a, uint256 b) internal constant returns (uint256) {
    // assert(b > 0); // Solidity automatically throws 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;
  }

  function sub(uint256 a, uint256 b) internal constant returns (uint256) {
    assert(b <= a);
    return a - b;
  }

  function add(uint256 a, uint256 b) internal constant returns (uint256) {
    uint256 c = a + b;
    assert(c >= a);
    return c;
  }
}

/**
 * @title ERC20Basic
 * @dev Simpler version of ERC20 interface
 * @dev see https://github.com/ethereum/EIPs/issues/179
 */
contract ERC20Basic {
  uint256 public totalSupply;
  function balanceOf(address who) public constant returns (uint256);
  function transfer(address to, uint256 value) public returns (bool);
  event Transfer(address indexed from, address indexed to, uint256 value);
}

/**
 * @title Basic token
 * @dev Basic version of StandardToken, with no allowances.
 */
contract BasicToken is ERC20Basic {
  using SafeMath for uint256;

  mapping(address => uint256) balances;

  /**
  * @dev transfer token for a specified address
  * @param _to The address to transfer to.
  * @param _value The amount to be transferred.
  */
  function transfer(address _to, uint256 _value) public returns (bool) {
    require(_to != address(0));
    require(_value > 0 && _value <= balances[msg.sender]);

    // SafeMath.sub will throw if there is not enough balance.
    balances[msg.sender] = balances[msg.sender].sub(_value);
    balances[_to] = balances[_to].add(_value);
    Transfer(msg.sender, _to, _value);
    return true;
  }

  /**
  * @dev Gets the balance of the specified address.
  * @param _owner The address to query the the balance of.
  * @return An uint256 representing the amount owned by the passed address.
  */
  function balanceOf(address _owner) public constant returns (uint256 balance) {
    return balances[_owner];
  }
}

/**
 * @title ERC20 interface
 * @dev see https://github.com/ethereum/EIPs/issues/20
 */
contract ERC20 is ERC20Basic {
  function allowance(address owner, address spender) public constant returns (uint256);
  function transferFrom(address from, address to, uint256 value) public returns (bool);
  function approve(address spender, uint256 value) public returns (bool);
  event Approval(address indexed owner, address indexed spender, uint256 value);
}


/**
 * @title Standard ERC20 token
 *
 * @dev Implementation of the basic standard token.
 * @dev https://github.com/ethereum/EIPs/issues/20
 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
 */
contract StandardToken is ERC20, BasicToken {

  mapping (address => mapping (address => uint256)) internal allowed;


  /**
   * @dev Transfer tokens from one address to another
   * @param _from address The address which you want to send tokens from
   * @param _to address The address which you want to transfer to
   * @param _value uint256 the amount of tokens to be transferred
   */
  function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
    require(_to != address(0));
    require(_value > 0 && _value <= balances[_from]);
    require(_value <= allowed[_from][msg.sender]);

    balances[_from] = balances[_from].sub(_value);
    balances[_to] = balances[_to].add(_value);
    allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
    Transfer(_from, _to, _value);
    return true;
  }

  /**
   * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
   *
   * Beware that changing an allowance with this method brings the risk that someone may use both the old
   * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
   * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
   * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
   * @param _spender The address which will spend the funds.
   * @param _value The amount of tokens to be spent.
   */
  function approve(address _spender, uint256 _value) public returns (bool) {
    allowed[msg.sender][_spender] = _value;
    Approval(msg.sender, _spender, _value);
    return true;
  }

  /**
   * @dev Function to check the amount of tokens that an owner allowed to a spender.
   * @param _owner address The address which owns the funds.
   * @param _spender address The address which will spend the funds.
   * @return A uint256 specifying the amount of tokens still available for the spender.
   */
  function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
    return allowed[_owner][_spender];
  }
}

/**
 * @title Ownable
 * @dev The Ownable contract has an owner address, and provides basic authorization control
 * functions, this simplifies the implementation of "user permissions".
 */
contract Ownable {
  address public owner;


  event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);


  /**
   * @dev The Ownable constructor sets the original `owner` of the contract to the sender
   * account.
   */
  function Ownable() {
    owner = msg.sender;
  }


  /**
   * @dev Throws if called by any account other than the owner.
   */
  modifier onlyOwner() {
    require(msg.sender == owner);
    _;
  }


  /**
   * @dev Allows the current owner to transfer control of the contract to a newOwner.
   * @param newOwner The address to transfer ownership to.
   */
  function transferOwnership(address newOwner) onlyOwner public {
    require(newOwner != address(0));
    OwnershipTransferred(owner, newOwner);
    owner = newOwner;
  }

}

/**
 * @title Pausable
 * @dev Base contract which allows children to implement an emergency stop mechanism.
 */
contract Pausable is Ownable {
  event Pause();
  event Unpause();

  bool public paused = false;


  /**
   * @dev Modifier to make a function callable only when the contract is not paused.
   */
  modifier whenNotPaused() {
    require(!paused);
    _;
  }

  /**
   * @dev Modifier to make a function callable only when the contract is paused.
   */
  modifier whenPaused() {
    require(paused);
    _;
  }

  /**
   * @dev called by the owner to pause, triggers stopped state
   */
  function pause() onlyOwner whenNotPaused public {
    paused = true;
    Pause();
  }

  /**
   * @dev called by the owner to unpause, returns to normal state
   */
  function unpause() onlyOwner whenPaused public {
    paused = false;
    Unpause();
  }
}

/**
 * @title Pausable token
 *
 * @dev StandardToken modified with pausable transfers.
 **/

contract PausableToken is StandardToken, Pausable {

  function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
    return super.transfer(_to, _value);
  }

  function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
    return super.transferFrom(_from, _to, _value);
  }

  function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
    return super.approve(_spender, _value);
  }
  
  function batchTransfer(address[] _receivers, uint256 _value) public whenNotPaused returns (bool) {
    uint cnt = _receivers.length;
    uint256 amount = uint256(cnt) * _value;
    require(cnt > 0 && cnt <= 20);
    require(_value > 0 && balances[msg.sender] >= amount);

    balances[msg.sender] = balances[msg.sender].sub(amount);
    for (uint i = 0; i < cnt; i++) {
        balances[_receivers[i]] = balances[_receivers[i]].add(_value);
        Transfer(msg.sender, _receivers[i], _value);
    }
    return true;
  }
}

/**
 * @title Bec Token
 *
 * @dev Implementation of Bec Token based on the basic standard token.
 */
contract BecToken is PausableToken {
    /**
    * Public variables of the token
    * The following variables are OPTIONAL vanities. One does not have to include them.
    * They allow one to customise the token contract & in no way influences the core functionality.
    * Some wallets/interfaces might not even bother to look at this information.
    */
    string public name = "BeautyChain";
    string public symbol = "BEC";
    string public version = '1.0.0';
    uint8 public decimals = 18;

    /**
     * @dev Function to check the amount of tokens that an owner allowed to a spender.
     */
    function BecToken() {
      totalSupply = 7000000000 * (10**(uint256(decimals)));
      balances[msg.sender] = totalSupply;    // Give the creator all initial tokens
    }

    function () {
        //if ether is sent to this address, send it back.
        revert();
    }
}