Integer Overflow in Smart Contracts - Auditing and Mitigating the BEC Token Risk

Disclaimer: This article is a personal technical study note. Any operations described should only be performed in authorized environments. Users bear full responsibility for any misuse.

This article is part of a series on Solidity contract security, and reviews a historical incident in order to derive auditing and mitigation practices that remain applicable today.

The case examined here is the BeautyChain (https://www.beauty.io/) contract. The incident occurred in 2018 and is one of the most frequently cited examples of an arithmetic overflow in a deployed token contract.

The original site is no longer reachable; an archived copy is available at Web Archive.

Web Archive: https://web.archive.org/web/20180419222450/http://www.beauty.io/

CoinFI: https://www.coinfi.com/coins/beauty-chain

BeautyChain(BEC) Contract Code: https://etherscan.io/token/0xc5d105e63711398af9bbff092d4b6769c82f793d

TX: https://etherscan.io/tx/0xad89ff16fd1ebe3a0a7cf4ed282302c06626c1af33221ebe0d3a470aba4a660f

The root cause is a classic integer overflow in contract arithmetic. Because the overflow was reachable from a public function, an unbounded amount of tokens could be credited in a single transaction, and the resulting imbalance drove the token’s market value to zero.

On-chain records show the transaction credited an amount of 57,896,044,618,658,097,711,785,492,504,343,953,926,634,992,332,820,282,019,728.792003956564819968 BEC, which is far beyond the total supply declared by the contract and effectively rendered the token worthless.

From an auditing standpoint, the transaction input has a conventional structure: a function selector, followed by an array of receiver addresses and a per-recipient value. Two receiver addresses appear in the _receivers array, and both are supplied as parameters to the batchTransfer function. The exact calldata is deliberately not reproduced here; the relevant point is that every field of the call was attacker-controlled and no bound was enforced on the arithmetic. To understand why the call succeeded, the contract code has to be examined.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
/**
*Submitted for verification at Etherscan.io on 2018-02-09
*/

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();
}
}

The function takes an array of _receivers and a single _value, and credits _value to every receiver in that array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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;
}
}

The intended semantics are straightforward: the total debit is the number of recipients multiplied by the per-recipient amount. The function verifies that the caller holds at least that total, debits it once, and then credits each recipient inside the loop.

1
uint256 amount = uint256(cnt) * _value;

The defect lies in this line. _value is a uint256 supplied by the caller, and cnt is derived from a caller-supplied array. Their product is computed with the unchecked multiplication operator, so a product exceeding 2^256 - 1 wraps around and amount is reduced to a small residue rather than reverting. The balance check and the subsequent debit are then evaluated against that residue, and both pass even though the loop credits each recipient with the full _value.

1
balances[msg.sender] = balances[msg.sender].sub(amount);

The asymmetry is decisive: the debit uses the wrapped amount, while the credit inside the loop uses the original _value. The caller is therefore debited an insignificant quantity and credited with an arbitrarily large quantity, distributed across the receiver array.

The value range of uint256 is 0 to 115792089237316195423570985008687907853269984665640564039457584007913129639935, that is $2^{256}$. Any result at or above that bound wraps modulo $2^{256}$. Consequently, the smallest per-recipient value that forces amount to wrap to zero with two receivers is $2^{255}$, i.e. 0x8000000000000000000000000000000000000000000000000000000000000000 in the second argument. The value is not a crafted payload in any meaningful sense: it is simply the boundary value that the missing check was supposed to reject, which is why boundary inputs belong in every arithmetic review.

1
uint256 amount = uint256(cnt) * _value;

Remediation at the code level

