What Are DeFi Flash Loans & How To Prevent Flash Loan Attacks?

Flash loans, a type of uncollateralized lending, have gained in popularity, as well as bad press. Flash loan attacks are a common threat that enable hackers to steal massive amounts of cryptocurrency reaching up into the hundreds of millions.

By: Kiril Ivanov, Founder and Technical Lead, Bright Union

What is a flash loan?

A flash loan is an ultra-fast, unsecured loan, where the whole lending and returning process occurs within a single transaction on the blockchain. The loan is able to by-pass the numerous prerequisites of a traditional loan, used to guarantee their repayment. No credit checks, collateral and guarantors are needed, provided that the liquidity is returned to the pool within a single transaction block. If this fails to occur, the whole transaction is reversed, effectively undoing the actions executed up until that point. This guarantees the safety of the funds in the reserve pool.

Watch this 1 min video to see how a flash loan works. Source: Coindesk. https://www.youtube.com/watch?v=4CEeP7ar2X0&ab_channel=CoinDesk

The primary intended reason for these flash loans is for users to capitalize on arbitrage opportunities. Arbitrage is the simultaneous purchase and sale of the same asset in different markets in order to profit from marginal differences in the asset’s listed price. Arbitrage traders are vital for their role in increasing market efficiency as they narrow the gap in these price discrepancies. Other use-cases include collateral swapping, self-liquidation, and more.

Typically, the concept works well, but some misuse this form of lending, intending to drain vulnerable DeFi protocols of millions of dollars.

Flash loan attacks – why they are easily executed

Flash loan attacks are relatively common because they are easy for a hacker to perform and low-risk due to the probability of exposure being so low. The resources required to execute a flash loan attack are nothing more than a computer, internet connection and ingenuity as stated by Coinmarketcap.

DeFi hackers can easily exploit flash loans as they can be used to create artificial arbitrage opportunities. It involves manipulating asset prices in order to take advantage of arbitrage opportunities on DeFi services that would not otherwise have existed. In short, due to the theoretically infinite size of the loan, the attacker is able to ‘increase demand’ and raise the price. They can make a trade just like any other arbitrage opportunity [buy low, sell high], then pay off the loan and keep the profits. The maximum size of the loan could be as great as the liquidity pool could handle; theoretically reaching into the billions of dollars, draining the liquidity of the effect pools.

