Use Your Spell Against You: Threat Prevention of Smart Contract Exploit By Reusing Opcode Trace

Unknown

Black Hat USA 2024 · Day 1 · Briefing

Overview

Decentralized Finance (DeFi) platforms have become a prime target for malicious actors, with billions of dollars lost annually due to sophisticated exploits. Despite advancements in pre-launch security measures like auditing and formal verification, zero-day vulnerabilities and complex inter-protocol dependencies continue to leave DeFi protocols exposed. This talk, presented by Andy, CEO of Blocksec and a university professor, introduces a novel and proactive approach to combat DeFi hacks after a vulnerability has been identified and an attack transaction broadcast, but before it is confirmed on the blockchain.

Watch on YouTube

Visual summary for Use Your Spell Against You: Threat Prevention of Smart Contract Exploit By Reusing Opcode Trace by Unknown
Visual summary for Use Your Spell Against You: Threat Prevention of Smart Contract Exploit By Reusing Opcode Trace by Unknown

Key moments

  1. 0:38 The growing problem of DeFi hacks
  2. 2:00 Six reasons why DeFi hacks are prevalent
  3. 6:20 Why pre-launch security methods are insufficient
  4. 6:50 Need for post-launch detection and blocking
  5. 8:00 Detecting and blocking attacks in the mempool

Use Your Spell Against You: Threat Prevention of Smart Contract Exploit By Reusing Opcode Trace

Speakers: Andy, CEO of Blocksec, Professor at University

Conference: Black Hat USA

YouTube: https://www.youtube.com/watch?v=Gqxc9zf0OZY

Overview

Decentralized Finance (DeFi) platforms have become a prime target for malicious actors, with billions of dollars lost annually due to sophisticated exploits. Despite advancements in pre-launch security measures like auditing and formal verification, zero-day vulnerabilities and complex inter-protocol dependencies continue to leave DeFi protocols exposed. This talk, presented by Andy, CEO of Blocksec and a university professor, introduces a novel and proactive approach to combat DeFi hacks after a vulnerability has been identified and an attack transaction broadcast, but before it is confirmed on the blockchain.

The core of Andy's presentation revolves around an innovative technique that intercepts pending attack transactions in the blockchain's mempool, analyzes their malicious intent by simulating their execution and extracting their opcode trace, and then automatically synthesizes a rescue transaction. This rescue transaction mirrors the attacker's logic but redirects the illicit profits to a secure, white-hat address. By leveraging sophisticated gas bidding strategies, Blocksec aims to ensure their rescue transaction is confirmed ahead of the attacker's, effectively neutralizing the exploit and salvaging assets. This "post-launch" security paradigm represents a significant shift from reactive incident response to proactive threat prevention, offering a critical layer of defense for the vulnerable DeFi ecosystem.

Background

▶ Watch: The growing problem of DeFi hacks (0:38)

The prevalence of security incidents in Web3, particularly within the DeFi sector, is a growing concern, with losses due to hacks reaching billions of US dollars annually. Andy attributes this alarming trend to several interconnected factors that create a uniquely fertile ground for exploitation:

  1. Economic Incentive: Unlike traditional cybercrime where attackers might sell data or deploy ransomware, DeFi hackers directly acquire cryptocurrencies, which are easily convertible into fiat currency. This direct and liquid financial incentive fuels a relentless pursuit of vulnerabilities.
  2. Lack of Qualified Developers: The development of secure DeFi protocols demands a rare blend of expertise spanning security, finance, and mathematics. Many developers prioritize functionality over robust security, contributing to a scarcity of truly secure implementations.
  3. DeFi Composability and Attack Surfaces: DeFi protocols are often built upon a complex ecosystem of interdependent smart contracts. Even a meticulously secured protocol can become vulnerable if one of its dependencies, such as a price oracle, is compromised. This intricate interoperability exponentially expands the potential attack surface.
  4. Openness and Accessibility: The open-source nature of most smart contracts on the blockchain means anyone can scrutinize the code for vulnerabilities. Furthermore, unlike traditional banking systems that require physical or network access for exploitation, DeFi protocols can be interacted with by anyone via transaction broadcasts, making exploitation highly accessible.
  5. Anonymity: The pseudonymous nature of blockchain transactions makes tracing and identifying attackers exceptionally challenging. If hackers meticulously obscure their fund flows, recovery and accountability become nearly impossible.
  6. Flash Loans: A critical enabler for large-scale DeFi exploits, flash loans allow attackers to borrow vast sums of cryptocurrency (e.g., millions of USD) without collateral, provided the loan is repaid within the same transaction block. This mechanism significantly lowers the barrier to entry for executing high-value attacks, as attackers no longer need substantial capital to initiate an exploit.

