Onion-layered code

Zwiebel, TUM CTF 2016: an ELF that decrypts itself layer by layer

Zwiebel checks a key one character and one bit at a time, each check wrapped in its own layer of XOR-encrypted code. Getting the flag means automating gdb rather than stepping through it by hand.

Hexfield editorial

EventTUM CTF 2016
CategoryReverse, 50 points
Binary64-bit ELF, not stripped
LayersAbout 1,600 XOR-decrypted chunks
Reverse50 pts
  1. 01

    Inspect

    The binary reads a key, copies roughly 150 KB of data into executable memory with mmap and jumps into it. A ptrace check blocks naive debugging.

  2. 02

    Hypothesize

    Each jump target is a small XOR-encrypted block that checks one bit of one input character, then decrypts and jumps to the next block, repeated for the whole key.

  3. 03

    Test

    Stepping through the first few layers by hand in gdb confirms the pattern: a fixed-size XOR key unlocks the next chunk, which checks a different bit of a different character.

  4. 04

    Solve

    Script the decrypt-and-disassemble loop so each layer's bit result is recorded automatically, then assemble the recovered bits into the flag.

Entropy trace across an ELF binary, flat and low over the headers and strings, then rising sharply over a block of XOR-encrypted self-modifying code
Plotting entropy byte by byte across the file shows exactly where the encrypted code layer begins, well before any of it is decrypted at runtime.

Zwiebel, German for onion, was worth 50 points in TUM CTF 2016 and lived in the reverse category. The task description only pointed to a short video and a single download: a 64-bit ELF executable with no further hints, which made the binary itself the entire task statement.

First run and first obstacle

Executed directly, the binary prints Input key: and, for any guess, replies :(. file on the binary shows a standard 64-bit ELF, dynamically linked, not stripped, so function names are intact. Running info functions inside gdb lists the usual C runtime entries alongside one that stands out: ptrace@plt. A binary that imports ptrace and does nothing visible with it is very likely testing for a debugger, since ptrace(PTRACE_TRACEME, ...) returns -1 when a tracer is already attached, which is a one-line way to detect gdb.

Confirming that hypothesis took one step: running the binary under gdb directly produced the :( message immediately, without even printing the key prompt, exactly what a failed trace-detection check followed by an early exit would look like. The fix is to intercept the call. Setting a breakpoint on ptrace, letting it return, and then setting rax to 0 makes the process see the untraced result regardless of the real one:

gdb-peda$ b ptrace
gdb-peda$ run
(breakpoint hits)
gdb-peda$ finish
gdb-peda$ set $rax = 0

With that in place the program behaves as if no debugger were attached.

The self-modifying jump

main, still readable thanks to the retained symbols, is short: it prints the prompt, flushes stdout, reads a line with fgets into a 0x90-byte buffer, then calls mmap for roughly 150 KB (0x24c8d bytes) of fresh memory, memcpys the same number of bytes from a fixed address into it, and jumps straight into the freshly copied region with a plain call. Nothing about the key appears in main itself, which means the actual check logic lives entirely inside that copied block, and the copy is not simply a relocation: the bytes at the jump target do not disassemble into anything sensible until something has transformed them.

Setting a breakpoint right at the jump and inspecting the first instructions there shows why. The code at the target address reads one byte from the input (through a saved register pointing at it), masks it against a single bit, and branches depending on the result. If the bit does not match, execution falls into a short block that prints :( and exits. If it does, the code instead performs a loop: it reads a 4-byte count and a 4-byte key from a fixed offset ahead of the current position, then XORs that many following 4-byte words with the key, before jumping into the region it just decrypted.

That is the entire mechanism, repeated: decrypt a small block using a key stored just ahead of it, jump in, check one bit of one input character, and on success decrypt the next block the same way. Each layer undoes exactly enough encryption to reveal the next check and nothing more, which is why the binary is called an onion: every peel reveals one more layer identical in shape to the last.

From manual stepping to a script

Walking through two or three layers by hand in gdb is enough to confirm the pattern and to see that it repeats for what turns out to be around 1,600 iterations, one per bit of the roughly 200-character input buffer. That count rules out manual analysis entirely.

The automation strategy: dump the full copied region from memory once with dump binary memory packed.dump <start> <start+0x24c8d>, then repeatedly disassemble a growing prefix of that dump with objdump -D -b binary -mi386 -Mintel,x86-64, read off the byte index and bit mask from the mov al, BYTE PTR [rax+N] and and al, M instructions at the start of each decrypted chunk, apply the XOR key found just before the chunk to decrypt the next region in place, and repeat. The script tracks, for every layer, which byte index and bit were tested and whether the expected branch was the matching or the non-matching one, accumulating that information into a 100-entry result table as it goes.

def get_flag(data):
    result = [0] * 100
    for byte, bit, val in data:
        if val:
            result[byte] |= bit
    return [chr(x) for x in result]

Running the full loop over roughly 1,600 layers reconstructs every tested bit of the key buffer, and converting the recovered byte values to characters produces the flag in the format hxp{...}.

Wrong turns worth avoiding

Treating the mmap’d region as static code and disassembling it once is a dead end, since almost all of it is still encrypted at that point; only the first chunk makes sense before anything has run. Patching out the ptrace check by NOPing the call also works but is riskier than overriding the return value, since the surrounding code may depend on the call actually returning. Finally, assuming the loop count is small enough for manual stepping wastes real time before the scale of the layering becomes clear.

What transfers to other challenges

Self-decrypting, layer-at-a-time code is a recognizable shape: a single generic unpacking stub, repeated with different keys and different embedded checks. Once one layer is understood, the rest is scripting, not analysis. The same anti-debug bypass, overriding a register after a breakpoint on the detection call rather than patching code, applies to any ptrace-based check. For the pwn-side equivalent of planting and later triggering injected code inside a running environment, see boot2brainfuck from the same event. An entropy trace is the fastest way to locate where an encrypted or packed region starts inside a binary before setting the first breakpoint, covered in compression versus encryption and in binary data visualization.

Questions readers ask

What does the ptrace check actually block?

The binary calls ptrace with PTRACE_TRACEME, which fails and returns -1 whenever the process is already being traced by a debugger. Running the binary directly under gdb trips this check immediately, so the program prints its failure message before asking for input.

How is the ptrace check defeated?

A breakpoint placed directly on the ptrace call lets the debugger step past the call and overwrite the return value in the rax register with 0 before the check reads it, which matches what an untraced process would see.

Why does each layer decrypt only a small chunk at a time?

The binary reads a 4-byte count and a 4-byte XOR key from the current position, then applies the key across that many following bytes. Keeping each decrypted region small means a wrong guess for one input character only exposes one check's worth of code, not the whole program.

Why was manual stepping replaced with a script?

The binary repeats the same four-instruction pattern, checking one bit of one byte, for roughly 1,600 layers. A Python script that parses the objdump output of each decrypted chunk, extracts the byte index, the bit mask and the expected branch outcome, then decrypts the next chunk using the key found in the current one, turns a task that would take hours of manual stepping into a loop that finishes in a few minutes.

New to capture the flag? Formats, teams and a first-month plan in one place.

Read the CTF guide