Attacking the DeFi Ecosystem with Flash Loans for Fun and Profit

TL;DR Flash loans are a recent blockchain smart contract construct that enable the issuance of loans that are only valid within one transaction and must be repaid by the end of that transaction. This concept has led to a number of interesting attack possibilities, some of which have been exploited recently (February 2020). We analyze those two existing DeFi flash loan attack vectors with significant ROIs (beyond 500k%). We go on to formulate finding flash loan-based attack parameters as an optimization problem over the state of the underlying DeFi state and Ethereum blockchain. Our results show how the two previously executed attacks can be boosted to result in a profit of 829.5k USD (instead of 350k USD) and 1.1M USD (instead of 600k USD), respectively. For a light read feel free to proceed, for all details, we would like to refer to our paper.

Flash Loans - the New DeFi Kid on the Block

In the traditional economy, when a lender grants a loan to a borrower, there always is a risk that the borrower might not repay its debt. This brings us to the following question:

What if it were possible to offer credit, without the risk that the borrower does not pay back the debt?
Flash loan steps within one blockchain transaction.

A flash loan, taken from a liquidity pool, used, and repaid within one transaction.

Here, blockchain-based flash loans come into play. A flash loan is a loan that is only valid within one blockchain transaction. Flash loans fail, if the borrower does not repay its debt before the end of the transaction borrowing the loan. That is, because a blockchain transaction can be reverted during its execution, if the condition of a repayment is not satisfied.

The assets for the flash loan are taken from a publicly funded smart contract pool. At the time of writing, some of the biggest flash loan pools are provided by Aave and dYdX, each exceeding 20M USD in value. Aave charges an interest rate of 0.09%, while dYdX’s smart contract only demands the repayment plus 1 Wei in fees.

To gauge flash loan usage, we collected flash loan data between the 8th of January 2020 and the 26th of February 2020 with a full archive Ethereum node gathering all event logs from the Aave smart contract. Note that Aave only went live early January 2020. We observe a total of 105 loans, and most flash loans interact with lending/exchange DeFi systems (e.g. Compound, Dai, MakerDAI, Uniswap). The flash loan's transaction costs (i.e. gas) appear significant (at times beyond 4M gas, compared to 21k gas for regular Ether transfer). The full details can be found in Figure 5 in the accompanying paper.

Flash Loan Use Cases

But what are flash loans really good for? Based on the community feedback and our own thoughts we identified four uses cases for flash loans: arbitrage, wash trading, collateral swapping and flash minting.

Arbitrage

Given flash loans, a trader can perform arbitrage on different DEX, without the need to hold a monetary position or being exposed to volatility risks. The trader can simply open a loan, perform an arbitrage trade and pay back the loan plus interests. One may argue that flash loans render arbitrage risk-free, the risks of smart contract vulnerabilities however remain.

Arbitrage Example On the 18th Jan 2020, a flash loan borrowed 3,137.41 DAI from Aave to make an arbitrage trade on the AMM DEX Uniswap. To prepare the arbitrage, DAI is converted to 3137.41 SAI using MakerDAO's migration contract. The arbitrage converts SAI for 18.16 ETH using SAI/ETH Uniswap, and then immediately converts 18.16 ETH back to 3,148.39 DAI using DAI/ETH Uniswap. After the arbitrage, 3,148.38 DAI is transferred back to Aave to pay the loan plus fees. This transaction costs 0.02 ETH of gas. Note that even though the transaction sender gains 3.29 DAI from the arbitrage, this particular transaction is not profitable.

Wash Trading

Another potential flash loan use case is wash trading.

The trading volume of an asset, is a metric indicating its trading popularity. The most popular assets therefore, are supposed to be traded the most --- e.g. Bitcoin to date enjoys the highest trading volume (reported up to 50T USD per day) of all cryptocurrencies.

Malicious exchanges or traders can mislead other traders by artificially inflating the trading volume of an asset to attract interests. According to the Blockchain Transparency Institute Market Surveillance report, from September 2019, 73 out of the top 100 exchanges on Coinmarketcap were wash trading over 90% of their volumes. Wash trading of securities appears illegal under U.S. law.

While wash trading on centralised exchanges may be performed at little to no cost, and possibly even without real assets, wash trading on DEX requires wash traders to hold and use assets. Flash loans can remove this “obstacle” to reduce the costs to loan interests, trading fees, and (blockchain) transaction fees. A wash trading endeavour to increase the 24-hour volume of the ETH/DAI market of Uniswap by 50% would for instance cost about 1,298 USD (with a flash loan from dYdX).

