Call of DeFi: The Battleground of Blockchain

Bishop Fox blog on the battleground of blockchain illustrated by multiple purple and teal blocks with cryptocurrency bitcoin floating inside some of the cubes on a dark purple background.

Share

Last year, decentralized finance (DeFi) grew tremendously, not only in usage, but also in cybersecurity attacks. Wallets were emptied, smart contracts stripped, and investors left with dreams and regrets. To understand the risks of these new blockchain technologies and use cases, we analyzed the main hacks that occurred in 2021. Let’s look back on a year as innovative as it was chaotic.

Total analyzed loss: ~ $1,800,000,000

Total events: 65

Total losses due to unsophisticated attacks: 90%+

2021 DeFi Hacks Timeline showing the cost of DefiHacks for each month, Source: CryptoSec 2022

The graph above groups together all the events taken into account in our analysis. The world of decentralized finance is extremely vast, and we can’t be aware of all the projects and all the hacks that may have taken place. In addition, we limited our analysis of rug pull and exit scams, since both are more a matter of fraud than security weaknesses – though we will address them, on their own terms, later in this article. Regardless, this sample of 2021’s most impactful and interesting events allows us to obtain a fairly thorough view of DeFi’s security risks.

First, let's look back at the events of the year 2021 in numbers:

Line Graph showing the Number of Attacks on DeFi Projects Per Month; source: CryptoSec 2022

As the graph shows, the DeFi world experienced an average of five hacks per month, with two peaks in activity in May and December. These activity peaks were due to two issues:

  • The discovery of a new method of exploitation or type of vulnerability. Once a technique is mastered, attackers go through applications to find and hack all those that are vulnerable before developers can patch their code.
  • Chain attacks targeting SmartContracts that have been forked multiple times. Often, if the original application is vulnerable, then all the forks are, too. We will come back to the case of forks later in this article.

Now, let's explore the origin of these attacks:

From a quick perusal of the chart, we can see that in most cases, the attack came from a vulnerability in SmartContracts or in the very logic of the protocol. This is not surprising for a recent technology that may lack a certain technical hindsight on the implementation of security measures. Another important vector was the compromise of wallets and their private keys. And finally, these attacks included the famous rug pull or exit scam, in which the attacker is internal or at the origin of the project and is content to just take the money and run.

It would be wrong to assume that more than half of these events are due to new and sophisticated attacks. To begin with, we can remove from this category all key leaks, wallets, and front-end hacks, which only take place because of a lack of vigilance and consideration for infrastructure security – not exactly new or sophisticated techniques. Arbitrage and front-running are also due to configuration issues, rather than new technology, and rug pulls are not hacks, exactly. Therefore, after removing these categories, we are left with only 70% of the attacks to analyze as potentially complex or innovative attacks.

Smart Contracts and Protocol Flaws

Attack Categories of Smart Contracts

After analyzing the modus operandi of the events targeting SmartContracts and Protocols, we discovered three major categories: attacks exploiting known vulnerabilities, attacks exploiting forks of projects containing a vulnerability, and sophisticated or innovative attacks. (For 4% of these cases, the modus operandi is not clear or seems to have come from a backdoor left by the developers. We will talk about this specific case later.)

Well-Known Vulns and Forks

Unlikely as it sounds, 80% of these events could have been easily avoided. Why? Because they originated from the use of vulnerable code or from a fork of projects containing vulnerabilities.

The desire to develop quickly and save time, or perhaps just the lazy disinclination to review or recreate one's own code, too often leads to the use of untested, and therefore ultimately vulnerable, code.

Take, for example, the hack of the BurgerSwap Dex project that occurred on May 28, 2021, and led to a loss of $7.2M.

This hack used several common techniques and known flaws, such as the following:

  • Flash loans to gather tokens and run the attack
  • The use of a fake tokens pair
  • A missing x*y≥k check**
  • Reentrancy attacks

**The x*y≥k check is used to verify that during a swap() from a token x to y or vice versa, the total quantity x*y remains the same. In other words, if a token x is sold for a token y, the quantity of token x in the pool will increase reciprocally as the amount of token y obtained by the user decreases.

