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
去中心化金融安全:理解风险并降低风险
Salus Insights
特邀专栏作者
2024-02-12 07:00
This article is about 4821 words, reading the full article takes about 7 minutes
在去中心化金融(DeFi)领域中存在着大量的安全风险,这些风险可能对用户、平台和整个金融生态系统造成严重的危害。我们总结了三种 DeFi 安全风险,并通过分析最近发生的真实安全事件来阐述黑客攻击的过程以及相应的解决方案。

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 hacker attack process 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 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 in which 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.Attackers borrow large amounts of money through flash loans and perform a series of operations in the same transaction to commit fraud.

ShidoGlobal flash loan attack incident

On June 23, 2023, the ShidoGlobal flash loan attack occurred on BSC (Binance Smart Chain). The attacker achieves token arbitrage through the lock-and-claim mechanism and the price difference between the two pools.Successfully stole 976 WBNB.

Attack Tx:

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

How do attackers carry out flash loan attacks?

  • The attacker took out a flash loan of 40 WBNB.

  • 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 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.

  • The attacker then called ShidoLock.lockTokens and ShidoLock.claimTokens in sequence, 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 calls the lockTokens function in the ShidoLock contract, they lock 10, 436, 972, 685.676390697 Shido Inu: SHIDO tokens 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 called the claimTokens function to convert the locked tokens into 10, 436, 986, 704, 133, 494, 387, 000, 000, 000 SHIDO tokens. This step effectively increases the number of decimal places for SHIDO tokens from 9 to 18, increasing the total supply of the token.

  • There is a price difference between the PancakeSwap V2: SHIDO-WBNB pool and the PancakeSwap V2: SHIDO 28 pool through the lock-and-claim mechanism. 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 as the supply has not increased. The attacker took advantage of this price difference and exchanged tokens between the two pools, transferring 10, 436, 986, 704, 133, 494, 387, 000, 000, 000 SHIDO tokens (after the decimal point) at a more favorable price 18 bits) were exchanged into 1,016 WBNB.

  • In the end, the attacker repaid the flash loan of 40 WBNB and received a profit of approximately 976 WBNB.

Limit flash loan function

Restrict flash loan functions and introduce flash loan feesis a common way to reduce the risk of flash loan attacks and manipulation.

  • Restrict the flash loan function: You can restrict the flash loan function, such as setting the 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.

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 an attack method that exploits information asymmetry in decentralized exchanges (DEX).The attacker exploits the price difference to gain profit by inserting malicious transactions between the two transactions.

CurveFinance Sandwich Attack

On August 2, 2023, Hypernative systems launched a sandwich attack on Curve Finance. The attacker inserts malicious transactions between two transactions that add liquidity and remove liquidity.Earn 36.8K USDT.

Attack Tx:

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

How does an attacker carry out a sandwich attack?

  • The attacker obtained huge flash loans from multiple funding sources, including wstETH, WETH, and USDT.

  • The attacker provided 155, 000, 000 USDT liquidity to 3 pools and obtained 3 CRV LP tokens. 3 CRV is the LP token of Curve TriPool (Curve DAI/USDC/USDT mining pool), the mining pool that was compromised in the attack.

  • 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.

  • Call the UnderlyingBurner contract execute() function to continue adding liquidity to the Curve DAI/USDC/USDT mining pool. UnderlyingBurner mainly holds USDT, and the number of DAI:USDC:USDT added 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.

  • The attacker added his holdings of DAI and USDC to the Curve DAI/USDC/USDT pool and enjoyed the premium, which meant obtaining a higher amount of 3 CRV LP tokens.

  • The attacker destroyed its 3 CRV LP tokens and withdrew USDT liquidity.

  • The attacker repays the flash loan and keeps the profit of 36.8 K USDT.

In this process, the malicious transaction refers to a transaction in which the attacker removed a large amount of DAI and USDC liquidity from the Curve DAI/USDC/USDT mining pool and destroyed 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 added liquidity and withdrew liquidity. The attacker took advantage of the price difference by adding the DAI and USDC liquidity he held to the Curve DAI/USDC/USDT mining pool and withdrawing it at the premium, obtaining a higher amount of 3 CRV LP tokens.

In this way, the attacker packages the malicious transaction with two other transactions through a sandwich attack, purchases USDT liquidity at a low price, and then sells it at a high price to obtain profits.

Limit transaction order

When it comes to preventing sandwich attacks, code implementation can involve complex smart contracts and transaction logic. Here is a simplified example showing how to passLimit transaction order and introduce transaction delaysto prevent sandwich attacks.

In this example, we assume that there is a smart contract SandwichAttackPrevention that manages the users balance and transaction operations. To prevent sandwich attacks, we introduce two main defense mechanisms.