Wash trading example On March 2nd, 2020, a flash loan of 0.01 ETH borrowed from dYdX performed two back-and-forth trades (first converted 0.01 ETH to 122.1898 LOOM and then converted 122.1898 LOOM back to 0.0099 ETH) on the Uniswap ETH/LOOM market. The 24-hour trading volume of the ETH/LOOM market increased by 25.8% (from 17.71 USD to 22.28 USD) as a result of the two trades.

We elaborate on two other flash loan use cases, collateral swapping and flash minting, in our paper.

Flash Loan Post-Mortem

In the following we observe two adversarial flash loan trades, one pump and arbitrage, and one oracle manipulation attack.

Pump and Arbitrage

A flash loan transaction executed on the 15th of February 2020, followed by 74 transactions, yielded a profit of 1'193.69 ETH (350k USD) given a transaction fee of 132.36 USD (cumulative 50'237'867 gas, 0.5 ETH). We first discuss the details of this transaction, and then go about to explain why the adversary could have earned a profit exceeding 829.5k USD (the numbers in boxes in the Figure below correspond to the optimal attack parameters we find, while the non-surrounded numbers are those chosen by the adversary).

The core of this trade involves a margin trade on a DEX (bZx) to increase the price of WBTC/ETH on another DEX (Uniswap) and thus creates an arbitrage opportunity. The trader then borrows WBTC using ETH as collateral (on Compound), and then purchases ETH at a “cheaper” price on the distorted (Uniswap) DEX market. To maximise the profit, the adversary then converts the “cheap” ETH to purchase WBTC at a non-manipulated market price over a period of two days after the flash loan. The adversary then returns WBTC (to Compound) to redeem the ETH collateral. The following figure outlines how this trade mainly consists of two parts. For simplicity, we omit the conversion between WETH (the ERC20-tradable version of ETH) and ETH. The full details are outlined in the paper.

Flash loan pump and arbitrage attack.

Flash loan pump and arbitrage attack.

Oracle Manipulation

In the following, we discuss the details of a second flash loan trade, which yields a profit of 2,381.41 ETH (c. 650k USD) within a single transaction executed on the 18th of February 2020, given a transaction fee of 118.79 USD. We again find that the chosen attack parameters were sub-optimal and present attack parameters that would yield a profit of 1.1M USD instead. For this attack, the adversary involves three different exchanges for the same sUSD/ETH market pair (the Kyber-Uniswap reserve, Kyber, and Synthetix). Two of these exchanges (Kyber, Kyber-Uniswap) act as price oracles for the lending platform (bZx) from which the adversary borrows assets.

Price oracle: One of the goals of the DeFi ecosystem is to not rely on trusted third parties. This premise holds both for asset custody as well as additional information, such as asset pricing. One common method to determine an asset price is hence to rely on the pricing information of an on-chain DEX (e.g. Uniswap). One drawback of this approach, is the danger of a DEX price manipulation.

Attack intuition: The core of this trade is an oracle manipulation using a flash loan on the asset pair sUSD/ETH. The manipulation lowers the price of sUSD/ETH (from 268.30 sUSD/ETH to 106.05 sUSD/ETH on Uniswap and 108.44 sUSD/ETH on Kyber Reserve). In a second step, the adversary benefits from this sUSD/ETH price decrease by borrowing ETH with sUSD as collateral. The full details can again be found in the paper.

Flash loan pump and arbitrage attack.

Flash loan oracle manipulation attack.

Optimal DeFi Attack Parameter Generation

It’s clearly not trivial to (i) find the attack paths that the adversaries exploited, and (ii) to determine the optimal parameters to exploit the attacks to the fullest. We therefore seek help from constrained optimization techniques to guide us towards optimal attack parameters.

Parametrized DeFi optimizer

Parametrized DeFi optimizer.

To make use of constraint optimization, we first model different components that may engage in a DeFi attack. We quantitatively formalize every endpoint provided by DeFi platforms as a state transition function S’ = T(S,p) with the constraints C(S; p), where S is the given state, p are the parameters chosen by the adversary and S’ is the output state. The state can represent, for example, the adversarial balance or any internal status of the DeFi platform, while the constraints are set by the execution requirements of the Ethereum Virtual Machine (e.g. the Ether balance of an entity should never be a negative number) or the rules defined by the respective DeFi platform (e.g. a flash loan must be repaid before the transaction termination plus loan fees). Note that when quantifying profits, we ignore the loan interest/fee payments and Ethereum transaction fees, which are negligible in the present DeFi attacks. The constraints are enforced on the input parameters and output states to ensure that the optimizer yields (for the model) valid parameters. We refer to the paper for the full details.