Traditional security approaches, categorized as "pre-launch" methods, include security auditing, fuzz testing, and formal verification. While crucial for identifying and mitigating vulnerabilities before deployment, these methods are not foolproof. They cannot guarantee the discovery of all zero-day vulnerabilities, nor can they fully account for risks arising from external dependencies or complex interactions between protocols. This inherent limitation underscores the urgent need for "post-launch" security measures that can detect and block attacks after a protocol is live on the blockchain.

A typical DeFi hack unfolds in several stages:

  1. Preparation: The attacker acquires initial seed funds.
  2. Attack Contract Creation: A malicious smart contract is deployed to orchestrate the exploit.
  3. Exploit Execution: The attack contract interacts with the vulnerable DeFi protocol, often leveraging flash loans to amplify the impact.
  4. Profit Laundering: The stolen assets are moved through various addresses and services to obscure their origin and make tracing difficult.

The solution proposed by Andy and Blocksec specifically targets the window between the broadcast of an attack transaction and its confirmation on the blockchain, aiming to detect and block the exploit before it can inflict damage.

Key Findings

▶ Watch: Six reasons why DeFi hacks are prevalent (2:00)

The central discovery and contribution presented in this talk is a novel, automated system for proactive threat prevention in DeFi by intercepting and neutralizing pending attack transactions. The system operates on the principle of "using the attacker's spell against them" by leveraging the very opcode trace of a malicious transaction to construct a defensive counter-attack.

The key findings and contributions are:

  1. Mempool-Based Proactive Defense: The system establishes a real-time monitoring capability for the blockchain's mempool, enabling the detection of malicious transactions before they are confirmed. This shifts the security paradigm from reactive incident response to pre-emptive blocking.
  2. Automated Attack Logic Extraction and Synthesis: The system can automatically extract the core attack logic from a pending malicious transaction. Crucially, it then synthesizes a new smart contract that replicates this logic but replaces the attacker's revenue addresses with a designated white-hat address. This allows the system to effectively "hijack" the exploit.
  3. Asset Rescue via Gas Bidding: By broadcasting this synthesized rescue transaction to the mempool with an optimized gas bidding strategy, the system aims to ensure its transaction is confirmed in an earlier block than the original malicious transaction, thereby rescuing the vulnerable assets.
  4. Demonstrated Efficacy: Blocksec has successfully applied this technique, reporting the rescue of over 20 million USD from various DeFi exploits. This practical success underscores the viability and impact of their approach.
  5. Commercialization: The technology has been commercialized and integrated into Blocksec's security product, Falcon, making it accessible for broader application within the DeFi ecosystem.
  6. Addressing Attacker Evasion: The system incorporates solutions for key attacker evasion techniques, such as bypassing verification logic within attacker contracts (e.g., msg.sender checks) by intelligently manipulating execution flow, and iteratively identifying and replacing profit addresses.

This approach offers a powerful new tool in the ongoing battle against DeFi hacks, providing a crucial "last line of defense" that can mitigate significant financial losses even when pre-launch security measures have failed.

Technical Deep Dive

▶ Watch: Why pre-launch security methods are insufficient (6:20)

The technical methodology presented by Andy is a sophisticated multi-stage process designed to detect, analyze, and neutralize pending DeFi exploits. It leverages deep understanding of blockchain transaction processing and smart contract execution.

The overall process can be broken down into these steps:

  1. Mempool Monitoring: The system continuously listens to the Ethereum mempool (or BSC network's equivalent), which is a public pool of pending transactions that have been broadcast but not yet confirmed by a validator. This "time window" between broadcasting (T1) and confirmation (T3) is critical, typically 12 seconds on Ethereum and 2-3 seconds on BSC.
  2. Transaction Simulation and Trace Generation: Upon detecting a new pending transaction, the system immediately simulates its execution. This simulation generates a detailed opcode trace (similar to a program trace in traditional security, linking basic blocks), which captures every operation performed by the smart contract during its execution.
  3. Profit Analysis and Malicious Intent Detection: From the opcode trace, the system analyzes the financial impact of the transaction. It calculates the profit accrued by various addresses involved. If a transaction results in significant, unauthorized profit for an unknown or suspicious address, it is flagged as a potential hack. This involves building a balance change table to track which addresses gain or lose assets.
  4. Rescue Smart Contract Construction (Synthesis): This is the core innovation. Once a malicious transaction is identified, the system automatically constructs a new smart contract. This new contract is a modified version of the attacker's original malicious contract. The key modification is that the revenue addresses (the hacker's addresses intended to receive the stolen funds) are replaced with the defender's own secure address. The goal is to replicate the attack's logic but redirect the profit.
  5. Broadcasting Rescue Transaction and Gas Bidding: The newly synthesized rescue transaction, designed to execute the exploit but redirect funds, is then immediately broadcast back into the mempool. To ensure its confirmation before the attacker's transaction, the system employs gas bidding strategies. This involves dynamically setting a higher gas price for the rescue transaction, incentivizing validators to include it in an earlier block.

