All in Vain Overnight? | LianAn Technology Smart Contract Vulnerability Analysis Series Phase I
Overflow/Underflow Vulnerability Analysis
The BEC and SMT attacks in April has past for a while, the detailed situations were reported by so many medias that everybody can find relevant analysis and fix-up methods of vulnerabilities now. Chengdu LianAn Technology Team organized those vulnerabilities and put the corresponding fix-up solutions here to share with you all.
Incident Review
On 22nd, April, 2018, hackers attacked BEC token smart contract, withdrew 57,896,044,618,658,100,000,000,000,000,000,000,000,000,000,000,000,000,000,000.792003956564819968 tokens and dumped them on the market, the value of BEC dropped rapidly to almost 0. BEC market died instantly.
On 25th, SMT project manager found a few transactions on the market were abnormal, which was caused by hackers creating 65,133,050,195,990,400,000,000,000,000,000,000,000,000,000,000,000,000,000,000
+
50,659,039,041,325,800,000,000,000,000,000,000,000,000,000,000,000,000,000,000
SMT tokens exploiting vulnerabilities. Huobi Pro Exchanges shut down all the trading related to SMT immediately.
Let us grieve in peace for a minute ☹.
However, within 12 hours after the BEC attack, there had been 12 other tokens found similar overflow/underflow vulnerabilities. Hackers could exploit this kind of bug to create huge amount of tokens, which is what we call ‘excessive minting of tokens’.
Why excessive minting can result in value drop
There is an old saying, “when a thing is scarce, it is precious”.
Gold was selected as the earliest currency around the world because of its rarity, limited amount on earth, stability, and easy segmentation.
Chinese invented “jiaozi” first to replace gold because it’s inconvenient to carry.
So the concept of ‘Gold Standard’ came out, every country started issuing currency based on the gold reserves, instead of on free will.
Imagine if a meteor made from gold hit the earth and gold were everywhere, will gold still be worth a lot of money?
Hence the limit of the token issued. If the number of tokens increased without control, the corresponding value would drop rapidly for sure, or even lose the meaning of trading. This is the consequence of excessive minting of tokens.
Integer Overflow/Underflow Vulnerability Analysis
On the first paragraph we mentioned that hacker used integer overflow to go around relevant smart contract rules to mint tremendous amount of tokens.
Then what is ‘integer overflow’? Why can hackers create more tokens with it?
Here is an example
We suppose there is a country where all the people can only count from 0 to 9. Whenever they count to 9, they will start from 0 again. Things go well everyday with a situation like that, but one day, there is a man in black coming from another country and he spotted this issue. So he went to the bank to withdraw some gold, however the number of gold he got for the bank assistant was over 9, specifically, it was the multiple of 9. The bank assistant counted to 9 and went back to 0 again so the final result was 0. In fact, this man in black withdrew almost all the gold from the bank.
The hackers exploited similar mechanism to transfer large amount of tokens to their account with very few tokens.
Chengdu LianAn Technology organized past excessive minting incident and summarized integer overflow/underflow vulnerability analysis here blow.
EVM specifies data type of fixed size for integers, which means an integer variable can only be in a range. For instance, a uint 8 can only store a number in range of [0,255], otherwise it’s shown as 0. If developers don’t pay attention and the input data is not checked, the number goes beyond the range allowed Thus the variables being exploited to attack the smart contract in Solidity language.
Integer overflow/underflow includes Overflow in multiplication, Overflow in Addition, Minus Underflow in subtraction.
Out team analyzed BEC attacks and found it belongs to Overflow in multiplication category, the mechanism is as follows:
Overflow in multiplication:
Case(CVE-2018–10299)
In the smart contract above, the bugged code is uint256 amount = uint256(cnt)*_value;, the transfer-out amount didn’t use SafeMath or overflow check. Instead, it multiplies the transfer address with transfer amount. If the _value was set to be extremely large, the result of amount could be overflowed, hence the excessive minting.
Testing in Remix-ide:
1, deploy contract;
2, call batchTransfer function, then deliver the address array [“0xb4D30Cac5124b46C2Df0CF3e3e1Be05f42119033”,”0x0e823fFE018727585EaF5Bc769Fa80472F76C3d7"] and _value”0x8000000000000000000000000000000000000000000000000000000000000000" into batchTransfer which equals to 2*255, to make amount=2\*255*2. Now the result of amount is beyond the range [0,2*256–1] and counted as 0, the sender’s balance didn’t decrease. In this case, the balance can even be 0 to make such thing happen.
3, check the balance;
It’s still the same.
After analyzing SMT incident, we categorize it into Overflow in Addition the mechanism is shown as follows:
Overflow in Addition:
Case
In the code above, mintToken function means owner issues mintedAmount of tokens to specific account. But there is no overflow check aiming at balanceOf[target] or totalSupply, which leads to possible overflow. This bug can be exploited to arbitrarily increase or decrease the balance of any account, and issue excessive amount of tokens out of the totalSupply limit.
Testing in Remix-ide,
1, Deploy contract;
2, Transfer part of the tokens into Target account, to simulate that the target account already has certain balance. Call the transfer function, to transfer some tokens such as 2000000000000000000(2 * 10**uint256(decimals)); into its address: 0x14723a09acff6d2a60dcdf7aa4aff308fddc160c;
3, If owner wants to deduct half of the balance of target, he/she only needs to mint 2*256-balanceOf[Target]+10\*18=0xfffffffffffffffffffffffffffffffffffffffffffffffff21f494c589c0000 worth of tokens. Now we can try call mintToken function to do this:
4, check the balance;
We can see that the overflow truly happened.
As for Underflow in Subtraction, we also provide case like below:
Underflow in Subtraction
Case
The distribute function is used to transfer 2000*10**8 tokens into specific account. Same mistake happened here, there is no SafeMath for balance[owner] calculation, nor does the case check whether owner has enough balance. So when the transferred amount exceeds the balance, balance[owner] generates underflow in subtraction and turned into an extreme.
Testing in Remix-ide:
1, Also deploy contract;
2, Call distribute function, deliver address arrays:
[“0x14723a09acff6d2a60dcdf7aa4aff308fddc160c”,”0x4b0897b0513fdc7c541b6d9d7e929c4e5364d2db”]
Owner sends 2000*10**8 tokens to go over the limit of owner balance, thus the underflow of balance[owner];
3, Check the balance of owner account, the result turned out to be 2*256–2000*10**8
Although hackers found these loopholes to attack smart contracts, we also came up with some countermeasures as follows:
Bug Fix-up
OpenZeppelin offered a SafeMath library, which can be used to perfectly prevent overflow/underflow. The source code is as follow:
What can we learn from mistakes?
Those attacks mentioned above are tragic for both exchanges and investors, we should beware of follow things:
1, Smart contracts developed based on ERC20 protocol gave too much power to owners, and these integer overflow problems should be tested on the underlying platform before going online.
2, Developers didn’t treat the writing of contracts cautiously. They should do some test using SafeMath for overflow/underflow.
3, Without rigorous logic, innovation could turn into disaster. Developers should invent functions based on given SafeMath library.
After all, Chengdu LianAn Technology team highly recommend the use of SafeMath library during development to avoid similar integer overflow/underflow problems and disorder of smart contract logic.
About LianAn Technology
Chengdu LianAn Technology Co. Ltd., focusing on blockchain security field, has developed “One-button” formal verification tool called VaaS, which is the world’s first automated blockchain formal verification platform supporting both EOS and Ethereum. As the one and only company which has obtained the strategic investment from Fenbushi Capital on the aspect of blockchain security layout, LianAn Tech has established cooperation with several companies such as Huobi、OKEX、KuCoin、LBank、CoinMex、Becent、ONT、Scry、CareerOn、IoTeX、DALICHAIN、Bplus, Bytom, Bubi Blockchain, and YUNPHANT. LianAn Tech has audited over 500 smart contracts up till now, and was also nominated in the “2018 China Blockchain Industry White Paper” issued by the Ministry of Industry and Information Technology of the People’s republic of China.
E-mail:vaas@lianantech.com
Official website:https://www.lianantech.com
Twitter: https://twitter.com/LianAnTech_com
Facebook: https://www.facebook.com/LianAnTechChengdu/
Telegram Chinese Group:https://t.me/joinchat/IRgNDA4iCF0Rs92sg5qoVg
Telegram English group: https://t.me/joinchat/IRgNDBBpCon-695ATmbA4w