Securing Your Blockchain Protocol: Essential Techniques for Blockchain Security Specialist and Blockchain Forensic Specialist

Ervin Zubic
Coinmonks
6 min readJan 5, 2024

--

Discover the power of custom Python scripts for blockchain security. Explore monitoring, detection, and prevention techniques to protect blockchain protocols. Learn from real-world applications and fortify your blockchain defenses with Python and web3.py.

Image featuring a good Ethereum smart contract character looking through binoculars at a malicious Ethereum smart contract character, with the two characters facing each other.
I see you… up to no good. Image created using DALL-E.

Opening Insights

In the swiftly changing world of blockchain technology and decentralized finance (DeFi), securing and maintaining the integrity of transactions has become of utmost importance. As blockchain-based applications and cryptocurrencies gain traction, they increasingly become targets for sophisticated cyber-attacks. Understanding these attacks and developing methods to monitor and prevent them is crucial. This article delves into the dynamics of blockchain attacks. It explores how we can use Python and the web3.py library to create scripts that monitor and potentially thwart such attacks, drawing insights from specific incidents and expert analyses.

Background Context

Historically, experts have praised blockchain technology for its robust security and decentralization features. Yet, as this technology matures and gains broader adoption, it increasingly attracts the attention of cybercriminals. In this article, we will explore the typical patterns of attacks on blockchain protocols and the strategies employed by attackers.

Core Concepts

It is crucial to grasp certain concepts to understand the mechanisms of monitoring and preventing blockchain attacks.

  • Web3.py: Python library for interacting with Ethereum. It allows the creation of scripts to communicate with the blockchain, send transactions, and access blockchain data.
  • Smart Contracts: Programs running on the blockchain execute transactions when they meet predetermined conditions.
  • ERC20 Tokens: A standard for fungible tokens created on Ethereum, allowing for implementing a standard API for tokens within smart contracts.
  • EOAs (Externally Owned Accounts): Private keys control addresses, not smart contract codes.

In-Depth Exploration

A typical attack on blockchain systems unfolds in distinct stages, each offering opportunities for monitoring and intervention:

  1. Funding: In this initial phase, attackers accumulate or transfer funds necessary to finance their subsequent malicious activities, including covering transaction fees.
  2. Preparation: Here, attackers lay the groundwork for their assault. This often involves deploying malicious smart contracts or setting up the infrastructure needed for the attack.
  3. Exploration: During this stage, attackers probe for vulnerabilities within the system, identify potential targets, and refine their strategies based on the gathered intelligence.
  4. Exploitation: This critical phase is where the actual attack occurs. Attackers execute their planned actions, such as stealing funds or disrupting services, exploiting the vulnerabilities they previously identified.
  5. Money Laundering: Post-exploitation, attackers focus on concealing their tracks and legitimizing their ill-gotten gains. They may use various methods, such as cryptocurrency mixers or moving assets through multiple accounts, to obfuscate the flow of stolen funds.

Understanding the distinct stages of a blockchain attack is essential for devising effective monitoring and preventive strategies and recognizing these phases, such as funding, preparation, exploration, exploitation, and money laundering. Each stage presents unique indicators that, when identified early, can be critical in thwarting potential attacks.

Python and the web3.py library are powerful tools for creating scripts tailored for such monitoring. You can program these scripts to detect specific blockchain events that signal different stages of an attack. Indicators could be the deployment of new smart contracts or unusual token approval requests. The following section will review a sample Python code demonstrating how these scripts can be applied in real-world scenarios, offering a practical perspective on their deployment and effectiveness.

Real-World Applications

By now the Badger DAO attack is familiar to most and it highlights the inherent vulnerabilities in blockchain systems, marked by API key exploits and smart contract manipulation. Central to the attack was the misuse of a routine dApp process: token spending approvals typically granted via the approve or increaseAllowance methods on ERC20 tokens.

An image of a software code snippet defining a function ‘approve’ with parameters ‘address spender’ and ‘uint256 value’ that returns a boolean, in a programming documentation style.
Figure 1. Source OpenZeppelin ERC20 documentation.
Figure 2. Source OpenZeppelin ERC20 documentation.

Unusually, the approvals here were made to an externally owned address (EOA) rather than a smart contract. This was abnormal as the attacker’s EOA, unlike EOAs used by some exchanges, had minimal transaction history. This red flag, coupled with over 600 EOAs authorizing the same EOA, indicated a clear malicious pattern.

