📈 Get daily crypto insights that make you smarter about your money

Advanced Smart Contract Auditing: Detecting and Preventing Reentrancy Attacks

The October 7, 2023 exploit of Stars Arena, where a reentrancy vulnerability in an Avalanche C-Chain smart contract resulted in the loss of 266,103 AVAX tokens worth approximately $2.88 million, demonstrates why advanced smart contract auditing skills are essential for any serious DeFi developer or security researcher. This tutorial provides a technical walkthrough of how reentrancy attacks work, how to detect them during code review, and how to implement robust defenses in your own smart contracts.

The Objective

This tutorial aims to equip experienced developers and security auditors with the knowledge and techniques needed to identify reentrancy vulnerabilities in Solidity smart contracts. By the end of this walkthrough, you will understand the mechanics of reentrancy at the EVM level, be able to recognize vulnerable code patterns during manual review, know how to use automated tools to detect these vulnerabilities, and be able to implement proper defenses including the Checks-Effects-Interactions pattern and reentrancy guards.

Prerequisites

This advanced tutorial assumes you have a working knowledge of Solidity, the Ethereum Virtual Machine, and basic smart contract development. You should be familiar with concepts such as function visibility modifiers, ether transfer methods including call, send, and transfer, and the execution model of the EVM including the call stack and gas mechanics. Access to a development environment with Foundry or Hardhat installed is recommended for following along with the code examples.

Understanding the specific Stars Arena attack provides helpful context. The attacker exploited a callback mechanism in the deposit function that allowed them to re-enter the contract and modify a pricing variable before the deposit completed. When the sellShares function later read this modified variable, it calculated a drastically inflated payout, enabling the attacker to extract 266,103 AVAX from a deposit of just 1 AVAX.

Step-by-Step Walkthrough

Step one involves understanding the EVM execution model that makes reentrancy possible. When a smart contract makes an external call to another address, whether to transfer ether or invoke a function on another contract, the EVM creates a new execution context for the called address. If the called address is a contract, its fallback or receive function is invoked. This is where reentrancy occurs: the called contract can call back into the original contract before the first function has finished executing, potentially modifying state in unexpected ways.

Step two is learning to identify the vulnerable pattern. A contract is vulnerable to reentrancy when it makes an external call before updating its internal state. Consider a simplified version of the vulnerable Stars Arena pattern: a deposit function that transfers AVAX to the user via a low-level call before updating the user balance. If the receiving address is a malicious contract, its receive function can call back into the deposit function, which will execute again with the old balance state, allowing repeated withdrawals.

The critical code pattern to look for during audits is any function that follows an Interactions-Effects-Checks order rather than the safe Checks-Effects-Interactions order. Specifically, watch for low-level call operations that transfer value to user-controlled addresses before state variables are updated. The call function is particularly dangerous because it forwards all remaining gas, giving the receiving contract ample gas to execute a reentrancy attack.

Step three involves using automated analysis tools. Slither, a static analysis framework for Solidity, can detect many reentrancy patterns automatically. Running Slither against a codebase with the command slither path/to/contracts will flag potential reentrancy vulnerabilities along with their severity. Mythril, a symbolic execution tool, takes analysis further by exploring possible execution paths to find reentrancy vectors that static analysis might miss. For comprehensive coverage, combine static analysis with dynamic testing using Foundry fuzz tests that specifically target state inconsistency during reentrant calls.

Step four is implementing proper defenses. The primary defense is the Checks-Effects-Interactions pattern, which ensures that all condition checks are performed first, all state modifications are made second, and all external interactions happen last. This ensures that by the time an external call is made, the contract state already reflects the effects of the current operation, preventing a reentrant call from exploiting stale state.

The secondary defense is a reentrancy guard modifier that prevents reentrant calls entirely. OpenZeppelin provides a battle-tested ReentrancyGuard implementation that uses a status variable to track whether a function is currently executing. When the modifier is applied to a function, any attempt to re-enter that function before the initial call completes will revert, preventing the attack vector entirely.

Troubleshooting

When auditing contracts, be aware that reentrancy can occur in forms beyond the classic single-function pattern. Cross-function reentrancy involves a callback from one function calling a different function in the same contract that shares state with the first function. Cross-contract reentrancy extends this across multiple contracts that interact with shared state. Read-only reentrancy, where a view function returns stale data during an ongoing state modification, can be particularly difficult to detect because the vulnerable function does not itself modify state.

For unverified contracts like the Stars Arena proxy, use decompilation tools such as Dedaub or Panoramix to recover approximate source code from the deployed bytecode. While decompiled code is not identical to the original source, it reveals the control flow and state interactions needed to identify vulnerability patterns. Pay special attention to functions that use low-level calls with the value parameter, as these represent the primary reentrancy surface.

