Risk Warning: Beware of illegal fundraising in the name of 'virtual currency' and 'blockchain'. — Five departments including the Banking and Insurance Regulatory Commission
Information
Discover
Search
Login
简中
繁中
English
日本語
한국어
ภาษาไทย
Tiếng Việt
BTC
ETH
HTX
SOL
BNB
View Market
BlockSec DeFi Attack Analysis Series 4 Misconceptions: Sanshu Inu’s Memestake Contract Attack Event Analysis
BlockSec
特邀专栏作者
2021-08-03 07:27
This article is about 5655 words, reading the full article takes about 9 minutes
Systematically analyze DeFi security incidents and analyze the root causes behind the security incidents

Decentralized finance (DeFi), as a popular project form in the blockchain ecology, its security is particularly important. Since last year, dozens of security incidents have occurred.

As a long-term research team (https://blocksecteam.com) concerned with DeFi security, BlockSec has independently discovered a number of DeFi security incidents, and the research results have been published in top security conferences (including USENIX Security, CCS and Blackhat). In the next period of time, we will systematically analyze DeFi security incidents and analyze the root causes behind the security incidents.

Past review:

(1)Past review:

(2)[One of BlockSec DeFi attack analysis series] I speak for myself: ChainSwap attack event analysis

(3)[BlockSec DeFi Attack Analysis Series 2] Give away everything: Sushiswap fees stolen

[BlockSec DeFi Attack Analysis Series 3] Stealing the sky and changing the day: In-depth analysis of the Akropolis attack incident

0xffffffff. Preface

At 03:40 on July 21, 2021, Beijing time, our attack detection system detected an abnormal transaction. Through the extended analysis of this transaction, we found that this is an incident of using the deflation token (deflation token) KEANU mechanism to attack the vulnerability of the reward calculation mechanism of the Memestake contract deployed by Sanshu Inu. The attacker finally made a profit of about 56 ETH indivual. The following detailed analysis is as follows:

  • Reading suggestions:

  • If you are new to DeFi (Ethereum), you can read it from the beginning, but the article is relatively long, so if you can’t read it, remember to pay attention before leaving.

If you have a better understanding of DeFi aggregator projects such as Akropolis, you can start directly from "0x2 Attack Analysis".

0x0. Background introduction

Since the beginning of this year, Dogecoin (DOGE) and Shiba Inucoin (SHIB) have attracted widespread attention. At the same time, other related meme coins have become popular, which has also triggered a large number of project parties to develop their own meme coins and provide meme coins around meme coins. services, of which Sanshu Inu is a member. Sanshu Inu not only issued the meme coin SANSHU, but also created the contract Memestake as a farming pool for the meme coin. As long as users pledge meme coins in Memestake, they can get the token Mfund as a reward.

On the other hand, a large number of meme coins are deflationary tokens, that is, the issuance of such tokens will gradually decrease. The deflation of some meme coins is realized by deducting a certain proportion of coins for destruction and redistribution every time the user makes a transaction transfer (transfer), which will cause the actual amount of tokens received by the receiver to be less than the actual payment by the payer quantity. The deflationary token KEANU involved this time adopts this kind of implementation.

The general principle of the attack is to reduce the number of KEANU it holds by controlling Memestake to perform multiple KEANU transfers in and out, so as to use the loopholes in its reward calculation function to cause Memestake to send a large amount of Mfund to the attacker.

0x1. Code Analysis

For ease of understanding, we first briefly introduce two physical contracts related to this attack: the KeanuInu contract of the KEANU token and the Memestake contract.

KeanuInu contract


As mentioned earlier, when KeanuInu realizes the transfer of token KEANU, it will deduct a certain proportion of coins for destruction and redistribution, and the proportion for destruction is set to a fixed value - 2%. As shown in the figure, when KeanuInu's transfer() and transferFrom() functions are called, the transfer amount displayed in the function call is not consistent with the amount recorded in the emit event log.http://tx.blocksecteam.com:8080/Due to the complexity of its actual code implementation call, it will not be shown here. Interested friends can check the contract implementation on etherscan.io according to the contract address given in the appendix later. In addition, the above two screenshots are from our self-developed transaction analysis tool, which is currently in open beta. Welcome to click

try out. The way our tool combines function calls with event logs generated during the process is more helpful for analyzing issues such as deflationary tokens.

Memestake contract

The figure below is the deposit function of MemeStake. The function first calls updatePool to update the state of the fund pool, and then transfers the user's token to itself. When the incoming _amount is greater than 0, the transfer will be performed on line 1295 of the code.

However, due to the deflationary characteristics of KEANU token, although the amount passed in when calling the safeTransferFrom function is _amount, the amount actually transferred to the fund pool is less than _amount. And in the code analysis, we noticed that the destination of the transfer is yourself, that is to say, for MemeStake, all users' deposits of a certain currency (such as KEANU token) belong to MemeStake.

In line 1296 after the transfer, MemeStake will register the user's deposit, but the registration here is still _amount (and the actual transfer amount is less than _amount), so the user's real deposit amount is smaller than the registered user.amount .

Finally, in line 1299, it can be seen that the user.rewardDebt parameter is also calculated based on (larger than the real value) user.amount.

The figure below is the withdraw function of MemeStake. The function first checks if user.amount has sufficient balance, but since user.amount itself is larger than the real value, the check here is inaccurate. Next, the updatePool function will also be called to update the status of the fund pool.

In line 1321, the withdraw function will first deduct the balance registered in user.amount, and then call the transfer function to transfer the token back to the user. Like the deposit function, there is also a problem with the logic here. Since each transfer will cause deflation, the amount transferred to the user will be less than the actual transfer amount.

Finally, look at the updatePool function of MemeStake. First of all, it can be seen from line 1255 that each call will record the last updated blockNumber, if the block called this time is the same as the last update, it will return directly, that is to say, updatePool will only update each block A fund pool status.

pool.accMfundPerShare += mFundReward / token.balanceOf(MemeStake)

Next, in line 1259, the balance of MemeStake itself in the token contract will be obtained (as mentioned above, every time the user deposits, the token will be transferred to MemeStake). Finally, in line 1275, this balance will be used as the denominator to calculate the rewards for each deposit and withdrawal of the fund pool (that is, the pool.accMfundPerShare parameter). It is calculated as follows:

rewardMfund = user.amont * pool.accMfundPerShare / 1e18 - user.rewardDebt。

Back to withdraw, let's see how the deposit and withdrawal reward token Mfund is transferred. First, in line 1325 of the withdraw function in the above figure, calculate whether the user has a pending Mfund token that has not been issued. The calculation formula is:

user.rewardDebt = user.amount * pool.accMfundPerShare / 1e18

And rewardDebt is calculated like this (line 1325 in the figure):

  • Therefore, it is not difficult for us to construct a possible attack from the code:

    • First, within a transaction, the MemeStake's fund pool is drained by repeatedly calling the deposit and withdraw functions. This operation exploits three code issues:

    • First of all, user.amount is billed more than the real value, so every withdraw can succeed.

    • Second, the funds of all users in MemeStake are in one pool, so each transfer actually burns the KEANU token deposited by other users in the pool.

  • Third, since updatePool does not perform status updates in the same block, it will not affect the pool.accMfundPerShare parameter, nor will it generate Mfund token rewards.

    • Next, in the next block, directly call the withdraw function.

    • Then in line 1315 of the withdraw function, the calculated Mfund reward amount is very large, resulting in a huge Mfund reward.

0x2. Attack Analysis

0x2. Attack Analysis

The cause of the vulnerability and the way to exploit the vulnerability have been introduced above. Next, we will introduce how the attacker actually conducts the attack.

  • As shown in the figure, the attack can be divided into 4 steps, of which the key attack step is step 2, which uses the characteristics of deflationary tokens to manipulate the reward calculation of Memestake.Step 1 (preparation), first the attacker creates and initializes two contracts, among whichcontract oneKEANUIn order to perform a normal investment contract, the attacker deposited about 2,049B into Memestake through contract 1, to pave the way for step 3 to earn a large amount of MFUND rewards.contract two

  • In order to manipulate the Memestake reward calculation contract, the approve operation of the relevant token is first performed.0x00edIn the second step (manipulation), the attacker first flash loan a large amount of KEANU tokens from uniswapV2, and then deposit and withdraw a large number of KEANU tokens to Memestake through contract 2, causing Memestake to be forced to trade a large amount of KEANU. Since KEANU is a deflationary token, each transaction will burn 2% of the transaction amount, resulting in the user's actual deposit in Memestake being smaller than the registered user.amount, and the withdrawal is transferred to the user according to the user.amount ( See code analysis for details), resulting in the continuous decrease of KEANU token holdings in the Memestake pool, and finally 1e-07. As shown in the figure below, the transactions involved are

  • , the screenshot of the transaction is not complete, please click the link to view it yourself.MfundStep 3 (profit), the attacker first calls the Memestake.updatePool() function through contract 2, and modifies accMfundPerShare of the pool where KEANU is located, because this value depends on the amount of KEANU tokens held by the pool, and this is in It was manipulated in the second step (see the code analysis below for the specific formula). This allows contract 2 to obtain far more than the normal value in the next withdrawal0xa945(about 61M) This token is used as a reward. Step 3 happens in the transaction

  • At the same time, the attacker began to exchange part of the obtained MFund for tokens such as WETH.Tornado.CashStep 4 (end), the attacker will exchange the obtained MFund, KEANU and other tokens into ETH, and pass

Transfer away, so far the attack is over, and the attacker has profited 55.9484578158357 ETH (the attacker's EOA address and deployed attack contract still have some SANSHU and KEANU tokens not counted), about 100,000 US dollars.0x0333The following figure shows the attack address

The screenshot of the transaction, the transaction screenshot is not complete, please click the address link to view the details.

attack related

Interestingly, both steps 2 and 3 of the attack are related to flashbots transactions.0x00edThe transactions involved in step 2

Due to the adoption of UniswapV2 flashloan, and before and after the transaction, it is equivalent to using about 38ETH to purchase KEANU, which creates a large arbitrage space. Therefore, the transaction was sandwiched by another attacker (sandwich attack), that is, the attacker in this event was also a victim of another sandwich event. The sandwich attacker made a profit of 3.2769697165652474ETH, but gave the miner 2.405295771958891249ETH, with a net profit of 0.8716739446063562ETH.0xa945while the transaction involved in the attack in step 3

Since a large number of MFunds were sold in the uniswap pool, arbitrage space was created, so it was back-running and became a flashbots transaction. The searcher made a profit of 0.13858054192600666ETH, of which 0.099085087477094764ETH was handed over to the miners, and the net profit was 0.03949545444891189ETH.A detailed introduction to flashbots and sandwich attacks can be found in our other attack introduction. Since the implementation of flash loan is combined with ordinary Swap in UniswapV2, please refer to our paper for the specific implementation principle and why there is arbitrage space in the second step.Towards A First Step to Understand Flash Loan and Its Applications in DeFi Ecosystem (SBC 2021).

0x3. Summary and security recommendations

0x3. Summary and security recommendations

The attacker used the characteristics of deflationary tokens to control the number of tokens held by the platform, which affected the calculation and distribution of reward tokens, and thus made a profit of 55.9484578158357 ETH. The reason for this is that the Sanshu Inu platform lacks certain security considerations when introducing deflationary tokens, allowing attackers to take advantage of it.

  • Therefore, our security recommendations to relevant project parties are as follows:

  • Before the project goes live, it is necessary to find a qualified security company to conduct a security audit. We can see that due to the money lego attribute of defi, many defi projects can be combined at will, thus producing mutual influence, and this is the reason for the frequent occurrence of security incidents in the defi field. Therefore, the security issues that project parties need to pay attention to are not limited to their own projects, but also need to consider the security vulnerabilities that exist in the process of interacting with other projects.

Driven by core security technology, the BlockSec team has long been concerned with DeFi security, digital currency anti-money laundering and digital asset custody based on privacy computing, providing contract security and digital asset security services for DApp project parties. The team has published more than 20 top security academic papers (CCS, USENIX Security, S&P), and its partners have won the title of AMiner's most influential security and privacy scholar in the world (ranked sixth in the world in 2011-2020). The research results have been awarded by CCTV, Xinhua News agency and overseas media reports. Independently discovered dozens of DeFi security vulnerabilities and threats, and won the first place in the world in the 2019 National Institutes of Health Privacy Computing Competition (SGX Track). Driven by technology, the team adheres to the concept of openness and win-win, and works with community partners to build a safe DeFi ecosystem.

https://www.blocksecteam.com/
contact@blocksecteam.com

DeFi
Safety
smart contract
Dogecoin
Welcome to Join Odaily Official Community