Skip to content

0x-Professor/HTB-BlockChain-Track

Repository files navigation

HackTheBox Blockchain Challenge Solutions

Blockchain Solidity Python Web3

Complete solutions for HackTheBox Blockchain CTF challenges


πŸ“– Overview

This repository contains comprehensive solutions and detailed writeups for HackTheBox Blockchain challenges. Each solution includes:

  • βœ… Working exploit code (Python + Solidity)
  • πŸ“š Detailed README documenting the problem-solving journey
  • πŸ” Failed attempts and why they didn't work
  • πŸ’‘ Breakthrough moments and key insights
  • πŸ›‘οΈ Defense mechanisms and security best practices
  • 🎯 Automatic flag extraction from HTB endpoints

All solutions are tested and verified to work against live HTB instances.


πŸ—‚οΈ Challenge Directory

Very Easy

Challenge Vulnerability Type Key Concepts Status
Survival of the Fittest Direct Combat Basic contract interaction, function calls βœ… Solved
Distract and Destroy Access Control tx.origin vs msg.sender, proxy contracts βœ… Solved

Easy

Challenge Vulnerability Type Key Concepts Status
Honor Among Thieves Event Analysis XOR encryption, transaction forensics, event logs βœ… Solved
Magic Vault Storage Reading Private storage variables, password extraction βœ… Solved
Token to Wonderland Integer Underflow ERC20 vulnerabilities, unchecked arithmetic βœ… Solved

Medium

Challenge Vulnerability Type Key Concepts Status
False Bidding Integer Overflow uint32 overflow, time manipulation, helper contracts βœ… Solved
Portal Noncense Address Prediction Deterministic addresses, RLP encoding, nonce burning βœ… Solved
Locked and Loaded Reentrancy CEI pattern violation, recursive external calls βœ… Solved

🎯 Challenge Solutions

Survival of the Fittest

Difficulty: Very Easy | Category: Combat Mechanics

πŸ“‹ Challenge Details

Description: Face your first monster on a mysterious island. Learn basic smart contract interaction by attacking a creature and claiming its loot.

Win Condition: Drain the Creature contract's balance to 0 by reducing its life points.

Key Vulnerability:

  • Simple combat system with no access controls
  • attack() function reduces life points
  • loot() function withdraws funds when creature is defeated

Concepts Learned:

  • Basic contract interaction
  • Reading contract state
  • Function calls and transactions
  • Balance manipulation

Flag: HTB{...}

Files:

  • solve.py - Automated exploit script
  • Creature.sol - Vulnerable combat contract
  • Setup.sol - Challenge setup and win condition
  • README.md - Detailed writeup

Distract and Destroy

Difficulty: Very Easy | Category: Access Control

πŸ“‹ Challenge Details

Description: Face a stronger monster with defense mechanisms. Learn to bypass tx.origin checks using intermediate contracts.

Win Condition: Drain the Creature contract despite the tx.origin defense check.

Key Vulnerability:

  • Uses tx.origin == msg.sender check in attack()
  • This check fails when called through a contract
  • Solution: Deploy a proxy contract to call attack()

Concepts Learned:

  • tx.origin vs msg.sender differences
  • Proxy contract patterns
  • Access control vulnerabilities
  • Contract-to-contract calls

Flag: HTB{...}

Files:

  • solution.py - Automated exploit with proxy contract
  • Creature.sol - Contract with tx.origin check
  • Setup.sol - Challenge setup
  • README.md - Detailed writeup

Honor Among Thieves

Difficulty: Easy | Category: Cryptography + Blockchain

πŸ“‹ Challenge Details

Description: Spy on a rival group and steal their key. Extract the flag by analyzing blockchain events and reversing XOR encryption.

Win Condition: Call talk() with the correct key to become the solver.

Key Vulnerability:

  • Previous successful transaction emitted Voice(5) event
  • Transaction data reveals the correct _key parameter
  • Flag can be extracted from event logs without solving XOR

Concepts Learned:

  • Blockchain forensics and event analysis
  • Reading past transactions
  • Event log extraction
  • XOR encryption properties
  • Transaction replay analysis

Flag: HTB{d0n7_741k_11573n_70_3v3n75!}

Files:

  • solve.py - Event analysis exploit (145 lines)
  • Rivals.sol - XOR challenge contract
  • Setup.sol - Challenge initialization
  • README.md - Complete writeup with 5 failed attempts (476 lines)

Magic Vault

Difficulty: Easy | Category: Storage Manipulation

πŸ“‹ Challenge Details

Description: Unlock a magic vault protected by complex password validation. Learn to read private storage variables from the blockchain.

Win Condition: Call openVault() with the correct password to become the map holder.

Key Vulnerability:

  • Password stored in "private" storage variable
  • Blockchain storage is always readable
  • Can extract password using web3.eth.get_storage_at()

