In-depth understanding of the underlying logic of Flash Loan attacks

This article is machine translated
Show original
Go deep into the source code of Flash Loan to understand what Flash Loan are and Flash Loan attacks.

Sharing Guest: Frog, Numen Blockchain Security Researcher

Arranging: Xiao Hu

Edit: Chen Yi

In our last article, we mainly introduced the Flash Loan attack on Euler Finance, a leading DeFi lending agreement. In this article, we will go one step further and go deep into the source code of Flash Loan to understand what Flash Loan and Flash Loan attacks are.

01 TL;DR

As in our previous article ( “Apocalypse of Thunderstorm: Euler Finance Reappears Before and After being Attacked ”), Flash Loan have the following keywords:

1. Loans that do not require collateral funds

2. Lending, using funds, and repaying loans "simultaneously"

So with large amounts of funds that are not collateralized, hackers can:

1. Manipulating prices, smashing or pulling orders

2. Multiply the existing vulnerabilities

02 What is Flash Loan

Flash Flash Loan is an innovative product of decentralized finance (DeFi), which allows users to borrow any amount of assets in the protocol pool without providing any collateral, as long as they are in the same transaction (one zone) block) to return the principal and interest. The advantage of Flash Loan is that it allows users to take advantage of arbitrage opportunities in the market to achieve low-cost, high-yield operations. The risk of Flash Loan is that if the user fails to repay the loan within the specified time, the transaction will be revoked and the user will lose transaction fees and interest.

1 Common Flash Loan platforms

When it comes to Flash Loan, you may immediately think of AAVE, the company that invented and led Flash Loan. Due to the low-risk characteristics of Flash Loan funds, a large number of Flash Loan platforms have emerged immediately due to high demand. The top platforms that provide Flash Loan services include:

- Uniswap: A decentralized trading platform that provides Flash Loan services. Users can borrow any supported token through Uniswap, and perform operations such as exchange, market making, and arbitrage in the same transaction.

- Compound: An open source lending protocol that supports lending and borrowing of multiple digital assets, and provides Flash Loan services. Users can borrow any available asset through Compound, and perform operations such as repayment, mortgage, and borrowing in the same transaction.

- MakerDAO: A decentralized Stablecoin platform that supports the issuance and trading of DAI Stablecoin and provides Flash Loan services. Users can borrow DAI through MakerDAO, and perform operations such as repayment, exchange, and repayment of liquidation penalties in the same transaction.

- dYdX: A decentralized exchange that provides Flash Loan services and an open lending market. Users can borrow any available asset through dYdX and make repayments, trades, leverage, etc. in the same transaction.

In addition, the common ones are Nuo, Fulcrum, bZx, DeFi Money Market, ETHLend, etc.

These Flash Loan platforms all provide unsecured and instant loan services functionally, and the differences in details are more reflected in the security, user experience and handling fees of the platforms.

2 Uniswap Flash Loan

Uniswap is one of the most popular decentralized exchanges in DeFi. The way for general users to access Uniswap is the web interface. For example, the figure below shows the exchange of ETH-DAI. We call an exchange between two tokens a trading pair.

But in addition to using the website to interact, we can also directly call the smart contract to interact. When you want to buy tokens on their platform:

  • First need to send token for payment
  • Then call a swap() function, which will send the token you just purchased.

Uniswap V2 has a new feature called Flashswap, which is Uniswap's name for Flash Loan. This functionality is integrated in the regular swap() function.

A common Flash Loan operation logic has four steps, which must be completed in the same block:

1. Send a transaction request and upload the smart contract

2. Send tokens to the protocol

3. The uploaded smart contract interacts with tokens

4. Return tokens to the protocol

Because Uniswap's swap() function mode is to transfer the account first and then verify it, so in the second step, you can first lend the required tokens, and then in the third step, call the uniswapV2Call() function in your own contract to perform other operations. Four steps and then return the borrowed tokens to complete the Flash Loan service.

In the code, the part in the red box is the contract pre-deployed by the user. In order to complete all the above operations in the same block, the user must pre-define how to use the loaned funds with the contract. After all, the speed of manual operation is not as fast as code execution.

And in the two lines above the red box, we see that there are two transfer functions. As the comment says, this is an "optimistic transfer" - that is, a transfer without checking whether it is paid or not. In the last part, after calling the user contract, the swap() function will slowly require the payment amount.

Regardless of whether the Flash Loan service is used or not, Uniswap will charge a handling fee of up to 0.3% for each transaction.

3 AAVE Flash Loan