In this hack, BurgerSwap's code was forked from UniswapV2Pair's, but an essential x*y≥k check was removed for mysterious reasons. From our perspective, it’s hard to say if this security measure was removed intentionally or if negligence was committed before the code was pushed in mainnet.

Code

In addition to this breach, the router contract that allowed the creation of swap routes from one token to another through different pools was vulnerable to a reentrance attack.

With these two vulnerabilities, the attacker needed to create a pool made from only a fake token of their creation and $BURGER tokens. Then, the attacker swapped this new fake token to $WBNB with the router contract via the Fake_Token=>$Burger=> $WBNB path. Finally, they exploited missing reentrancy protection to reenter the smart contract’s code and perform a second $Burger => $WBNB swap in the same previously initialized transaction. The transaction did not fail due to the missing requirement (x*y≥k).

The exploitation of these two vulnerabilities was possible due to basic deficiencies that still exist and have been exploited since the beginnings of DeFi. These types of vulnerabilities should no longer have existed in 2021 because they were already well-known at the time, leaving some users suspicious about how they could have been integrated into the BurgerSwap SmartContract.

The exploitation of this type of vulnerability was simple and known. Protecting a DeFi project from this kind of vulnerability forms the basis of smart contracts security. Seeing projects still suffer attacks like this in 2021 tells us several things:

The Lack of In-Depth Audit

First off, many projects are not audited properly or at all. Some audit reports seem to be simple, automated code scans with no real added value and thus result in a false feeling of security for project creators and users.

But these ineffective audits are not the majority. Additionally, very often we find:

  • Smarts contracts without any audit
  • Smart contracts that have been excluded from the scope of the audit
  • Unaudited code updates

We can't emphasize it enough – Maintain a recurring audit process and test each piece of code before it goes into production. In decentralized finance, even the shortest line of vulnerable code can lead to a total loss of project tokens and the collapse of the project.

Fork Fast, Earn Quickly, Lose Everything

Secondly, there are many forks for different reasons. Sometimes teams simply take advantage of a new project to win quickly. At other times, a team prefers to start with an interesting base that they can modify and improve in their own way.

Unfortunately, whether the fork is greatly modified or not, developers often start from the forked base without checking it. Therefore, when the source project is compromised, attackers hunt down all related forks to exploit and steal funds from all projects containing the same weakness.

As we can see in Figure 2, the May event spike was due to a chain of exploits that targeted a vulnerability in a heavily forked contract. The BurgerSwap attack we reviewed earlier was a consequence of a bad fork, too.

But how fast can an attack spread from a core project to other forks? And how can we avoid this domino effect?

The story of PancakeBunny is a perfect example of why it is necessary to re-evaluate the security of a forked project.

On May 19, 2021, the DeFi project PancakeBunny suffered from price manipulation via a flash loan attack. This assault allowed the attacker to mine a large amount of $Bunny tokens and then immediately dump them, not only gaining profits, but also destroying the token price in the meantime.

A common use case for DeFi is earning rewards in exchange for providing tokens in a token pool made of paired LP tokens (tokens A and B). In the case of PancakeBunny, the project allowed its users to mortgage their LP pool tokens from PancakeSwap (a widely used decentralized exchange) in a vault in exchange for $BUNNY token rewards.

The getReward() function, which allowed the user to create and receive $BUNNY tokens based on the LP tokens mortgaged in the vault, also calculated the amount of the reward a user had earned. This $BUNNY amount was based on the number of LP tokens provided and the value of the A token used to make the LP. But on the occasion of the PancakeBunny scam, attackers used a flash loan and a large swap of token A to unbalance the pool for a moment, allowing the calculation to be distorted when calculating the reward.

Although exploiting such a vulnerability may seem painfully simple in retrospect, it did occur, with not-insignificant consequences. However, what is more notable were the events that followed this attack. A few days after the PancakeBunny hack, Autoshark and MerlinLabs, two forks of PancakeBunny, also suffered the same attack. Even though the teams from both projects were aware of having copied the PancakeBunny code with very few modifications, they nevertheless suffered the same attack five and seven days, respectively, after the initial project.