Concepts Learned:

  • Storage slot calculation
  • Reading private variables
  • Complex password validation logic
  • Storage layout in Solidity
  • Keccak256 hashing

Flag: HTB{...}

Files:

  • solve.py - Storage reading exploit
  • Vault.sol - Password-protected vault
  • VaultExploit.sol - Optional exploit contract
  • Setup.sol - Challenge setup
  • README.md - Detailed writeup (426 lines)

Token to Wonderland

Difficulty: Easy | Category: ERC20 Security

πŸ“‹ Challenge Details

Description: Buy a golden key from a shop using silver coins. Exploit integer underflow to generate unlimited tokens and purchase the key.

Win Condition: Own item #2 (the Golden Key) by accumulating enough SilverCoins.

Key Vulnerability:

  • SilverCoin.transfer() uses unchecked arithmetic
  • Transferring more than your balance causes underflow
  • Balance wraps around to 2^256 - 1 (unlimited coins)

Concepts Learned:

  • Integer underflow vulnerabilities
  • ERC20 token mechanics
  • Unchecked arithmetic blocks
  • Balance manipulation
  • Safe math patterns

Flag: HTB{...}

Files:

  • main.py - Underflow exploit script
  • Shop.sol - Item shop contract
  • SilverCoin.sol - Vulnerable ERC20 token
  • Setup.sol - Challenge initialization
  • README.md - Complete writeup (405 lines)

False Bidding

Difficulty: Medium | Category: Integer Overflow

πŸ“‹ Challenge Details

Description: Win a secret auction for the Phoenix Key. Exploit uint32 overflow in the timeout mechanism to claim the prize instantly.

Win Condition: Become the owner of the Phoenix Key by claiming it before timeout expires normally.

Key Vulnerability:

  • timeout is uint32 (max: 4,294,967,295 seconds = ~136 years)
  • Each bid adds 1 year (31,556,926 seconds)
  • 136 bids cause overflow β†’ timeout wraps to small value
  • Can claim prize immediately after overflow

Exploitation Strategy:

  1. Bid 1 ETH to become top bidder
  2. Deploy 136 helper contracts
  3. Each helper bids then withdraws (increments timeout)
  4. Helper contracts have no receive() β†’ refund fails β†’ blacklisted
  5. After 136 cycles, timeout overflows
  6. Claim the Phoenix Key

Concepts Learned:

  • Integer overflow in uint32
  • Time-based vulnerabilities
  • Helper contract patterns
  • Blacklist bypass mechanics
  • Nonce burning for contract deployment

Flag: HTB{0v32f10w_70_w1n_7h3_4uc710n}

Files:

  • solve.py - Complete overflow exploit (169 lines)
  • AuctionHouse.sol - Vulnerable auction contract
  • Setup.sol - Challenge setup
  • README.md - Comprehensive writeup with 5 failed attempts (653 lines)

Portal Noncense

Difficulty: Medium | Category: Address Calculation

πŸ“‹ Challenge Details

Description: Navigate the portal station to reach the Orc Kingdom. Calculate the exact nonce needed to deploy a contract at a predetermined address.

Win Condition: Activate the orcKingdom portal by deploying a contract at the hardcoded destination address.

Key Vulnerability:

  • Portal destinations are hardcoded addresses
  • delegatecall to destination requires a contract with connect() function
  • Contract addresses are deterministic: keccak256(rlp([sender, nonce]))[12:]
  • Can calculate which nonce deploys to the target address

Exploitation Strategy:

  1. Read hardcoded address: 0xFC31cde4aCbF2b1d2996a2C7f695E850918e4007
  2. Burn nonces by deploying dummy contracts
  3. Calculate when next deployment matches target address
  4. Deploy exploit contract with connect() function at exact nonce
  5. Call createPortal("orcKingdom") β†’ delegatecall succeeds
  6. Portal activated!

Concepts Learned:

  • Deterministic contract address calculation
  • RLP encoding in Python
  • Keccak256 hashing
  • Nonce manipulation
  • Delegatecall mechanics
  • CREATE opcode behavior

Flag: HTB{7h3_4dd2355_0f_4_c0n724c7_15_41m057_d3732m1n1571c}

Files:

  • solve.py - Dynamic nonce calculation exploit (173 lines)
  • main.py - Original script with hardcoded nonce
  • Portal.sol - Portal station contract
  • Setup.sol - Challenge setup
  • README.md - Detailed writeup with clarifications (682 lines)

Important Clarification: The address 0xFC31cde4... IS hardcoded in the Lockers.sol constructor, but we CALCULATE which nonce from our account will deploy a contract to that exact address.


Locked and Loaded

Difficulty: Medium | Category: Reentrancy

πŸ“‹ Challenge Details

