#!/usr/bin/python

import distorm3

def get_codes(binary):
    ''' parse binary to extract access codes
    '''
    codes = []
    disasm = {}

    # disassemble everything into memory... yuck
    iterable = distorm3.DecodeGenerator(0x0, binary, distorm3.Decode32Bits)
    for (offset, size, instruction, hexdump) in iterable:
        disasm[offset] = (size, instruction)


    # this is where the check sequence starts
    start = 0x000007bf
    instructions = []


    # get interesting instructions
    for x in range(16):
        size, instr = disasm[start]
        instructions.append(instr)

        # hop 2 instructions
        start += size
        size, instr = disasm[start]
    
        start += size
        size, instr = disasm[start]
        start += size


    # parse interesting instructions
    for instr in instructions:
        # just checking it's != 0
        if instr == 'TEST EAX, EAX':
            codes.append("1")

        # else we get the check value
        elif instr.startswith('CMP EAX, '):
            value = instr.split(" ")[-1]
            codes.append(str(eval(value)))

    return codes


print get_codes(open("./gift", 'rb').read())
