Decentralized Finance Security: Understanding Risks and Mitigating Risks

CN
8 months ago

There are a large number of security risks in the field of decentralized finance (DeFi), which may cause serious harm to users, platforms, and the entire financial ecosystem. We have summarized three types of DeFi security risks and explained the process of hacker attacks and corresponding solutions by analyzing recent real security incidents.

  • Price manipulation risk

  • Smart contract vulnerability risk

  • User operation risk

1. Price manipulation risk

In DeFi, price manipulation risk refers to malicious actors attempting to profit or influence market behavior by manipulating asset prices. This manipulation may lead to abnormal market price changes, causing losses to other participants. Below, we summarize three possible scenarios of price manipulation risk in DeFi:

  • Flash loan attack

  • Sandwich attack

  • Oracle attack

1.1 Flash loan attack

A flash loan attack is a type of attack that occurs in DeFi applications. It exploits the use of flash loans, which do not require collateral for borrowing. Attackers borrow a large amount of funds through flash loans and conduct a series of operations in the same transaction to carry out fraudulent activities.

ShidoGlobal Flash Loan Attack

On June 23, 2023, a flash loan attack occurred on the Binance Smart Chain (BSC) by ShidoGlobal. The attacker used locking and claiming mechanisms, as well as price differences between two pools, to carry out arbitrage of tokens, successfully stealing 976 WBNB.

Attack Tx:

https://explorer.phalcon.xyz/tx/bsc/0x72f8dd2bcfe2c9fbf0d933678170417802ac8a0d8995ff9a56bfbabe3aa712d6

How did the attacker carry out the flash loan attack?

  • The attacker borrowed a flash loan of 40 WBNB.

Understanding and Reducing Risks in Decentralized Finance Security

  • The attacker exchanged 39 WBNB for 10,436,972,685,676,390,697 Shido Inu: SHIDO tokens (9 decimal places) and deposited them into the PancakeSwapV2: SHIDO-WBNB pool. This operation increased the supply of Shido Inu: SHIDO tokens in the pool, causing the token price to drop.

Understanding and Reducing Risks in Decentralized Finance Security

  • Subsequently, the attacker sequentially called ShidoLock.lockTokens and ShidoLock.claimTokens, converting 10,436,972,685.676390697 Shido Inu: SHIDO tokens (9 decimal places) into 10,436,986,704,133,494,387,000,000,000 SHIDO tokens (18 decimal places).

When the attacker called the lockTokens function in the ShidoLock contract, they locked 10,436,972,685.676390697 Shido Inu: SHIDO tokens in the contract. This meant that these tokens could not be transferred or traded until specific conditions were met. By locking the tokens, the attacker could to some extent maintain the stability of the token price.

The attacker called the claimTokens function, converting the locked tokens into 10,436,986,704,133,494,387,000,000,000 SHIDO tokens. This step effectively increased the decimal places of the SHIDO token from 9 to 18, increasing the total supply of the token.

Understanding and Reducing Risks in Decentralized Finance Security

  • Through the locking and claiming mechanisms, there was a price difference between the PancakeSwapV2: SHIDO-WBNB pool and the PancakeSwapV2: SHIDO28 pool. Specifically, due to the increased supply of SHIDO tokens in the PancakeSwapV2: SHIDO-WBNB pool, the price dropped. In the PancakeSwapV2: SHIDO28 pool, the price was relatively higher because the supply had not increased. The attacker exploited this price difference to exchange 10,436,986,704,133,494,387,000,000,000 SHIDO tokens (18 decimal places) for 1,016 WBNB at a more favorable price.

Understanding and Reducing Risks in Decentralized Finance Security

  • Finally, the attacker repaid the 40 WBNB flash loan and made a profit of approximately 976 WBNB.

Understanding and Reducing Risks in Decentralized Finance Security

Limiting flash loan functionality

Limiting flash loan functionality and introducing flash loan fees are common methods to reduce flash loan attacks and manipulation risks.

  • Limiting flash loan functionality: Flash loan functionality can be restricted, for example, by setting minimum borrowing amounts, borrowing time limits, etc. This can reduce the opportunities for attackers to exploit flash loans for attacks.

  • Introducing flash loan fees: Charging borrowers a certain fee can increase the cost of attacks, making attackers face higher risks and costs when carrying out flash loan attacks.

Understanding and Reducing Risks in Decentralized Finance Security

