The final challenge we are given a series of similar Win32 PE Binaries to analyze. We need to unlock each level to get to the next challenge. When we run any of the executables they just print out some asterisks.

When we open a challenge in IDA there is a long line moving bytes and then there is a call to the unpacked code. We can set a breakpoint at that location on the call to the register to take a look.

After a jmp we are at our shellcode that immediately calls LoadLibrary and GetProcAddress to resolve some APIs and then some more moving of bytes around and some hashing functions. If we keep debugging we get to the interesting part where GetEnvironmentVariableA is called looking for a long variable.

If the environment variable is found the result is then compared with a string and this determines the execution path. This process happens again and again taking different paths depending on if the correct environment variable was found or not.

We can instrument the program with a debugger to fuzz the correct path through the program to find the key. We break on GetEnvironmentVariableA to determine the variable that the program is checking for and then we look ahead to see what that value should be. We can then keep track of each path we have tried and decide whether or not to give the correct response.

We can see what this looks like when we run it on the final binary to print the key.

#!/usr/bin/env python

solve for tos challenge
from builtins import range
import sys
import random

from pykd import *
from flaredbg import flaredbg

from treelib import Node, Tree

import argparse
import logging

__author__ = "fdivrp"
__version__ = "v0.1"

tree = Tree()
last = ""
path = []

class Track(object):
    def __init__(self, explored):
        self.explored = explored

