Skip to content

micro services for smartcontract exploit detection, notification, and prevention, along with detailed reporting.

License

Notifications You must be signed in to change notification settings

akshaydevh/SC-vulnerability-detection

Repository files navigation

Smartcontract Vulnerability Detection, Analysis and Reports

This project leverages a microservices architecture to provide comprehensive smartcontract security. It includes services for detecting potential vulnerabilities and exploits, notifying users in real-time, preventing or mitigating the impact of attacks, and generating detailed reports on detected issues, attempted exploits, and the effectiveness of prevention measures. This approach allows for modularity, scalability, and independent development, ensuring a robust and adaptable security system for smart contracts. This project is done as a part of QUILLAUDIT Interview process.

Project Goals

  • Smartcontract Security: Develop an upgradable smartcontract with a vulnerability and a system that proactively identifies potential vulnerabilities and exploits in smart contracts.
  • Real-Time Notification: Alert users immediately when a potential exploit is detected.
  • Prevention: Implement mechanisms to prevent or mitigate the impact of exploits, potentially by pausing or modifying contract execution.
  • Detailed Reporting: Provide comprehensive reports on detected vulnerabilities, attempted exploits, and the effectiveness of prevention measures.

Requirements

  1. Smartcontract Development:

    Develop an upgradeable Solidity smartcontract vulnerable to reentrancy or flash loan attacks, including Ownable and Pausable functionalities using OpenZeppelin libraries.

  2. Exploit Detection and Notification Microservice:

    Using Node.js/Python/Rust/Go, write a simple notification microservice that sends an email whenever someone tries to exploit the vulnerability.

  3. Front-running Microservice:

    Write a second microservice that triggers a transaction to pause the contract before a suspicious transaction occurs, implementing a dynamic gas pricing script.

  4. Detailed Reporting and Analytics:

    Develop a system to store detailed reports in a database, providing analytics on system performance, potential vulnerabilities (using Slither), and the effectiveness of the pausing mechanism.

  5. Manual Upgrade Functionality:

    Ensure the smartcontract can be manually upgraded to fix the vulnerability after receiving an email notification.

System Architecture

sysytem_arch

components

  • Smartcontract Deployer
    • This is the smartcontract development environment.
    • Deploys the smartcontract to the blockchain using Hardhat and OpenZeppelin hardhat upgrades.
    • Helps to generate audit report of smartcontracts using slither.
  • Notification Microservice
    • Monitors the blockchain for suspicious transactions.
    • Sends an email notification when a potential exploit is detected.
  • Front-running Microservice
    • Monitors the blockchain for suspicious transactions.
    • Triggers a transaction to pause the contract before a suspicious transaction occurs.
  • Storage Service
    • Stores detailed reports on detected vulnerabilities, attempted exploits, and the effectiveness of prevention measures.

Implementation Details

Pre-Requisite

Smartcontract Deployer

This environment contains 3 solidity based smartcontracts, a vulnerable smartcontract Deposit_V1.sol, a fix smartcontract Deposit_v2.sol and a an attacker smartcontract Attacker.sol. The deployment and testing environment is setup with Hardhat. Slither is used for code analysis. Configuration for hardhat local node and a public network (polygon amoy) is added. Deposit_V1.sol and Deposit_V2.sol are deployed using hardhat scripts and Attacker.sol is deployed using hardhat ignition.

  • Install Packages


  • make sure you are inside smartcontract_deployer directory
  • Install packages using npm
npm install
  • Create .env by copying .env.sample
  • Start Hardhat Node (If required). Hardhat node is configured using hardhat.config.js file. Auto mining is disabled and each block is set to mine at an interval of 10 seconds.
npx hardhat node
  • Deploy Upgradable Smartcontract


npx hardhat run .\scripts\deploy_deposit_v1.js --network localhost
  • use --network polygonAmoy for deploying to amoy network.

  • Deploy Attacker Smartcontract


  • Deployed using hardhat ignition
npx hardhat ignition deploy .\ignition\modules\Attacker.js --network localhost
  • Deploy V2 Smartcontract


  • Refer .\scripts\deploy_deposit_v2.js and make sure the proxy address is the same as the deployed V1 contract address.
npx hardhat run .\scripts\deploy_deposit_v2.js --network localhost
  • Deployed Contract Address


Amoy Deployed V1 - 0x0b57a8895e34e34B89Db330e1Ecf9fe1d808Da24
Amoy Deployed V2 - 0x9EDc36594340Fc039259012DD01A92A2B944Ac32
Amoy Deployed Proxy - 0xbB4D61bDae7B1e1b29966F56078f6d333e06Ef8A

  • Verify Deployment (For Public Networks)


npx hardhat verify --network polygonAmoy "CONTRACT ADDRESS"
  • Slither Analysis


Slither is configured to generate report as JSON file. The generated report will be available on analysis directory. Configure slither response using slither.config.json file.

slither contracts/Attacker.sol --json ./analysis/attacker.json --show-ignored-findings
slither contracts/Deposit_V1.sol --json ./analysis/deposit_v1.json --show-ignored-findings
slither contracts/Deposit_V2.sol --json ./analysis/deposit_v2.json --show-ignored-findings