In the example code above, we have set some limiting conditions to restrict the use of flash loan functionality, such as minimum borrowing amount, maximum borrowing amount, and borrowing time. Before executing the flash loan operation, we calculate and collect a certain percentage of fees.

1.2 Sandwich attack

A sandwich attack is a type of attack in decentralized exchanges (DEX) that exploits information asymmetry. Attackers insert malicious transactions between two trades to exploit price differences and make a profit.

CurveFinance Sandwich Attack

On August 2, 2023, Hypernative systems launched a sandwich attack against Curve Finance. The attacker inserted a malicious transaction between adding liquidity and removing liquidity trades, earning 36.8K USDT.

Attack Tx:

https://explorer.phalcon.xyz/tx/eth/0xd493c73397952049644c531309df3dd4134bf3db1e64eb6f0b68b016ee0bffde

How did the attacker carry out the sandwich attack?

  • The attacker obtained a large flash loan from multiple sources, including wstETH, WETH, and USDT.

Understanding and Reducing Risks in Decentralized Finance Security

  • The attacker provided 155,000,000 USDT liquidity to the 3pool and received 3CRV LP tokens. 3CRV is the LP token of the Curve TriPool (Curve DAI/USDC/USDT pool), which was the pool affected in this attack event.

Understanding and Reducing Risks in Decentralized Finance Security

  • The attacker removed (almost all) DAI and USDC liquidity from the pool and destroyed the 3CRV LP tokens. At this point, the pool was almost entirely USDT, making it much cheaper than DAI and USDC temporarily.

Understanding and Reducing Risks in Decentralized Finance Security

  • The execute() function of the UnderlyingBurner contract was called to continue adding liquidity to the Curve DAI/USDC/USDT pool. The UnderlyingBurner primarily held USDT, and the added DAI:USDC:USDT amount was 100,000:100,000:227,079,039,776. This further unbalanced the pool, with a higher relative quantity of USDT and lower value.

Understanding and Reducing Risks in Decentralized Finance Security

  • The attacker added their DAI and USDC to the Curve DAI/USDC/USDT pool and enjoyed a premium, meaning they obtained a higher quantity of 3CRV LP tokens.

Understanding and Reducing Risks in Decentralized Finance Security

  • The attacker then destroyed their 3CRV LP tokens and withdrew the USDT liquidity.

Understanding and Reducing Risks in Decentralized Finance Security

  • The attacker repaid the flash loan and retained a profit of 36.8K USDT.

Understanding and Reducing Risks in Decentralized Finance Security

In this process, the malicious transaction refers to the attacker removing a large amount of DAI and USDC liquidity from the Curve DAI/USDC/USDT pool and destroying the 3CRV LP tokens. This transaction made the pool extremely unbalanced, with a higher relative quantity of USDT and lower value.

The other two transactions refer to the attacker adding and withdrawing liquidity. The attacker used the price difference to add their DAI and USDC liquidity to the Curve DAI/USDC/USDT pool and withdrew it at a premium, obtaining a higher quantity of 3CRV LP tokens.

In this way, the attacker packaged the malicious transaction with the other two transactions in a sandwich attack, buying USDT liquidity at a low price and then selling it at a high price to make a profit.

Limiting transaction sequence

When it comes to preventing sandwich attacks, code implementation may involve complex smart contracts and transaction logic. Here is a simplified example showing how to prevent sandwich attacks by limiting transaction sequence and introducing transaction delay.

Understanding and Reducing Risks in Decentralized Finance Security

In this example, we assume there is a smart contract called SandwichAttackPrevention, which manages user balances and transactions. To prevent sandwich attacks, we have introduced two main defense mechanisms.

First, in the allowTransaction function, only the contract owner can set isTransactionAllowed to true, allowing users to execute transactions. This ensures that transactions are executed in the correct sequence and prevents attackers from inserting malicious transactions between two transactions.

Second, in the executeTransaction function, we have introduced the concept of transaction delay. Users can only execute transactions after the current block time exceeds the set delay time. This gives other users enough time to execute transactions and update prices, reducing the opportunity for attackers to exploit price differences.

1.3 Oracle Attack

Price oracles are data sources that provide real-time price information for cryptocurrencies. This information is crucial for the normal operation of many DeFi protocols. An oracle attack refers to attackers artificially changing the data provided by oracles, with the aim of profiting from price-manipulated transactions.

Rodeo Finance Oracle Attack