The contract already imports a SafeMath library and uses it for the debit and the per-recipient credit, but this single multiplication was written with the raw operator. The fix is to route every arithmetic operation through the checked library, or to compile with a Solidity version that performs overflow checks by default.

  • Route all arithmetic through checked operations. Replace the unchecked multiplication uint256(cnt) * _value with SafeMath.mul(cnt, _value). The mul implementation asserts a == 0 || c / a == b, which reverts the transaction when the product does not survive the round trip, so an overflowing call fails instead of silently succeeding.
  • Prefer compiler-level checks where the toolchain allows it. Solidity 0.8.0 and later revert on overflow and underflow by default, which removes this class of defect from ordinary arithmetic. This contract is compiled with pragma solidity ^0.4.16, a version that predates those checks, so any remaining 0.4.x deployment depends entirely on library discipline. Unchecked blocks, when used for gas reasons, must be justified individually and covered by a test.
  • Derive the invariant instead of the check. Rather than validating amount in isolation, assert the property that must hold for the whole function: total debited equals recipients multiplied by value, and no balance may exceed totalSupply. A batchTransfer that violates either invariant should revert.
  • Constrain the inputs. Receiver count is already limited to 20; a per-call upper bound on _value (for example, no larger than totalSupply) makes the multiplication overflow unreachable rather than merely detected.

https://github.com/ConsenSysMesh/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol

Detection in audit and review

  1. Grep for raw arithmetic. Enumerate every +, - and * applied to user-controlled values outside a checked library. In this contract the sink is a single line inside a batch function, which is the pattern most often missed: the surrounding code looks defensive because it performs a balance check, yet the check operates on an already wrapped intermediate value.
  2. Static analysis. Automated analyzers for Solidity report integer overflow and underflow on unchecked arithmetic. Running them over the full contract set, not only over the token contract, and triaging every arithmetic finding against the compiler version, is a reasonable baseline.
  3. Boundary and property testing. Test arithmetic paths with 0, 1, type(uint256).max, max - 1, and values chosen so the product lands exactly on $2^{256}$. Fuzzing frameworks can generate these inputs, and the invariant assertions described above convert the test into a property rather than a single case.
  4. Review multi-recipient and airdrop functions specifically. Any function that credits N recipients from a single amount is a multiplication sink. Confirm that the multiplication, the debit and the loop all reference the same value, and that the total credit cannot exceed totalSupply.

Detection and response in production

Overflow exploitation of this kind is visible on-chain, and because it is contained in a single transaction, monitoring can flag it as soon as the transaction is mined.

  1. Balance invariant monitoring. Track Transfer events and alert when a credited amount exceeds totalSupply, when a sender’s balance goes negative under any accounting model, or when the sum of all balances diverges from totalSupply.
  2. Abnormal call monitoring. Alert on calls to batch distribution functions carrying extreme _value parameters, and on transfers whose amount is close to $2^{255}$ or $2^{256}$; legitimate business flows do not use boundary values.
  3. Market-side signals. Sudden supply inflation is followed by immediate selling pressure, so liquidity and price monitors on the exchanges listing the token are an effective secondary detection layer.
  4. Incident response for non-upgradeable contracts. Bytecode cannot be patched in place. Where the contract inherits a Pausable mechanism, as this one does, the owner can halt transfers using the existing pause() function, which stops the loop from being exercised again while the incident is assessed. The remaining options are coordination with exchanges and liquidity providers, and migration to a corrected contract with a balance snapshot.

Audit checklist for review

  • Does every arithmetic operation on user-controlled values go through a checked library, and does the compiler version provide default checks?
  • Are boundary values (0, max, max - 1) covered by tests for every arithmetic path?
  • Is there a defined invariant tying total debits to total credits, and is it asserted rather than assumed?
  • Do batch or airdrop functions bound the per-recipient value in addition to the recipient count?
  • Is there a pause or circuit-breaker capability, and is its owner key held under multi-signature control?

In this contract, the conclusion is narrow and worth stating plainly: SafeMath was present and used elsewhere, and the vulnerability exists because one line bypassed it. Arithmetic completeness, not the presence of a safety library, is what the review has to verify.

Reference

  1. https://medium.com/secbit-media/a-disastrous-vulnerability-found-in-smart-contracts-of-beautychain-bec-dbf24ddbc30e

  2. https://finance.sina.com.cn/blockchain/roll/2018-04-24/doc-ifzqvvsa5144276.shtml

  3. https://learnblockchain.cn/2018/04/25/bec-overflow

  4. https://tttang.com/archive/1292/

Support via Solana

Solana

Solana

Solana Pay

Solana Pay

WeChat

WeChat