Optimizing the Pump and Arbitrage Attack

To solve the constraints, we apply the Sequential Least Squares Programming (SLSQP) algorithm from SciPy and use the minimize function in the optimize package. Our program is evaluated on a Ubuntu 18.04.2 machine, 16 CPU cores and 32 GB RAM. We repeated our experiment a 1'000 times, the optimizer spent 6.1 ms on average converging to the optimum.

For the Pump and Arbitrage attack, the optimizer provides parameters that would yield a maximum revenue of 2,778.94 ETH, while in the original attack the parameters only yield 1,171.70 ETH. Our Figure above highlights the ideal amounts that should have been used in the attacks. Note, due to the ignorance of trading fees and precision differences, there is a minor discrepancy between the original attack revenue calculated with our model and the real revenue which is 1,193.69 ETH. This is a 829.5k USD gain over the attack that took place.

Optimizing the Oracle Manipulation Attack

We again execute our optimizer 1,000 times on the same Ubuntu 18.04.2 machine and find an average convergence time of 12.9 ms. The optimizer discovers a setting that results in 6,323.93 ETH profit for the adversary. This results in a gain of 1.1M USD instead of about 600k USD for the attack that took place.

Discussing Flash Loans and DeFi

The current generation of DeFi had developed organically, without much scrutiny when it comes to financial security; it, therefore, presents an interesting security challenge to confront. DeFi, on the one hand welcomes innovation and the advent of new protocols, such as MakerDAO, Compound, and Uniswap. On the other hand, despite a great deal of effort spent on trying to secure smart contacts, and to avoid various forms of market manipulation, etc., there has been little-to-no effort to secure entire protocols.

As such, DeFi protocols join the ecosystem, which leads to both exploits against protocols themselves as well as multi-step attacks that utilize several protocols (see above). In a certain poignant way, this highlights the fact that a DeFi, lacking a central authority that would enforce a strong security posture, is ultimately vulnerable to a multitude of attacks effectively by design. Flash loans are merely a mechanism that accelerates these attacks. It does so by requiring no collateral (except for the minor gas costs), which, in a certain way, democratizes the attack, opening this strategy to the masses. However, it is quite likely that there will be other mechanisms invented that will enable further, potentially even more devastating, attacks in the near future.

Responsible disclosure

It is somewhat unclear how to perform responsible disclosure within DeFi, given that the underlying vulnerability and victim are not always perfectly clear and that there is a lack of security standards to apply. We reached out to Aave, Kyber, and Uniswap to disclose the contents of this work.

Determining what is malicious

An interesting question remains whether we can qualify the use of flash loans, as clearly malicious (or clearly benign). We believe this is a difficult question to answer and prefer to withhold the value judgement. The two attacks described are clearly malicious: pump and arbitrate involves manipulating the WBTC/ETH price on Uniswap; the oracle manipulation attack involves price oracle by manipulatively lowering the price of ETH against sUSD on Kyber. However, the arbitrage mechanism in general is not malicious --- it is merely a consequence of the decentralized nature of the DeFi ecosystem, where many exchanges and DEXs are allowed to exist without much coordination with each other. As such, arbitrage will continue to exist as a phenomenon, with good and bad consequences.

Does extra capital help

The main attraction of flash loans stems from them not requiring a collateral that needs to be raised. One can, however, wonder whether extra capital would make the attacks we focus on more potent and the ROI greater. Based on our results, extra collateral for the two attacks presented would not increase the ROI, as the liquidity constraints of the intermediate protocols do not allow for a higher impact.

Potential defenses

Here we discuss several potential defenses. However, we would be the first to admit that these are not foolproof and come with potential downsides that would significantly hamper normal interactions.

  • Should DEX accept trades coming from flash loans?
  • Should DEX accept coins from an address if the previous block did not show those funds in the address?
  • Would introducing a delay may make sense, e.g. in governance voting, or price oracles?
  • When designing a DeFi protocol, a single transaction should be limited in its abilities: a DEX should not allow a single transaction triggering a slippage beyond 100%.

Outlook

In the future, we anticipate DeFi protocols eventually starting to comply with a higher standard of security testing, both within the protocol itself, as well as part of integration testing into the DeFi ecosystem. We believe that eventually, this may lead to some form of DeFi standards where it comes to financial security, similar to what is imposed on banks and other financial institutions in traditional centralized (government-controlled) finance.

We anticipate that either whole-system penetration testing or an analytical approach of modeling the space of possibilities like in this work are two ways to improve future DeFi protocols.

Share on Linkedin
Share on Reddit
comments powered by Disqus