The training method behind a top Chinese CTF team: Part 7 smart contracts

CTF · Part 7

A CTF finals competition hall

This closes my walk through "Handbook for CTFers", the training book from Nu1L, one of China's strongest CTF teams. Part 1 was the overview, and the parts since covered web, reverse engineering and PWN, cryptography, forensics and misc, and the finals. This last part covers the newest category the book teaches: smart contracts. It is the one place in CTF where the target is money on a public ledger, and where every move you make is visible to everyone.

Summary

A smart-contract challenge is code auditing with two twists. The code runs on a blockchain, so the whole state is public and every transaction is recorded, and the bug is almost always in how the contract handles money or who is allowed to call a function. You read the contract, find the function that pays out or the state you are not supposed to change, and send the transaction that reaches it.

The book is honest that these challenges cannot be made very hard. When the source is published on the block explorer, the difficulty scales with how much code you have to read, not with cleverness. When the source is withheld, you reverse the contract's bytecode instead, which is harder but rare. Either way the lesson is the one from the code-auditing part, applied to Solidity: read the flow, find the sink, send the call. Below is the map.

The territory

The book centres on Ethereum and Solidity. Here is the whole map before the detail, the book's own cases alongside the vulnerability classes that define the category.

#TechniqueWhat it doesTools
1Toolchain and reconReads a deployed contract's source and stateRemix, Etherscan, web3.py
2Reading private statePulls "private" variables straight from storageweb3, getStorageAt
3Broken access controlCalls a function that should have been guardedweb3.py
4ReentrancyRe-enters a withdraw before the balance updatesRemix
5Integer overflowWraps a balance past its maximum on old Solidityweb3.py
6tx.origin authPhishes a privileged account into making the callRemix
7Bad randomnessPredicts an on-chain "random" numberweb3.py
8delegatecall and storageHijacks a contract through a library callRemix
9Logic and airdrop farmingMints and concentrates balance to pass a checkweb3.py
10Bytecode reversingRecovers logic from a contract with no sourcepanoramix, evm

Getting on chain: tools and transparency

Toolchain and recon

A smart-contract challenge gives you a contract address on a test network, usually one with free coins so nothing costs real money. The first job is recon. Etherscan shows a deployed contract's verified source and its whole transaction history, Remix is the browser IDE you compile and deploy from, MetaMask is the wallet, and web3.py scripts the attack. You read the contract first, exactly like the code-auditing part of this series.

from web3 import Web3
w3 = Web3(Web3.HTTPProvider("https://sepolia.infura.io/v3/KEY"))
c = w3.eth.contract(address=target, abi=abi)
print(c.functions.balanceOf(me).call())    # read state for free, no transaction
# a function selector is the first 4 bytes of keccak256("getAirdrop()")

Reading private state

Solidity's private keyword hides a variable from other contracts, not from you. Everything a contract stores sits in public storage slots, so a value the author marked private is still readable with a storage query. Fixed variables take slots 0, 1, 2 in order; a mapping's slot is the hash of its key and the mapping's own slot number.

secret = w3.eth.get_storage_at(target, 0)   # slot 0, whatever "private" var lives there
# mapping value: slot = keccak256(pad(key) + pad(mapping_slot))

The lesson is that nothing on chain is secret. If a challenge's flag or password is stored in the contract, you read it out of storage rather than guessing it, and the author has to design around that transparency rather than rely on a keyword.

The core bugs: Solidity gone wrong

Broken access control

The most common bug, and the one the book's own cases use, is a function that changes money or ownership without checking who called it. An internal transfer helper left callable, an owner-only function with no owner check, or a weak custom check all let you move balance you should not control.

// the bug: a transfer helper with no caller check, callable by anyone
function _transfer(address from, address to, uint amt) public {
    balances[from] -= amt;
    balances[to]   += amt;
}

The book's ez2win case is exactly this: the contract gives its creator a huge balance at deployment and leaves the transfer function open, so you move the creator's balance to yourself and clear the payout threshold. You call the unguarded function from web3.py and the chain does the rest.

Reentrancy

Reentrancy is the famous one. A contract that sends you ether before it updates your balance can be called back into during that send, and if your own contract's receive function calls withdraw again, you drain the balance in a loop because the bookkeeping has not happened yet.

// vulnerable: it pays out BEFORE zeroing the balance
function withdraw() public {
    (bool ok,) = msg.sender.call{value: balances[msg.sender]}("");
    balances[msg.sender] = 0;    // too late: your fallback re-entered withdraw first
}

The fix is to update state before the external call, the checks-effects-interactions order. In a challenge you exploit it with an attacking contract whose fallback re-enters, which you deploy from Remix. This is the bug behind the 2016 DAO hack, and it is a staple of smart-contract CTFs.

Integer overflow

