La Quinta Maquina

They said this machine was unbeatable, but they were wrong! This version introduces an unprecedented architecture: Matryoshka JIT.

Recon

“La quinta máquina” is Spanish for “the fifth machine”, and this binary is the fifth in the author’s series of custom-machine reversals.

The handout LaQuintaMaquina.zip holds a single 18,568-byte stripped x86-64 PIE ELF, la_quinta_maquina_v5, that takes the flag as argv[1] and validates it locally. The announced architecture turned out to be accurate: the program copies a blob from .rodata into freshly mapped executable memory, runs it, and that layer decrypts and runs the next one, four layers deep, each checking 8 flag bytes through its own bytecode program. None of that was visible at first contact, because at first contact the machine refused to say a word.

First contact, and what the machine actually answers

We executed the binary with a few probe arguments:

$ timeout 10 ./la_quinta_maquina_v5 'NVR{test_test}'
EXIT=124
$ ./la_quinta_maquina_v5 hello
Usage: ./la_quinta_maquina_v5 NVR{...}
EXIT=1
$ ./la_quinta_maquina_v5
Usage: ./la_quinta_maquina_v5 <flag>
EXIT=1

Format errors answer instantly, and the two usage strings differ (a missing argument and a malformed one print different tails), so the NVR{ check runs in main before anything else. A well-formed input, right or wrong, produced no verdict at all, only silence until the timeout killed the process, and an strace attempt left an empty log. The live program was an argument checker that then stalls, so we moved to strings and the disassembler.

Strings and imports

$ strings la_quinta_maquina_v5 | grep -E "Stage|Oracle|Matryoshka|Usage|expand|proc"
[Stage %d] INVALID! Oracle signals failure.
Correct! Matryoshka JIT payload fully unlocked.
[Stage %d] Checksum OK. Proceeding deeper...
Usage: %s <flag>
Usage: %s NVR{...}
/proc/self/status
expand 32-byte k

expand 32-byte k is the ChaCha20 sigma constant that seeds the cipher state in RFC 8439, so a ChaCha20 implementation is hand-rolled inside, and the stage strings are the verdict vocabulary we never got to see live.

$ objdump -T la_quinta_maquina_v5 | awk '{print $NF}' | sort -u | grep -E '^(fopen|fork|mmap|mprotect|ptrace|raise|sigaction|strlen|strncmp|waitpid)$'
fopen
fork
mmap
mprotect
ptrace
raise
sigaction
strlen
strncmp
waitpid

mmap and mprotect mean runtime-generated code, sigaction and raise mean signal-driven dispatch, and ptrace with fork and waitpid plus a /proc/self/status read is the classic anti-debug toolkit. Together with the hang, that set said the stall is a fork/ptrace handshake that never completes, and the disassembly confirmed it.

Exploitation

main hands the machine a struct of function pointers

main sits at 0x12a0 (in this binary the virtual address always equals the file offset). After the strncmp format checks it builds a 0x38-byte struct of function pointers on the stack and passes it to the machine along with the flag pointer and the dword at 0x501c. The internal entries arrive through R_X86_64_RELATIVE relocations at 0x4fb0, 0x4fd0 and 0x4ff8 with addends 0x19d0, 0x1e80 and 0x2570, and GOT slots supply mmap and mprotect:

slot value role
+0x00 0x2570 the bytecode interpreter (the “oracle” of the stage strings)
+0x08 0x1e80 SHA-256
+0x10 0x19d0 ChaCha20 decryptor
+0x18 &mmap
+0x20 0x15c0 report(stage)
+0x28 0x1590 invalid(stage)
+0x30 &mprotect

main then mmaps 0x39b writable bytes, copies the blob at file offset 0x3100 into them, flips the pages to read plus execute with mprotect, and calls the result as a function. No decrypted layer calls libc directly, everything goes through this struct, which keeps each layer position-independent while mmap lands it at a different random address.

The anti-debug key factory, and why the binary hangs

The function at 0x2320, called from main before the machine starts, accumulates four XORs into the dword at 0x501c.

The first check polls /proc/self/status. The scan is readable right in the disassembly: movabs r13, 0x6950726563617254 spells TracerPi in ASCII, and the dword compare against 0x093a6469 completes the pattern as TracerPid:\t. fgets reads the file, strtol parses the number, and a zero (no tracer) jumps to 0x2550, which loads 0xcafebabe, while a nonzero value falls through to 0x23ce, which loads 0xdeadbeef. Either way xor dword ptr [rip + 0x2c33], eax at 0x23e3 folds the constant into 0x501c.

The second check is a trap. The call at 0x2424 resolves to sigaction, and the lea rax, [rip - 0xe0] just above it computes 0x2310, the handler being installed. The very next instruction, int3 at 0x2429, fires it, and the handler’s entire body is:

0x2314: xor dword ptr [rip + 0x2cfe], 0x55555555
0x231e: ret

Both rip-relative targets resolve to 0x501c, so the trap execution itself mixes a third constant into the accumulator.

The third check is self-tracing. call fork at 0x242a, and in the child call ptrace at 0x2443 with all four argument registers zeroed, which is PTRACE_TRACEME, the child asking its own parent to trace it. The result feeds a branchless select:

0x2448: cmp  eax, 1
0x244b: sbb  eax, eax
0x244d: and  eax, 0x678aa105
0x2452: sub  eax, 0x5452e216
0x2457: xor  eax, dword ptr [rip + 0x2bbf]

A successful TRACEME returns 0, the borrow from cmp turns sbb eax, eax into -1, the AND keeps the full mask, and the SUB lands on 0x1337beef (0x678aa105 - 0x5452e216). A failed call returns -1, the compare against 1 then takes no borrow, sbb leaves the register at 0, and the SUB produces 0xabad1dea. Writing the constants as mask - const instead of mov eax, imm32 hides them from a byte search, which is why we found no trace of them until we did the arithmetic.

The fourth check is timing. Two rdtsc instructions bracket a 1000-iteration busy loop (the counter is compared against 0x3e7), and the elapsed cycles are compared against 0x2faf080, fifty million. The same sbb/and/sub shape with 0x585c11ef - 0x45245300 yields 0x1337beef when the loop ran fast and 0xbadbad00 when it did not. Then mov dword ptr [rip + 0x2b58], eax at 0x24be stores the accumulated key back to 0x501c, and the child parks itself with raise(SIGSTOP) at 0x24c4 (edi holds 0x13, which is SIGSTOP) until the parent PTRACE_CONTs it.

On a clean run every good branch fires and the two 0x1337beef contributions cancel, so the machine receives 0 ^ 0xcafebabe ^ 0x55555555 = 0x9fabefeb as its third argument. Nothing here aborts on detection; a traced process runs the same path with a silently poisoned key. The first-contact hang also has its cause now: if the TRACEME handshake ever fails, the child still SIGSTOPs itself, the parent’s PTRACE_CONT gets nothing, and both processes end up waiting on each other forever. Any well-formed flag stalls before the first stage message, which is what we observed.

Patching the machine awake

For a live oracle we copied the binary and neutralized the three ptrace-dependent call sites. A byte diff of the copy against the original shows exactly these three ranges and nothing else:

0x242a  call fork   e8 61 ee ff ff -> 31 c0 90 90 90   xor eax,eax; nops, always the child path
0x2443  call ptrace e8 e8 ed ff ff -> 31 c0 90 90 90   xor eax,eax, TRACEME reads as success
0x24c4  call raise  e8 b7 ec ff ff -> 90 90 90 90 90   nops, no SIGSTOP

The int3 and its handler stay untouched, so the 0x55555555 fold still happens and the key remains 0x9fabefeb, the value a clean run computes. The patched copy behaves like a working verdict machine for bad formats:

$ ./laqm_patched hello
Usage: ./laqm_patched NVR{...}
EXIT=1

The oracle and its bytecode

The ctx entry at 0x2570 is a bytecode interpreter. Its prologue shows the setup: the first 8 flag bytes become two little-endian dword registers (mov rax, qword ptr [rsi] then mov qword ptr [rsp], rax), the key from edx lands in reg[2], reg[3] starts at 0, and a dispatch loop reads the program pointed to by rdi. The fetch at 0x25a6 and the comparison ladder that follows give seven opcodes:

opcode semantics
0x10 MOV reg[a], imm32
0x20 ADD reg[a], reg[b]
0x30 XOR reg[a], reg[b]
0x40 ROL reg[a], imm8
0x50 BSWAP reg[a]
0x60 CMP reg[a], reg[b], mismatch returns 0
0x00 halt, return 1

An unknown byte is skipped, so the program tolerates padding. The stage-0 program is the 31 bytes at layer-blob offset 0xf0, file offset 0x31f0, and every layer ships the same shape with different constants:

30 00 02        r0 ^= key
20 00 01        r0 += r1
40 01 05        r1 = rol(r1, 5)
30 01 00        r1 ^= r0
10 02 f2ed3057  r2 = 0x5730edf2
60 00 02        r0 == r2 ?
10 03 5c64d611  r3 = 0x11d6645c
60 01 03        r1 == r3 ?
00              halt, return 1

Each stage therefore imposes exactly two equations on its 8 bytes, where f0 and f1 are the two little-endian dwords of the chunk and r0 stands for (f0 ^ key) + f1 mod 2^32. Passing requires r0 == T0 and rol(f1, 5) ^ r0 == T1. Both are invertible, and the second one does not even involve the key, because on a passing run r0 equals T0:

f1 = ror32(T1 ^ T0, 5)
f0 = ((T0 - f1) mod 2^32) ^ key

For stage 0 the first line gives M47r with no key needed, and the second line with 0x9fabefeb gives NVR{. The flag format forces the first four bytes to be NVR{, so the same pair of equations also runs in reverse: assuming f0 is NVR{ pins the key at exactly 0x9fabefeb, the same value the anti-debug chain produced. Two independent derivations agreeing is what let us trust the offline solve.

Our first attempt was sloppier than that reasoning. We read the two immediates out of a hex dump by eye and slipped by two bytes; on the last layer that turned T1 into 0xa67d5276 instead of 0xda276517, and at stage 0 the mangled chunk came out as M, an unprintable 0x04, hr, instead of M47r. The candidate our notes recorded from that attempt is the one we tested against the patched binary:

$ ./laqm_patched 'NVR{MhrAAAA}'
[Stage 0] INVALID! Oracle signals failure.
EXIT=1

An early Unicorn harness we built to debug this returned 0 for every candidate at that point, which was the push to stop reading hex by hand. The targets sit at fixed offsets in the 31-byte program, right after the 10 02 and 10 03 opcode pairs, so they can be pulled programmatically and never misread again. With the corrected constants the emulator confirmed the model. The harness maps the whole ELF at 0x400000, points rdi at the stage-0 program, writes the candidate chunk where rsi points, puts the key in edx, and runs from 0x2570 until a sentinel return address:

import struct
from unicorn import *
from unicorn.x86_const import *

BIN = open('la_quinta_maquina_v5','rb').read()
BASE, STACK, FSBASE, MAGIC_RET = 0x400000, 0x7ff000000000, 0x7fb000000000, 0x900000

def check(f0, f1, key):
    mu = Uc(UC_ARCH_X86, UC_MODE_64)
    mu.mem_map(BASE, 0x10000); mu.mem_write(BASE, BIN)
    mu.mem_map(STACK - 0x100000, 0x200000); mu.mem_map(FSBASE, 0x10000)
    mu.mem_write(FSBASE + 0x28, struct.pack('<Q', 0x1234567890abcdef))
    mu.reg_write(UC_X86_REG_FS_BASE, FSBASE)
    flagbuf = STACK + 0x1000
    mu.mem_write(flagbuf, struct.pack('<II', f0, f1) + b'\x00' * 24)
    mu.reg_write(UC_X86_REG_RDI, BASE + 0x31f0)   # stage-0 bytecode
    mu.reg_write(UC_X86_REG_RSI, flagbuf)
    mu.reg_write(UC_X86_REG_RDX, key)
    RSP = STACK + 0x80000
    mu.mem_write(RSP, struct.pack('<Q', MAGIC_RET)); mu.reg_write(UC_X86_REG_RSP, RSP)
    mu.emu_start(BASE + 0x2570, MAGIC_RET, count=500000)
    return mu.reg_read(UC_X86_REG_EAX)

f0 = struct.unpack('<I', b'NVR{')[0]
f1 = struct.unpack('<I', b'M47r')[0]
print('NVR{ + M47r + key 0x9fabefeb ->', check(f0, f1, 0x9fabefeb))
print('NVR{ + M47r + key 0xdeadbeef ->', check(f0, f1, 0xdeadbeef))
print('NVR{ + M47s + key 0x9fabefeb ->', check(f0, f1 ^ 1, 0x9fabefeb))
$ ./emu.py
NVR{ + M47r + key 0x9fabefeb -> 1
NVR{ + M47r + key 0xdeadbeef -> 0
NVR{ + M47s + key 0x9fabefeb -> 0

The interpreter returns 1 only for the recovered bytes under the clean-run key; a wrong key or a one-bit-wrong chunk returns 0.

Peeling the layers offline

Every layer blob shares one layout: dispatcher code up front, a 12-byte nonce of all zeros at +0xe4 (we checked the bytes in the dump), the 31-byte bytecode at +0xf0, and the ChaCha20 ciphertext of the next layer at +0x10f. The layer sizes are 0x39b for the copy from 0x3100, then 0x28c, 0x17d and 0x6e. The last layer is only 0x6e bytes, so its bytecode sits at +0x4f and there is no further ciphertext; its decrypted bytes end with mov edi, 3 followed by call qword ptr [rax + 0x20], which is ctx+0x20, so on a pass it calls report(3) and that prints the win message. The decryption key for each layer is SHA-256 of the 8 bytes the previous layer just validated, so every solved chunk unlocks exactly one more layer.

We pinned the ChaCha20 parameters empirically instead of reading the cipher, by decrypting the layer-2 ciphertext (at layer-1 offset 0x10f, length 0x28c) under the key SHA-256(NVR{M47r) with counter 0 and with counter 1, nonce fixed at the 12 zero bytes:

$ python3 layer2.py
ctr0-nonce-before: head=554889e54883ec4048897df8488975f0 ascii-ish=24/64
ctr1-nonce-before: head=677e5d22920244c4d3c81b7b91df97f6 ascii-ish=31/64
ctr0-nonce-after:  head=554889e54883ec4048897df8488975f0 ascii-ish=24/64

Counter 0 produces 55 48 89 e5 48 83 ec 40, the textbook x86-64 function prologue push rbp; mov rbp, rsp; sub rsp, 0x40, while counter 1 produces noise. (The script’s third variant differs only in an argument the function ignores, hence the identical head.)

With the parameters settled, the whole chain reduces to one loop. The script starts from layer 1 carved out of the ELF, solves the stage program inside it, uses the solved chunk as the ChaCha20 key for the next layer’s ciphertext, and repeats until layer 4. The targets function is the programmatic fix for the misread: the two immediates sit at offsets 0x0e and 0x17 of the program, right after the 10 02 and 10 03 pairs.

import hashlib, struct

M = 0xffffffff
def rol(x, n): return ((x << n) | (x >> (32 - n))) & M
def ror(x, n): return ((x >> n) | (x << (32 - n))) & M

KEY = 0x9fabefeb          # anti-debug XOR chain: 0 ^ 0xcafebabe ^ 0x55555555

def solve_stage(t0, t1):
    f1 = ror(t1 ^ t0, 5)                  # key-independent
    f0 = ((t0 - f1) & M) ^ KEY
    return struct.pack('<II', f0, f1)

def targets(bc):                          # the two MOV imm32s in the 31-byte program
    assert bc[:0x0c] == bytes.fromhex('300002200001400105300100')
    t0 = struct.unpack('<I', bc[0x0e:0x12])[0]   # after '10 02'
    t1 = struct.unpack('<I', bc[0x17:0x1b])[0]   # after '10 03'
    return t0, t1

# --- ChaCha20 (RFC 8439), counter 0, 12-byte zero nonce ---
def qr(s, a, b, c, d):
    s[a] = (s[a] + s[b]) & M; s[d] = rol(s[d] ^ s[a], 16)
    s[c] = (s[c] + s[d]) & M; s[b] = rol(s[b] ^ s[c], 12)
    s[a] = (s[a] + s[b]) & M; s[d] = rol(s[d] ^ s[a], 8)
    s[c] = (s[c] + s[d]) & M; s[b] = rol(s[b] ^ s[c], 7)

def chacha(key, data):
    out = bytearray()
    for off in range(0, len(data), 64):
        st = list(struct.unpack('<4I', b'expand 32-byte k')) \
           + list(struct.unpack('<8I', key)) + [off // 64] + [0, 0, 0]
        w = st[:]
        for _ in range(10):
            qr(w,0,4,8,12); qr(w,1,5,9,13); qr(w,2,6,10,14); qr(w,3,7,11,15)
            qr(w,0,5,10,15); qr(w,1,6,11,12); qr(w,2,7,8,13); qr(w,3,4,9,14)
        ks = struct.pack('<16I', *[(a + b) & M for a, b in zip(w, st)])
        out += bytes(x ^ y for x, y in zip(data[off:off + 64], ks))
    return bytes(out)

# --- walk the onion ---
elf  = open('la_quinta_maquina_v5', 'rb').read()
blob = elf[0x3100:0x3100 + 0x39b]         # layer 1: dispatcher + stage-0 program + layer-2 ct
flag = b''
for i in range(4):
    bc_off = 0xf0 if i < 3 else 0x4f      # layer 4 is only 0x6e bytes long
    t0, t1 = targets(blob[bc_off:bc_off + 31])
    chunk = solve_stage(t0, t1)
    flag += chunk
    print(f"stage {i}: T0={t0:#010x} T1={t1:#010x} -> {chunk}")
    if i < 3:
        ct_len = [0x28c, 0x17d, 0x6e][i]
        blob = chacha(hashlib.sha256(flag[-8:]).digest(), blob[0x10f:0x10f + ct_len])
        print(f"        next layer head: {blob[:8].hex()}")
print("flag:", flag.decode())

Flag capture

The solver assembles all four chunks into the flag, whose inner text is the machine describing itself in leetspeak, a matryoshka VM with an oracle. Feeding its output straight into the patched binary confirms every byte through the real oracle (tail -1 | cut -d' ' -f2 picks the flag out of the solver’s last line):

$ python3 solve.py
stage 0: T0=0x5730edf2 T1=0x11d6645c -> b'NVR{M47r'
        next layer head: 554889e54883ec40
stage 1: T0=0x4e3813fd T1=0x85de9e97 -> b'y0shk4_V'
        next layer head: 554889e54883ec40
stage 2: T0=0xdf3c191a T1=0xd4d1179c -> b'M_w1th_0'
        next layer head: 554889e54883ec40
stage 3: T0=0x71210ef8 T1=0xda276517 -> b'r4cl_3X}'
flag: NVR{M47ry0shk4_VM_w1th_0r4cl_3X}

$ ./laqm_patched "$(python3 solve.py | tail -1 | cut -d' ' -f2)"
[Stage 0] Checksum OK. Proceeding deeper...
[Stage 1] Checksum OK. Proceeding deeper...
[Stage 2] Checksum OK. Proceeding deeper...
Correct! Matryoshka JIT payload fully unlocked.