Author: Salus Insights
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 summarized three types of DeFi security risks, and explained the process of hacker attacks and the corresponding responses by analyzing recent real security incidents. s solution.
1. Price manipulation risk
In DeFi , price manipulation risk refers to malicious actors trying to profit or influence the market by manipulating the price of an asset. Such manipulation may lead to abnormal changes in market prices and cause losses to other participants. Below, we summarize three situations where price manipulation risks may occur in DeFi :
Flash loan attack
Sandwich attack
Oracle attack
1.1 Flash loan attack
Flash loan attack is an attack method that appears in DeFi applications. It takes advantage of flash loans, a financial operation that allows you to borrow money without providing collateral. The attacker borrowed large amounts of funds through flash loans and performed a series of operations in the same transaction to commit fraud.
ShidoGlobal Flash Loan Attack
On June 23, 2023, a ShidoGlobal flash loan attack occurred on BSC (Binance Smart Chain). The attacker achieved token arbitrage through the locking and claiming mechanism, as well as the price difference between the two pools, and successfully stole 976 WBNB.
Attack Tx:
https://explorer.phalcon.xyz /tx/bsc/0x72f8dd2bcfe2c9fbf0d933678170417802ac8a0d8995ff9a56bfbabe3aa712d6
How does an attacker implement a flash loan attack?
![Decentralized Financial Security: Understanding Risks and Mitigating Risks](https://img. jinse.cn/7178392_watermarknone.png)
The attacker exchanged 39 WBNB s for 10, 436, 972, 685, 676, 390, 697 Shido Inu: SHIDO Tokens ( 9 digits after the decimal point), and deposited into the PancakeSwap V2: SHIDO-WBNB pool. This action increases the supply of Shido Inu: SHIDO tokens in the pool, causing the price of the token to decrease.
![Decentralized Financial Security: Understanding Risks and Mitigating Risks](https://img. jinse.cn/7178393_watermarknone.png)
The attacker then called ShidoLock.lockTokens and ShidoLock.claimTokens in sequence, replacing 10, 436, 972, 685.676390697 Shido Inu: SHIDO Coins ( 9 digits after the decimal point) are converted into 10, 436, 986, 704, 133, 494, 387, 000, 000,  ;000 SHIDO tokens ( 18 digits after the decimal point).
When an attacker calls the lockTokens function in the ShidoLock contract, they will 10,  ;436, 972, 685.676390697 Shido Inu: SHIDO Tokens locked in the contract. This means that these tokens cannot be transferred or traded until certain conditions are met. By locking the token, the attacker can maintain the price stability of the token to a certain extent.
The attacker calls the claimTokens function to convert the locked tokens into 10, 436, 986, 704, 133, 494, 387, 000, 000, 000 SHIDO tokens. This step actually increases the number of decimal places of the SHIDO token from 9 to 18 digits, increasing the total supply of the token.
![Decentralized Financial Security: Understand Risks and Reduce Risks](https://img.jinse.cn/7178394_watermarknone.png)
By locking and claiming Mechanism, there is a price difference between the PancakeSwap V2: SHIDO-WBNB pool and the PancakeSwap V2:SHIDO 28 pool. Specifically, the price dropped due to an increase in the supply of SHIDO tokens in the PancakeSwap V2: SHIDO-WBNB pool. In the PancakeSwap V2: SHIDO 28 pool, the price is relatively high because the supply has not increased. The attacker exploited this price difference to swap tokens between the two pools, transferring 10, 436, 986, 704, 133, 494, at a more favorable price. 387,000,000,000 SHIDO tokens (18 decimal places) were exchanged for 1,016 WBNB.
![Decentralized Financial Security: Understanding Risks and Mitigating Risks](https://img. jinse.cn/7178395_watermarknone.png)
![Decentralized Financial Security: Understanding Risks and Mitigating Risks](https://img. jinse.cn/7178396_watermarknone.png)
Restrict flash loan function
Restrict flash loan functions and introduce flash loan fees is a common way to reduce the risk of flash loan attacks and manipulation.
Restrict the flash loan function: You can limit the flash loan function, for example Set minimum loan amount, loan time limit, etc. This reduces the chances of attackers using flash loans to carry out attacks.
Introducing flash loan handling fees: a certain handling fee can be charged to borrowers. This can increase the cost of attacks, making attackers face higher risks and costs when conducting flash loan attacks.
![Decentralized Financial Security: Understanding Risks and Mitigating Risks](https://img. jinse.cn/7178397_watermarknone.png)
In the above sample code, we set some restrictions to limit the use of the flash loan function, such as the minimum loan amount, maximum loan amount, and loan time. Before performing a flash loan operation, we first calculate and charge a certain percentage of handling fees.
1.2 Sandwich Attack
Sandwich Attack is a Attack methods that exploit information asymmetry in decentralized exchanges (DEX). The attacker exploits the price difference to make a profit by inserting a malicious transaction between the two transactions.
CurveFinance Sandwich Attack
On August 2, 2023, Hypernative systems launched a sandwich attack on Curve Finance. The attacker earned 36.8 K USDT by inserting malicious transactions between two transactions that added liquidity and removed liquidity.
Attack Tx:
https://explorer .phalcon.xyz/tx/eth/0xd493c73397952049644c531309df3dd4134bf3db1e64eb6f0b68b016ee0bffde
How does an attacker implement a sandwich attack?
![Decentralized Financial Security: Understanding Risks and Mitigating Risks](https://img. jinse.cn/7178398_watermarknone.png)
The attacker provided 155,000,000 USDT liquidity to 3 pool and obtained 3 CRV LP tokens. 3 CRV is the LP token of Curve TriPool (Curve DAI/USDC/USDT mining pool), the mining pool compromised in the attack.
![Decentralized Financial Security: Understanding Risks and Mitigating Risks](https://img. jinse.cn/7178399_watermarknone.png)
The attacker removed (almost all) DAI and USDC liquidity from the pool and destroyed 3 CRV LP tokens. At this point, the pool is almost entirely in USDT, which temporarily makes it much cheaper than DAI and USDC.
![Decentralized Financial Security: Understanding Risks and Mitigating Risks](https://img. jinse.cn/7178400_watermarknone.png)
Call the UnderlyingBurner contract execute() function to continue adding liquidity to the Curve DAI/USDC/USDT mining pool. UnderlyingBurner mainly holds USDT, and the added DAI:USDC:USDT number is 100, 000: 100, 000: 227, 079, 039, 776  ;. This results in the pool being more unbalanced, with a higher relative amount of USDT and a lower value.
![Decentralized Financial Security: Understanding Risks and Mitigating Risks](https://img. jinse.cn/7178401_watermarknone.png)
![Decentralized Financial Security: Understanding Risks and Mitigating Risks](https://img. jinse.cn/7178402_watermarknone.png)
![Decentralized Financial Security: Understanding Risks and Mitigating Risks](https://img. jinse.cn/7178403_watermarknone.png)
![Decentralized Financial Security: Understanding Risks and Mitigating Risks](https: //img.jinse.cn/7178404_watermarknone.png)
In this process, malicious transactions refer to It was the attacker who removed a large amount of DAI and USDC liquidity from the Curve DAI/USDC/USDT mining pool and destroyed the transaction of 3 CRV LP tokens. This transaction made the pool very unbalanced, with a higher relative amount of USDT, resulting in a lower value.
The other two transactions refer to transactions where the attacker adds liquidity and withdraws liquidity. The attacker exploited the price difference to obtain a higher amount of 3 CRV LP tokens by adding their own DAI and USDC liquidity holdings to the Curve DAI/USDC/USDT pool and withdrawing them at the premium.
In this way, the attacker wraps the malicious transaction with two other transactions through a sandwich attack Together, buy USDT liquidity at a low price and then sell it at a high price to make a profit.
Restrict transaction order
When it comes to preventing sandwich attacks, code implementation may involve complex smart contracts and transaction logic. Below is a simplified example that shows how to prevent sandwich attacks by limiting the order of transactions and introducing transaction delays.
![Decentralized financial security: understand risks and reduce risks](https://img.jinse.cn/ 7178405_watermarknone.png)
In this In the example, we assume that there is a smart contract SandwichAttackPrevention, which is used to manage the user's balance and transaction operations. To prevent sandwich attacks, we introduce two main defense mechanisms.
First of all, in the allowTransaction function, only the owner of the contract can set isTransactionAllowed is true, allowing the user to perform transactions. This ensures that transactions are executed in the correct order and does not allow an attacker to insert malicious transactions between two transactions.
Secondly, in the executeTransaction function, we introduce 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
The price oracle is a cryptographic Data source for currency real-time price information. This information is critical to the proper functioning of many DeFi protocols. Oracle attacks refer to attackers artificially changing the data provided by oracles in order to profit from transactions based on price manipulation.
Rodeo Finance Oracle attack incident
Rodeo is a DeFi platform that provides price oracle services. On July 11, 2023, price oracle manipulation led to hackers stealingapproximately 472 ETH (approximately $888,000 USD) from the Rodeo protocol.
Attack Tx:
https://explorer.phalcon.xyz /tx/arbitrum/0xb1be5dee3852c818af742f5dd44def285b497ffc5c2eda0d893af542a09fb25a
How are price oracles manipulated?
The key to the Rodeo Finance attack is the Rodeo TWAP Oracle. This oracle is used to track the price ratio between ETH and unshETH.
Analysis of attack transactions: The attack process begins with the attacker executing a carefully crafted planned transactions. The attackers leveraged a deep understanding of the platform architecture and potential vulnerabilities in the Time Weighted Average Price (TWAP) oracle to launch the attack.
Manipulating TWAP oracles: An attacker can use the earn function associated with an unconfigured policy address , force exchange USDC for unshETH. This manipulation effectively bypasses the slippage control caused by the flawed unshETH price oracle. Essentially, the earn function is forced from USDC to WETH, and then to unshETH.
Calculate TWAP prices: TWAP prices are calculated by averaging the prices of the last four updates, Each update interval is 45 minutes. However, the flawed price oracle returned a manipulated price, causing the smart contract to consider the position healthy.
Opening a leveraged position: The attacker manipulates the TWAP oracle via a sandwich attack, then by calling from the investor contract ;earn function to open a leveraged position. They borrowed $400,000 worth of USDC.
![Decentralized Financial Security: Understanding Risks and Mitigating Risks](https://img. jinse.cn/7178406_watermarknone.png)
Exchanging assets: The attacker exchanges the borrowed assets with the underlying CamelotDEX pool, and at the same time sells his prepared unshETH back to the pool.
Bypass execution verification: Contracts usually verify whether the operation is valid. However, since the attackers controlled this strategy, they easily bypassed this check. This allows attackers to exploit manipulated positions by selling prepared unshETH back to the pool, effectively extracting liquidity from the platform.
Transfer stolen funds: The attacker transferred stolen funds from Arbitrum to Ethereum, transferring 285  ;ETH replaced with unshETH and then transferred them to Arbitrum to continue the attack. The stolen funds, worth 150 ETH, were subsequently transferred to Tornado Cash, a privacy-focused Ethereum mixing service. The remaining 371.2 ETH (approximately worth 701, 679 USD) are still held by addresses controlled by the attacker.
A major vulnerability in this attack is Rodeo TWAP Oracle 's implementation is flawed. The oracle relies on reserves of the WETH/unshETH trading pair, which has low liquidity and therefore high price volatility.
Calculating prices based on multiple oracles
Ensure the reliability of price queries. A reliable oracle should use multiple oracles or aggregate price feeds to calculate prices, and Don’t just rely on token comparison ratios. Especially in situations where mining pool liquidity is low, this diverse source of pricing information can improve the accuracy of price data and make it more difficult for attackers to manipulate the data.
To achieve this goal, one possible solution is to use a decentralized oracle, such as Chainlink. Chainlink's oracles can collect data from various data sources and use blockchain technology to verify and confirm the accuracy of the data. By using multiple data sources, Chainlink reduces the possibility of single points of failure and makes data more difficult for attackers to manipulate.
Here is a sample code that uses a Chainlink aggregator contract to get price data:
span>
![Decentralized Financial Security: Understand Risks and Reduce Risks](https://img.jinse.cn/7178407_watermarknone. png)
In the above code , we use an array of AggregatorV3Interface type to store multiple oracle instances. The constructor accepts an array of oracle addresses as a parameter and instantiates each address as an AggregatorV3Interface object.
getLatestPrice function is used to obtain the latest price data from multiple data sources. It loops through the priceFeeds array and gets the price data by calling each oracle's latestRoundData function. All price data is stored in an array of type int and returned to the caller.
In this way, we can obtain price data from multiple data sources, and ensure price queries more accurately reflect asset prices.
2. Smart contract vulnerability risk
Smart contract vulnerability Smart contract vulnerability Refers to security vulnerabilities or bugs in code written on Ethereum or other smart contract platforms. The core of DeFi is a financial protocol based on smart contracts, so smart contract vulnerabilities may lead to the loss of user funds, market manipulation, or other malicious behaviors.
Identifying these vulnerabilities is critical, we's audit covers a variety of potential issues. This includes, but is not limited to, reentrancy vulnerabilities, access control vulnerabilities, integer overflow vulnerabilities, and business logic vulnerabilities. Our comprehensive auditing services are designed to strengthen the security of your smart contracts and protect against these risks.
The following uses access control vulnerabilities as an example to illustrate the impact of smart contract vulnerabilities on DeFi  ;Impact.
LeetSwap Access control vulnerability
LeetSwap has been attacked,< strong>The loss exceeded 340 ETH. The root cause is that the LeetSwap V2 Pair contract has an access control vulnerability, and the _transferFeesSupportingTaxTokens function visibility is public.
Attack Tx:
https://dashboard.tenderly.co/tx/base /0xbb837d417b76dd237b4418e1695a50941a69259a1c4dee561ea57d982b9f10ec
Vulnerable Contract:
https://basescan.org/address/0x94dac4a3ce998143a a119c05460731da80ad90cf
![Decentralized Financial Security: Understand Risks and Reduce Risks](https://img.jinse.cn/7178408_watermarknone.png)
The attacker called the _transferFeesSupportingTaxTokens function To manipulate the pool, the attack process is as follows:
Exchange WETH for another token Coin A.
The _transferFeesSupportingTaxTokens function is called to transfer token A, and the sync function is subsequently called, causing the price of token A to increase.
Exchange token A for more WETH and empty the pool.
Solution
In order to fix the _transferFeesSupportingTaxTokens function Access control vulnerability, function visibility should be changed to private or internal. Declare the function as private so that only other functions within the contract can call it. Declare the function as internal, which can be accessed by contracts that inherit this contract. When other contracts inherit the LeetSwap V2 Pair contract, they can call the _transferFeesSupportingTaxTokens function through the super keyword. External users cannot directly access this function, which improves the security of the contract.
It is necessary to decide how to change the visibility of the function based on the specific contract logic and requirements to ensure that the normal operation of the contract is not affected while improving security.
Smart contract auditing is an important step in identifying and preventing vulnerabilities. At Salus,we have a team of experienced smart contract developers and audit experts who can help you enhance the security of your contracts. Our expertise allows us to pinpoint potential weaknesses and ensure the safety and reliability of your project.
3. User operation risk
In the DeFi field, user operation risk It refers to the risk of capital losses caused by users’ operational errors, lack of security awareness or imprudent behavior when using the DeFi platform. The following are some common user action risks:
Clicking on malicious links: Users Malicious links may be mistakenly clicked, causing malware or viruses to infect their devices, which attackers can use to gain access to users' sensitive information or take control of their wallets.
Using insecure wallets: If users choose to use insecure wallet applications or hardware wallets, attackers may be able to exploit these Vulnerabilities to steal users' private keys or operating permissions.
Leaking the private key: If the user leaks the private key in an unencrypted environment, or stores the private key in an unsafe place , then an attacker may easily obtain the user's private key and control his or her funds.
Imprudent transaction operations: When users conduct transactions, if they do not carefully check the transaction details (such as target address, transaction quantity, etc. ), may result in funds being sent to the wrong address or the wrong amount being sent.
In order to reduce user operation risks, the following are some suggestions:
Increase security awareness: Understand common phishing, malware, and scam tactics and learn how to recognize and avoid them. Be vigilant and carefully examine links and applications related to DeFi.
Use a secure wallet: Choose to use a wallet application or hardware wallet that has been security audited and has a good reputation. Make sure your wallet application and firmware are up to date and follow best security practices.
Back up and protect private keys: Store private keys in a safe place and encrypt them with a strong password. Back up your private keys regularly and store them in an offline, secure location to prevent accidental data loss.
Check the transaction details carefully: Before executing any transaction, carefully check the transaction details to ensure that the target address, transaction quantity, etc. are correct of. Double checking can avoid the loss of funds due to negligence.
4. Summary
Please note that the solutions for each of the above attacks and vulnerabilities are only simple examples and cannot completely prevent the corresponding attacks or fix the corresponding vulnerabilities. If you are interested in smart contract audit, pleasecontact us, we will work with you to provide you with professional audit services to ensure that your contract is safe and reliable . We are committed to providing you with high-quality services and comprehensive technical support to ensure that your smart contracts run in a safe and reliable environment.