Flash Crash For Cash: Cyber Threats in Decentralized Finance
Flash Crash For Cash: Cyber Threats in Decentralized Finance
Flash Crash For Cash: Cyber Threats in Decentralized Finance
Abstract—Decentralized Finance (DeFi) took shape in 2020. An The ‘DeFi summer’ of 2020 reflected the increased excite-
unprecedented amount of over 14 billion USD moved into DeFi ment of investors for DeFi’s potential, as the total value locked
projects offering trading, loans and insurance. But its growth in DeFi projects grew from 1 billion to 12 billion USD in a few
has also drawn the attention of malicious actors. Many projects
were exploited as quickly as they launched and millions of USD months time. But many DeFi projects were attacked as quickly
were lost. While many developers understand integer overflows as they launched. Much of the dynamic was reminiscent of the
and reentrancy attacks, security threats to the DeFi ecosystem 2017 ICO hype, showing that many DeFi projects are high-
are more complex and still poorly understood. In this paper we risk ventures from a financial and a technological perspective.
provide the first overview of in-the-wild DeFi security incidents. Due to a fear of missing out accelerated by media coverage
We observe that many of these exploits are market attacks,
weaponizing weakly implemented business logic in one protocol of high yields, many unskilled investors lost money. While
with credit provided by another to inflate appropriations. Rather speculative investing is implicitly financially risky, risk in these
than misusing individual protocols, attackers increasingly use projects was also non-financial. Millions of USD value were
DeFi’s strength of permissionless composability against itself. put into new, unaudited smart contracts of developers with
By providing the first holistic analysis of real-world security Twitter handles stating they ‘test in prod’ [1]. Many projects
incidents within the nascent financial ecosystem DeFi is, we
hope to inform threat modeling in decentralized cryptoeconomic were launched with a focus on speed and agility and less
initiatives in the years ahead. on security. Audit processes were omitted and funds were
Index Terms—cryptoeconomics, decentralized finance, smart lost due to a lack of basic security hygiene. Incidents also
contracts, cyber security, threat intelligence occurred with projects audited by multiple reputable security
companies, which simply failed to observe critical issues.
I. I NTRODUCTION Awareness of ‘technical’ software weaknesses in
Ethereum’s smart contract language Solidity, such as
More than ten years after the introduction of Bitcoin as reentrancy, access control and integer overflow vulnerabilities
a peer-to-peer digital cash system, its societal impact is is now widespread due to early attacks on The DAO,
reflected in the pioneering of central banks with Central Parity Wallet and ERC-20 tokens respectively. While still
Bank Digital Currency, as well the International Monetary a significant issue, this area has seen significant academic
Fund’s announcement of a new Bretton Woods for 2021. contributions [2]–[5] and has improved much. Technical
Institutional players have recognized the staying power of vulnerabilities in smart contracts are relatively easily
‘programmable’ digital money and explore its application to mitigated if adhering to community-audited ERC-20 and
their benefit. But other than currency, blockchains also hold ERC-721 contract standards instead of coding from scratch.
potential for other financial applications with which the open- In DeFi, it appears that attackers prefer other avenues
source cryptoeconomic community has moved forward. of exploitation, misusing legitimate Ethereum and DeFi
Decentralized Finance (DeFi) aims to disentangle and pro- functionality. Projects are primarily hacked through misuse
vide freedom of choice in financial services. It aspires to of the economic functionality that they seek to disrupt.
replace central bureaucratic institutions with computer code, Decentralized capabilities such as voting, arbitrage and
stored in a smart contract and available on the blockchain for flash loans are exploited and have cascading effects through
inspection by everyone. As smart contracts are application- interdependencies between DeFi protocols, known as ‘money
agnostic and permissionless, DeFi allows everyone with devel- lego’. A DeFi derivatives platform might depend on third-
opment competencies to interact with and build financial sys- party services to supply the bid-ask prices, but a vulnerability
tems. Clients don’t have to trust the promises or reputation of allowing to read price data during a transaction may introduce
a middleman, only the protocol. Redeeming control from the significant financial risk.
middleman provides freedom, but comes with a responsibility. As opposed to traditional finance, developers of DeFi
A user can only hold himself accountable for costly mistakes. projects often lack financial experience and cyber security is
‘Don’t trust, verify’ in crypto parlance. Each transaction must an afterthought in a hasty development process. The hosting of
be verified as users can’t outsource trust to a middleman. smart contract code on Ethereum further enables an attacker’s
opportunity to locate vulnerabilities quickly and efficiently. eventual financial transactions. Transactions are not managed
Exploiting DeFi projects currently is a low-risk high reward by a central institution but transparently deployed on a public
opportunity to malicious actors. Where Ethereum has seen blockchain. There is no middleman to be trusted, only a pro-
isolated smart contract attacks in the past, over the ‘DeFi tocol (code is law). It also allows everyone to create financial
summer’ of 2020 adversaries ‘flash crashed’ compositions of systems of their own or to participate in those offered by
DeFi protocols and cashed out lavishly. As the increase in others. New applications can be built by composing multiple
private and institutional investor interest in cryptoeconomics DeFi protocols, also known as ‘money lego’. The DeFi space
will also attract malicious actors, it is key to extract cyber is largely experimental and still in its nascency. It is forgotten
threat intelligence from these events. By exploring in-the-wild quickly that projects aren’t final, stable financial products yet.
security incidents with DeFi in this paper and proposing a The yield farming hype in 2020, is exemplary of DeFi’s
classification scheme, we make the following contributions: current state. Many of experimental projects resulted in high
• We give an overview of reported attacks on DeFi projects gains to early investors, which thus attracted speculative in-
to explore how malicious actors are exploiting DeFi. vestors. The high initial yields of few projects led to copycat
• We show that the major attacks in terms of financial projects being launched with food names like Sushi, Yam,
impact employed compositions of DeFi protocols. Spaghetti and Kimchi. Basically attempts to ‘get rich quick’
• We provide a framework of cyber security threats to DeFi for both aspiring developers, but also speculative investors who
projects to standardize the discussion on threats to DeFi. dumped money into a project without a white paper or website.
• We provide an attack life cycle of flash-loan funded As many of these projects were forks of other immature and
attacks, the ubiquitous attack vector in 2020. untested projects with minor tweaks, this introduced major
• Per threat in the framework we provide guidance on how attack surface. While many of these initiatives experienced a
these can be mitigated in protocol development. short live span, it is also normal behavior of more risk-oriented
actors early in the technology adoption life cycle.
II. A N OVERVIEW OF D ECENTRALIZED F INANCE While DeFi aims to provide the seamless user experience
Decentralized Finance (DeFi), sometimes called Open Fi- associated with ATMs and store POS as currently provided
nance, is the cryptoeconomic system experimenting with al- by traditional players, currently its user experience is still
ternative financial services. It aims to do disrupt finance by relatively spartan. But apart from accessibility challenges due
replacing the security and integrity provided by traditional to its experimental nature, DeFi has systematic challenges it
central bookkeepers such as banks with trustless, transparent needs to solve. Apart from the financial risk of investing in
protocols executed by a smart contract. For many financial DeFi, there are many facets to non-financial risk. Examples
services such as exchanges, lending, derivatives, payments are inadequate storage of private admin keys, causing single
and assets, a decentralized offering already exists. The DeFi points of failure and thus centrality. Many DeFi projects also
community is also experimenting with more niche applications inherit risk from the projects on which they are building
such as prediction markets and margin trading. (composability), or run the risk of receiving prices from vul-
Currently most value is locked within DeFi protocols fo- nerable or simply dishonest price oracles. Furthermore, risk is
cused at lending and borrowing, in which users deposit an caused by developers launching DeFi protocols while lacking
asset such as ETH to take a loan in another asset, such as a financial literacy, let alone the risk of protocols getting shut
stablecoin. Other protocols such as Uniswap and Curve run down through regulatory action. DeFi is a space with many
the decentralized exchange (DEX) of assets, as an alternative threats, both from a financial and non-financial perspective. As
to centralized counterparts such as Coinbase. Yield farming, however usual with early innovations, security is not a primary
prompted by Yearn, can be compared to highly active asset concern. Where names such as Dridex, ZeuS, Carbanak and
management as traditionally performed by hedge funds. Fur- the Lazarus Group have become household names for actor
thermore price oracles, which provide ‘ground truth’ price groups targeting traditional financial institutions, this intelli-
information to DeFi protocols, are not so much end-user gence is absent in DeFi. Therefore it is crucial to retrieve a
protocols but critical DeFi infrastructure. full holistic overview of in-the-wild security threats to DeFi.
In 2020 the total value locked in DeFi projects has reached
an all-time high of 14.744 billion USD on December 1, 2020 16.00 B
[6]. The largest financial market in the world, currency trading 14.00 B
12.00 B
on the foreign exchange market accounted for $2,409,000,000 10.00 B
($2.409 quadrillion) in the same year. Proportionally as well as 8.00 B
nominally DeFi is still insignificant. Although ‘DeFi’ is likely 6.00 B
4.00 B
obsolete terminology soon, its fundamental dynamics play a 2.00 B
key role in the disruption of global financial services. 0.00 B
DeFi initiatives are built on the Ethereum blockchain and Dec 19 Feb 20 Apr 20 Jun 20 Aug 20 Oct 20 Dec 20
use smart contracts to implement financial protocols. The
encoding of financial protocols in smart contracts provides Fig. 1. Total Value Locked in DeFi Protocols December 2019-2020
trustlessness, permissionless and interoperable provision of
III. R ELATED W ORK IV. M ETHODOLOGY
Extensive research has been performed in the area of Our research goal was to provide insight into the nature
smart contracts. From previous work a lot is known about of security threats to DeFi projects. We did this by building
vulnerabilities and weaknesses in smart contract code, while a dataset of vulnerabilities exploited by malicious actors as
research on DeFi attacks specifically is still in its early stages. well verified attack vectors disclosed by security researchers.
Based on observations from this dataset, we have developed
A. Smart Contract Attacks a framework to understand how these threats relate to other
cryptoeconomic and Ethereum threats.
Research into smart contract security threats is interchange-
Data Collection: A dataset of incidents was gathered in
ably referred to as smart contract security and smart contract
November 2020 using Google Custom Search API queries
risk [7], [8]. An early overview of security incidents with
defi attack and defi hack. In addition defi abbreviated, these
smart contracts was provided by Buterin [9]. Praitheeshan et
queries were also executed for decentralized finance. The
al. have focused on vulnerabilities inherent to smart contracts
interim dataset was cross-checked against the href attributes
on Ethereum and surveyed older incidents, such as the DAO
of each result to discover cross-links to incidents missed
and Parity multisig attacks [5]. Chen et al. have performed
initially. Automated search queries on popular crypto websites
a similar survey and provide a classification of Ethereum
cointelegraph.com and coindesk.com were used as a final
vulnerabilities and appropriate defenses [10]. Several authors
check for completeness. Using word frequency analysis, we
have focused on historical attacks on the DAO, Governmental,
found an initial 26 incidents.
King of the Ether Throne and mitigations against those [2], [4],
Only incidents with protocols listed on DeFi Pulse [6]
[11], [12]. Other authors have surveyed specific vulnerabilities
were included in our sample. DeFi Pulse is the de facto
such as reentrancy [13], [14] and integer overflows [15],
standard source for DeFi market information and is referenced
[16]. Similar to the Common Weakness Enumeration (CWE)
in related academic contributions [27], [28]. Listing requires a
for application software, initiatives have been launched for a
whitepaper, Github repo, Twitter profile and project page thus
category system of Solidity weaknesses, such as SWC Registry
filters out scams, which excluded 5 projects.
[17] and the Decentralized Application Security Project [18].
Furthermore we have only included incidents with on-chain
Dingman et al. have classified smart contract weaknesses using
contracts. Through the inclusion of on-chain contracts, we
NIST’s Bugs Framework [19]. These however capture Solidity
exclude vulnerabilities found in code hosted in repositories,
vulnerabilities, not the recent attack vectors observed in DeFi.
which are not a direct threat to a project’s continuity. This
An adjacent field focuses on security analysis through
requirement excluded the double spend bug in SushiSwap’s
static testing and formal analysis. Harz and Knottenbelt have
governance, discovered in code hosted in the official Github
surveyed high-level smart contract languages and their secu-
repository. With this requirement, the eventual amount of
rity characteristics, as well verification methods [3]. Other
incidents in our dataset was 20. Addresses of affected contracts
authors have analyzed the security of smart contracts using
are available for reference in Table I.
symbolic execution and static analysis tools [20]–[23]. Such
Attack Classification: As we found the terminology on
mechanisms inherently leave some real-world attack vectors
attacks DeFi to be fuzzy and non-standardized, we have
unaddressed. Perez and Livshits however regarded vulnerabil-
developed a framework to structure the discussion on security
ities against their real-world impact and found that of 23,327
threats to DeFi projects and show how these differ from attacks
vulnerable contracts, only 1.98% had been exploited [24].
to individual smart contracts. The framework is informed by
B. DeFi Protocol Attacks previous work in the area of smart contract security, as well
security incidents in DeFi recorded in our dataset. We have
Related work on our primary research topic, exploitation of plotted the attacks in our dataset on this framework based on
DeFi protocols, is relatively limited due to the short existence information available by post-mortems from a primary source,
of the industry. Significant work has been performed by Daian as well transaction actions on Etherscan.
et al., who studied arbitrage bots in DEXes ‘front running’ Financial Impact: We have used Etherscan and official post-
transactions of ordinary users through priority gas auctions to mortems to establish the financial impact of security incidents.
manipulate order transaction execution [25]. Qin et al. were the
first to explore the phenomenon of flash loans [26], which first V. ATTACKS ON D E F I P ROJECTS
surfaced in 2020 and is also present in our analysis. Gudgeon In this section we enumerate attack techniques used in DeFi
et al. have published a governance exploit in the Maker security incidents, which include exploits by malicious actors
protocol [27]. By exploiting the its governance system, they or attack vectors disclosed by security researchers.
were able to increase Maker’s token supply. From an economic Table I provides an overview of the attacks discussed in
security perspective, Gudgeon et al. found that liquidity in chronological order. From left to right, the Date column
three of the current major lending platforms in DeFi, as few provides the date of the incident. The Project column lists the
as three accounts controlled the majority of the total liquidity name of the affected project, the Type column the financial
[28]. Furthermore Klages-Mundt have regarded economic and service it provides. The Contract column lists the address of
security risks to custodial and non-custodial stablecoins [7]. the contract running the affected DeFi protocol. The Attack and
Technique columns list attack type and technique. USD Impact flash loans to manipulate wBTC and sUSD prices. As bZx
shows the financial impact of incidents in which funds were relied on a single price oracle exclusively [33], [34], the price
stolen. Funds retrieved from or returned by the attacker are information from this single source was what finalized the
subtracted in order to accurately reflect total value lost. The attack. A similar attack vector was disclosed to Nexus Mutual,
Source column references first-hand incident reports, which which uses a price oracle to trigger a re-balance via Uniswap
were used to classify the attack and provide background on of the holdings of its mutual fund. The callback function to
the tools, techniques and procedures (TTPs) employed. the oracle however was implemented such that everyone could
trigger the re-balance and interact with Uniswap on behalf of
A. Market Attacks this function [36]. Balancer suffered an attack in which an
The attack vector in 10 of the total 20 incidents in our attacker took a flash loan of wrapped ether, which then was
sample targeted DeFi market mechanisms by exploiting repeatedly swapped for a deflationary token [41]. In October,
compositions of multiple DeFi protocols. In accordance Harvest was attacked used a flash loan to funnel 24 million
with observations by other authors [25], [26] we find that USD from liquidity pools used as vaults by the protocol. This
flash-loan funded price oracle attacks are a significant attack was the biggest attack in terms of attacker yield to date, due
vector. Out of the 10 attacks that exploited compositions of to an ‘engineering error’ that allowed to bypass a checking
multiple protocols, all but one were flash loan-funded price function. The smart contract was independently audited by
oracle attacks. The prevalence and novelty of this specific three reputable auditors [45]. Half November, Akropolis was
category of attacks is further discussed in the next section. attacked with a flash loan-funded attack that exploited an
unchecked token whitelist used for price oracle input handling,
1) Price Oracle Exploits: In total 9 projects in our sample to drain its 2 million Dai holdings [46]. Value was attacked
were attacked through their implementation of a price oracle. through a vulnerability in its deposit handling [47].
Of these, 6 projects were exploited by malicious actors and Both DDEX and bZx were vulnerable to price manipulation
consequently lost funds. As price oracles are usually exploited as they used price oracles without validating the price returned.
with flash loans, both concepts are considered briefly below. Both attack vectors were disclosed by a security researcher in
Price Oracle Exploits: in order to exploit a vulnerable September 2019 [31], [33]. While not exploited, both could
implementation of a price data feed into a DeFi protocol, have been weaponized using flash loans.
adversaries need to fabricate arbitrage opportunities. By swap- Flash loans provide low risk high reward opportunities to
ping large amounts of tokens, usually on a DEX or with a attackers, as they allow them to attack without upfront cost.
liquidity pool, they create price variations to create an arbitrage If the attack fails, the flash loan simply reverts at the end of
opportunity. As many DeFi projects depend on a ‘price oracle’ the block time with only gas fees as a marginal sunk cost.
- a price data feed from another project to establish market Developing fully flash loan-resistant protocols is challenging,
price. Especially when depending on a feed from a single as it would deny large-quantity orders with differently sourced
source, the dependency this creates can be catastrophic to a capital. We will cover mitigation scenarios in Section VI.
project. Flash loans are a welcome vehicle to facilitate large
loans that trigger substantial liquidity changes. 2) Other Market Attacks: A rebase mechanism in a clone of
Flash Loans: a DeFi concept without an equivalent in Yearn called SoftYearn was exploited to obtain a large amount
traditional finance, these are loans with a term of a single of funds [43]. This mechanism was implemented to adjust an
blockchain transaction. They allow borrowers to pursue arbi- elastic token supply based on demand. After manipulating the
trage opportunities in the time span of the transaction. Lenders, rebase, the attacker was able to sell his tokens for the previous
usually assembled in a liquidity pool, run no risk of borrowers price as Uniswap’s token price did not account for the rebase,
defaulting, as the transaction will fail if the lender does not which also makes this a market attack.
pay back. Hence flash loans are non-collateralized as they do
not require advance collateral from the debtor. First introduced B. Protocol Attacks
by Aave, flash loans provide an opportunity for the creation Within our dataset, 6 protocols had vulnerabilities affecting
of novel financial products [48]. internal protocol security, without involvement of other DeFi
Flash Loan-Funded Price Oracle Exploits: flash loans protocols. Of these, 2 were exploited by adversaries, the others
provide a vehicle to ‘weaponize’ attacks to amplify profit. The reported by security researchers. Protocol attacks to individual
only limitation is that all the attack steps should be executed protocols are generally performed to gain partial or full control
within a single block. In case of these attacks, the flash loan over a protocol’s governance.
is however just part of a bigger attack vector. It also requires In 2 protocols, a vulnerability existed to manipulate token
vulnerable smart contract code or business logic, the flash balances. The September 2020 attack on bZx allowed attackers
loan is used to multiply the potential outcomes of exploitation. to create and transfer tokens towards them to artificially
increase their token balance [44]. Within Opyn, a vulnerability
In February 2020, bZx, a margin trading and lending in its contract allowed double-spending of tokens due to a
service, was attacked twice on two consecutive days using faulty loop function [42]. In both cases the vulnerabilities were
a flash loan-funded price oracle attack. The attackers used the exploited by malicious actors.
TABLE I
D ECENTRALIZED F INANCE I NCIDENTS
Access Error
High-Level Input/Output Integer
Public
Delegatecall
Description Smart Contracts Control Handling Overflow/ Reentrancy untrusted
Language Attacks Underflow
Method
contract
Attacks Attacks
• Composability: while DeFi’s ‘money lego’ architecture Protocol Attacks exploit weaknesses in the implementation of
is advantageous in many regards, a deficiency in one a single protocol, such as a protocol’s internal governance,
protocol might cause failure of the whole stack. with impact is limited to that protocol. Market Attacks exploit
• Lack of custody: discarding middlemen removes delega- compositions of multiple DeFi projects or ‘money legos’, for
tion of risk/responsibility prevalent in traditional finance. example the exploitation of a price oracle having a cascading
These root causes directly affect the security of individual effect on other projects. While Market Attacks are initiated
DeFi protocols and the DeFi markets formed by compositions through exploitation of usually flawed business and financial
of protocols. However the dynamics of these ‘market attacks’ logic in a single protocol, they potentially have far-reaching
and ‘protocol attacks’ are fundamentally different than than effects, impacting multiple protocols. We cover potential mit-
smart contract attacks and the narrative around them can be igation scenarios separately in the next section.
fuzzy. Our framework structures the narrative around threat B. Smart Contracts
mitigation within DeFi. We deem this necessary as the secu- Smart contracts are exploited through exploits of high-level
rity threats to ‘composable’ DeFi protocols instead of smart languages like Solidity and Vyper for implementing smart con-
contracts operating in isolation is still a black box to many tracts, which are application layer threats [4], [11], targeting
projects. By standardization of the discussion, a framework access control, input/output and error handling. Mitigation of
promotes better understanding of the threat landscape. An integer underflow/overflow, Delegatecall and Floating Pragma
example of this within enterprise security is ATT&CK, which threats takes place through safe and secure smart contract
successfully standardized the narrative on adversary TTPs programming. Examples are the ‘classic’ attacks on The DAO
[50]. and the Parity Wallet, which had weak implementations of
We present our framework as a stack model because, as Solidity. The application layer threat of contract code exploits
pointed out by others, threats on one layer instigate risk to is different than the business layer threats of the top DeFi layer.
other layers [25]. Figure 2 is a stack representation of how Smart contracts are technically vulnerable to exploitation of
DeFi protocols are supported by smart contracts, which in software errors and Solidity subtleties, whereas the business
turn rely on the Ethereum Virtual Machine (EVM), which layer of DeFi is attacked through weakly implemented busi-
depends on Internet network, transport and routing protocols. ness logic.
The first column represents the layers of this architecture. Each To avoid vulnerability to attacks directly exploiting weak
architecture layer has vulnerabilities of its own, which can be smart contract code, projects should implement safe coding
exploited during an attack and thus facilitates threats (second practices. Projects should preferably use standard libraries
column). Attacks are carried out with a specific technique such as SafeMath and community-audited token implemen-
and take several forms depending on the technique employed. tations. Their legitimacy must be verified to avoid tampering
The third column lists techniques observed in incidents in our by malicious actors. Third-party auditing and publication of
sample, as well as common examples. Per architecture stack reports also has become a best-practice. The number of audits
layer, we have identified the following threat categories: performed and the ‘age’ of the most recent audit report, as well
total engineer weeks spent are useful external metrics. The
A. DeFi Protocols most recent bZx exploit showed that two audit firms reviewed
The business layer of DeFi is composed by DeFi proto- bZx’s code, but failed to find the vulnerability [44]. Besides
cols, vulnerable through the implementation of financial and locating weak Solidity code, audits must focus on business and
business logic which serves as their value proposition. DeFi financial logic. Security audits are never an adequate measure,
protocols are attacked by Protocol Attacks and Market Attacks. just like static testing is never a security measure on its own.
C. Ethereum Virtual Machine bottom rows provide a graphical overview of the specific
Adhering to Ethereum architecture, EVM is the consensus services (mis)used in the Harvest attack, discussed in more
layer [5], [10]. Attacks directly exploit Ethereum blockchain detail below, as well the financial impact per phase. It has
economics and governance on which DeFi projects depend and a Repeat phase to account for the additional iterations to
can potentially impact the Ethereum ‘cryptoeconomic’ system circumvent an arbitrage threshold.
broader than DeFi (hence economic and governance attacks). Harvest, an automated yield farming service, was attacked
Attacks such as the mempool congestion targeting Maker as on October 26, 2020 [45]. Harvest was exploited through
discussed in the previous section exploit Ethereum’s consensus arbitrage assumptions in its financial logic and dependency
mechanisms in order to attack DeFi protocols. The execution on price data from a single source, which made it vulnerable
of 51% attacks at smart contracts overseeing active price ora- to market manipulation. The attacker used funds provided by
cles is another example of threats on this layer. Fundamentally a flash loan to cause price swings in the underlying Curve
mitigation of this dependency threat happens in Ethereum core liquidity pool. Due to the project’s dependence on Curve’s
development, but on the level of DeFi protocols developers Y Pool, the price variation within the pool was reflected
can account for them in their protocol’s business logic. The in Harvest’s share price calculation that takes place during
effects of a 51% attack to alter operational price oracles deposit. While Harvest operated a 3% arbitrage check to detect
can partly be mitigated by DeFi projects by implementing price variations due to large-scale market manipulation, this
a voting system. Furthermore DeFi projects can account for threshold was too lenient. The attacker simply bypassed it by
dependency by storing (a part of) their locked value in custody. running multiple cycles causing 1% price swings. The official
If the custodian fails to secure funds adequately, losses are incident post mortem does not mention how the 3% threshold
offset through insurance reserves. was established initially [45]. While it is a vector captured
logically in threat modeling, according to the project it wasn’t
D. Internet recognized in security audits. The attacker seized 24 million
The Internet is the infrastructure on which Ethereum is built. USD of the project’s funds. For reasons unknown 2.4 million
Routing threats such as DNS spoofing, but also threats such USD were returned to the project, the rest is still missing.
as phishing, key-stealing malware (KryptoCibule, AppleJeus) Figure 3 shows how the Harvest attack was executed in
and social engineering attempts on users acquiring tampered the bottom row, but the life cycle as described in the three
hardware wallets from eBay, put users of DeFi projects and top rows are generic to all flash loan-funded attacks in our
their funds at risk. We include this layer in our framework dataset. While the Repeat phase was novel to Harvest, it could
as these threats have caused significant financial losses token theoretically take place in any price oracle attack.
holders in the past [51] and are a threat to the many DeFi
B. Mitigation Scenarios
projects with centralized admin key storage.
While it is beyond the scope of this paper to provide an Below we focus on phases for which Harvest could have
overview of such threats and their mitigations, in general a denied the attack as part of protocol development.
project’s degree of trustlessness and decentralization are key
towards mitigation. Central private key storage is currently a 1) Swap: For its pricing Harvest singularly depended on
single point of failure to many projects. Obtained by malicious price data derived from Curve, an exchange liquidity pool.
actors these can be used to unilaterally modify a contract and This is necessary as Harvest’s pool is located in Curve’s Y
affect user funds. Time locks and multisignature wallets secure pool and must accurately reflect its price level. Decentralized
against third-party attacks, but cannot avoid collusion by oracles are not a logical solution as these would also introduce
internal actors. Token-based project governance is promising, attack surface. However Curve’s virtual price feed with price
but requires controls against majority holdings by the admin data not derived from a stablecoin was already available and
team to avoid collusion. would have mitigated this. In general and for other protocols
the time-weighted average price oracle in Uniswap V2 is
VII. M ARKET ATTACK M ITIGATION resistant against manipulation as the upfront cost will exceed
This section focuses on the mitigation of flash loan-funded return on investment. Maker has a similar mechanism with
exploits, a market attack vector of growing concern to the an Oracle Security Module operating separately from the
DeFi industry. We deconstruct the largest attack to date into oracle. A drawback of using oracles resistant against timing
a life cycle to promote better understanding of this relatively attacks, or simply implementing thresholds for extreme
complex attack vector and its potential mitigation. price variations, is their slower response to extreme market
volatility. For other projects, multiple price feeds can mitigate
A. The Harvest Attack vulnerability to exploits of single price oracles, a single point
Figure 3 shows the attack life cycle of the Harvest attack, of failure to many projects. A decentralized oracle network
with attack phases generic to flash-loan funded price oracle providing multiple price feeds also provides protection against
exploits listed in the Tactic row. The Tool row lists the relevant Sybil attacks, in which an attacker operates multiple oracle
DeFi service for each phase. Together with Objective, this nodes to manipulate results.
shows how attackers attack compositions of DeFi. The two
Tactic Fund Flash Loan Swap Deposit Swap Withdraw Repeat Launder
Tool Coin mixer DEX Liquidity Pool Victim Protocol Liquidity Pool Victim Protocol (ibidem) Coin Mixer
Objective Subsidize attack Magnify profit Increase price Receive tokens Correct price Profit Multiply profit Obfuscate funds
(impermanent loss) (revert impermanent loss)
Monetary 10 ETH 18.3m USDT + 17.2m USDT > 51.5m fUSDC 17.2m USDC > 0.62m USDC 0.62m USDC x 30 Liquidity Pool
Impact 50m USDC 17.2m USDC 17.2 USDT
Fig. 3. Life cycle of the loan-funded attack against Harvest, October 26, 2020
2) Deposit: with its price driven up, attacker could deposit ments requires developers to take an adversary perspective
USDC into Harvest. The 3% arbitrage check was bypassed towards their project and advances understanding of attack
by making the swaps cause 1% price changes and executing vectors and their mitigation.
additional cycles to multiply profit with 30. Decreasing the
VIII. L IMITATIONS
threshold isn’t feasible as it would result in false positives
for legitimate deposits and withdrawals, however disallowing DeFi is a nascent field. While the quantity of incidents in
deposit and withdrawal in a single transaction is a feasible our dataset is relatively limited, it covers significant security
mitigation. Handling the distribution of Harvest shares in incidents with on-chain DeFi. We deemed the threat significant
a subsequent transaction after withdrawal would also have and critical enough to perform this early analysis, considering
mitigated the attacker opportunity to cause share fluctuation. all incidents occurred over an 18-month timeline. The threat
In their post-mortem, Harvest suggested a commit-reveal landscape is dynamic and the DeFi field will unequivocally
scheme as a potential mitigation. While not truly a commit- advance in the years ahead, so it remains a work in progress.
reveal scheme as nothing is cryptographically hidden, deposit Our analysis however represents the state-of-the-art in DeFi
and distribution of shares would be separated in different and can inform security improvement of DeFi protocols.
blocks, which avoids flash loan-funded attacks [45]. IX. C ONCLUSION
DeFi is experimental software running in production. Pro-
3) Withdraw: Harvest operated its own fUSDC tokens tocols might fail, falling short to generate cash flow and
which were swappable for stablecoin, which was weaponized evaporating user funds. The public blockchain on which they
by the attacker. Directly depending on the underlying rely is a complex and adversarial environment. The freedom
stablecoin would have denied opportunity as the adversary it facilitates breeds opportunity for ignorant behavior by
would have to arbitrage the value of his own assets. Like irrational and illiterate actors, while each vulnerability will
traditional exchanges, DEXes could benefit from traditional be exploited eventually. With many on-chain protocols still a
approaches such as circuit breakers halting trading during work in progress, DeFi is a risky cryptoeconomic system.
extreme market circumstances. Liquidity and whale alerts In this paper we have enumerated security threats to DeFi
to signal suspicious activity can serve as low-cost alerts to projects based on in-the-wild attacks, as well as countermea-
inform security monitoring. sures to inform mitigation. We have introduced a framework
to holistically regard security threats and attacks to DeFi,
This section lists a flash-loan funded price oracle attack. which we hope contributes to inform better threat modeling
This is a type of market attack, which is mitigated by assuming and consequent security decision-making in current and future
extreme market behavior in a project’s financial logic. Mitiga- protocols. With institutional interest increasing, security is a
tion of a hypothetical attack against a project by front runners key and potentially pivotal responsibility to the ecosystem writ
colluding with miners to perform malicious transactions over large. The attack vectors covered in this paper need to be
multiple blocks is mitigated on the underlying infrastructure addressed, or they will impede DeFi’s potential to develop
layer. We have presented our framework as a stack to empha- into what it aspires. Similar to zero trust in computer network
size that inheritance of capabilities from other layers implies security, DeFi’s ‘don’t trust, verify’ must become default
inheritance of vulnerabilities - while responsibility can’t be security architecture, rather than a cryptoeconomic ideal.
shifted. Modeling attack life cycles as part of threat assess-
R EFERENCES [25] P. Daian, S. Goldfeder, T. Kell, Y. Li, X. Zhao, I. Bentov, L. Breidenbach,
and A. Juels, “Flash boys 2.0: Frontrunning in decentralized exchanges,
[1] “Statement.” [Online]. Available: miner extractable value, and consensus instability,” in 2020 IEEE
https://twitter.com/AndreCronjeTech/status/1310763509521805312 Symposium on Security and Privacy (SP). IEEE, 2020, pp. 910–927.
[2] N. Atzei, M. Bartoletti, and T. Cimoli, “A survey of attacks on ethereum [26] K. Qin, L. Zhou, B. Livshits, and A. Gervais, “Attacking the
smart contracts.” defi ecosystem with flash loans for fun and profit,” arXiv preprint
[3] D. Harz and W. Knottenbelt, “Towards safer smart contracts: A survey of arXiv:2003.03810, 2020.
languages and verification methods,” arXiv preprint arXiv:1809.09805, [27] L. Gudgeon, D. Perez, D. Harz, B. Livshits, and A. Gervais, “The
2018. decentralized financial crisis,” 2020.
[4] S. Wang, L. Ouyang, Y. Yuan, X. Ni, X. Han, and F. Y. Wang, [28] L. Gudgeon, S. Werner, D. Perez, and W. J. Knottenbelt, “Defi protocols
“Blockchain-Enabled Smart Contracts: Architecture, Applications, and for loanable funds: Interest rates, liquidity and market efficiency,” in
Future Trends,” IEEE Transactions on Systems, Man, and Cybernetics: Proceedings of the 2nd ACM Conference on Advances in Financial
Systems, 2019. Technologies, 2020, pp. 92–112.
[5] P. Praitheeshan, L. Pan, J. Yu, J. Liu, and R. Doss, “Security analysis [29] “Technical description of critical vulnerability in makerdao governance.”
methods on ethereum smart contract vulnerabilities: a survey,” arXiv [Online]. Available: https://blog.openzeppelin.com/makerdao-critical-
preprint arXiv:1908.08605, 2019. vulnerability/
[6] “The defi list: Defi pulse.” [Online]. Available: [30] “Shut down of 0x exchange v2.0 con-
https://defipulse.com/defi-list tract and migration to patched version.” [Online].
[7] A. Klages-Mundt, D. Harz, L. Gudgeon, J.-Y. Liu, and A. Minca, Available: https://blog.0xproject.com/shut-down-of-0x-exchange-v2-0-
“Stablecoins 2.0: Economic foundations and risk-based models,” in 2nd contract-and-migration-to-patched-version-6185097a1f39
ACM Conference on Advances in Financial Technologies, 2020. [31] “Fixed: potential vulnerability in contract used during private
[8] X. Li, P. Jiang, T. Chen, X. Luo, and Q. Wen, “A survey on the security beta.” [Online]. Available: https://medium.com/ddex/fixed-potential-
of blockchain systems,” Future Generation Computer Systems, vol. 107, vulnerability-in-contract-used-during-private-beta-217c0ed6f694
pp. 841–853, 2020. [32] “Critical vulnerability in a new airswap smart contract.”
[9] V. Buterin, “Thinking about smart contract security,” 2016. [Online]. [Online]. Available: https://medium.com/fluidity/critical-vulnerability-
Available: https://blog.ethereum.org/2016/06/19/thinking-smartcontract- in-a-new-airswap-smart-contract-c1204e04d7d3
security [33] “Your funds are safe.” [Online]. Available:
[10] H. Chen, M. Pendleton, L. Njilla, and S. Xu, “A survey on ethereum sys- https://medium.com/@b0xNet/your-funds-are-safe-d35826fe9a87
tems security: Vulnerabilities, attacks, and defenses,” ACM Computing [34] “Post-mortem.” [Online]. Available:
Surveys (CSUR), vol. 53, no. 3, pp. 1–43, 2020. https://bzx.network/blog/postmortem-ethdenver
[11] A. López Vivar, A. T. Castedo, A. L. Sandoval Orozco, and L. J. [35] “bzx hack ii full disclosure.” [Online]. Available:
Garcı́a Villalba, “An analysis of smart contracts security threats along- https://blog.peckshield.com/2020/02/18/bZx/
side existing solutions.” Entropy, vol. 22, no. 2, 2020.
[36] “Responsible vulnerability disclosure.” [Online]. Avail-
[12] S. Sayeed, H. Marco-Gisbert, and T. Caira, “Smart contract: Attacks and
able: https://medium.com/nexus-mutual/responsible-vulnerability-
protections,” IEEE Access, vol. 8, pp. 24 416–24 427, 2020.
disclosure-ece3fe3bcefa
[13] C. Liu, H. Liu, Z. Cao, Z. Chen, B. Chen, and B. Roscoe, “Reguard:
[37] “Evidence of mempool manipulation on black thursday.” [Online].
finding reentrancy bugs in smart contracts,” in 2018 IEEE/ACM 40th
Available: https://www.blocknative.com/blog/mempool-forensics
International Conference on Software Engineering: Companion (ICSE-
Companion). IEEE, 2018, pp. 65–68. [38] “Uniswap/lendf.me hacks: Root cause and loss analysis.” [Online].
Available: https://medium.com/@peckshield/uniswap-lendf-me-hacks-
[14] P. Qian, Z. Liu, Q. He, R. Zimmermann, and X. Wang, “Towards
root-cause-and-loss-analysis-50f3263dcc09
automated reentrancy detection for smart contracts based on sequential
models,” IEEE Access, vol. 8, pp. 19 685–19 695, 2020. [39] “Lendf.me hack resolution part i: Asset redistribution plan.” [Online].
[15] J. Gao, H. Liu, C. Liu, Q. Li, Z. Guan, and Z. Chen, “Easyflow: Keep Available: https://medium.com/dforcenet/lendf-me-hack-resolution-part-
ethereum away from overflow,” in 2019 IEEE/ACM 41st International i-asset-redistribution-plan-9cefee49f209
Conference on Software Engineering: Companion Proceedings (ICSE- [40] “Bancor’s response to today’s smart contract vulnerability.”
Companion). IEEE, 2019, pp. 23–26. [Online]. Available: https://blog.bancor.network/bancors-response-to-
[16] E. Lai and W. Luo, “Static analysis of integer overflow of smart contracts today-s-smart-contract-vulnerability-dc888c589fe4?gi=f2b8f85372ee
in ethereum,” in Proceedings of the 2020 4th International Conference [41] “Incident with non-standard erc20 deflationary tokens.” [Online]. Avail-
on Cryptography, Security and Privacy, 2020, pp. 110–115. able: https://medium.com/balancer-protocol/incident-with-non-standard-
[17] “Swc registry.” [Online]. Available: https://swcregistry.io/ erc20-deflationary-tokens-95a0f6d46dea
[18] “Decentralized application security project.” [Online]. Available: [42] “Opyn eth put exploit.” [Online]. Available:
https://dasp.co https://medium.com/opyn/opyn-eth-put-exploit-c5565c528ad2
[19] W. Dingman, A. Cohen, N. Ferrara, A. Lynch, P. Jasinski, P. E. [43] “Statement.” [Online]. Available:
Black, and L. Deng, “Defects and vulnerabilities in smart contracts, a https://twitter.com/softyearnfi/status/1301915560654131202
classification using the nist bugs framework,” Int. Journal of Networked [44] “itoken duplication incident report.” [Online]. Available:
and Distributed Computing, vol. 7, no. 3, pp. 121–132, 2019. https://bzx.network/blog/incident
[20] L. Luu, D.-H. Chu, H. Olickel, P. Saxena, and A. Hobor, “Making smart [45] “Harvest flashloan economic attack post-mortem.” [Online]. Avail-
contracts smarter,” in 2016 ACM SIGSAC conference on computer and able: https://medium.com/harvest-finance/harvest-flashloan-economic-
communications security, 2016, pp. 254–269. attack-post-mortem-3cf900d65217
[21] I. Grishchenko, M. Maffei, and C. Schneidewind, “A semantic frame- [46] “Delphi savings pool exploit.” [Online]. Available:
work for the security analysis of ethereum smart contracts,” in Interna- https://akropolis.substack.com/p/delphi-savings-pool-exploit
tional Conference on Principles of Security and Trust. Springer, 2018, [47] “Multistables vault exploit post-mortem.” [Online].
pp. 243–269. Available: https://valuedefi.medium.com/multistables-vault-exploit-post-
[22] P. Tsankov, A. Dan, D. Drachsler-Cohen, A. Gervais, F. Buenzli, and mortem-d11b0635788f
M. Vechev, “Securify: Practical security analysis of smart contracts,” [48] “Performing a flash loan.” [Online]. Available:
in 2018 ACM SIGSAC Conference on Computer and Communications https://docs.aave.com/developers/tutorials/performing-a-flash-loan
Security, 2018, pp. 67–82. [49] “Exploiting an erc777-token uniswap exchange.” [Online]. Available:
[23] S. Tikhomirov, E. Voskresenskaya, I. Ivanitskiy, R. Takhaviev, https://github.com/OpenZeppelin/exploit-uniswap
E. Marchenko, and Y. Alexandrov, “Smartcheck: Static analysis of [50] K. Oosthoek and C. Doerr, “Sok: Att&ck techniques and trends in
ethereum smart contracts,” in Proceedings of the 1st International windows malware,” in International Conference on Security and Privacy
Workshop on Emerging Trends in Software Engineering for Blockchain, in Communication Systems. Springer, 2019, pp. 406–425.
2018, pp. 9–16. [51] ——, “From hodl to heist: Analysis of cyber security threats to bitcoin
[24] D. Perez and B. Livshits, “Smart contract vulnerabilities: Vulnerable exchanges,” in 2020 IEEE International Conference on Blockchain and
does not imply exploited,” 2020. Cryptocurrency (ICBC). IEEE, 2020.