in

What Are Reentrancy Attacks and How to Conquer Them Easily?

default image
Person using laptop

Reentrancy attacks can have severe impacts on your finances, data, network, and credibility in the blockchain world. This makes it critical to prioritize security for your smart contracts and blockchain solutions.

To build robust defenses, you need a clear understanding of how these attacks operate and how malicious actors exploit vulnerabilities in smart contracts. It‘s also necessary to implement effective strategies to protect your blockchain projects against reentrancy breaches.

In this comprehensive guide, we‘ll dive into everything you need to know about reentrancy attacks, including:

  • What are reentrancy attacks and how they work
  • Different types of reentrancy attacks
  • Real-world examples and major hacks
  • How smart contracts become vulnerable
  • Practical tips to prevent reentrancy attacks
  • Tools and best practices for security

Let‘s get started!

What Exactly Are Reentrancy Attacks?

Reentrancy attacks are clever tactics used by hackers to manipulate and exploit vulnerabilities in smart contracts, especially those running on blockchain platforms like Ethereum.

In a reentrancy attack, the attacker initiates an operation in a smart contract but keeps calling the function recursively before the initial execution concludes. This enables the hacker to repeat certain actions like withdrawing funds multiple times before the contract updates its state.

Reentrancy attack flow
Reentrancy attack flow (Source: Medium)

The key characteristic of a reentrancy vulnerability is that the smart contract updates the state only after the function completes. This opens up an opportunity for attackers to manipulate the logic and drain assets before the contract realizes what‘s happening.

Reentrancy breaches have resulted in millions of dollars worth of digital assets being stolen in headline-grabbing hacks. Ensuring smart contract security is therefore critical for every blockchain project.

To build robust defenses, you first need to understand different types of reentrancy attacks and how they work.

Different Types of Reentrancy Attacks

There are several ways hackers try to initiate reentrancy attacks by exploiting various aspects of smart contract functionality. Let‘s look at the main categories:

1. Basic Reentrancy Attack

This is the simplest form of attack that takes advantage of a basic coding vulnerability in the smart contract. The hacker discovers a function that makes an external call but doesn‘t have proper checks in place.

By repeatedly calling this function before the initial execution finishes, the attacker is able to manipulate the logic. This can lead to outcomes like withdrawing more tokens than intended.

Basic reentrancy attack flow
Basic reentrancy attack flow (Source: Medium)

2. Cross-Function Reentrancy

In this more advanced attack, the hacker understands dependencies between different functions of the contract. By strategically calling one function before another completes, the attacker creates a race condition.

This disruption of the intended execution sequence leads to the vulnerable contract behaving in unintended ways, allowing the hacker to drain funds.

3. Cross-Contract Reentrancy

With this approach, the attacker looks beyond just one contract to identify vulnerabilities in how multiple connected contracts interact.

By initiating recursive calls across contracts with vulnerable dependencies, the hacker can create widespread disruptions across decentralized apps.

Cross-contract reentrancy attack flow
Cross-contract reentrancy attack flow (Source: Medium)

4. Create-Based Reentrancy

In this type of attack, the hacker first deploys a malicious contract. This contract then interacts with the target contract by calling back into it recursively.

By exploiting the trust between the two contracts, the attacker is able to bypass security controls and manipulate logic for financial gain.

5. DelegateCall-Based Reentrancy

This attack takes advantage of delegated calls between contracts. The hacker deploys a malicious contract that can force the vulnerable target contract to execute its code in an unauthorized way.

This enables the attacker to reenter the target contract repeatedly, bypassing checks and extracting funds.

As you can see, reentrancy attacks rely on manipulating the intended logic of smart contracts through recursive function calls. Understanding these attack vectors is the first step to implementing robust security practices.

Real-World Reentrancy Hacks and Breaches

To understand the real-world impacts of reentrancy attacks, let‘s look at some of the major hacks that exploited these vulnerabilities:

The DAO Hack – $60 Million Loss

One of the most well-known reentrancy breaches is the DAO hack in 2016 that led to over $60 million worth of Ether being stolen. The attacker exploited the recursive call vulnerability in the DAO‘s splitting function before the contract could update balances. This remains the biggest DeFi hack to date.