Overall, the Flashloan function in AAVE 's LendingPool contract provides a similar Flash Loan function. By calling the Flashloan function, parameters such as the loan amount and token type loan address are passed in. After the token is transferred to the incoming receiving address during execution, the executeOperation function of the incoming address will be called. At this time, other operations can be completed in the executeOperation function.

AAVE and Uniswap have a little difference in the repayment process. The repayment of AAVE Flash Loan requires the borrower to authorize the LendingPool contract. After the Flash Loan process is completed, the AAVE contract will transfer the borrowed money and handling fee back from the borrowing address. In Uniswap, users call safeTransfer to perform manual transfers.

This can ensure a higher success rate, but there may be a certain risk of contract loopholes.

03 Flash Loan attack

Discussions about Flash Loan attacks are constant. Some people say that the Flash Loan attack is strictly speaking a misnomer, because it does not use the loopholes of the Flash Loan, but uses a large amount of funds to discover the existing loopholes in advance. For example, using Flash Loan with large amounts of low-cost funds, you can:

1. Manipulating the price by using the large amount of funds in the Flash Loan. There are problems in the price acquisition logic in some projects.

2. Some projects will generate instant rewards during the mortgage or other processes, and use Flash Loan to obtain large rewards.

3. There are other logical loopholes in the project, and the large amount of funds in the Flash Loan is used to enlarge the arbitrage space.

Let's analyze the case first, and then discuss which vulnerabilities are vulnerable to Flash Loan attacks.

1 DFX attack event

To put it simply, the attack on DFX is divided into three steps:

1. Complete the Flash Loan of USDC and XIDR from UniswapV3.

2. Call the flash function from the DFX contract to loan to UCDC and XIDR, and then call the deposit function to mortgage. When mortgaging, you can see that the money lent by the hacker is mortgaged back to the DFX contract.

3. Because the user transferred the token back to the DFX contract when mortgaging, the balance verification before and after the borrowing passed, and there is no need to return the loaned Flash Loan. However, the hacker has a mortgage operation, and the extraction function can be called at this time. After the mortgage is withdrawn leave.

2 Analysis of Common Vulnerabilities

Let's take stock of the vulnerabilities in the code below.

1. Get the price by the number of tokens:

This code directly reads the number of tokens in the pair contract of the decentralized exchange, and uses the quotient of the two as the price of the token. For someone who lacks experience in code auditing, it may seem that there is nothing wrong with writing this way at first glance. But when you consider the fact that Uniswap supports Flash Loan, things get interesting.

If there is no Flash Loan, the quantity of the two tokens must be reduced by one and increased by the other. But with Flash Loan, it is very likely that one token will decrease and the other token will not increase. If the amount of the Flash Loan is not large, the difference in the two cases is not large. But if a huge Flash Loan is lent, the price difference will be widened immediately, forming a huge arbitrage space.

Such loopholes are difficult to find for people without code auditing experience. It takes a long time to cultivate and accumulate in the security field to form a mature code auditing system.

2. Distribution of rewards:

In this code, the contract will immediately return the reward to the user's address according to the amount of mortgage. We have already mentioned the problem here, and it is relatively easy to think about. If there is no delay in the distribution of rewards, the Flash Loan money can be rewarded only for a moment after being pledged in the contract, which is undoubtedly a huge arbitrage loophole.

3 Precautions

During the time period when DeFi has not yet matured, Flash Loan attacks will continue, becoming a sword of Damocles hanging over people's heads. Different Flash Loan attacks have different impact ranges, some may cause a seemingly irrelevant DeFi protocol to be thundered, and some may affect many users. What we can do well is to take preventive measures and wait for DeFi to continue to mature:

1. The pledge mining function is separated from the lending contract. Do not transfer the tokens mortgaged by the user to the lending contract or record variables for calculation.

2. Add a special re-entry lock when borrowing, and mortgages are not allowed when borrowing.

3. The project adopts the form of multiple data sources when obtaining prices, and the price error is reduced after data comparison.

4. When removing Liquidity, LP should be destroyed first before making other calls.

5. The generation of rewards should be in the form of block intervals or time differences, which can effectively avoid Flash Loan attacks.

6. The project logic problem is the most common situation that causes hackers to use Flash Loan to enlarge arbitrage. Therefore, before the project goes online, security audits and tests must be done to ensure the security of the project.

Source
Disclaimer: The content above is only the author's opinion which does not represent any position of Followin, and is not intended as, and shall not be understood or construed as, investment advice from Followin.
Like
Add to Favorites
Comments