Translator’s Note: The price oracle is an important part of decentralized finance (DeFi). However, it is the possible loopholes in this link that caused many DeFi projects to suffer catastrophic losses, and some losses even reached several Tens of millions of dollars, what is going on with these attacks? How to prevent them? In this article, Samczsun, a well-known white hat hacker and Paradigm research partner, analyzed 5 real-life cases of price oracle attacks and summarized 6 ways to defend against such attacks.
At the end of 2019, I published a post entitled “”. In this article, I described an economic attack on Ethereum dApps that relies on accurate price data for one or more tokens. It is now the end of 2020. Unfortunately, many projects have made similar mistakes. The most recent example is Harvest Finance, which was hacked and caused collective losses of USD 33 million for agreement users.
Although developers are familiar with vulnerabilities such as reentrancy, oracle manipulation is obviously not a frequently considered issue. In fact, attacks based on reentrant vulnerabilities have declined in the past few years, while the utilization of vulnerabilities based on price oracle manipulation is now rising. Therefore, I think it’s time to publish some definitive information on the manipulation of price oracles.
This article is divided into three parts. In the first part, we will give a brief introduction to oracles and oracles manipulation for those who are not familiar with this topic. The second part is some case studies (in which we will review past vulnerabilities and attacks related to oracles), and those who want to test their knowledge can skip them. Finally, we summarized some techniques that developers can use to protect their projects from oracles.
Oracle manipulation in real life
Time to go back to December 1, 2015 (Wednesday), suppose your current identity is David Spargo, and you are now at the Peking Duk concert in Melbourne, Australia. You want to go to the backstage lounge to meet the members of this band in person, but there is Two security guards stopped in front of you. They couldn’t let ordinary people in directly.
You want to know how the security guard will react if you act like a relative of Peking Duk. Because family members will definitely be allowed to visit the band in the background, all you have to do is make the security guard believe you are a relative of the band. You think for a while and come up with a plan that can only be described as “genius” or “absolutely crazy.”
After arranging everything quickly, you walk to the security guard confidently. You introduce yourself as David Spargo, a family member of the Peking Duk band. When the guard asks you to provide evidence, you show them irrefutable evidence-Wikipedia.
The guard waved you over and asked you to wait a moment. One minute passed, two minutes passed… Five minutes later, you want to know if you should run away before the law enforcement officers show up. Just when you were about to give up, Peking Duk member Reuben Styles walked over, and then you walked into the lounge with him. The band was impressed by your ingenuity. At the end, you had a few beers together. Later, they I shared what happened that night on my Facebook page.
What is a price oracle machine?
A price oracle machine can refer to anything for which you consult price information. When Pam asked Dwight for the cash value of a Schrute dollar, Dwight acted as a price oracle.
On Ethereum, everything is a smart contract, and so are price oracles. Therefore, it is more useful to distinguish the way the price oracle obtains price information. In one method, you can simply obtain existing off-chain price data from the price API or exchange and bring it to the chain. In another way, you can calculate the real-time price by consulting the on-chain decentralized exchange (DEX).
Both options have their pros and cons. Off-chain data is usually slower to respond to volatility. Whether this is good or bad depends on the purpose for which you are trying to use it. This method usually requires a small number of privileged users to push data onto the chain, so you must trust these people not to Will do evil and will not be forced to push bad updates. The data on the chain does not require any privileged access and is always up-to-date, but this means that it can be easily manipulated by attackers, leading to catastrophic failure.
What could go wrong?
Let us look at a few examples of price oracle integration issues leading to significant financial losses in DeFi projects.
1. Synthetix sKRW oracle failure
Synthetix is a derivatives platform that allows users to access assets such as other currencies. In order to achieve this goal, Synthetix at that time relied on a customized off-chain price feed implementation, and its price feed data was released to the chain at fixed time intervals. These prices allow users to go long or short on the supported assets.
On June 25, 2019, a price feed report that Synthetix relied on stated that the price of the Korean won was 1,000 times higher than the real exchange rate. Due to errors elsewhere in the price oracle system, this price was accepted by the system and published on the chain, and then a trading robot quickly entered and exited the sKRW market.
Although the Synthetix team can negotiate with traders to return funds (in exchange for bug rewards), in general, this robot is capable of making more than $1 billion in profits.
Synthetix correctly implemented the price oracle and obtained prices from multiple sources to prevent traders from predicting price changes before they were posted on the chain. However, an isolated upstream feed failure led to a devastating attack. This illustrates the risk of price oracles using off-chain data: you don’t know how the price is calculated, so your system must be carefully designed to correctly handle all potential failure modes .
Low-secured loans
As mentioned above, I published an article in September 2019 that outlined the risks associated with the use of on-chain data price oracles. Although I strongly recommend you to read this article, it is very long and the technical details are heavy, which may be difficult to understand. Therefore, I will provide a simplified explanation here.
Imagine you put decentralized lending on the blockchain. Users can deposit assets as collateral or borrow other assets, and the maximum amount that can be borrowed is determined by the value of the assets they deposit. Suppose a user uses ETH as collateral and then borrows USD. The current price of ETH is 400 USD and the mortgage rate is 150%.
If the user deposits 375 ETH, the deposited collateral is worth 150,000 US dollars. According to the rule that every 1.5 US dollars of collateral can borrow 1 US dollar, then the user can borrow up to 100,000 US dollars from the system.
Of course, on the blockchain, this is not as simple as simply declaring that 1 ETH is worth $400, because a malicious user can simply declare that 1 ETH is worth $1,000 and then take all the money from the system. Therefore, it is easy for developers to access the spot prices of Uniswap, Kyber or other decentralized exchanges (DEX).
At first glance, this seems to be the correct approach. After all, whenever you want to buy or sell ETH, Uniwap’s price is always roughly correct, because arbitrageurs will quickly correct any deviations. However, it turns out that the spot price of a decentralized exchange (DEX) can be very incorrect during the trading period, as shown in the example below.
Consider the storage function of Uniswap. The price is calculated based on the amount of reserve assets, but as users trade between ETH and USD, the assets held by the reserve will change. What if a malicious user executes a transaction before and after taking a loan from the platform?
Before the user took a loan, they bought 5000 ETH at a price of 2 million USD. Now, the price calculated by Uniswap exchange is 1 ETH = 2,600 USD. Now, their 375 ETH can be used as collateral and can borrow up to $650,000 in assets. In the end, they exchanged $2 million for 5000 ETH, which would reset the price, and your lending platform lost $550,000.
This case study illustrates the most common mistake encountered when using a decentralized exchange (DEX) as a price oracle-the attacker almost completely controls the price during the transaction, and trying to accurately read the price It is like reading the weight on the scale before completing the settlement.
You may get the wrong number, which may cost you a lot of money depending on the circumstances.
2. Synthetix MKR manipulation
In December 2019, Synthetix suffered another price oracle manipulation attack. It is worth noting that this attack crossed the boundary between on-chain data and off-chain data.
A Reddit user with the username u/MusaTheRedGuard observed that an attacker made some very suspicious transactions with sMKR and iMKR. The attacker first buys sMKR to make long MKR, and then buys a large amount of MKR from the Uniswap ETH/MKR asset trading pair. After waiting for a while, the attackers exchanged their sMKR for iMKR short positions and sold their MKR back to Uniswap. Then they repeated the process.
Behind the scenes, the attackers traded through Uniswap, allowing them to move the price of MKR on Synthetix at will. This is probably because the off-chain price feed that Synthetix relies on actually relies on the MKR on-chain price, and arbitrageurs do not have enough liquidity to reset the market to optimal conditions.
This incident illustrates the fact that even if you think you are using off-chain price data, in fact you may still be using on-chain price data, and you may still encounter complex attacks because of using these data.
3. bZx hacker incident
In February 2020, bZx suffered two hacking attacks within a few days, and the loss value was approximately US$1 million. You can find excellent technical analysis articles about two hacking attacks written by palkeo, but we are only focusing on the second attack here.
In the second hacking attack, the attacker first used ETH to purchase almost all of the sUSD on Kyber. Then, the attacker purchased the second batch of sUSD from the Synthetix platform and deposited it on bZx. Using sUSD as collateral, the attackers borrowed the maximum amount of ETH allowed, and then they sold sUSD back to Kyber.
If you notice, you will find that this is essentially the same low-collateral lending attack, but using different collateral and different decentralized exchanges.
4. yVault vulnerability
On July 25, 2020, I reported a vulnerability in the new yVault contract launched by yEarn. You can read the official announcement about this vulnerability, but I will briefly summarize it below.
The yVault system allows users to deposit tokens and earn revenue without the need for self-management. Internally, this vault tracks the total amount of minted yVault tokens and the total amount of base tokens deposited. The value of a single yVault token is determined by the ratio of minted tokens to deposited tokens. Any revenue from the vault will be shared among all minted yVault tokens (and therefore, all yVault token holders).
The first yVault allows users to obtain USDC income by providing liquidity to the Balancer MUSD/USDC reserve pool. When users provide liquidity to Balancer, they will receive BPT as a voucher (which can be used to redeem assets in the pool). Therefore, yVault calculates the value of its holdings based on the amount of MUSD/USDC redeemable by its BPT.
This seems to be the correct implementation, but unfortunately, the principle is the same as the previously mentioned-during the transaction, the state of the Balancer pool is unstable and therefore cannot be trusted. In this case, due to the joint curve chosen by Balancer, users who exchange between USDC and MUSD will not get a 1:1 exchange rate, but will actually leave some MUSD in the reserve pool. This means that the value of BPT can temporarily inflate, which allows an attacker to manipulate the price at will and subsequently deplete the vault.
This incident shows that price oracles are not always reliable. Developers need to be wary of what data they are ingesting, and consider whether these data can be easily manipulated by unprivileged users.
5. Harvest Finance hacker attack
On October 26, 2020, an anonymous user used a technique (as you may have guessed by now) to attack the Harvest Finance reserve pool. You can read the official one here, but I want to summarize it again for you: the attacker reduces the USDC price in the Curve pool by executing transactions, then enters the Harvest pool at the reduced price, restores the price by reversing the previous transaction, and Higher prices exit the Harvest pool. This ultimately resulted in users losing $33 million.
How to protect yourself?
Now, I hope you understand the price oracle manipulation attack. In addition, if you don’t take proper defense measures, the attacker may deceive your agreement and let them hand over the money to them. Although there is currently no solution for all situations, there are some solutions that have worked in other projects, and maybe one of them will suit you.
Recommendation 1: Don’t jump into the shallow market
Just like jumping into the shallow water of a swimming pool, jumping into a shallow market is also painful, which can lead to huge losses and thus change your life forever. Before considering the specific price oracle plan, consider whether the liquidity of the token is sufficient to ensure integration with your platform.
Suggestion 2: One bird in the hand is better than two in the forest (the one with the finger is the real one)
It can be fascinating to see the potential exchange rates on Uniswap, but everything will not be final until you actually click the “trade” button and put the tokens in your wallet. Similarly, to determine the exchange rate between two assets, the best way is to exchange assets directly. This method is good because there is no undo and no assumptions. However, for agreements such as loan platforms, it may not work because these agreements need to preserve the original assets.
Recommendation 3: Almost decentralized oracles
To sum up, one of the problems with relying on on-chain data oracles is that they update a bit too quickly. If so, why not introduce a little artificial delay? Write a contract to update yourself with the latest price of a decentralized exchange (such as Uniswap), but through a few privileged users. Now, even if an attacker can manipulate the price, they cannot take advantage of this.
This method is simple to implement and easy to take effect, but it also has some disadvantages-when the blockchain is congested, you may not be able to update the price as fast as you want, and you are still vulnerable to sandwich attacks. ). In addition, now, your users also need to trust you to keep prices updated.
Suggestion 4: Increase the minimum delay
Manipulating price oracles is a time-sensitive operation because arbitrageurs are always observing and hoping to have the opportunity to optimize any suboptimal market. If the attacker wants to minimize the risk, they will want to complete the two transactions required to manipulate the price oracle in a single transaction, so that the arbitrageur has no chance to jump to the middle. As a protocol developer, if your system supports it, then it is enough to achieve the shortest delay between the user entering and exiting the system.
Of course, this may affect composability, and cooperation between miners and traders is increasing. In the future, bad actors may perform price oracle manipulation in multiple transactions because they know that miners will ensure that no one can jump in and profit from it.
Recommendation 5: Time Weighted Average Price (TWAP)
Uniswap V2 introduces a time-weighted average price (TWAP) oracle machine for developers on the chain. This article describes in detail the exact security guarantees provided by this oracle. Generally speaking, for large asset pools that have not been congested for a long time, this TWAP oracle has a strong ability to resist oracle manipulation attacks. However, due to the nature of its implementation, it may not be able to respond quickly enough to moments of violent market fluctuations, and it only applies to token assets with on-chain liquidity.
Recommendation 6: M-of-N reporter mechanism
Sometimes people will say that if you want to do a good job, do it yourself. So what if you gather N trustworthy friends, ask them to submit the on-chain price they think is correct, and then gather the M best answers into the current price?
Nowadays, many large-scale projects are using this method: Maker runs a set of price feeds operated by trusted entities, Compound created Open Oracle, and there are oracle bidders like Coinbase, Chainlink aggregates chainlink operators Price data, and publish these data on the chain. Remember, if you choose to use one of these solutions, then you have now delegated trust to a third party, and your users must do the same. Requiring bidders to manually release the latest information on the chain also means that during periods of high market volatility and blockchain congestion, price updates may not be completed on time.
in conclusion
Price predictors are an important but often overlooked component for DeFi security. It is difficult to use price oracles safely, and there are many ways to catch you and your users by surprise. In this article, we discussed some examples of price oracles being manipulated and determined that it may be unsafe to read price information during a transaction (and thus lead to possible catastrophic financial losses). We also discussed some of the technologies used by other projects in the past to resist price manipulation by oracles. In the end, each situation is unique, and you may find yourself unsure whether you are using the price oracle correctly. If this is the case, please feel free to seek advice.
Special thanks to Dan Robinson and Georgios Konstantopoulos for reviewing this article.