Andy highlighted several significant technical challenges and their proposed solutions:

Challenge 1: Extracting Attack Logic and Bypassing Verification

Attackers often include verification logic within their smart contracts to ensure that the malicious functions can only be invoked by their own specific addresses (e.g., using msg.sender checks). If the rescue transaction were to simply re-execute the attacker's contract as a different sender, these checks would cause the transaction to revert.

  • Solution: Freezing Conditional Jumps: To bypass such verification logic, the system employs a technique called freezing conditional jumps. During the simulation and synthesis phase, the system identifies conditional jump instructions (JUMPI) that might prevent the attack logic from executing if the msg.sender or other conditions are not met. By "freezing" these jumps, the system can force the execution path to follow the malicious logic, effectively ignoring the attacker's verification checks and ensuring the exploit path is taken, regardless of the calling address. This allows the rescue contract to execute the attack even when invoked by a different (white-hat) address.

Challenge 2: Locating and Replacing Revenue Addresses

Accurately identifying all the specific addresses that will receive illicit profit from the hack is crucial for successful asset redirection. Attackers might use multiple addresses or complex internal transfers.

  • Solution: Balance Change Table and Iterative Replacement: The system addresses this by building a balance change table during the initial simulation phase. This table comprehensively tracks which addresses experience a net positive balance change (i.e., receive profit) as a result of the transaction. Once potential revenue addresses are identified, the system iteratively replaces these addresses within the synthesized contract with the white-hat address. After each replacement, the system re-simulates the transaction. If the re-simulation results in an error or a revert (meaning the replacement was incorrect or incomplete), it indicates that not all revenue addresses were correctly identified or replaced. This iterative process continues until the synthesized transaction executes successfully without errors and the profit is redirected to the defender's address.

Challenge 3: Handling Multiple-Transaction Attacks

Sophisticated attackers may split their exploits across multiple transactions. For example, they might first deploy a malicious contract, then deposit tokens into it, and finally invoke a function to trigger the hack. This mirrors complex exploit chains in traditional systems (e.g., multiple system calls to exploit a kernel vulnerability).

  • Solution: While Andy acknowledges this challenge, the talk does not go into specific technical details on how Blocksec's system fully addresses complex multi-transaction attack sequences within the mempool. It implies that the system aims to detect and block the final transaction that triggers the primary exploit and profit transfer, but the exact mechanism for correlating and anticipating multi-stage attacks is not elaborated upon in the provided transcript. The general approach would likely involve monitoring the state changes caused by preceding transactions and understanding their dependency on the final attack transaction.

Overhead and Private Mempools

During the Q&A, Andy addressed concerns about the system's overhead and the challenge of private mempools:

  • Overhead: The detection process is reported to take approximately 25 milliseconds. This speed is deemed sufficient for Ethereum (with a 12-second block time) and BSC (with 2-3 seconds block time). For blockchains with faster block times and no public mempool, the system's current design may not be applicable.
  • Private Mempools: Attackers increasingly use private mempools (e.g., via MEV-boost relays) to submit transactions directly to block builders, bypassing public monitoring. Andy outlined two strategies to counter this:
  1. Collaboration with Builders/Relayers: Blocksec seeks collaboration with block builders and relayers on Ethereum. These entities have compliance concerns and may be willing to exclude known malicious transactions from their blocks, providing an avenue to prevent private mempool attacks.
  2. Post-Confirmation Prevention of Further Hacks: If a private mempool attack is successfully executed and confirmed, the system can still identify the exploit on-chain. While the initial hack cannot be prevented, the system can then use its methodology to prevent further similar attack transactions from being executed against the same or similar vulnerabilities.

The overall technical architecture represents a robust, real-time defense mechanism that pushes the boundaries of proactive security in the highly dynamic and high-stakes DeFi environment.

Demo / Proof of Concept

▶ Watch: Need for post-launch detection and blocking (6:50)

While the talk did not feature a live, real-time demonstration of the asset rescue system in action, Andy thoroughly described the underlying methodology and provided evidence of its efficacy. The entire technical deep dive serves as a detailed explanation of the system's operational proof of concept.

Andy frequently referenced a "Defi security incident dashboard developed by us," which tracks the number of losses and root causes for various DeFi hacks. This dashboard (likely a Blocksec product) serves to illustrate the scale of the problem and Blocksec's ongoing engagement with DeFi security incidents. However, it is distinct from a live demo of the specific mempool monitoring and rescue transaction synthesis system being presented.

