Address was changed covertly, owner was switched with secrecy? | Chengdu LianAn Technology Vulnerability Analysis Series Phase IV
In the last article we talked about Reentry and Race Condition. Controlling the critical variables and use built-in mechanism help contracts mitigate the risk of getting attacked using these two methods.
This time, let’s talk about underlying function calling, namely the call and delegatecall functions.
Currently the cryptocurrency market value has reached 300 billion USD, more than twice as much as the value of the biggest Canadian bank RBC. Some of the valuable cryptocurrencies contain huge capitals, like diamonds in the vault. Meanwhile, they draw attentions of many hackers and ‘thieves’. Therefore, the security of smart contracts becomes fairly important. However, iterations of protocols for security reasons cannot guarantee the improvement of security, there will be unexpected exceptions. Hence the hackers’ intention of spotting loopholes.
Now let’s focus on the security risks while using call and delegatecall.
On 11th of May, 2018, the AI project initiator ATN found an anomaly related to their total supply of ATN tokens. There are extra 11 million tokens on the market without any operations of their own. Besides, the attacker returned the address with access to complete the attack and distributed the stolen tokens to 14 different user accounts, trying to hide his tracks.
Fortunately, ATN took counter-measures immediately, including locating all suspicious accounts, freeze those tokens and destroy them. They maintained the running of the market afterwards.
To implement token exchange, access expansion and control, and contract iteration, ATN applied relatively new ERC223 protocol, plus the use of DS-Auth library, to develop their smart contract. It is expected to be a effective way to improve the security level. The result turned out to be otherwise.
If we take a closer look at its source code, we can see that the major problem is hiding inside the function which implements token exchange. More specifically, the call function, which means the process of main contract calling external function.
Calling external function is widely used in the recently booming Ethereum game contracts. The advantages of using that includes increasing reuse rate and simplification of code. The most recent MyCryptoChamp game contract bug derives from the built-in Random Number Generation function, which is supposed to be borrowed externally. So we can see that external calls is useful under certain circumstances, although it depends on the experience of developers.
How to define External Calls
Strictly speaking, call and delegatecall functions let developers modularize their code. The code will execute in the external contract while using call function to process Standard Message Call. delegatecall is another form of Standard Message Call, but the code in the targeted address will execute with calling the original contract, in another word, msg.sender and msg.value remain unchanged. This function is stored in Implementation Repository, which can be used for creating reusable code for future contracts.
Generally speaking, it is a way that one contract calls some functions of another contract.
If we use an analogy to explain how hackers exploit External Calls, we can put that into a terminator movie.
Imagine John Conner was taken, and Sarah is trying to find T-800 to save him, but the one she called is actually T-1000 who disguised as T-800. In this case, John will be in much more trouble.
This is how attackers infiltrate the contract.
Vulnerability Analysis and Bug-Fix
- Misuse of call function
call is an underlying function of solidity to interact with external contracts or libraries. Using such function requires verification of the security of the parameters being called. Precautions are necessary.
Let’s use below code as an example.
In this case, receiver, _custom_fallback, _from, _amount, data are controlled by users, which means user are in control of the whole call function, including the contract address (receiver) being called, the function (_custom_fallback), and the parameters (_from, amount and data). In fact, this puts contract itself in danger. In the ATN incident mentioned above, attacker called function within the original contract through the authorization of DS-Auth to set receiver as the case contract (simulated attack contract), this series of operation allowed the attacker to acquire the access of owner authority.
Let’s see another wrong implementation of call under ERC223 protocol.
This type of contract allows user to customize the design of any function on any address of call()，which is very dangerous because attacker can easily ‘borrow’ the authority to do anything. The possible consequences are:
1) Allowing attacker to disguise as the original contract owner to steal tokens from other token contracts.
2) Using methods combined with ds-auth to bypass the authority check of contract itself.
3) Allowing attacker to disguise as the original contract to steal the tokens approved by other token accounts
4) Allowing attacker to send fake _data to deceive Receiver contract
1)Recommend using following method to call tokenFallback function
2) When using DS-Auth to set authorities, do not add contract itself to the white list.
2. Misuse of delegatecall
The feature of DELEGATECALL which keeps the calling environment unchanged suggests that constructing bug-free customized library is not as easy as it seems. The codes within the library may be secure and bug-free, however new bugs might appear when running in the new environment of an application.
Let’s take a look at the following case:
This case comes from Level 6 of Ethernaut.
In the fallback function of the main contract Delegation, the functions of Delegate contract can be called via delegatecall and executed in the main contract environment. If msg.data is 0xdd365b8b (the signature of pwn() ), which means calling pwn function of Delegate, then the message sender is able to become the owner of the main contract.
Solidity provides key word ‘library’ to implement library contracts (refer to SolidityDocs for details). This ensures library is stateless and unable to self-destruct. Forcing library to be stateless can reduce the complexity of storage environment. Stateless library can also prevent attacker from directly alter the state of library, which may allow attacks towards those contracts counting on library code. When using delegatecall, beware that library contracts and calling contracts may alter state variables, or construct stateless library.
How to defend
Hackers are trying every way to bypass contract logic, or to find the back doors. That is a challenge for the development of the contract, to become fearless to this challenge, we need to achieve two goals:
1, When calling functions externally, be cautious about the external functions, fully consider the consequences may be caused by this action so as to add rules and logic to mitigate risks accordingly.
2, Consider all the possibilities of authority being stolen from both logic aspect and function correctness aspect, especially during external calling.
Security improvement is surely a long journey for blockchain industry, learning and practice is the only way to reach the destination.
: ATN抵御合约攻击的报告 https://atn.io/resource/aareport.pdf
: 以太坊智能合约call注入攻击 https://blog.csdn.net/u011721501/article/details/80757811
: ERC223-token-standard https:/github.com/Dexaran/ERC223-token-standard/tree/Recommended
: Ethernaut https://ethernaut.zeppelin.solutions
: delegatecall https://blog.sigmaprime.io/solidity-security.html
About Chengdu LianAn Technology
Chengdu LianAn Technology Co. Ltd. is headquartered in Chengdu and focuses on blockchain security field. Founded by Prof. Xia Yang and Prof. Wensheng Guo of UESTC, LianAn Tech’s core team members consist of more than 30 associate professors, postdoctoral students, doctors and masters with experience of studying at overseas leading universities and laboratories (CSDS, Yale, and UCLA) as well as industry elite from Alibaba Huawei, and other famous enterprises. Using formal verification as its core technology, this team has been providing years of services for security critical systems in aerospace, military and other fields. Chengdu LianAn Technology Co. Ltd. is the one and only company in China that applies this technology to blockchain security field.
As the only blockchain security company obtained strategic equity investment from Fenbushi Capital, Chengdu LianAn Technology has signed strategic partnership agreements with well-known corporations such as Huobi, OKEX, LBank, CoinBene, Kucoin, CoinMex, Becent, JBEX, ONT, Scry, CareerOn, loTeX, DALICHAIN, Bytom, Bubi Blockchain, YUNPHANT, and BiXiaoBai. In addition, it has built partnership with Inria France, the top formal verification team in the world. LianAn Technology is on the “2018 China Blockchain Industry White Paper” issued by the Ministry of Industry and Information Technology and has also been selected for the smart contract security audit recommendation list on Etherscan.
Telegram Chinese Group：https://t.me/joinchat/IRgNDA4iCF0Rs92sg5qoVg
Telegram English group： https://t.me/joinchat/IRgNDBBpCon-695ATmbA4w