First, in the allowTransaction function, only the owner of the contract can set isTransactionAllowed to true, allowing users 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

A price oracle is a data source that provides real-time price information for cryptocurrencies. This information is critical to the proper functioning of many DeFi protocols.An oracle attack refers to an attacker artificially changing the data provided by an oracle 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 stealing from the Rodeo protocolAbout 472 ETH (about 888,000 USD).

Attack Tx:

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

How are price oracles manipulated?

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

  • Analyzing attack transactions: The attack process begins with the attacker executing a carefully planned transaction. 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 is able to force the exchange of USDC for unshETH using the earn function associated with an unconfigured policy address. 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 updated 45 minutes apart. 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 through a sandwich attack and then opens a leveraged position by calling the earn function from the investor contract. They borrowed $400,000 worth of USDC.

  • Swap assets: The attacker swaps the borrowed assets with the underlying CamelotDEX pool, while simultaneously selling their prepared unshETH back to the pool.

  • Bypassing execution verification: Contracts often verify that operations are 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.

  • Transferring Stolen Funds: The attacker moved the stolen funds from Arbitrum to Ethereum, exchanging 285 ETH for unshETH and then moved them to Arbitrum to continue the attack. The stolen funds, worth 150 ETH, were then transferred to Tornado Cash, a privacy-focused Ethereum mixing service. The remaining 371.2 ETH (approximately worth $701,679) is still held by an address controlled by the attacker.

A significant vulnerability in this attack is a flaw in the execution of the Rodeo TWAP Oracle. The oracle relies on reserves of the WETH/unshETH trading pair, which has low liquidity and therefore high price fluctuations.

Calculate prices based on multiple oracles

To ensure the reliability of price queries, a reliable oracle should be usedMultiple oracles or aggregate price feedsto calculate prices rather than relying solely on token pairing 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, one possible solution is to use a decentralized oracle, such as Chainlink. Chainlink oracles can collect data from a variety of 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 an example code that uses the Chainlink aggregator contract to get price data:


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.

The getLatestPrice function is used to obtain the latest price data from multiple data sources. It iterates through the priceFeeds array and gets the 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.

This way we can obtain price data from multiple data sources and ensure that price queries more accurately reflect asset prices.

2. Smart contract vulnerability risk

Smart Contract Vulnerabilities Smart contract vulnerabilities refer to security holes 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,usThe audit coversVarious potential problems. 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.

LeetSwap access control vulnerability

LeetSwap was attacked,The loss exceeded 340 ETH. The root cause is that there is an access control vulnerability in the LeetSwap V2 Pair contract, and the visibility of the _transferFeesSupportingTaxTokens function is public.

Attack Tx:

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

Vulnerable Contract:

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

The attacker called the _transferFeesSupportingTaxTokens function to manipulate the pool. The attack process is as follows:

  • Use WETH to exchange for another token 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

To fix the access control vulnerability of the _transferFeesSupportingTaxTokens function, the 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 so that it 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. existSalusWe 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 risks

In the field of DeFi, user operational risk refers to the risk of capital losses caused by users own operational errors, lack of security awareness, or imprudent behavior when using the DeFi platform.Here are some common user action risks:

  • Clicking on malicious links: Users may accidentally click on malicious links, 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.

  • Use an insecure wallet: If a user chooses to use an insecure wallet application or hardware wallet, attackers may exploit these vulnerabilities to steal the users private keys or operational permissions.

  • Leakage of private keys: If a user leaks a private key in an unencrypted environment or stores the private key in an unsafe place, an attacker may easily obtain the users private key and control their funds.

  • Imprudent trading operations: If users do not carefully check the transaction details (such as target address, transaction amount, etc.) when making transactions, funds may be sent to the wrong address or the wrong amount.

In order to reduce user operational risks, here 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 DeFi-related links and applications.

  • Use a secure wallet: Choose to use a wallet app 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.

  • Double-check transaction details: Before executing any transaction, double-check the transaction details to make sure the destination address, transaction amount, etc. are correct. 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 simple examples and do not completely prevent the corresponding attacks or fix the corresponding vulnerabilities. If you are interested in smart contract auditing, 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.

Safety
finance
DeFi
Welcome to Join Odaily Official Community
AI Summary
Back to Top
在去中心化金融(DeFi)领域中存在着大量的安全风险,这些风险可能对用户、平台和整个金融生态系统造成严重的危害。我们总结了三种 DeFi 安全风险,并通过分析最近发生的真实安全事件来阐述黑客攻击的过程以及相应的解决方案。
Author Library
Download Odaily App
Let Some People Understand Web3.0 First
IOS
Android