In other words, the forked codes were neither checked nor reviewed, and no action was taken following the hack of the main project. Some fork teams even reacted on social media following the PancakeBunny incident but still did not patch their own code, which inevitably led to further losses.

Of course, there are perfectly legitimate reasons to fork projects, and it is not up to us to judge a business’s reasons for forking; however, if a fork is considered necessary, then we strongly advise one thing:

Never trust the work of others – always review code before using it.


Frontend and Wallet Hacks

As we’ve seen, the greatest vector for DeFi attacks in 2021 was known vulnerabilities. Still, nearly 20% of hacks - -a significant number as well – came from negligence in the security of project architecture. Indeed, the need for security is not limited to SmartContracts. To be usable, these projects rely on websites, servers, and human operators. The compromise of any one of these elements can harm not only the security of the project, but also that of its users – and their wallets.

Compromise of User Wallets by Frontend Attack

Users are rarely aware of how SmartContracts work, nor are they able to read their source code. As a result, DeFi projects instead offer website interfaces, so users can connect to their digital wallet and use the service with ease. Unfortunately, this convenience also provides an additional layer – a front end – that can be vulnerable to attack.

As with all web applications, the compromise of a front end can create a risk for users. With DeFi, the risk is even greater, because before carrying out any actions (such as spending or sending tokens), approvals are required and are normally limited in the amount and the recipient address. The compromise of a front end can therefore lead a user to unknowingly giving authorization to a contract or malicious wallet that does not belong to the project.

For example, this scenario of a frontend attack actually occurred on December 2 for BadgerDAO.

Badger is a decentralized autonomous organization (DAO) powered by developers, DeFi strategists, and content creators. Through the BadgerDAO website and after connecting their digital wallet, users can bridge their bitcoins on different blockchains, invest in Badger strategies, or buy Badger products.

For BadgerDAO, the attackers had carefully prepared for months. They had exploited a CloudFlare vulnerability to obtain an API key and modified the front-end code discreetly. They had also made sure not to raise suspicion by targeting only wallets with a large balance and that were not owned by the project team.

As with any DeFi project offering a front end, users must approve SmartContract addresses before using them. Unfortunately, the user does not often take the time to verify the number of tokens authorized for the transaction or to verify the address of the SmartContract for which the approval is made. In the case of BadgerDAO, the attacker modified the website source code so that unaware users allowed the spending of a large number of tokens toward the address of the attacker (which they had previously injected into the front end).