Effective monitoring of such abnormal approval patterns could have been a key indicator of the attack’s onset. Tracking blockchain events, especially irregular approvals as observed in the Badger DAO case, might have helped in early detection and prevention or mitigation of the attack.

  • Listening for Events: In the wake of the Badger DAO attack, it becomes clear that creating scripts to monitor specific blockchain events is not just useful but critical. These scripts should be specifically designed to flag unusual activities, such as the atypical smart contract deployments or token approvals that were central to this attack. The next section will showcase a code snippet that demonstrates how to listen for and identify these critical events.
An image of a Python script with functions to fetch recent transactions from the blockchain using web3 and Etherscan API, including error handling and a placeholder function to identify token approval events.
Figure 3. VS Code Python code snippet of functions that fetch recent transactions from the blockchain using Web3 and Etherscan API, including error handling and a placeholder function to identify token approval events.
  • Analyzing Transactions: A fundamental aspect of these scripts is their ability to analyze transaction patterns, vital in identifying anomalies that could signal an impending attack. In the case of the Badger DAO attack, a sudden and unusual surge in ERC20 token approvals could have been a vital warning sign. This code snippet demonstrates how to implement transaction analysis.
An image of a Python code snippet for a function that handles transactions, checking for token approvals, blacklisted addresses, EOA (Externally Owned Addresses), and anomalous patterns, with comments explaining each step.
Figure 4. VS Code Python code snippet of a function that handles transactions, checking for token approvals, blacklisted addresses, EOA, and anomalous patterns.
  • Address Validation: Distinguishing between transaction participants, whether they are EOAs or smart contracts, is another crucial step. This distinction is vital for differentiating between normal activities and potential threats, as was evident in the Badger DAO situation. The following code snippet provides a practical example of how to perform address validation.
An image showing a portion of Python code that includes functions to check if an address is an EOA (Externally Owned Address), to identify token approval events, to extract spender addresses from transactions, and to fetch recent transactions, with placeholder comments for parts requiring specific contract details.
Figure 5. VS Code Python code snippet of a function that checks if an address is an EOA.
  • Threshold Alerts: Establishing threshold alerts is a proactive security measure. Had such alerts been set for abnormal levels of token approvals or interactions with new or less active EOAs in the Badger DAO case, it might have led to an early investigation, potentially averting the attack or reducing its severity. We will now review a code snippet that demonstrates setting up such threshold alerts.
An image displaying Python code for setting up a blockchain connection with Web3, loading environment variables, initializing connection status checks, and defining global variables and thresholds for blockchain transaction analysis.
Figure 6. VS Code Python code snippet for setting up a blockchain connection with Web3.

By implementing these steps, the use of Python scripts for monitoring proves to be a powerful strategy for enhancing the security of the blockchain space. The lessons learned from the Badger DAO attack provide valuable insights into the efficacy and necessity of such monitoring techniques.

Critical Viewpoints

Python scripts, although valuable for monitoring blockchain activities, have limited effectiveness. Attackers frequently update their methods, often outpacing traditional tracking tools. To stay effective, these scripts need continuous updates and refinement. Moreover, distinguishing between actual threats and false positives, where benign activities are mistakenly flagged, demands a careful balance of alertness and precision.

In this scenario, Forta Network, an advanced real-time detection network for blockchain security, emerges as a more potent alternative. Forta specializes in providing enhanced detection capabilities and real-time threat intelligence, enabling more accurate and timely responses to potential security breaches in the blockchain ecosystem.

Forward Thinking

The future of blockchain monitoring will likely involve more advanced machine learning algorithms and AI integration. These technologies could predict and identify attack patterns more efficiently, adapting to new strategies employed by cybercriminals. Collaborative efforts across the blockchain community are also crucial in developing more sophisticated and communal defense mechanisms.

Key Takeaways

Python scripts using web3.py provides a straightforward and proactive method for monitoring and protecting blockchain protocols. By comprehending the phases of attacks and applying targeted monitoring strategies, we can detect and counter potential threats. Yet, the ever-evolving landscape of cyber threats in the blockchain domain requires unceasing vigilance and continual innovation in our monitoring techniques.

Further Reading: How to Make $1000/Day Passive Income on Uniswap — But Not Really, This is Likely a Scam.

--

--

Ervin Zubic
Coinmonks

Exploring cyber threat intelligence with a focus on FinCrime & blockchain forensics. Check out my work on GitHub and Mirror.xyz. Connect on Twitter for updates.