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

Anatomy of a Reentrancy Attack: Advanced Smart Contract Auditing Techniques After the Penpie Exploit

The $27 million Penpie exploit on September 3, 2024, provided the DeFi community with yet another textbook example of one of the oldest smart contract vulnerabilities in existence: reentrancy. Despite being documented since the infamous 2016 DAO hack on Ethereum, reentrancy attacks continue to plague the ecosystem. This advanced tutorial dissects the Penpie attack mechanics and walks through professional auditing techniques that can identify and prevent these vulnerabilities before they reach production.

The Objective

This guide aims to equip experienced Solidity developers and security auditors with a systematic methodology for identifying reentrancy vulnerabilities in complex DeFi protocols. By the end, you will understand how the Penpie attacker combined reentrancy with permissionless market registration and flash loans to drain $27 million, and you will have practical tools to catch similar vulnerabilities in your own code reviews.

Prerequisites

This tutorial assumes familiarity with Solidity, the EVM execution model, and basic DeFi concepts. You should understand how ERC-20 token transfers work, what a flash loan is, and how yield farming protocols distribute rewards. Tools you will need: Foundry or Hardhat for local testing, Slither for static analysis, and access to a block explorer like Etherscan for transaction analysis.

Step-by-Step Walkthrough

Step 1: Understanding the Vulnerable Pattern. The Penpie exploit centered on the _harvestBatchMarketRewards() function in the PendleStakingBaseUpg contract. This function calculated staking rewards by measuring token balances before and after calling redeemRewards() on an external contract. The critical flaw: no reentrancy guard protected this function, allowing the attacker to re-enter during the external call.

The attack pattern follows a specific sequence. First, the attacker deploys a malicious SY contract that implements a callback in its redeemRewards() function. When Penpie’s contract calls this function, the malicious contract calls back into _harvestBatchMarketRewards() before the original invocation completes its state updates. This allows the attacker to claim rewards multiple times with the same deposit.

Step 2: Identifying the Attack Surface. The second critical vulnerability was permissionless market registration. Penpie’s PendleStakingBaseUpg contract allowed anyone to register new markets without validation. The attacker registered a malicious market tied to their fake SY token, which then became part of the reward distribution system. Auditing for this involves checking all external-facing registration functions and verifying they include proper validation and access controls.

Step 3: Analyzing the Flash Loan Component. The attacker used flash loans to borrow massive amounts of wstETH, sUSDe, egETH, and rswETH. These borrowed funds were deposited into the malicious SY contract during the reentrancy window, artificially inflating the token balance measured by _harvestBatchMarketRewards(). The inflated balance generated exaggerated reward claims, which the attacker then withdrew and used to repay the flash loans, pocketing the difference.

To detect flash loan amplification risks in your audits, trace all paths where external token amounts influence reward calculations. If a function measures balanceOf(this) before and after an external call, it is inherently vulnerable to balance manipulation via flash loans during the reentrancy window.

Step 4: Static Analysis with Slither. Run Slither on the target contract with the reentrancy detector: slither . --detect reentrancy. Slither identifies functions that make external calls before updating state variables. For the Penpie contract, this would have flagged _harvestBatchMarketRewards() immediately. However, static analysis has limitations — it produces false positives and can miss complex cross-contract reentrancy paths.

Step 5: Dynamic Testing with Foundry. Write a Foundry test that simulates the attack. Create a malicious contract that implements redeemRewards() with a callback to _harvestBatchMarketRewards(). Fund it with flash-loaned tokens and verify that the reward balance increases beyond what the deposit justifies. This confirms the vulnerability and quantifies the potential loss.

Step 6: Implementing the Fix. The standard remedy is to add a reentrancy guard. Using OpenZeppelin’s ReentrancyGuard modifier ensures that the function cannot be re-entered while still executing. For higher assurance, refactor the function to follow the checks-effects-interactions pattern: update all state variables before making any external calls.

Troubleshooting

Cross-contract reentrancy is harder to detect than single-contract reentrancy because the re-entry path spans multiple contracts. Use Foundry’s cheatcodes to trace all external calls during a test transaction. If an external call goes to a contract you control in testing, you have a reentrancy vector.

Another common issue is developers assuming that ERC-20 tokens are safe to call without reentrancy concerns. Some tokens implement hooks (like ERC-777) that invoke callbacks on transfers, creating reentrancy paths even in functions that only transfer tokens. Always assume external calls can re-enter.

Mastering the Skill

To go beyond basic reentrancy detection, study formal verification tools like Certora Prover and Halmos. These tools mathematically prove properties about smart contracts, catching vulnerabilities that manual audits and static analysis miss. Follow real-world exploits on platforms like Rekt News and ImmuneBytes, and reconstruct each attack in a local Foundry environment. The September 2024 DeFi hacks, with over $120 million lost, provide ample case studies. The skill that separates good auditors from great ones is the ability to think like an attacker — to see not just what the code does, but what it allows someone to do.

Disclaimer: This article is for educational purposes only. The techniques described are intended for legitimate security auditing and should not be used to exploit vulnerabilities in live protocols.

🌱 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.

9 thoughts on “Anatomy of a Reentrancy Attack: Advanced Smart Contract Auditing Techniques After the Penpie Exploit”

  1. reentrancy in 2024 is wild. how do you ship a defi protocol without a reentrancy guard on withdraw functions at this point

    1. flash_loan_detective

      solmaxi_v2 they probably had a reentrancy guard but only on the functions they audited. permissionless market registration creates a new entry point that wasnt in the original threat model

    1. the flash loan combo with permissionless registration was the real innovation here. most audits check for basic reentrancy but miss the composability angle

      1. the composability angle is what most solo auditors miss. you can have every function individually secured but the interaction between flash loan + permissionless registration + reentrancy creates a vulnerability that only shows up in integration testing

    2. wei c is spot on, audit culture is broken. but the real question is why penpie didnt have a bug bounty proportional to their tvl

      1. Ana G. because bug bounties on DeFi protocols are usually capped at like $50k when the TVL is $200M+. the math doesnt work for white hats

  2. stack_too_deep_

    Penpie lost 27M to the same bug class that killed the DAO in 2016. we have formal verification tools now and teams still ship reentrant code

  3. the flash loan plus permissionless market registration combo was brutal. you can audit the reentrancy guard in isolation and it passes. the vulnerability only surfaces when both features interact

Leave a Comment

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

BTC$64,632.00+1.1%ETH$1,744.86+1.3%SOL$73.46-0.6%BNB$596.24+1.2%XRP$1.14+0.2%ADA$0.1598-0.8%DOGE$0.0833+0.2%DOT$0.9553-0.4%AVAX$6.32+1.3%LINK$7.96+0.7%UNI$3.04+0.6%ATOM$1.80+1.9%LTC$44.93-0.4%ARB$0.0849+1.8%NEAR$2.13-1.3%FIL$0.8035+0.2%SUI$0.7232+2.3%BTC$64,632.00+1.1%ETH$1,744.86+1.3%SOL$73.46-0.6%BNB$596.24+1.2%XRP$1.14+0.2%ADA$0.1598-0.8%DOGE$0.0833+0.2%DOT$0.9553-0.4%AVAX$6.32+1.3%LINK$7.96+0.7%UNI$3.04+0.6%ATOM$1.80+1.9%LTC$44.93-0.4%ARB$0.0849+1.8%NEAR$2.13-1.3%FIL$0.8035+0.2%SUI$0.7232+2.3%
Scroll to Top