Before Solidity 0.8 made it automatic, arithmetic wrapped silently. Subtracting one from a zero balance gave the maximum possible number, so a transfer of more than you hold could leave you with a near-infinite balance. The batchTransfer bug that hit real tokens in 2018 was exactly this.

// pre-0.8: no overflow check, so this underflows to a huge number
require(balances[msg.sender] - amt >= 0);   // always true, even when amt is huge
balances[msg.sender] -= amt;                 // wraps around to near-maximum

On an old-compiler challenge you look for arithmetic with no SafeMath wrapper, then send the input that wraps it. On a 0.8 or later contract this door is closed unless the author used an unchecked block.

tx.origin auth

A contract that authorises with tx.origin instead of msg.sender checks the original account that started the transaction chain, not the immediate caller. So if you can get a privileged user to call your contract, your contract calls the target, and the check sees the privileged user. It is a phishing bug in contract form.

// vulnerable: tx.origin is the human who signed, not the calling contract
require(tx.origin == owner);   // your contract passes this if the owner calls yours

Bad randomness

There is no real randomness on a blockchain, because every node must compute the same result. A contract that seeds a "random" number from the block timestamp, the block number, or a blockhash is fully predictable, since you can read those same values in the same transaction and compute the answer before you play.

// vulnerable: all three inputs are known to the caller at call time
uint n = uint(keccak256(abi.encode(block.timestamp, block.number))) % 100;
// your attacking contract computes the same n, then calls with the winning guess

Deeper: the EVM itself

delegatecall and storage

delegatecall runs another contract's code in your contract's storage. If the two contracts lay out their storage slots differently, the called code writes to the wrong slots, which can overwrite the owner variable. A contract that delegatecalls into an address you control, or into a library with a mismatched layout, hands you its storage.

the storage-collision exploit:
1. the proxy delegatecalls a library; both share the proxy's storage slots
2. the library writes to "its" slot 0, but that is the proxy's owner slot
3. craft a call that writes your address into slot 0 -> you are now owner

Logic and airdrop farming

Some challenges have no single broken function, only a flow you abuse at scale. The book's ggbank airdrop is the example: each account may claim a one-time airdrop, and a payout needs a large balance, so you generate many accounts, claim the airdrop on each, and concentrate the total into one account to pass the threshold. The contract is sound; the economics are not.

# generate N accounts, claim the one-time airdrop on each, sweep to the main one
for acct in accounts:
    send(acct, target, selector("getAirdrop()"))
    send(acct, target, selector("transfer(address,uint256)"), main, 1000)
# main now holds N * 1000, enough to call PayForFlag

Bytecode reversing

When the author does not publish the source, you reverse the bytecode. The runtime code dispatches on a function selector, the first four bytes of the hash of the function signature, so you recover the callable functions and their logic from the opcodes. It is the reverse-engineering part of this series applied to the EVM, and the book notes it is where the genuinely hard smart-contract challenges live.

# pull the deployed bytecode, then decompile it back toward readable logic
cast code 0xCONTRACT                 # the runtime bytecode
panoramix 0xCONTRACT                 # decompile to pseudo-Solidity, recover selectors

Practice beats theory

1. Nothing on chain is private. Public storage, public transactions, a public mempool. A value marked private in Solidity is still readable from storage, and your winning transaction is visible to everyone. Read the state before you assume anything is hidden.

2. The bug is in the money or the caller. Almost every smart-contract challenge is a payout function with a missing check or arithmetic that wraps. Audit who can call what and how balances change, and you have found most bugs before you write any exploit.

3. It is code auditing with gas. The method is the one from Part 6: read the flow, find the sink, send the call. Solidity adds the blockchain's rules (transparency, gas, the EVM) on top, but the core skill is the same read-the-source discipline, which is why the book places it last.

Prepare for CTF with CyberLearner

The logic these bugs turn on, balances, transfers, and authorisation on a financial application, is practised today on CyberLearner for free.

  • BahCoin. A cryptocurrency bank: recover a leaked source repository, run a blind SQL injection to read the account table, crack a truncated hash, and log in to drain the balance. The same money-and-authorisation logic that smart-contract bugs exploit, on a traditional web stack.
  • GateCrasher. Forge an admin token and bypass an authorisation check to reach a privileged account, the web version of the broken-access-control bug above.

Browse the full set on the challenges page.

The end of the series

That closes the walk through "Handbook for CTFers". Seven parts, from a first web flag to a smart-contract drain. The book's lesson is the same in every category: learn the fundamentals, prepare before the match, and chain what you know. Get good enough at the basics and a new target is a puzzle, not a wall.

If you read the whole series, do the obvious next thing. Open a lab, fail at it, and learn why. Start with Part 1 if you came in at the end, or go straight to the challenges and pick one that scares you.

Sources


TopicsCTFSmart contractsEthereumSolidityBlockchain
Share this article LinkedIn X Facebook Email
← Back to all posts