Rodeo is a DeFi platform that provides price oracle services. On July 11, 2023, price oracle manipulation led to hackers stealing approximately 472 ETH (about 888,000 USD) from the Rodeo protocol.

Attack Tx:

https://explorer.phalcon.xyz/tx/arbitrum/0xb1be5dee3852c818af742f5dd44def285b497ffc5c2eda0d893af542a09fb25a

How was the price oracle manipulated?

The key to the Rodeo Finance attack was the Rodeo TWAP Oracle. This oracle was used to track the price ratio between ETH and unshETH.

  • Analyzing the attack transaction: The attack process began with the attacker executing a carefully planned transaction. The attacker utilized a deep understanding of the platform architecture and Time-Weighted Average Price (TWAP) oracle potential vulnerabilities to launch the attack.

  • Manipulating the TWAP oracle: The attacker was able to use the earn function associated with an unconfigured strategy address to force the exchange of USDC for unshETH. This manipulation effectively bypassed the slippage control caused by the flawed unshETH price oracle. Essentially, the earn function was forced to swap from USDC to WETH and then to unshETH.

  • Calculating TWAP price: The TWAP price is calculated by averaging the last four updated prices, with each update interval being 45 minutes. However, the flawed price oracle returned a manipulated price, causing the smart contract to consider the position healthy.

  • Opening leveraged positions: The attacker manipulated the TWAP oracle through a sandwich attack and then opened leveraged positions by calling the earn function from an investor contract. They borrowed $400,000 worth of USDC.

Understanding and Reducing Risks in Decentralized Finance Security

  • Swapping assets: The attacker exchanged the borrowed assets with the underlying CamelotDEX pool and simultaneously sold their prepared unshETH back to the pool.

  • Bypassing execution verification: Contracts typically verify the validity of operations. However, since the attacker controlled this strategy, they easily bypassed this check. This allowed the attacker to exploit the manipulated position by selling the prepared unshETH back to the pool, effectively extracting liquidity from the platform.

  • Transferring stolen funds: The attacker transferred the stolen funds from Arbitrum to Ethereum, exchanged 285 ETH for unshETH, and then transferred them back to Arbitrum to continue the attack. A portion of the stolen funds worth 150 ETH was subsequently transferred to Tornado Cash, a privacy-focused Ethereum mixer service. The remaining 371.2 ETH (approximately $701,679) is still held by the address controlled by the attacker.

A significant vulnerability in this attack was the flawed execution of the Rodeo TWAP Oracle. The oracle relies on the reserves of the WETH/unshETH trading pair, which has low liquidity, leading to significant price fluctuations.

Calculating Prices Based on Multiple Oracles

To ensure the reliability of price queries, a reliable oracle should use multiple oracles or aggregate price feeds to calculate prices, rather than relying solely on token pair ratios. Especially in cases of poor pool liquidity, this diversified pricing information can improve the accuracy of price data and make it more difficult for attackers to manipulate data.

To achieve this goal, a possible solution is to use decentralized oracles, such as Chainlink. Chainlink oracles can collect data from various sources and use blockchain technology to verify and confirm the accuracy of the data. By using multiple data sources, Chainlink reduces the likelihood of single points of failure and makes it more difficult for attackers to manipulate data.

Here is an example code using a Chainlink aggregator contract to retrieve price data:

Understanding and Reducing Risks in Decentralized Finance Security

In the above code, we use an array of AggregatorV3Interface type to store instances of multiple oracles. The constructor takes an array of oracle addresses as a parameter and instantiates each address as an AggregatorV3Interface object.

The getLatestPrice function is used to retrieve the latest price data from multiple sources. It iterates through the priceFeeds array and retrieves price data by calling the latestRoundData function of each oracle. All price data is stored in an array of type int and returned to the caller.

In this way, we can retrieve price data from multiple sources and ensure that price queries more accurately reflect asset prices.

2. Smart Contract Vulnerability Risks

Smart contract vulnerabilities refer to security flaws or errors present in the code written on Ethereum or other smart contract platforms. The core of DeFi is financial protocols based on smart contracts, so smart contract vulnerabilities may lead to loss of user funds, market manipulation, or other malicious activities.

Identifying these vulnerabilities is crucial, and our audits cover various potential issues. This includes but is not limited to reentrancy vulnerabilities, access control vulnerabilities, integer overflow vulnerabilities, and business logic vulnerabilities. Our comprehensive audit services aim to strengthen the security of your smart contracts and protect against the impact of these risks.