Description: Raid a wizard's locker system to steal the WizardsScepter and drain all funds. Exploit a classic reentrancy vulnerability in the payment mechanism.

Win Condition: Drain the Lockers contract completely (balance must be 0 ETH).

Key Vulnerability:

  • sellItem() sends payment via .call{value:} BEFORE deleting the item
  • External call triggers the receiver's fallback() or receive() function
  • Can call sellItem() recursively before the item is deleted
  • Each call pays out 1 ETH until contract is drained

Exploitation Strategy:

  1. Deploy attack contract with reentrancy callback
  2. Register username = attack contract address (as string)
  3. Transfer WizardsScepter (Mythic, 1 ETH) to attack contract's username
  4. Call start() β†’ triggers sellItem()
  5. Payment sent to attack contract β†’ receive() called
  6. receive() calls sellItem() again (item not deleted yet!)
  7. Recursive reentrancy drains all 2 ETH
  8. Contract balance = 0 β†’ Challenge solved!

Concepts Learned:

  • Reentrancy attack patterns
  • Checks-Effects-Interactions pattern
  • Memory vs storage modifications
  • Fallback and receive functions
  • Recursive external calls
  • Address-to-string conversion

Flag: HTB{und32574nd1n9_7h3_s70rag3_47_7h3_m4x}

Files:

  • exploit.py - Complete reentrancy attack (168 lines)
  • Attack.sol - Exploit contract with fallback reentrancy
  • Lockers.sol - Vulnerable locker system
  • Setup.sol - Challenge setup
  • README.md - Comprehensive writeup with 5 failed attempts (717 lines)

πŸ› οΈ Technical Stack

Languages & Frameworks

  • Solidity: 0.7.0, 0.8.13 (Smart contract development)
  • Python: 3.10+ (Exploit scripts)
  • Web3.py: Ethereum interaction library

Key Libraries

web3              # Ethereum JSON-RPC interaction
eth_abi           # ABI encoding/decoding
requests          # HTTP requests for flag retrieval
solcx             # Solidity compiler wrapper
rlp               # Recursive Length Prefix encoding

Tools

  • Foundry/Forge: Smart contract testing
  • Remix: Contract compilation and debugging
  • Ganache: Local blockchain testing
  • MetaMask: Wallet interaction

πŸš€ Quick Start

Prerequisites

# Install Python dependencies
pip install web3 eth_abi requests py-solc-x rlp

# Or using the project's pyproject.toml
pip install -e .

Running a Solution

Each challenge directory contains a solve script. General usage:

# Navigate to challenge directory
cd "Challenge Name"

# Run the exploit
python solve.py
# or
python exploit.py
# or  
python main.py
# or
python solution.py

Most scripts automatically:

  1. πŸ”— Fetch connection info from HTB endpoint
  2. πŸš€ Deploy necessary contracts
  3. πŸ’₯ Execute the exploit
  4. 🏁 Retrieve and display the flag

Manual Configuration

If automatic fetching fails, update the script with your instance details:

RPC_URL = "http://your-instance-ip:port"
PRIVATE_KEY = "0x..."
PLAYER_ADDRESS = "0x..."
SETUP_ADDRESS = "0x..."
TARGET_ADDRESS = "0x..."

πŸ“š Learning Path

Recommended challenge order for learning:

🟒 Beginner Track

  1. Survival of the Fittest - Basic contract interaction
  2. Distract and Destroy - Access control basics
  3. Honor Among Thieves - Event analysis and forensics

🟑 Intermediate Track

  1. Magic Vault - Storage reading techniques
  2. Token to Wonderland - Integer vulnerabilities
  3. False Bidding - Advanced overflow exploitation

πŸ”΄ Advanced Track

  1. Portal Noncense - Deterministic address calculation
  2. Locked and Loaded - Reentrancy attacks

πŸ” Key Vulnerability Categories

1. Integer Overflow/Underflow

  • Challenges: False Bidding, Token to Wonderland
  • Concept: Arithmetic wrapping in fixed-size integers
  • Defense: Use SafeMath or Solidity 0.8+ built-in checks

2. Reentrancy

  • Challenges: Locked and Loaded
  • Concept: Recursive external calls before state updates
  • Defense: Checks-Effects-Interactions pattern, ReentrancyGuard

3. Access Control

  • Challenges: Distract and Destroy
  • Concept: tx.origin vs msg.sender confusion
  • Defense: Always use msg.sender for authorization

4. Storage Manipulation

  • Challenges: Magic Vault, Honor Among Thieves
  • Concept: "Private" variables are publicly readable
  • Defense: Never store secrets on-chain

5. Address Prediction

  • Challenges: Portal Noncense
  • Concept: Deterministic contract address calculation
  • Defense: Don't rely on address secrecy, validate deployed code