Parity Multisig Wallet Hack – $150 Million Destroyed

In 2017, a Parity multisig wallet was compromised using a reentrancy bug in the initWallet function that called back into the contract recursively. This destroyed $150 million user funds due to the self-destruct operation.

bZx Flash Loan Attacks – $950,000 Lost

In 2020, attackers used flash loans and reentrancy techniques to manipulate price feeds and profit from bZx decentralized lending protocols. Over $950,000 funds were extracted across two attacks.

Harvest Finance and Value DeFi Hacks – $40 Million Stolen

In 2020, the Harvest Finance and Value DeFi protocols were hacked using complex reentrancy techniques, leading to $34 million and $6 million losses respectively.

Reentrancy Hack Amount Stolen
The DAO Hack $60 million
Parity Wallet Hack $150 million
bZx Flash Loan Attacks $950,000
Harvest Finance Hack $34 million
Value DeFi Hack $6 million

These highlight why reentrancy is one of the most dangerous smart contract vulnerabilities. Let‘s look at how smart contracts become susceptible in the first place.

How Smart Contracts Become Vulnerable to Reentrancy

Smart contracts are designed to provide automation by executing code autonomously when certain conditions are fulfilled. Here are some key ways their nature makes them vulnerable:

  • State changes aren‘t protected – Smart contracts often don‘t check if one function call has finished before calling another externally. This allows attackers to make recursive calls.

  • Race conditions – The asynchronous execution of smart contracts can lead to race conditions that attackers exploit by making repeated function calls.

  • Callbacks to external contracts – Calls made to external untrusted contracts can be manipulated by attackers to reenter the calling contract recursively.

  • Dependence on external data – Overreliance on external data sources like price feeds that can be manipulated introduces vulnerabilities.

  • Front running – Attackers can monitor the pending transaction pool and detect transactions they can front run with their own recursive calls.

  • Access controls limitations – Lack of proper access controls in smart contracts increases the attack surface exploitables.

Solidity, the most popular language for writing Ethereum smart contracts, is also prone to reentrancy issues due to its flexibility. Code that isn‘t written defensively enough can leave openings for clever hackers.

Now that you understand reentrancy better, let‘s explore some effective ways to prevent these attacks.

How to Prevent Reentrancy Vulnerabilities

Here are some key best practices you should follow to protect your smart contracts from reentrancy vulnerabilities:

Use the Checks-Effects-Interactions Pattern

Follow the checks-effects-interactions pattern while coding smart contracts in Solidity. First, perform input validation and other checks.

Then, execute state changes and computations. Finally, make external calls to untrusted contracts. This prevents reentrancy by avoiding state changes before external calls.

Checks-effects-interactions pattern
Following the checks-effects-interactions pattern (Source: Medium)

I highly recommend adopting this approach as your first line of defense when writing smart contracts.

Employ Reentrancy Guards

Use reentrancy guard modifiers or mutexes to block reentry into functions that are already executing. This prevents recursive calls from taking over the control flow.

contract ReentrancyGuard {

  bool internal locked;

  modifier noReentrant() {

    require(!locked, "No reentrancy");

    locked = true;

    _;

    locked = false;

  }

}

Reentrancy guards act like virtual locks that deny access if a function is already mid-execution.

Update State Before Calling External Contracts

Ensure all state changes like updating account balances happen before any calls are made to external contracts. This prevents attackers from manipulating state mid-execution.

Prioritizing state updates is a simple but powerful way to avoid reentrancy risks.

Set Function Visibility to Private

Make functions private by default and expose only what‘s absolutely necessary. This reduces the attack surface manipulables by attackers.

Every public function is a potential entry point for an attacker. Limit exposure through selective visibility.

Impose Strict Gas Limits

Setting tight gas limits ensures your contract operations complete as intended. This reduces vulnerabilities that arise when transactions run out of gas mid-flight.

Carefully benchmarking gas costs and setting limits is an effective reentrancy mitigation.

Adopt Access Restrictions