Their unlimited and instantaneous nature mean that a well-planned attack can be executed in one go, with no risk if it fails [since the loan transaction will automatically reverse if the loan isn’t repaid.

Examples of flash loan attacks in 2021

C.R.E.A.M. Attack October 2021 loss of ~$130m

The hacker borrowed $500m DAI and $2bn ETH with two separate addresses. Through a series of trades, and using the loans as collateral for more loans, the attacker was able to artificially double the price of the yUSD and repay the loans. With the remaining $1bn of collateralized crYUSD, the attacker borrowed all the liquidity from the C.R.E.A.M. Ethereum v1 markets.

In the post-mortem by C.R.E.A.M., it is stated that the key vulnerability lies within the price calculation of the wrappable token.

xToken Attack August 2021 loss of ~$4.5m

This hack was the result of a flash loan being used to deflate an xSNX token price and the hacker’s ability to call a function which shouldn’t have been within their power to do so. The source of value extraction was the artificial arbitrage by the price manipulation of xSNX. Interestingly, xToken has since retired the xSNX product due to its complexity.

Pancake Bunny Attack May 2021 loss of ~$200m

The hacker used pancakeswap to borrow BNB. They used this to manipulate the price of USD/BNB and BUNNY/BNB, gaining a huge amount of BUNNY. They then dumped the BUNNY and remaining BNB which was at the time worth around $200m.

**The figures quoted are the amount of value extracted at the time of the hack. The protocols may have recovered some of the tokens or compensated the users after.

Consequences of flash loan attacks

Depending on the scale of the attack, consequences can vary. But one thing is certain, the reputational damage is great, and the other protocol users pay the adverse effects. Seemingly never out of the spotlight, C.R.E.A.M. has been attacked three times in 2021, two of which were flash loan attacks. In the case of flash loans, lightning can and does strike the same place twice.

The primary and most important consequence is the impact that flash loan attacks can have on other users. DeFi would be nothing without the loyalty and money of the users who are all key players in an intricate autonomous ecosystem. It is presumptuous to assume that victims have available cash to put back into a system that has failed to protect their assets adequately.

Questions about whose responsibility it is to ensure that flash loan attacks don’t occur will continue to rise and protocols will rightfully be expected to defend themselves. Is taking preventative measures enough to adequately prove that the platform isn’t responsible if an exploit occurs? A prudent protocol or exchange should also consider a post-exploit action plan, if the worst is to occur.

5 Steps for protocols to take to minimize the likelihood and impact of flash loan exploits

The recommendations here align with the three pillars of cyber security: security, vigilance and resilience.

1. Design of the protocol matters

Complexity comes with risk. While developing a large smart contract or building a dApp it is difficult to pinpoint loopholes. Therefore, all external calls should be located, to explore if these could serve as a path for the malicious actors in the contracts. In older versions of Solidity, even reading a public field could lead to unsafe external calls that can be easily manipulated. Therefore, developers should always use the stable and updated versions of Solidity.

2. Use a decentralized oracle

Oracle manipulations are the biggest cause of flash loan attacks. Smart contracts heavily rely on oracles which provide an effective interface between the contracts and the external source to push the required data. Decentralized Oracles like Chainlink, gather data about prices from multiple sources, which reduces the likelihood of a single data point influencing the oracle. If a platform relies solely on the data of one particular DEX, then its data is at risk of being flawed. Mal Intended users could directly manipulate the price of the singular DEX where the loan price is based off, resulting in loans issued with an inaccurate average price. On the other hand, limited data could form an inaccurate representation of the average market price and thus promote excessive slippage exploitation.

3. Get audited

Getting a smart contract audit is one of the most vital steps before launching your product. These audits identify and remediate vulnerabilities in the smart contracts before they can be exploited by someone with malicious intent. Source Consensys Source Certik

Due to the interwoven nature of these protocols, just focusing the attention of the audit on the critical components isn’t enough to guarantee their security. A chain is only as strong as its

weakest link, perfectly showcased by the recently detected Log4Shell vulnerability. If an audited protocol integrates with, for example, an un-audited bridge, well this might be the gap that a hacker is looking for.

If a hole in the code of the platform is found, then it is crucial for the developers to remedy it as soon as possible. It may sound obvious, but apparently it isn’t to everyone. As described in the examples above, in May of 2021, Pancake Bunny was hit resulting in an enormous loss. Just days after, AutoShark was hit in a copy-cat attack, which fortunately resulted in significantly smaller losses. The kicker, however, is that AutoShark officially published its acknowledgement that it was vulnerable to a similar style hack.

4. Participate in a Bug Bounty program

Continual vigilance over the smart contracts while they are in operation is critical, especially if updates and integrations are occurring. Offering a bug bounty incentivizes those with ‘hacking skills’ to act ethically. They are prizes for ethical hackers who report holes in code, which they could have exploited. It encourages these white hat hackers to work with the protocols rather

than against them. ImmuneFi is a platform that advocates for the rights of white hat hackers. Protocols list their bounty on the database and offer a portal for hackers to submit their findings.

It isn’t enough to just offer a few thousand dollars as a bounty. ImmuneFi suggests 10% of TVL. It has to be enough to incentivize a hacker to act ethically when they know they have ‘illegal’ access to a much larger pool of funds. The incentives provided are attractive with a record amount of $10m being offered by BXH after a hack where over $139m was taken.

5. Offer in-App coverage

Despite all efforts to prevent a flash loan exploit, there is always a possibility for the event to occur. Proactively educating users about the risks of investing should be the responsibility of the protocols. Do your own research (DYOR) is one of the most thrown-around phrases. However, in the context of deciding which protocols to use, the protocols themselves should do the research about their risks and present these to users in a clear way.

The impact of an exploit can cause a serious business crisis if the protocol doesn’t act transparently. By offering in-app coverage, crypto’s alternative to insurance, protocols are acknowledging the risks and presenting their users with a discretionary option to mitigate the risks based on their risk appetite.

How does it work in practice? There are multiple risk platforms offering coverage against smart contract failures for hundreds of protocols, exchanges and wallets. Nexus Mutual is currently the best known, with TVL around $1B. New players are slowly building up traction in the market like Bright Union and Bridge Mutual.

Bright Union, DeFi coverage aggregator, has developed a way for protocols to offer their users coverage from their own app with an SDK. The cost of coverage can even be deducted from the APY so no out of pocket costs for users creating a seamless customer journey.

A protocol proactively offering users coverage is Alpaca Finance. The app connects the users directly to these risk coverage platforms, where they are then able to buy coverage. Similarly Don-key finance, a social platform for yield farming, is soon offering a fully covered strategy for users to invest in, with coverage just a click away.

About The Author

Kiril Ivanov is the Founder and Technical Lead at Bright Union. He is one of the Bright Union founders, has 20 years of development experience comprising 15 years in finance, 10 years in the insurance space and the last five in blockchain and decentralized finance. Before starting Bright Union, Kiril provided blockchain powered solutions for innovative digital insurance. He’s been highly interested in the growing DeFi space for years, where decentralized networks transform old financial products into trustless and transparent protocols that run without intermediaries. Kiril can be reached online at https://www.linkedin.com/in/kirivanov/ and our company website https://brightunion.io/.

FAIR USE NOTICE: Under the "fair use" act, another author may make limited use of the original author's work without asking permission. Pursuant to 17 U.S. Code § 107, certain uses of copyrighted material "for purposes such as criticism, comment, news reporting, teaching (including multiple copies for classroom use), scholarship, or research, is not an infringement of copyright." As a matter of policy, fair use is based on the belief that the public is entitled to freely use portions of copyrighted materials for purposes of commentary and criticism. The fair use privilege is perhaps the most significant limitation on a copyright owner's exclusive rights. Cyber Defense Media Group is a news reporting company, reporting cyber news, events, information and much more at no charge at our website Cyber Defense Magazine. All images and reporting are done exclusively under the Fair Use of the US copyright act.

Global InfoSec Awards 2022

We are in our 10th year, and these awards are incredibly well received – helping build buzz, customer awareness, sales and marketing growth opportunities, investment opportunities and so much more.

APPLY NOW

10th Anniversary Exclusive Top 100 CISO Conference & Innovators Showcase

X