Also note that ERC-777 and ERC-1155 token standards introduce additional reentrancy vectors through their hook mechanisms, which automatically call recipient contracts during token transfers. When auditing contracts that interact with these token standards, treat every token transfer as a potential reentrancy point even if the contract does not explicitly make low-level calls.

Mastering the Skill

To develop expertise in reentrancy detection, practice auditing real-world exploits retrospectively. Review post-mortem analyses of major reentrancy attacks including the DAO hack of 2016, the Vyper reentrancy incidents of July 2023, and the Stars Arena exploit. For each incident, examine the vulnerable code, trace the attack flow, and verify that you can identify the vulnerability pattern from the code alone before reading the exploit description.

Participate in audit competitions on platforms like Code4rena, Sherlock, and Cantina, where you can test your skills against real DeFi protocols and earn bounties for finding vulnerabilities. These platforms provide an excellent training ground because they expose you to a wide variety of code patterns and vulnerability classes in production-grade contracts.

Finally, build and maintain a personal checklist of reentrancy patterns to look for during audits. This checklist should cover classic single-function reentrancy, cross-function reentrancy, cross-contract reentrancy, read-only reentrancy, ERC-777 and ERC-1155 hook reentrancy, and any new patterns that emerge as the EVM and Solidity continue to evolve. The security landscape is constantly changing, and the most effective auditors are those who continuously update their knowledge and techniques.

Disclaimer: This tutorial is for educational purposes only. Always engage professional security auditors before deploying smart contracts that handle real user funds.

🌱 FOR BUSINESSES BitcoinsNews.com
Reach 100K+ Crypto Readers
Sponsored content, press releases, banner ads, and newsletter placements. Put your brand in front of Bitcoin's most engaged audience.

13 thoughts on “Advanced Smart Contract Auditing: Detecting and Preventing Reentrancy Attacks”

  1. 266,103 AVAX gone because nobody ran a static analysis tool. Slither would have caught this in 30 seconds. Solid technical breakdown though, the EVM-level explanation of the call stack is spot on.

    1. slither catches the obvious ones but the tricky reentrancy is in the cross-function stuff. static analysis misses those more often than people think

      1. yolotrade cross-function reentrancy is exactly what slipped past audits on the old ERC-20 implementations. static analysis catches patterns, not logic errors

        1. cross-function reentrancy is where formal verification earns its keep. slither and mythril both missed the one on the old erc-677 implementation back in the day

  2. the Checks-Effects-Interactions pattern should be day one material for any Solidity dev. good to see it laid out this clearly with actual exploit context

  3. $2.88M lost on an AVAX contract that probably had less than 100 lines of actual logic. complexity isnt what kills you, its the basic stuff you gloss over

    1. 100 lines is generous. the vulnerable function was probably 15 lines. nobody reviewed it because the UI looked fine

    2. fewer than 100 lines and $2.88m gone. the stars arena dev literally pushed to mainnet with no external audit. at some point you cant blame the tools

      1. debug_me nailed it. 100 lines of logic and nobody thought to pay for a review. the cost of the audit was probably 1% of what they lost

  4. Stars Arena was live for like 6 weeks before someone found the reentrancy. at that point just use a multisig instead of a custom contract

  5. 2.88M on an AVAX contract. Stars Arena was barely 3 months old. ship fast break things culture meets real money and the result is always the same

    1. ship fast break things works for social apps, not for contracts holding millions. the culture clash between web2 and web3 dev mindset is expensive

Leave a Comment

Your email address will not be published. Required fields are marked *

BTC$62,406.00-3.9%ETH$1,658.95-5.4%SOL$69.04-6.1%BNB$573.32-4.1%XRP$1.10-3.9%ADA$0.1509-5.5%DOGE$0.0789-6.1%DOT$0.9005-6.7%AVAX$6.33+0.1%LINK$7.60-5.2%UNI$2.90-5.9%ATOM$1.74-4.4%LTC$42.44-6.1%ARB$0.0790-7.5%NEAR$1.99-6.6%FIL$0.7696-4.6%SUI$0.7035-3.2%BTC$62,406.00-3.9%ETH$1,658.95-5.4%SOL$69.04-6.1%BNB$573.32-4.1%XRP$1.10-3.9%ADA$0.1509-5.5%DOGE$0.0789-6.1%DOT$0.9005-6.7%AVAX$6.33+0.1%LINK$7.60-5.2%UNI$2.90-5.9%ATOM$1.74-4.4%LTC$42.44-6.1%ARB$0.0790-7.5%NEAR$1.99-6.6%FIL$0.7696-4.6%SUI$0.7035-3.2%
Scroll to Top