The true proof of concept for the presented technique lies in Blocksec's reported success: they have demonstrably rescued over 20 million USD using this methodology. This real-world impact, rather than a simulated demonstration, validates the system's capabilities in detecting and blocking live exploits. The commercialization of this technique within Blocksec's Falcon product further indicates its robustness and practical applicability. Therefore, while a direct "show-and-tell" of the rescue process was not part of the presentation, the detailed technical explanation combined with significant real-world results serves as a compelling proof of concept for the proposed proactive threat prevention system.

Defensive Implications

▶ Watch: Detecting and blocking attacks in the mempool (8:00)

The proactive threat prevention system introduced by Andy carries significant implications for DeFi protocol developers, security teams, and the broader Web3 ecosystem. It represents a crucial shift in defensive strategy, moving beyond traditional pre-launch auditing to establish a dynamic, real-time safeguard.

  1. Enhanced Post-Launch Security: The most immediate implication is the availability of a robust post-launch security layer. Even protocols that have undergone rigorous audits, fuzzing, and formal verification can still fall victim to zero-day exploits or complex inter-protocol vulnerabilities. This system offers a critical last line of defense by intercepting attacks in the narrow window between broadcast and confirmation. DeFi projects should consider integrating or subscribing to such services to protect their assets from emerging threats.
  2. Mitigation of Flash Loan Attacks: Given that flash loans significantly amplify the scale and ease of DeFi exploits, a system capable of neutralizing these attacks in real-time is invaluable. Defenders can gain a crucial advantage against attackers who rely on flash loans for capital.
  3. Importance of Mempool Monitoring: This work highlights the strategic importance of mempool monitoring as a security primitive. Understanding pending transactions and their potential impact is no longer just for arbitrageurs or MEV bots but also for proactive defense. Security teams should develop or leverage tools that provide deep visibility into mempool activity.
  4. Rapid Response Capabilities: The system's ability to automatically synthesize and broadcast a rescue transaction within milliseconds demonstrates the necessity for extremely rapid response capabilities in blockchain security. Manual intervention is often too slow to prevent confirmed exploits.
  5. Addressing Developer Skill Gaps: While not a direct solution, the availability of such an automated defense mechanism can provide a safety net for protocols developed by teams lacking comprehensive security expertise. It doesn't absolve developers of responsibility but offers an additional layer of protection against human error or oversight.
  6. Challenges with Private Mempools: Defenders must acknowledge the limitations posed by private mempools. While collaboration with block builders and relayers is a potential avenue, a complete solution for private transaction exploits remains an ongoing challenge. Protocols and security providers need to advocate for transparency or develop alternative strategies to detect and mitigate these stealthier attacks.
  7. Economic Incentive for Defenders: The commercialization of this technology (e.g., in Falcon) suggests a viable economic model for providing such advanced security services. This can incentivize more security researchers and firms to develop and deploy similar defensive tools, fostering a more secure ecosystem.
  8. Shift from Reactive to Proactive: Fundamentally, this system encourages a paradigm shift from reacting to confirmed hacks (e.g., incident response, post-mortem analysis, attempts at fund recovery) to actively preventing them from ever being written to the blockchain. This proactive stance can significantly reduce financial losses and reputational damage for DeFi projects.

In essence, the work presented by Andy offers a powerful "spell" for defenders, allowing them to turn an attacker's own malicious code into a tool for asset recovery, thereby significantly strengthening the security posture of the entire DeFi landscape.

Key Takeaways

  • DeFi hacks continue to cause billions in annual losses due to economic incentives, developer skill gaps, composability, openness, anonymity, and flash loans.
  • Traditional pre-launch security measures (auditing, fuzzing, formal verification) are insufficient to prevent all exploits, necessitating robust post-launch defenses.
  • Blocksec's system proactively detects pending attack transactions in the blockchain mempool by simulating their execution and analyzing opcode traces for malicious profit.
  • The system automatically synthesizes a "rescue transaction" by reusing the attacker's logic but replacing the hacker's profit addresses with a secure white-hat address.
  • Rescue transactions are broadcast with optimized gas bidding strategies to ensure they are confirmed before the original malicious transaction, thereby salvaging assets.
  • Blocksec has successfully rescued over 20 million USD using this technique, which has been commercialized in their Falcon product, demonstrating its real-world effectiveness.

About the Speaker(s)

The talk was delivered by Andy, who is the CEO and co-founder of Blocksec. In addition to his leadership role at Blocksec, Andy is also a professor at a university, indicating a strong academic background. His research interests are primarily focused on DeFi security and blockchain system security. Andy describes himself as someone who publishes academic work, but also enjoys hacking and building systems, highlighting a blend of theoretical expertise and practical, hands-on experience in the security domain. He encourages interested individuals to visit his homepage for more information.

All talks from Black Hat USA 2024