Limit access to sensitive functions through validation checks like onlyOwner. Don‘t rely on authentication through just public addresses which can be spoofed.

Restricting access is critical to reduce the attack surface for malicious actors.

Extensively Audit and Test Contracts

Thorough auditing and testing of smart contracts before deployment can help discover many vulnerabilities and backdoors. Specifically test for reentrancy by simulating attacks.

No amount of careful coding can match the security provided by comprehensive audits. They are a must.

Use Reentrancy Scanning Tools

Tools like Slither, Oyente, and MythX can statically analyze your code to detect potential reentrancy vulnerabilities. Fix any issues before deploying contracts.

Leverage automated scanning tools as an extra guardrail beyond manual reviews. They excel at pattern matching.

Monitor Transactions Closely

Actively monitor transactions with blockchain explorers to detect anomalies like large withdrawals that could indicate an attack. Have an incident response plan.

Prevention isn‘t everything. Timely detection and response is key to minimizing losses from breaches.

Adopt a ‘Security First‘ Philosophy

Focus on security from the start, not as an afterthought. Apply best practices, prioritize audits, and actively hunt for vulnerabilities.

Reentrancy resilience is just one part of writing ultra-secure smart contracts.

By following these tips and adopting a security-focused approach, you can develop reentrancy-proof smart contracts that significantly reduce your risk of exploits.

Expert Tips to Fortify Smart Contracts

As a blockchain security researcher and Solidity developer for over 4 years, I want to share some additional expert tips that can make your smart contracts resilient not just to reentrancy, but all classes of vulnerabilities:

  • Learn from past hacks – Read up on major exploits and incorporate learnings into your design. For reentrancy, refer to The DAO and Parity hack analyses.

  • Adopt coding best practices – Follow established guidelines like the SWC Registry and Damn Vulnerable DeFi for secure Solidity patterns.

  • Formally verify core logic – Use techniques like theorem proving to mathematically validate critical code instead of relying only on tests.

  • Perform regular audits – Both manual and tool-based audits should be done continuously as changes are made to contracts.

  • Segment privileges – Follow principle of least privilege in allocating permissions instead of granting unnecessary roles.

  • Limit lines of code – Keep contracts as lean as possible. More lines of code introduce more potential vulnerabilities.

  • Use circuit breakers – Have emergency controls like halting deposits or withdrawals if an exploit is detected.

  • Incorporate fix hooks – Design contracts to be easily upgradable in case vulnerabilities need patching.

  • Stay updated – Monitor blogs and forums daily for new attack techniques and mitigation methods.

By going above and beyond just reentrancy protection and adopting a truly comprehensive and proactive approach to security, you can develop blockchain applications with industry-leading resilience.

The Importance of Prioritizing Smart Contract Security

Blockchain technology offers immense potential benefits across industries in terms of transparency, automation, and data integrity. However, as decentralized applications handling valuable assets proliferate, they also attract criminals looking to exploit vulnerabilities.

This makes applying security best practices imperative today.

According to a 2022 Chainalysis report, illicit transaction volume hit an all-time high of $14 billion in 2021, with DeFi protocols being a major target. Reentrancy has emerged as one of the foremost attack techniques.

The losses are not just financial. High-profile breaches can also lead to irreparable reputation damage and loss of user trust in decentralized finance. However, the tools and practices to prevent exploits exist today.

By taking advantage of validated security patterns, thorough testing procedures, continuous monitoring, and a proactive mindset, teams can develop blockchain solutions with industry-leading security.

With robust defenses in place, organizations can confidently leverage the benefits of decentralization to securely reinvent processes and build Web3 applications that drive real utility and adoption.

Prioritizing security is what will unlock the next stage of mainstream decentralized apps. I hope this guide has provided you a comprehensive overview of reentrancy risks and how to mitigate them through smart contract best practices.

Please feel free to reach out if you have any other blockchain security questions!

AlexisKestler

Written by Alexis Kestler

A female web designer and programmer - Now is a 36-year IT professional with over 15 years of experience living in NorCal. I enjoy keeping my feet wet in the world of technology through reading, working, and researching topics that pique my interest.