Below, an example of the impact of smart contract vulnerabilities on DeFi is illustrated using an access control vulnerability.

LeetSwap Access Control Vulnerability

LeetSwap suffered an attack, resulting in a loss of over 340 ETH. The root cause was an access control vulnerability in the LeetSwapV2Pair contract, where the _transferFeesSupportingTaxTokens function had public visibility.

Attack Tx:

https://dashboard.tenderly.co/tx/base/0xbb837d417b76dd237b4418e1695a50941a69259a1c4dee561ea57d982b9f10ec

Vulnerable Contract:

https://basescan.org/address/0x94dac4a3ce998143aa119c05460731da80ad90cf

Understanding and Reducing Risks in Decentralized Finance SecurityThe attacker called the _transferFeesSupportingTaxTokens function to manipulate the pool, and the attack process is as follows:

  • Exchanged WETH for another token A.

  • Called the _transferFeesSupportingTaxTokens function to transfer token A and subsequently called the sync function, causing the price of token A to rise.

  • Exchanged more WETH for token A and drained the pool.

Solution

To fix the access control vulnerability in the _transferFeesSupportingTaxTokens function, the visibility of the function should be changed to private or internal. Declaring the function as private allows it to be called only by other functions within the contract. Declaring the function as internal allows it to be accessed by contracts that inherit from the LeetSwapV2Pair contract. When other contracts inherit the LeetSwapV2Pair contract, they can call the _transferFeesSupportingTaxTokens function using the super keyword. External users cannot directly access the function, thereby enhancing the contract's security.

The specific visibility change for the function should be determined based on the contract's logic and requirements, ensuring that the visibility change enhances security without affecting the contract's normal operation.

Smart contract audits are an important step in identifying and preventing vulnerabilities. At Salus, we have a team of experienced smart contract developers and auditing experts who can help enhance the security of your contracts. Our expertise enables us to accurately pinpoint potential weaknesses and ensure the security and reliability of your project.

3. User Operation Risks

In the DeFi field, user operation risks refer to the risk of users losing funds due to their own operational errors, lack of security awareness, or careless behavior when using DeFi platforms. Here are some common user operation risks:

  • Clicking on malicious links: Users may accidentally click on malicious links, leading to the infection of their devices with malware or viruses. Attackers can use this malware to obtain sensitive information from users or take control of their wallets.

  • Using insecure wallets: If users choose to use insecure wallet applications or hardware wallets, attackers may exploit these vulnerabilities to steal users' private keys or operational permissions.

  • Leakage of private keys: If users leak their private keys in unencrypted environments or store them in insecure locations, attackers may easily obtain the private keys and subsequently control the funds.

  • Careless trading operations: When conducting trades, if users do not carefully check the transaction details (such as the destination address, transaction amount, etc.), it may result in funds being sent to the wrong address or an incorrect amount being sent.

To reduce user operation risks, here are some recommendations:

  • Increase security awareness: Understand common phishing, malware, and scam tactics, and learn how to recognize and avoid them. Stay vigilant and carefully check links and applications related to DeFi.

  • Use secure wallets: Choose to use wallet applications or hardware wallets that have undergone security audits and have a good reputation. Ensure that wallet applications and firmware are up to date and follow best security practices.

  • Backup and protect private keys: Store private keys in secure locations and encrypt them with strong passwords. Regularly back up private keys and store them in offline, secure locations to prevent accidental data loss.

  • Carefully check transaction details: Before executing any transactions, carefully review the transaction details to ensure that the destination address, transaction amount, etc., are correct. Double-checking can help avoid fund losses due to negligence.

4. Conclusion

Please note that the solutions for each type of attack and vulnerability mentioned above are just simple examples and cannot completely prevent the corresponding attacks or fix the corresponding vulnerabilities. If you are interested in smart contract auditing, please contact us, and we will work with you to provide professional auditing services to ensure the security of your contracts. We are committed to providing you with high-quality services and comprehensive technical support to ensure that your smart contracts operate in a secure and reliable environment.

免责声明:本文章仅代表作者个人观点,不代表本平台的立场和观点。本文章仅供信息分享,不构成对任何人的任何投资建议。用户与作者之间的任何争议,与本平台无关。如网页中刊载的文章或图片涉及侵权,请提供相关的权利证明和身份证明发送邮件到support@aicoin.com,本平台相关工作人员将会进行核查。

Share To
APP

X

Telegram

Facebook

Reddit

CopyLink