Notification Microservice

The exploit detection and notification microservice is a express.js based application. The blockchain interaction is done with ethers.js. The system continuously listens for the following events:

  • withdrawal
  • reentrancy

Identifying and confirming reentrancy with a reentrancy event is pretty straightforward. This is smartcontract-level reentrancy identification, inspired by the OpenZeppelin reentrancy guard. This event emits only when there is a confirmed reentrancy attack.

withdrawal triggers when someone calls the withdrawal function. Upon receiving new transaction, the watcher service will check for "Reentrancy Patterns". To identify a possible reentrancy attack I have used the following transaction parameters.

  • contract balance
  • amount transferred
  • gas limit
  • gas used

CHECKING FOR REENTRANCY PATTERN

Following steps are carried out to check and suspect Reentrancy Attack.

* Check if the withdrawer is a contract address.
* Check if the amount transferred more than 1/3 of contract balance.
* Check if the gasLimit is more than 65000
* Check if the gasUsed (after confirmation) is greater than 55000

Yet another efficient way of identifying reentrancy attacks can be done by comparing smartcontracts ETH balance and total balance from smartcontract storage in the smartcontract, before and after a transaction. It should be the same before and after a transaction. Due to time constraints, I have not implemented this approach.

EMAIL NOTIFICATION

The notification microservice will listen to the available events and send two types of email notification using nodemailer to the user when a potential exploit is detected. The email will include the following information:

* Attack Probability - Suspected or Confirmed
* The transaction hash
* The contract address
* The amount of ETH transferred
* The attacker address

Storage Microservice

The storage microservice provides API's for storing detailed reports and details of reentrancy suspected transaction. This is a express.js based application and uses MongoDB as a database. The system allows statically storing smartcontract reports (only JSON and pdf formats allowed).

The server also contains a crawler function which iterates through reports in JSON format and stores all vulnerabilities. The API's are documented with swagger and UI available at path /api-docs/. The system will also provide analytics on potential vulnerabilities and the effectiveness of prevention measures.

Front-running Microservice

The front-running microservice is prevention mechanism to find and avoid reentrancy attack on smartcontracts. This is a express.js based application and uses ether.js for a blockchain interaction.

The server always monitor the mempool for pending transaction and check if any of the transaction targets vulnerable smartcontracts. The system identifies potential reentrancy attacks by analyzing the following patterns in the transaction object:

* gasLimit
* amount
* data

CHECKING FOR REENTRANCY PATTERN

Following steps are carried out to check and suspect Reentrancy Attack.

* Check if transaction data contains vulnerable contract address.
* Check if the transaction to address is a contract.
* Check if the amount transfered more than 1/3 of contract balance.
* Check if the gasLimit is more than 65000

PREVENTION MECHANISM

To prevent a vulnerability transaction from taking place, the system creates a new transaction to pause the smartcontract with higher gasPrice and same nonce. The gas price is calculated dynamically and ensures it is greater than gas provided in the attacking transaction. It also stores transaction details and status in the database throgh the storage service.

System Performance and Monitoring

This project uses PM2 load balancer to effectively deploy all microservices. PM2 offers a built-in load-balancer that can significantly enhance the scalability and reliability of the microservices.

The benefits of using PM2’s load-balancing feature:

  1. Scalability Across CPUs
  2. Performance Boost
  3. Zero-Downtime Reloads
  4. Graceful Start & Shutdown: PM2 ensures that all requests are properly handled during reloads or shutdowns.

The system performance can be monitored using:

pm2 monit

or PM2 Dashboard

Usage

As Individual Units

  • make sure you are inside any of the microservice directory

  • Install all packages

npm install
  • copy environment variables from .env.sample to .env and update the variables
  • start server in development mode. This mode uses nodemon utility to reload server automatically on change.
  • for storage microservice make sure mongodb is running.
npm run start:dev
  • To use server in production.
npm run build
npm run start

As a Single System

  • Deploy all smartcontracts and get the contract addresses. Refer Smartcontract Deployer

  • copy environment variables from .env.sample to .env and update the variables for all services.

  • ensure you are on project root directory.

USING CONCURRENTLY

  • Install package
npm install
  • development mode
npm run start:dev
  • production mode
npm run build
npm run start

USING PM2

npm run build
pm2 start .\ecosystem.config.js
  • to stop PM2
pm2 kill

Project Walkthrough (Try 1.7x 😅 )

Future Work

  • Implement a more sophisticated exploit detection system.
  • Develop a more robust front-running system.
  • Integrate the system with other security tools.
  • Develop a user interface for the system.

Conclusion

This project provides a comprehensive approach to smartcontract security. The microservices architecture allows for modularity, scalability, and independent development. The system is designed to proactively identify potential vulnerabilities and exploits, notify users in real-time, prevent or mitigate the impact of attacks, and generate detailed reports on detected issues.

License

This project is licensed under the MIT License.

About

micro services for smartcontract exploit detection, notification, and prevention, along with detailed reporting.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published