6. Event Analysis

  • Challenges: Honor Among Thieves
  • Concept: Historical transactions reveal sensitive data
  • Defense: Don't pass secrets as function parameters

πŸ“– Writeup Structure

Each challenge README follows a consistent structure:

  1. Challenge Description - Story and context
  2. Initial Reconnaissance - Contract analysis and win conditions
  3. Understanding the Mechanics - How the system works
  4. Failed Attempts - 5+ approaches that didn't work (with code)
  5. The Breakthrough - Discovery of the actual vulnerability
  6. Exploitation - Step-by-step attack execution
  7. Running the Solution - Usage instructions and expected output
  8. Key Takeaways - Lessons learned and defense mechanisms
  9. Real-World Implications - Similar vulnerabilities in production
  10. Resources - Additional reading and references

πŸŽ“ Educational Value

What You'll Learn

Smart Contract Security:

  • Common vulnerability patterns (OWASP Top 10)
  • Secure coding practices
  • Audit techniques and red flags

Blockchain Fundamentals:

  • EVM mechanics and opcodes
  • Storage layout and memory management
  • Gas optimization and transaction analysis

Exploitation Techniques:

  • Contract-to-contract interactions
  • State manipulation strategies
  • Advanced attack patterns

Python + Web3:

  • Contract compilation and deployment
  • Transaction signing and broadcasting
  • ABI encoding/decoding

πŸ›‘οΈ Security Best Practices

Defense Checklist

βœ… Use Solidity 0.8+ for automatic overflow checks
βœ… Implement reentrancy guards on external calls
βœ… Follow Checks-Effects-Interactions pattern
βœ… Use msg.sender not tx.origin for authorization
βœ… Never store secrets in contract storage
βœ… Validate all inputs and state transitions
βœ… Use OpenZeppelin libraries for standards
βœ… Conduct professional audits before mainnet
βœ… Implement circuit breakers for emergency stops
βœ… Test extensively with fuzzing and formal verification


πŸ“Š Repository Statistics

Total Challenges: 8
Difficulty Breakdown:
  - Very Easy: 2
  - Easy: 3
  - Medium: 3

Lines of Code:
  - Python Scripts: ~1,300 lines
  - Solidity Contracts: ~800 lines
  - Documentation: ~4,600 lines

Vulnerability Types:
  - Reentrancy: 1
  - Integer Overflow/Underflow: 2
  - Access Control: 1
  - Storage Reading: 1
  - Address Prediction: 1
  - Event Analysis: 1
  - Direct Interaction: 2

🀝 Contributing

While this is a personal solution repository, feedback and improvements are welcome:

  • πŸ› Bug Reports: Found an issue? Open an issue!
  • πŸ’‘ Alternative Solutions: Have a different approach? Share it!
  • πŸ“ Documentation: Improvements to writeups are appreciated
  • πŸ”’ Security: Found a vulnerability? Please report responsibly

βš–οΈ Legal Disclaimer

Educational Purpose Only

This repository is intended for:

  • βœ… Learning smart contract security
  • βœ… Understanding blockchain vulnerabilities
  • βœ… Practicing ethical hacking in controlled environments
  • βœ… Solving HackTheBox challenges

NOT intended for:

  • ❌ Attacking mainnet contracts
  • ❌ Unauthorized exploitation
  • ❌ Financial theft or fraud
  • ❌ Any illegal activities

Always obtain proper authorization before testing any system.


πŸ“ž Contact & Resources

HackTheBox

Learning Resources

Security Auditing


πŸ“œ License

This project is provided for educational purposes. Each challenge is the intellectual property of HackTheBox. Solutions and writeups are original work.


πŸ† Achievement Summary

╔══════════════════════════════════════════════════════════╗
β•‘                                                          β•‘
β•‘     βœ… All 8 Blockchain Challenges Solved               β•‘
β•‘                                                          β•‘
β•‘     🎯 Flags Captured: 8/8                              β•‘
β•‘     πŸ“š Writeups Completed: 8/8                          β•‘
β•‘     πŸ”§ Exploits Working: 8/8                            β•‘
β•‘                                                          β•‘
β•‘     πŸ’‘ Vulnerabilities Mastered:                        β•‘
β•‘        β€’ Reentrancy Attacks                             β•‘
β•‘        β€’ Integer Overflow/Underflow                     β•‘
β•‘        β€’ Access Control Bypasses                        β•‘
β•‘        β€’ Storage Manipulation                           β•‘
β•‘        β€’ Address Prediction                             β•‘
β•‘        β€’ Event Analysis                                 β•‘
β•‘                                                          β•‘
β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•

⭐ If you found this helpful, consider starring the repository! ⭐

Made with 🧠 for blockchain security enthusiasts

Happy Hacking! πŸš€