def tos_dbg():
    global tree
    global last
    global path

    # Reset last
    last = ""

    # Setup Debugger
    dbg = flaredbg.DebugUtils()

    bp_getenvironmentvariablea = module('kernel32').offset(
    # Set GetEnvironmentVariableA Breakpoint
        "[+]  ADDING BREAKPOINT FOR kernel32!GetEnvironmentVariableA AT: {}".
    DWORD WINAPI GetEnvironmentVariable(
      _In_opt_  LPCTSTR lpName,
      _Out_opt_ LPTSTR  lpBuffer,
      _In_      DWORD   nSize
    If the function succeeds, the return value is the number of characters stored in the buffer pointed to by lpBuffer, not including the terminating null character.

    # parent for tree set to empty to start first round
    tree_parent = ""
    local_path = []
        for i in range(1, 9000):
                # Break on environmentvariablea and get call parameters
                lpName = dbg.read_string(
                    dbg.read_pointer(dbg.get_stack_pointer() + 4))
                lpBuffer = dbg.read_pointer(dbg.get_stack_pointer() + 8)
                nSize = dbg.read_pointer(dbg.get_stack_pointer() + 12)

                # Set a BP on return from EnvironmentVariableA and set return eax to success nSize-1
                dbg.set_reg("eax", nSize - 1)

                # get location of compare
                va = dbg.get_pc()
                mnem = dbg.wdbg_get_mnem(va)
                while mnem != "cmp":
                    va += 1
                    mnem = dbg.wdbg_get_mnem(va)

                # get operand value from cmp
                disasm = dbg.disasm(va)
                offset = str(disasm).split(",")[-1].strip("byte ").lstrip(
                if "+" in offset:
                    offset = offset.split("+ ")[-1]
                offset = int(offset)

                # write cmp constant to EnvironmentVariableA return buffer
                Buffer = dbg.read_string(dbg.get_stack_pointer() + offset)

                # Create tree node if not already created
                node_name = "{}_{}_{}".format(i, lpName, tree_parent[0:9])
                if not tree_parent:
                    if not tree.get_node(node_name):
                        tree.create_node(Buffer, node_name, data=Track(False))
                    if not tree.get_node(node_name):

                # Set tree_parent to current node for next round
                tree_parent = node_name

                # Get immediate children of current node
                children = tree.children(node_name)

                # set all children explored to True unless proven wrong
                all_children_explored = True

                if not children:
                    # if children don't exist write buffer correctly
                    dbg.write_memory(lpBuffer, Buffer)
                    for index, child in enumerate(children):
                        if not and len(children) == 1:
                            # 1 Not Explored = Write Buffer
                            dbg.write_memory(lpBuffer, Buffer)
                            all_children_explored = False
                        elif and len(children) == 1:
                            # 1 Explored = Don't Write Buffer, more explore
                            all_children_explored = False
                            dbg.write_memory(lpBuffer, "NOTSET")
                        elif not
                            # > 1 Not Explored = Don't Write Buffer, more explore
                            all_children_explored = False
                            dbg.write_memory(lpBuffer, "NOTSET")
                    if all_children_explored:
                        # > 1 All Explored mark self explored and exit
                        tree.get_node(node_name).data.explored = True
                        dbg.write_memory(lpBuffer, "NOTSET")
                        del dbg
                """# Are you feeling lucky? Randomly write the buffer correctly
                if bool(random.getrandbits(1)):
                    dbg.write_memory(lpBuffer, Buffer)
                    dbg.write_memory(lpBuffer, "NOTSET")

                last = node_name
                logging.debug("[+] R{} lpName: {}=({},{})->{}".format(
                    i, lpName, hex(lpBuffer), nSize - 1, Buffer))



        # Check if this path was the same as last and set highest node explored
            if path == local_path:
                for path_index in range(len(path)):
                    if tree.get_node(
                            path[-(path_index + 1)]).data.explored == False:
                        logging.debug("[!] SAME PATH SET EXPLORED: {}".format(
                            tree.get_node(path[-(path_index + 1)]).identifier))
                            path[-(path_index + 1)]).data.explored = True
        except Exception as e:
            logging.debug("[!] SAME PATH ERROR {}".format(e))
        logging.debug("PATH: {}".format(path))
        logging.debug("LOCALPATH: {}".format(local_path))
        path = local_path

        tree.get_node(last).data.explored = True
        logging.debug("[+] Last: {}".format(last))
        parent = tree.parent(last).identifier
        logging.debug("[+] Parent: {}".format(parent))
        logging.debug("[+] Parent Children: {}".format(
            [x.identifier for x in tree.children(parent)]))
        del dbg

def main():
    """Main method
    global last
    global path
    parser = argparse.ArgumentParser(
        description="%s solves tos challenge" % __file__)
        help="Print verbose debugging information")
    parser.add_argument("filename", type=str, help="Filename test")
    args = parser.parse_args()

    if args.verbosity:
            format=' %(asctime)s - %(levelname)s - %(message)s')

    logging.debug("[+] Args: %s" % args)

    # Loop 5ever trying to test all paths
    while 1:
            # print tree.to_dict()

        except Exception as e:

if __name__ == '__main__':
env_vars1 = {
    'And my time was running wild',
    'Yes were lovers, and that is that',
    'I said that time may change me',
    'Oh we can be heroes, just for one day',
    'But I cant trace time',
    'Oh we can beat them, forever and ever'

env_vars2 = {
    'Dropped my cell phone down below',
    'Of warm impermanence and',
    'Oh we can beat them, forever and ever',
    'We can be heroes, just for one day',
    'A million deadend streets',
    'Wheres your shame',
    'And these children that you spit on',
    'Then we could be heroes, just for one day'


env_vars3 = {
    'I never did anything out of the blue',
    'Ashes to ashes, fun to funky',
    'Your circuits dead, theres something wrong',
    'Do you remember a guy thats been in such an early song',
    'And theres nothing I can do',
    'To get things done',
    'Im feeling very still',
    'Now its time to leave the capsule if you dare'


env_varsF = {
    'Ziggy played guitar',
    'Then we could be heroes just for one day',
    'Heaven knows, shed have taken anything, but',
    'Showing nothing, he swoops like a song',
    'Oh, look out you rock n rollers',
    'He kissed her then and there'

# PAN{dd864aebeeba3e125dce2e111e6ea04fb759333409a87da8e7bd413b3e36105b}