Unlike previous vulnerabilities, it is difficult to blame BadgerDAO for negligence in the development of a SmartContract or in the verification of the work done on the blockchain side. This attack required more preparation and required several conditions to be carried out. Still, more mature operational security could surely have prevented such an event. But with DeFi being a new field with young teams, mature security is something quite rare, making this type of situation nearly inevitable. (To their credit, the BadgerDAO team reacted relatively quickly to stop the impacted vaults and limit the damages from this hack.

What we can learn from BadgerDAO, though, is the simple fact that all technical layers must be tested and secured in a DeFi project – SmartContracts, front ends, and servers supporting these applications. As the attack surface in DeFi projects is larger than usual, teams must ensure that adequate precautions are taken to protect all assets. With this in mind, we recommend the following steps to developers and users:

  • Carry out security assessments on all the elements supporting the project (developers)/Check the existence of audit reports on all elements (users).
  • Limit the number of tokens in approvals to what is strictly necessary (developers)/Control and modify the amount of approval requested, if necessary (users).
  • Always check the addresses of the contracts and wallets used by the application, as many projects have an official address list in their documentation. (everyone)

Host and Projects’ Wallet Hacks

As we saw before, it is rare for a DeFi project to use only SmartContracts to run its service. In addition, servers are often used for various reasons, such as:

  • Providing a web interface for users so that they don't have to know the source code to be able to use the proposed contracts
  • Performing statistical analyses
  • Automating actions to be carried out by shared or projects’ wallets
  • Data storage

However, a server is only one part of the greater DeFi service chain. There are a number of steps and mechanisms between a user's click and executing the code on the blockchain. The figure below shows a simplified chain of action from the user's browser to the execution of the request on the blockchain:

Graph showing a simplified chain of action from the user's browser to the execution of the request on the blockchain: Browser to Frontend to Servers to Smart Contracts to Nodes & EVM

Similar to attacking the front end to reach user wallets, attacking the underlying services or architecture can be an attractive target in an attempt to obtain private keys or privileged access to wallets or administration functions of SmartContracts.

In decentralized finance, money or tokens are stored on the blockchain and tied to addresses that are controlled by the keyholders of those addresses.

Different solutions, called wallets, make it possible to interact with the blockchain and thus execute transactions. The most common wallets solutions are software wallets that, after filling in a unique private key, allow the user to easily manipulate their tokens. Although very easy to use, this method can still have devastating repercussions if the private key is stolen. Alternatively, some customers choose a hardware wallet and protect the private key via a second cryptographic solution.

However, for a DeFi project with multiple actors and contributors and a lot of funds, these solutions are faulty at best. In both, a single attacker could compromise the entire project simply by stealing a private key. If you held enormous amounts of money, would you leave your account information or passwords (or private keys, in the context of DeFi) on a server accessible by everyone on the internet? [Good news – if you're here on our blog, then the answer is probably “no.”]

Still, according to post-mortem analyses and declarations, this is exactly what several projects in 2021 seem to have done.

This is the case, for example, of EasyFi and Bitmart.

In April 2021, EasyFi, a DeFi lending project, carried out transactions on an address owning $60M in tokens. This address was protected only by a unique private key that was stored without additional protection on a server in charge of operations. Of course, the server was compromised and the key, like the funds, was stolen. Or consider Bitmart on December 5, 2021, which was robbed of several wallets via private key theft. (The details of this attack were not communicated to the public in detail.) In both cases, financial loss could have been avoided by auditing the companies’ underlying servers and adding technical and organizational measures (such as multi-signature wallets) with zero trust and least privilege principles.

In other words, the security of a DeFi project requires considering the security of the project as a whole, not only that of the SmartContracts.

But are all of these attacks (many of which are simplistic and due to authors’ negligence) simply the effect of a system and technology that is still young and sometimes poorly mastered? Or are there darker reasons hiding behind these events?

It's time to address the infamous scams on monetized blockchains.

Rug Pull, Exit Scams, and Shady Behavior

A technology brewing so much money is ripe for invested, malicious people in search of quick profits. Beyond the technical security risks, DeFi must also deal with a flow of scams. Unlike a project suffering from an attack on one of its contracts, some losses are the direct action of the project’s team. These actions, such as rug pulls or exit scams, have the sole purpose of getting the investors' money and running away with it.

Rug Pulls and Exit Scams

Rug pulls are lucrative crypto-scams that take advantage of investors’ money. Fraudulent developers create a new crypto token, pump up the price, and then pull as much value out of these fake tokens as possible before dropping the value to zero and abandoning the project. The coup de grace of these scams is that through them, attackers can sometimes steal even more than just the money invested by users.

Likewise, exit scams involve creating a fake project using investor money, then disappearing with the funds without giving anything in return.

The latter is well-illustrated in the case of the StableMagnet project, which robbed its users for close to $30 million.

The owners of the project had planned the attack from the start by using contracts that they had backdoored, going so far as to have their source on GitHub audited by an outside company, and then deploying other contracts containing malicious code.

Once the users were baited and the money accumulated on their SmartContract, the StableMagnet owners simply had to empty the contract and leave with the cash register. Greedy for maximum profit, StableMagnet had also designed the contract to contain functions that stole tokens from users who approved transactions with their contract. In total, SmartMagnet’s scams allowed them to make off with almost $30 million in tokens.

Rug pulls and exit scams -- these two techniques allow attackers to achieve the sole goals of obtaining a quick profit under false identities and then disappearing into the shadows. But at the top of the pile of DeFi hacks, an even more vicious and deceitful category has started to emerge: shady behavior.

Shady Behavior

The plain truth is that all projects are susceptible to hacks. As it is often written, "Invest at your own risk." If your project works, grows, and then suffers a hack due to a sophisticated vulnerability, are you responsible? But while many errors may be excusable in the right context, we can all agree that intentional errors are indisputably the fault of the creator, who put them there knowingly and with a purpose. It is in these situations—when the sea of DeFi platforms becomes murky – that it becomes difficult to know whether the project team and the attacker are two separate groups at all, and if the vulnerabilities created are accidental or malicious.

For our part, we will not name specific projects here, because only the authorities (and the community) can perhaps, through research, have the final say on the dubious stories of DeFi projects gone wrong. However, we will say that any hack not followed by a detailed statement of the facts and the measures applied to prevent said hack is likely to be a disguise to steal the money. And very often, the community does not hesitate to make this known.

This is why transparency is an important component of DeFi projects. A hack is not always fatal, and errors are inevitable. We appreciate seeing that some projects have learned from their mistakes, corrected their problems, and gotten back on their feet. But a lack of explanation and transparency can quickly label a team as the source of an attack on their own project.


So – Is DeFi Really a Dangerous Battlefield?

To conclude, we can say without hesitation that DeFi is currently a tasty target that attracts thieves looking for big and fast gains. This observation is obvious given the youth of this technology and the fact that it’s all about the money. Would a non-monetized public blockchain that allows surveillance image management have the same attraction for these attackers? Probably not. It would undoubtedly be targeted by criminal groups seeking to falsify records and hide information, but it would have no financial lure, thus reducing the constant risk of a devastating attack from all angles.

Rare are the technological advances and developments that have never run into problems. In the same way that the first computers were networked without really considering the possibility of spreading a virus, DeFi developers tend to seek innovation in their algorithms more than protection. Though this often leads to errors of judgment that cause devastating damage for users, we can hope that they will diminish over time. After all, if the world had abandoned any discovery simply because of the risk, the advancement of new inventions and technology wouldn’t have been possible.

Rather than being afraid, ignoring the blockchain, or wanting to censor it, what can we do to protect DeFi users and projects without shutting down altogether?

Be control freaks.

It is better to be late, hesitant, and neurotic – to redo a test 3 times, for example –than to be overconfident and lose everything in the space of a few minutes. It is more than necessary to audit your entire ecosystem, share audit reports to obtain an outside point of view, and apply all the necessary corrective measures before launching a project. Users, check the security strategy of the projects in which you want to begin: once the money is lost, it’s too late.

Don't trust anyone.

Don't worry, we're not talking about becoming dissociative paranoids here. In cybersecurity, we must apply the principle of zero trust: you can trust a friend or a family member, but even if you can protect yourself, you can never be sure that your friend will not be vulnerable or compromised one day. It is deeply flawed for a critical system or a set of important data to align its security based solely on the possession of a private key. The greater the risk, the greater the need to add layers of security to prevent an attacker from achieving their goals. It must always be assumed that a key will be compromised eventually; therefore, it is up to you to make sure to limit the impact of that loss.

Only invest what you can lose.

And finally, we can never say it enough: do not invest the money you need to live. When we talk about DeFi, we are talking about investing in a fledgling financial system that has yet to learn from its mistakes. One day or another, you will inevitably be a victim of this system. Take a page from all our unlucky friends in 2021. Enjoy your travel from web2 to web3 but stay safe.

Subscribe to Bishop Fox's Security Blog

Be first to learn about latest tools, advisories, and findings.


Dylan Dubief BF

About the author, Dylan Dubief

Senior Security Consultant I

Dylan Dubief is a Senior Security Consultant at Bishop Fox. He holds a Master of Science in Computer Security and has spent his life looking for bugs everywhere. Prior to joining Bishop Fox, he spent years developing security assessment services in France providing a holistic view of security for his clients, from physical intrusion to human behavior. He particularly enjoys working on new subjects where the vulnerabilities lie in the very design of the technology.

More by Dylan

This site uses cookies to provide you with a great user experience. By continuing to use our website, you consent to the use of cookies. To find out more about the cookies we use, please see our Privacy Policy.