#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# This exploit template was generated via:
# $ pwn template --host 111.186.63.16 --port 20193
from pwn import *
import hashlib

# Set up pwntools for the correct architecture
context.update(arch='i386')
exe = './path/to/binary'

# 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
host = args.HOST or '111.186.63.16'
port = int(args.PORT or 20193)

def local(argv=[], *a, **kw):
    '''Execute the target binary locally'''
    if args.GDB:
        return gdb.debug([exe] + argv, gdbscript=gdbscript, *a, **kw)
    else:
        return process([exe] + argv, *a, **kw)

def 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 local(argv, *a, **kw)
    else:
        return 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 = '''
continue
'''.format(**locals())

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

CHARS = ''.join([chr(i) for i in range(0x20, 0x7F)])

def treehash(pos, trees):
    counterlist = ""
    for tree in trees:
        counterlist += get_counters(pos, tree)
    return hashlib.md5(counterlist.encode("ascii")).hexdigest()

def get_counters(pos, tree):

    io = start()
    #a = sanitize_process.stdout.readline()
    inputstr = tree + "\n" + "4" + "\n" + str(pos) + "\n" + "1" + "\n" + "2" + "\n" +"3" + "\n"
    io.send(inputstr)
    output = io.recvall()
    #print(output)
    return output

def gettrees():
    trees = []
    for c in CHARS:
        trees.append(c * 27) 
    return trees

def gettable():
    tablefile = open("table2/table_new2.table", "r")
    table = []
    for i in tablefile.readlines():
        table.append(eval(i))
    return table

def teststr(pos, trees, table):
    key = treehash(pos, trees)
    print(key)
    possibilities = []
    for row in table: 
        if row[1] == key: 
            possibilities.append(row[0])
            print(row[0])
    return possibilities

trees = gettrees()
table = gettable()
print(table)

flag = []# ['flag{fr0M_C0vEr4ge_To_Fl4G_And_Enj0Y_0cTF_2Ol9!}']
for i in range(47):
    possibilities = teststr(i, trees, table)
    # if res:
    #     possibilities.append(target)
    #     print("Target HIT: " + target)
    # print(possibilities)
    flag.append(possibilities)
    print(flag)
    open("save","w").write(str(flag))
print(flag)
    

# 

#     
        


