Saturday, 1 April 2017

Remote debugging in IDA Pro by http tunnelling

IDA Pro provides remote debugging capability that allows us to debug a target binary residing on a different machine over the network. This feature is very useful in situations such as when we want to debug an executable for an arm device as installing IDA on it is not possible. IDA can remotely debug another binary in two ways - through a gdbserver or by the provided debugger servers (located in dbgsrv directory).

These debugging servers transport the debugger commands, messages and relevant data over a TCP/IP network through BSD sockets. So far so good, but what if the debugging server resided on a virtual host hosting multiple domain names? We cannot use sockets anymore.

A socket connection between two endpoints is characterized by a pair of socket addresses, one for each node. The socket address, in turn, comprises of the IP address and a port number. For an incoming socket connection, a server hosting multiple domains on the same IP address cannot decide which domain to actually forward the request based on socket address alone. Thus remote debugging using sockets is not possible. However, this is not entirely true as there are techniques such as port forwarding (aka virtual server) that can be used to reroute the incoming traffic to various private IPs based on a pre-decided table. Port forwarding capability is not available everywhere so we can ignore it for now. Instead, it would be much better if sockets supported connections based on domain names as described in this paper Name-based Virtual Hosting in TCP.

The Application Layer Protocol HTTP solves the virtual host problem by including the Host header in HTTP messages. It seems that if we can wrap the transport layer socket traffic in plain old HTTP messages our problem would be solved. The rest of the blog post describes this process in detail.

The problem

A few days ago, I was trying some CTF challenge involving an arm binary. The binary was loaded in IDA within a Windows XP VM. Debugging the binary would require a Linux box at the minimum with qemu-arm installed. Rather than powering up my ubuntu VM, I decided to debug it remotely on cloud9. Cloud9 is a sort of VPS that provide Docker Ubuntu containers called as workspaces where we can run whatever we want. The arm binary can be debugged using qemu as follows:

$ qemu-arm-static -g 8081 ./challenge

We are using the user mode emulation capability of qemu to run non-native elf binaries. The port on which qemu listens for incoming gdb connections is specified by the -g flag and is 8081 in this case. We have specified port 8081 as it is one of the few ports cloud9 allows incoming connections. Now, if we try to attach to the process in IDA using remote gdb debugger as the debugger type configured as shown in Figure 1, IDA fails.
Remote debugger configuration
Figure 1: Remote debugger configuration (ignore the paths)
This is expected as the container on which the debuggee is running is on a virtual host where multiple containers have same IP addresses with different domain names. A socket connects by IP addresses and not by domain names thus it is not possible to connect to our container using sockets. We can get a clearer picture using netcat.

Let us create a netcat server listening on port 8081 as shown in Figure 2.
Netcat server listening on port 8081
Figure 2: Netcat server listening on port 8081
We can try to connect to this server from our Windows XP VM as shown in Figure 3.

Trying to connect to our netcat server
Figure 3: Trying to connect to our netcat server

Unsurprisingly, this fails too for the same reason.

The workaround

We have seen that socket connection is be made using IP addresses. However, if we connect using HTTP we can use domain names. This is possible because of the Host header as mentioned earlier, Let's test this concept.

We create a netcat server listening on port 8081 which replies with a HTTP "HELLO WORLD" message. This is done as shown in Figure 4

Netcat server replying with http message
Figure 4: Netcat server replying with HTTP message
For the client part in the Windows XP box, we use curl instead of netcat as shown in Figure 5. We choose curl over netcat as we are performing an HTTP transaction and not a socket connection.

Figure 5: Using curl to connect to the netcat server

The connection succeeds and we get the HELLO WORLD response. The netcat server running on cloud9 also displays the success status as in Figure 6.
Netcat server replied to the request
Figure 6: Netcat server replied to the request
From the above experiments, it is clear that we must use HTTP in order to establish a connection to the remote container running on a virtual host. Similarly, if we intend to debug remotely an app using IDA we must also use HTTP instead of sockets.

Using HTTP Tunnelling

We have seen that connection using HTTP is only possible. If we want to use sockets, it must be wrapped in HTTP. This technique of encapsulating one protocol over HTTP is called HTTP tunnelling. Wikipedia explains this best. Primarily, HTTP tunnels are used to bypass restrictive network environments like firewalls where only connections to well-known ports are permitted. We can reuse the tunnelling technique for debugging in IDA as well.

A Http tunnel application consists of two parts - server and client both communicating over HTTP. Before using a Http tunnel the situation was like Figure 7.

Socket connection
Figure 7: Socket connection

After using Http tunnel, the situation would look like Figure 8.

Http tunnelling
Figure 8: Http tunnelling
The debugger and tunnel client reside on the same machine though they are depicted as separate computers. Similarly, the tunnel client and the debuggee reside on the same cloud9 container. The tunnel client-server pair encapsulates the socket in an Http connection. Using this mechanism we can remotely debug using IDA.

Searching for a Http tunnelling application, I came across Chisel. It is open-source and written in Go. Compiling this from source is simple:

$ git clone https://github.com/jpillora/chisel.git
$ cd chisel
$ go build -o chisel # for compiling native linux binaries
$ GOOS=windows GOARCH=386 go build -o chisel.exe # cross compiling for windows x86

Remote configuration


We run the chisel server on cloud9 listening on port 8081 on all network interfaces:

$ ./chisel server --port=8081
2017/03/31 19:57:03 server: Fingerprint 07:4e:00:e4:82:9b:76:3a:3a:70:55:30:2e:1d:c2:82
2017/03/31 19:57:03 server: Listening on 8081...

qemu runs with the gdbserver listening on port 23946 for incoming gdb connections from IDA.

$ qemu-arm-static -g 23946 ./challenge

The connection between chisel server and qemu is through sockets. The debugger traffic wrapped in Http will be passed to chisel server at port 8081, chisel will extract the payload of the message and pass it to qemu at port 23946 over a socket.

Local configuration

In our Windows XP box we run chisel in client mode with the following command line:

C:\>chisel client qemu-extremecoders-re.c9users.io:8081 1234:23946
2017/04/01 01:28:36 client: Connecting to ws://qemu-extremecoders-re.c9users.io:8081
2017/04/01 01:28:38 client: Fingerprint 07:4e:00:e4:82:9b:76:3a:3a:70:55:30:2e:1d:c2:82
2017/04/01 01:28:39 client: Connected (Latency 203.125ms)

The remote Url on which the chisel server listens (qemu-extremecoders-re.c9users.io:8081) is specified along with the port.

The second set of port (1234:23946) separated by a colon specifies the port mapping from local to remote. It means incoming traffic to chisel client at local port 1234 will be forwarded to the chisel server which will, in turn, relay the traffic over a socket to port 23946 where qemu is listening.

Finally, we need to configure IDA to use the local chisel client as the remote host. This is done as per Figure 9.
 IDA remote debugger configuration
Figure 9: IDA remote debugger configuration
The hostname is specified as 127.0.0.1 and the port as 1234. This is the address where the chisel client is accepting socket connections.

At this point, if we try to attach to the remote process, it succeeds with the following message as in Figure 10.
Attach successful
Figure 10: Attach successful

Mission accomplished!

Final words

Http tunnelling is a very effective technique in scenarios where only Http connections are allowed or possible. In this case of remote debugging, we used http tunnelling since normal socket connections cannot be established. With this we come to the end of this post. Hope you find this useful. Ciao!

Sunday, 26 March 2017

67,000 cuts with python-pefile

EasyCTF featured an interesting reversing engineering challenge. The problem statement is shown in Figure 1.
Figure 1: Problem statement
A file 67k.zip was provided containing 67,085 PE files numbered from 00000.exe to 1060c.exe as shown in Figure 2.

67k files to reverse
Figure 2: 67k files to reverse!

The task was to reverse engineer each of them and combine their solutions to get the flag. All of the files were exactly 2048 bytes in size as shown in Figure 3.

2048 all the way
Figure 3: 2048 all the way
Let's analyze one of the files, say the first one 00000.exe in IDA. The graph view is simple as in Figure 4.
Graph view
Figure 4: Graph view of 00000.exe
The program accepts one integer input through scanf. This is compared with another number generated by a simple operation like sub on two hard-coded integers stored in register eax and ecx. If they match, we go to the green basic block on the left. It does another calculation (sar - Shift Arithmetic Right at 402042) and finally prints this calculated value along with the success message at 40204F. This general pattern is followed by all of the 67,085 files with minor changes as enumerated below:

  • The imagebase and the entrypoint of the PE vary with each file.
  • The operation on the two hardcoded integers can be any of addition, subtraction or xor.
  • The address of the function (op_sub in the example) performing the operation varies.
  • The address of the hard coded integer (dword_403000 in the example) varies.
  • The amount of shift stored in byte_403007 also varies.

Obviously, reversing 67k files by hand is not possible and requires automation. For this task, I choose the pefile module by Ero Carrera. First, we need to get the offsets of the individual instructions from the Entry point. We can do this from OllyDbg as in the following listing. The offsets are in the left most column.

<Modul>/$  68 5E304000       push 0040305E                            ; /s = "Launch codes?"
$+5   >|.  FF15 44104000     call dword ptr [<&msvcrt.puts>]          ; \puts
$+B   >|.  58                pop eax
$+C   >|.  68 6C304000       push 0040306C
$+11  >|.  68 04304000       push 00403004                            ; /format = "%d"
$+16  >|.  FF15 48104000     call dword ptr [<&msvcrt.scanf>]         ; \scanf
$+1C  >|.  83C4 08           add esp,8
$+1F  >|.  A1 00304000       mov eax,dword ptr [403000]
$+24  >|.  B9 EDA7A8A1       mov ecx,A1A8A7ED
$+29  >|.  E8 CFFFFFFF       call <op_sub>
$+2E  >|.  3B05 6C304000     cmp eax,dword ptr [40306C]
$+34  >|.  75 1E             jnz short 0040205A
$+36  >|.  8A0D 07304000     mov cl,byte ptr [403007]
$+3C  >|.  D3F8              sar eax,cl
$+3E  >|.  25 FF000000       and eax,0FF
$+43  >|.  50                push eax                                 ; /<%c>
$+44  >|.  68 34304000       push 00403034                            ; |format = "Wow you got it. Here is the result: (%c)"
$+49  >|.  FF15 4C104000     call dword ptr [<&msvcrt.printf>]        ; \printf
$+4F  >|.  83C4 08           add esp,8
$+52  >|.  EB 0C             jmp short 00402066
$+54  >|>  68 08304000       push 00403008                            ; /s = "I think my dog figured this out before you."
$+59  >|.  FF15 44104000     call dword ptr [<&msvcrt.puts>]          ; \puts
$+5F  >|.  58                pop eax
$+60  >\>  C3                ret

The complete script is provided below.
import zipfile
import struct
import pefile
import cStringIO


def rshift(val, n):
    """
    Implements arithmetic right shift on 32 bits
    """
    return (val % 0x100000000) >> n

def process(buf):
    # Load the Pe file
    pe = pefile.PE(data=buf, fast_load=True)

    # RVA of Entry Point
    ep = pe.OPTIONAL_HEADER.AddressOfEntryPoint

    imagebase = pe.OPTIONAL_HEADER.ImageBase

    # $+1F  >|.  A1 00304000       mov eax,dword ptr [403000]
    # $+24  >|.  B9 EDA7A8A1       mov ecx,A1A8A7ED
    eax = pe.get_dword_at_rva(pe.get_dword_at_rva(ep + 0x1f + 1) - imagebase)
    ecx = pe.get_dword_at_rva(ep + 0x24 + 1)

    # $+29  >|.  E8 CFFFFFFF       call <op_sub>
    fn_offs = struct.unpack('<i', pe.get_data(ep + 0x29 + 1, length = 4))[0]

    # function rva = instruction address + length + func offset from imagebase
    fn_rva = 0x29 + 5 + fn_offs 

    # Get the first byte of the function (op_sub)
    func_byte = ord(pe.get_data(rva = ep+fn_rva, length=1))

    # Perform the operation based on the function byte

    # op_xor
    # 31C8            xor eax,ecx
    # C3              ret
    if func_byte == 0x31:
        eax ^= ecx

    # op_add
    # 01C8            add eax,ecx
    # C3              ret
    elif func_byte == 0x1:
        eax += ecx

    # op_sub
    # 29C8            sub eax,ecx
    # C3              ret
    elif func_byte == 0x29:
        eax -= ecx

    else:
        raise 'Error'

    # $+36  >|.  8A0D 07304000     mov cl,byte ptr [403007]
    # $+3C  >|.  D3F8              sar eax,cl
    # $+3E  >|.  25 FF000000       and eax,0FF
    cl = ord(pe.get_data(pe.get_dword_at_rva(ep+0x36+2)-imagebase, 1))

    return chr(rshift(eax, cl) & 0xFF)

if __name__ == '__main__':
    output = cStringIO.StringIO()
    with zipfile.ZipFile('67k.zip') as f:
        for idx in xrange(67085):
            fname = format(idx, 'x').zfill(5) + '.exe'
            buf = f.read(fname)
            output.write(process(buf))
            # Fast divisiblity check by 1024, 2^10 (last 10 bits must be zero)
            if idx & 0x3FF == 0: 
                print 'Completed', idx

    open('output.txt', 'w').write(output.getvalue())
    print 'Done!!'
Instead of unpacking 67,085 files to the hard drive and fragmenting it in the process, I have used the zipfile module to access the files within the archive. However, zipfile throws an error on opening the archive and must be modified slightly as described in this Stack Overflow answer.

We access the instructions by using the offsets from the entry point. The address of the operation function and the values of the hard-coded integers, shift amount are also obtained similarly. We discern the type of operation performed by examining its first byte. With this information, we can find the correct output.

Running the script on stock Python 2.7 takes close to 15 minutes. With PyPy, this is reduced to 2 minutes. We get a 66 kb output consisting of obfuscated javascript as shown in Figure 5.
Obfuscated javascript output
Figure 5: Obfuscated javascript output
Running the obfuscated javascript on jsfiddle gives us the flag easyctf{wtf_67k_binaries?why_so_mean?} as also shown in Figure 6:
Figure 6: Finally we get the flag

Thursday, 16 March 2017

Hacking the CPython virtual machine to support bytecode debugging


As you may know, Python is an interpreted programming language. By Python, I am referring to the standard implementation i.e CPython. The implication of being interpreted means that python code is never directly executed by the processor. The python compiler converts the source code into an intermediate representation called as the bytecode. The bytecode consists of instructions which at runtime are interpreted by the CPython virtual machine. For knowing more about the nitty-gritty details refer to ceval.c.

Unfortunately, the standard python implementation does not provide a way to debug the bytecode when they are being executed on the virtual machine. You may question, why is that even needed as I can already debug python source code using pdb and similar tools. Also, gdb 7 and above support debugging the virtual machine itself so bytecode debugging may seem unnecessary.

However, that is only one side of the coin. Pdb can be used for debugging only when the source code is available. Gdb no doubt can debug without the source as we are dealing directly with the virtual machine but it is too low level for our tasks. This is akin to finding bugs in your C code by using an In-Circuit Emulator on the processor. Sure, you would find bugs if you have the time and patience but it is unusable for the most of us. What we need, is something in between, one which can not only debug without source but also is not too low-level and can understand the python specific implementation details. Further, it would be an icing on the cake if this system can be implemented directly in python code.

Implementation details of a source code debugger

Firstly, we need to know how a source code debugger is implemented with respect to Python. The defacto python debugger is the pdb module. This is basically a derived class from bdb. Pdb provides a command line user interface and is a wrapper around bdp. Now, both pdb and bdp are coded in python. The main debugging harness in CPython is implemented right within the sys module. 

Among the multifarious utility functions in the sys module, settrace allows us to provide a callback function which just as its name suggest can trace code execution. Python will call this function in response to various events like when a function is called, a function is about to return, an exception is generated or when a new line of code is about to be executed. Refer to the documentation of settrace for knowing about the specifics. 

However, there are a couple of gotchas. Unlike a physical processor, the CPython virtual machine has no concept of breakpoints. There is no such instruction like an INT 3 on x86 or BKPT on ARM to automatically switch the processor to debug state. Instead, the breakpoint mechanism must be implemented in the trace callback function. The trace function will be called whenever a new line of code is about to be executed. We need to check whether the user has requested a break on this line and if so yield control. This mechanism is not without its downside. As the callback will be invoked for every line, and for every other important event, execution speed will be severely reduced. To speed things up, this may be implemented in C as an extension module like cpdb.

So far so good, and it seems line tracing is just the functionality we require, however, this works only at a source code level. The lowest granularity on which tracing works is at the line level. and not at the instruction level as we require.

How does line tracing work?


Python code objects have a special member called co_lnotab. also known as the line number table. It contains a series of unsigned bytes wrapped up in a string. This is used to map bytecode offsets back into the source code line from where the particular instruction originated.

When the CPython virtual machine interprets the source code, after execution of each instruction it checks whether the current bytecode offset is the start point of some source code line, if so; it calls the trace function. An example trace function taken from the bdb module is shown below.
def trace_dispatch(self, frame, event, arg):
    if self.quitting:
        return # None
    if event == 'line':
        return self.dispatch_line(frame)
    if event == 'call':
        return self.dispatch_call(frame, arg)
    if event == 'return':
        return self.dispatch_return(frame, arg)
    if event == 'exception':
        return self.dispatch_exception(frame, arg)
    if event == 'c_call':
        return self.trace_dispatch
    if event == 'c_exception':
        return self.trace_dispatch
    if event == 'c_return':
        return self.trace_dispatch
    print 'bdb.Bdb.dispatch: unknown debugging event:', repr(event)
    return self.trace_dispatch
The trace function is provided with the currently executing frame as an argument. The frame is a data structure that encapsulates the context under which a code object is executing. We can query the frame using the inspect module. We can change the currently executing line by changing f_lineno of the frame object. Similarly, we can modify variables by using the eval function in the context of the globals and locals obtained from the frame.

Bytecode Tracing Techniques

Listed below are some existing techniques for tracing python bytecode execution.

Extending co_lnotab

We have seen co_lnotab, the line number table is used for determining when to call the trace function. Ned Batchelder (2008) showed that it is possible to modify the line number table to include an entry for each instruction offset in the bytecode. To the Python VM, this implies that every instruction corresponds to a different line of source, and hence it calls the trace function for every instruction executed. This technique is very easy to implement and requires no modification to python. We only need to alter the line number table for each code object to include an entry for each instruction. The downside of this approach is that it increases the pyc file size, and more so if the bytecode is obfuscated when we have no idea which bytes are instruction and which are junk. To be on the safer side, we can add an entry for each byte no matter if it is a real instruction or a junk byte.

Compiling python with LLTRACE

An undocumented way to trace bytecode execution is to compile python from source with the LLTRACE flag enabled. At execution time, python prints every instruction it executes on the console. This method is not without its flaws. Printing every executed instruction on the console is an expensive operation slowing down execution speed. Further, we have no control over the execution, i.e. we cannot modify the operation of the code in any way and it is not possible to toggle off this feature when we do not need it.

Introducing a new opcode

Yet another way to implement tracing is to introduce a new opcode altogether (Rouault, 2015). This is a complicated process and requires a lot of modifications to python. The entire process with all its gory details is described on this page. The gist of the approach is that we create a new opcode which Roualt (2015) calls as DEBUG_OP. Whenever Python VM encounters this opcode, it calls a previously user supplied function. passing the execution context consisting of the Frame and the evaluation stack as the arguments.

Undoubtedly, this method is superior to the pre-existing methods, although it requires a lot of changes in the implementation of python. However, the main drawback of this approach is that it requires to modify the instruction stream and slip a DEBUG_OP opcode in between. This is feasible for normal bytecode generated by python but definitely not for the ones which are obfuscated. When the instructions are obfuscated, it is not possible to insert DEBUG_OP opcode in advance as we cannot differentiate between normal instructions and junk instructions.

The proposed method

Keeping note of the limitations of the above techniques, our proposed method must overcome these. Specifically, it must be resistant to obfuscation and should not require any changes to the bytecode itself. It would be ideal if we could reuse or extend existing functionality to support bytecode tracing and debugging.

As said before, the Python VM consults co_lnotab, the line number table before execution of each instruction to determine when to call the trace function. It looks like we can somehow modify this to call our tracing function right before execution of the individual instructions without checking the line number table. This is the approach we will take.

The function responsible for calling the tracing function is maybe_call_line_trace at line #4054 within ceval.c.
/* See Objects/lnotab_notes.txt for a description of how tracing works. */
static int
maybe_call_line_trace(Py_tracefunc func, PyObject *obj,
                      PyFrameObject *frame, int *instr_lb, int *instr_ub,
                      int *instr_prev)
{
    int result = 0;
    int line = frame->f_lineno;

    /* If the last instruction executed isn't in the current
       instruction window, reset the window.
    */
    if (frame->f_lasti < *instr_lb || frame->f_lasti >= *instr_ub) {
        PyAddrPair bounds;
        line = _PyCode_CheckLineNumber(frame->f_code, frame->f_lasti,
                                       &bounds);
        *instr_lb = bounds.ap_lower;
        *instr_ub = bounds.ap_upper;
    }
    /* If the last instruction falls at the start of a line or if
       it represents a jump backwards, update the frame's line
       number and call the trace function. */
    if (frame->f_lasti == *instr_lb || frame->f_lasti < *instr_prev) {
        frame->f_lineno = line;
        result = call_trace(func, obj, frame, PyTrace_LINE, Py_None);
    }
    *instr_prev = frame->f_lasti;
    return result;
}

Those If statements are mostly checking whether the current bytecode instruction maps to the beginning of some line. We can simply remove them to make it call our trace function per executed instruction than per source line.
static int
maybe_call_line_trace(Py_tracefunc func, PyObject *obj,
                      PyFrameObject *frame, int *instr_lb, int *instr_ub,
                      int *instr_prev)
{
    int result = 0;
 result = call_trace(func, obj, frame, PyTrace_LINE, Py_None);
    *instr_prev = frame->f_lasti;
    return result;
}

After building Python from source with those teeny-tiny changes in-place, we have implemented an execution tracer re-using the existing settrace functionality. We now need to code the callback function which will be called by settrace. This can be realized either in Python or C as an extension (like cpdb), but we choose the former for ease of development.

The Tracer


The code of the tracer is listed below and can also be found on GitHub at https://github.com/extremecoders-re/bytecode_tracer
import sys
import dis
import marshal
import argparse

tracefile = None
options = None

# List of valid python opcodes
valid_opcodes = dis.opmap.values()

def trace(frame, event, arg):
    global tracefile, valid_opcodes, options
    if event == 'line':
        # Get the code object
        co_object = frame.f_code

        # Retrieve the name of the associated code object
        co_name = co_object.co_name

        if options.name is None or co_name == options.name:
            # Get the code bytes
            co_bytes = co_object.co_code

            # f_lasti is the offset of the last bytecode instruction executed
            # w.r.t the current code object
            # For the very first instruction this is set to -1
            ins_offs = frame.f_lasti

            if ins_offs >= 0:
                opcode = ord(co_bytes[ins_offs])

                # Check if it is a valid opcode
                if opcode in valid_opcodes:
                    if opcode >= dis.HAVE_ARGUMENT:
                        # Fetch the operand
                        operand = arg = ord(co_bytes[ins_offs+1]) | (ord(co_bytes[ins_offs+2]) << 8)

                        # Resolve instriction arguments if specified
                        if options.resolve:
                            try:
                                if opcode in dis.hasconst:
                                    operand = co_object.co_consts[arg]
                                elif opcode in dis

For demonstrating the usage I have chosen the following piece of code taken from programiz.

# Python program to find the factorial of a number using recursion

def recur_factorial(n):
   """Function to return the factorial
   of a number using recursion"""
   if n == 1:
       return n
   else:
       return n*recur_factorial(n-1)

# Change this value for a different result
num = 7

# check is the number is negative
if num < 0:
   print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
   print("The factorial of 0 is 1")
else:
   print("The factorial of",num,"is",recur_factorial(num))

Suppose, we want to trace the execution of the recur_factorial function. We can do so, by running the following:

$ python tracer.py -t=only -n=recur_factorial -r factorial.pyc trace.txt

We are tracing the execution of only those code objects having a name of recur_factorial.
The -r flag means to resolve the operands of instructions. Instructions in python can take an argument. For some instructions like LOAD_CONST, the argument is an integer specifying the index of an item within the co_consts table which will be pushed on the evaluation stack. If resolution (-r flag) is enabled, the item will be written to the trace instead of the integer argument.

The input file name is factorial.pyc and the trace file name is trace.txt. Running this we get the execution trace like the following
recur_factorial> 0 LOAD_FAST (n)
recur_factorial> 3 LOAD_CONST (1)
recur_factorial> 6 COMPARE_OP (==)
recur_factorial> 16 LOAD_FAST (n)
recur_factorial> 19 LOAD_GLOBAL (recur_factorial)
recur_factorial> 22 LOAD_FAST (n)
recur_factorial> 25 LOAD_CONST (1)
recur_factorial> 28 BINARY_SUBTRACT
recur_factorial> 29 CALL_FUNCTION (1)
recur_factorial> 0 LOAD_FAST (n)
recur_factorial> 3 LOAD_CONST (1)
recur_factorial> 6 COMPARE_OP (==)
recur_factorial> 16 LOAD_FAST (n)
recur_factorial> 19 LOAD_GLOBAL (recur_factorial)
recur_factorial> 22 LOAD_FAST (n)
recur_factorial> 25 LOAD_CONST (1)
recur_factorial> 28 BINARY_SUBTRACT
recur_factorial> 29 CALL_FUNCTION (1)
recur_factorial> 0 LOAD_FAST (n)
recur_factorial> 3 LOAD_CONST (1)
recur_factorial> 6 COMPARE_OP (==)
recur_factorial> 16 LOAD_FAST (n)
recur_factorial> 19 LOAD_GLOBAL (recur_factorial)
recur_factorial> 22 LOAD_FAST (n)
recur_factorial> 25 LOAD_CONST (1)
recur_factorial> 28 BINARY_SUBTRACT
recur_factorial> 29 CALL_FUNCTION (1)
recur_factorial> 0 LOAD_FAST (n)
recur_factorial> 3 LOAD_CONST (1)
recur_factorial> 6 COMPARE_OP (==)
recur_factorial> 16 LOAD_FAST (n)
recur_factorial> 19 LOAD_GLOBAL (recur_factorial)
recur_factorial> 22 LOAD_FAST (n)
recur_factorial> 25 LOAD_CONST (1)
recur_factorial> 28 BINARY_SUBTRACT
recur_factorial> 29 CALL_FUNCTION (1)
recur_factorial> 0 LOAD_FAST (n)
recur_factorial> 3 LOAD_CONST (1)
recur_factorial> 6 COMPARE_OP (==)
recur_factorial> 16 LOAD_FAST (n)
recur_factorial> 19 LOAD_GLOBAL (recur_factorial)
recur_factorial> 22 LOAD_FAST (n)
recur_factorial> 25 LOAD_CONST (1)
recur_factorial> 28 BINARY_SUBTRACT
recur_factorial> 29 CALL_FUNCTION (1)
recur_factorial> 0 LOAD_FAST (n)
recur_factorial> 3 LOAD_CONST (1)
recur_factorial> 6 COMPARE_OP (==)
recur_factorial> 16 LOAD_FAST (n)
recur_factorial> 19 LOAD_GLOBAL (recur_factorial)
recur_factorial> 22 LOAD_FAST (n)
recur_factorial> 25 LOAD_CONST (1)
recur_factorial> 28 BINARY_SUBTRACT
recur_factorial> 29 CALL_FUNCTION (1)
recur_factorial> 0 LOAD_FAST (n)
recur_factorial> 3 LOAD_CONST (1)
recur_factorial> 6 COMPARE_OP (==)
recur_factorial> 12 LOAD_FAST (n)
recur_factorial> 15 RETURN_VALUE
recur_factorial> 32 BINARY_MULTIPLY
recur_factorial> 33 RETURN_VALUE
recur_factorial> 32 BINARY_MULTIPLY
recur_factorial> 33 RETURN_VALUE
recur_factorial> 32 BINARY_MULTIPLY
recur_factorial> 33 RETURN_VALUE
recur_factorial> 32 BINARY_MULTIPLY
recur_factorial> 33 RETURN_VALUE
recur_factorial> 32 BINARY_MULTIPLY
recur_factorial> 33 RETURN_VALUE
recur_factorial> 32 BINARY_MULTIPLY
recur_factorial> 33 RETURN_VALUE

That's pretty cool!. Now we now the exact opcodes that are executing. Tracing obfuscated bytecode is no longer a problem.

Extending tracing to full-fledged debugging

The tracer developed does not have advanced debugging capabilities. For instance, we cannot interact with the operand stack, tamper the values stored, modify the opcodes dynamically at the run time etc. We do have access to the frame object but the evaluation stack is not accessible from python. However, everything is accessible to a C extension. We can develop such a C extension which when given a frame object can allow python code to interact with the objects stored on the operand stack.

This will be the topic for another blog post. I also intend to show, how we can use such an advanced tracer to unpack & deobfuscate the layers of a PjOrion protected python application.


References


Batchelder, N. (2008, April 11). Wicked hack: Python bytecode tracing. Retrieved March 15, 2017, from https://nedbatchelder.com/blog/200804/wicked_hack_python_bytecode_tracing.html

Rouault, C. (2015, May 7)Understanding Python execution from inside: A Python assembly tracer. Retrieved March 15, 2017, from http://web.archive.org/web/20160830181828/http://blog.hakril.net/articles/2-understanding-python-execution-tracer.html?

Wednesday, 15 February 2017

Extracting encrypted pyinstaller executables

It has been more than a quarter since the last post, and in the meantime, I was very busy and did not have the time to write a proper post. The good news is at the moment, I am comparatively free and can put in a quick post. 

As said earlier, PyInstaller provides an option to encrypt the embedded files within the executable. This feature can be used by supplying an argument --key=key-string while generating the executable. 

Detecting encrypted pyinstaller executables is simple. If  pyinstxtractor is used, it would indicate this as shown in Figure 1.

Trying to extract encrypted pyinstaller archive
Figure 1: Trying to extract encrypted pyinstaller archive

The other tell-tale sign is the presence of the file pyimod00_crypto_key in the extracted directory as shown in Figure 2.
The file pyimod00_crypto_key indicates usage of crypto
Figure 2: The file pyimod00_crypto_key indicates usage of crypto

If encryption is used, pyinstaller AES encrypts all the embedded files present within ZLibArchive i.e. the out00-PYZ.pyz file. When pyinstxtractor encounters an encrypted pyz archive, it would extract the contents as-is without decrypting the individual files as shown in Figure 3.

Contents of an an encrypted pyz archive
Figure 3: Contents of an encrypted pyz archive

To decrypt the files, you would need the key, and the key is present right within the file pyimod00_crypto_key. This is just a pyc file, and can be fed to a decompiler to retrieve the key. 

With the key in hand, it is a matter of another script to decrypt.

from Crypto.Cipher import AES
import zlib

CRYPT_BLOCK_SIZE = 16

# key obtained from pyimod00_crypto_key
key = 'MySup3rS3cr3tK3y'

inf = open('_abcoll.pyc.encrypted', 'rb') # encrypted file input
outf = open('_abcoll.pyc', 'wb') # output file 

# Initialization vector
iv = inf.read(CRYPT_BLOCK_SIZE)

cipher = AES.new(key, AES.MODE_CFB, iv)

# Decrypt and decompress
plaintext = zlib.decompress(cipher.decrypt(inf.read()))

# Write pyc header
outf.write('\x03\xf3\x0d\x0a\0\0\0\0')

# Write decrypted data
outf.write(plaintext)

inf.close()
outf.close()
The above snippet can be used for decrypting the encrypted files. Afterward, you can run a decompiler to get back the source.

Wednesday, 9 November 2016

Flare-on Challenge 2016 Write-up


The Flare-on challenge is an annual CTF style challenge with a focus on reverse engineering. Official solutions have already been published, besides that there are other writeups available too, hence I will just skim through the parts.

Challenge #1

The first was simple. This is base64 encoding with a custom charset. This online tool does the job.
Flag: sh00ting_phish_in_a_barrel@flare-on.com

Fig 1: Challenge 1

Challenge #2 - DudeLocker

This is a file encrypting ransomware. An encrypted file (BusinessPapers.doc) is provided, the task is to decrypt it. As the encryption key is hardcoded in the binary, I simply changed the CryptEncrypt call to CryptDecrypt by modifying the IAT. This decrypts the file giving the following image.
flag: cl0se_t3h_f1le_0n_th1s_One@flare-on.com 

Fig 2: Challenge 2

Challenge #3 - Unknown

The challenge is named unknown, we need to find it proper name. This can be found from the embedded pdb file path debug information. The binary implements a custom md5 hash algorithm which is used to calculate a table from the command line argument and the executable path. Since we already know the proper path, the command line argument can simply be brute forced giving us the flag Ohs0pec1alpwd@flare-on.com 
sss = map(ord, list('__FLARE On!'))

target = [0xEE613E2F, 0xDE79EB45, 0xAF1B2F3D, 0x8747BBD7, 
0x739AC49C, 0xC9A4F5AE, 0x4632C5C1, 0xA0029B24, 0xD6165059, 
0xA6B79451, 0xE79D23BA, 0x8AAE92CE, 0x85991A18, 0xFEE05899, 
0x430C7994, 0x1AB9F36F, 0x70C42481, 0x05BD27CF, 0xC4FF6E6F, 
0x5A77847C, 0xDD9277B3, 0x25843CFF, 0x5FDCA944, 0x8EE42896, 
0x2AE961C7, 0xA77731DA]

def charsprod(li):
 prod = 0
 for i in xrange(len(li)):
  prod = ((prod*37)&0xFFFFFFFF) + li[i] 
 return prod

email = ''

for i in xrange(26):
 sss[1] = ord('`') + i
 for j in xrange(1, 256):
  sss[0] = j
  if charsprod(sss) == target[i]:
   email += chr(j)
   break

print email


Challenge #4 - flareon2016challenge

A dll is provided which exports 51 functions by ordinals. Among them functions 1 to 48 & 51 changes the global state in someway or the other and must be called first. Ordinal 50 makes call to Beep and also tries to decrypt some piece of data. The task is to calls the functions in proper order so that the decryption may succeed. Additionally these  functions return an integer byte value indicating the ordinal of the next function that must be called. We can use the return values to build up the call chain order using the following script.
import ctypes

dll = ctypes.windll.LoadLibrary('flareon2016challenge')
call_chain = {}

for i in range(1, 49):
 retval = dll[i]()
 call_chain[i] = retval

print sorted(call_chain.values())
# missing is ordinal 30, should be called first

The call chain table thus found has no entry for ordinal 30, hence that is the function to be called first. After calling the functions in the correct order, an embedded executable is decrypted which just makes a series of calls to the Beep function. Setting a logging breakpoint on Beep allows us to recover the parameters passed. Calling export 50 using the same parameters gives us the flag: f0ll0w_t3h_3xp0rts@flare-on.com 
import sys
import ctypes
import os

params =[(440, 500), (440, 500), (440, 500), (349, 350) , (523, 150), (440, 500), (349, 350), (523, 150), (440, 1000), (659, 500), 
(659, 500), (659, 500), (698, 350), (523, 150), (415, 500), (349, 350), (523, 150), (440 , 1000)]

dll = ctypes.cdll.LoadLibrary('flareon2016challenge')

# call first function
retval = dll[30]()

# do not call last function
while retval != 51:
 retval = dll[retval]()

# call last func
dll[51]()

for p in params:
 dll[50](p[0], p[1])

Challenge #5 - smokestack

The provided executable is a stack based virtual machine. It takes in an argument, and prints the flag if it is correct. I reimplemented the vm in python and brute forced the flag A_p0p_pu$H_&_a_Jmp@flare-on.com
instructions = [0, 33, 2, 0, 145, 8, 0, 22, 0, 12, 9, 10, 11, 0, 0,
12, 2, 12, 0, 0, 29, 10, 11, 0, 0, 99, 2, 12, 0, 0,
24, 6, 0, 84, 8, 0, 51, 0, 41, 9, 10, 11, 0, 0, 44,
2, 12, 0, 0, 61, 10, 0, 14, 1, 11, 0, 0, 89, 2, 12,
0, 11, 0, 0, 0, 12, 1, 0, 9, 12, 0, 11, 1, 0, 2, 2,
12, 1, 11, 0, 0, 1, 3, 12, 0, 11, 0, 0, 0, 8, 0, 71,
0, 96, 9, 10, 12, 0, 11, 1, 3, 0, 93, 8, 0, 124, 0,
110, 9, 10, 11, 0, 0, 7, 3, 12, 0, 0, 91, 12, 1, 0,
135, 10, 0, 54, 12, 1, 11, 0, 11, 1, 2, 12, 1, 11, 1,
0, 88, 2, 6, 0, 249, 8, 0, 160, 0, 150, 9, 10, 11, 0,
0, 77, 6, 12, 0, 0, 174, 10, 0, 803, 0, 299, 3, 12,
1, 11, 0, 11, 1, 2, 12, 1, 12, 1, 11, 1, 11, 1, 0, 1,
3, 12, 1, 0, 3, 2, 11, 1, 0, 0, 8, 0, 178, 0, 199, 9,
10, 7, 0, 65143, 8, 0, 216, 0, 209, 9, 10, 11, 0, 0,
88, 2, 12, 0, 0, 3, 4, 0, 140, 2, 0, 24724, 8, 0, 238,
0, 231, 9, 10, 11, 0, 0, 231, 2, 12, 0, 11, 1, 2, 0,
12, 6, 0, 116, 8, 0, 263, 0, 253, 9, 10, 11, 0, 0, 9,
3, 12, 0, 0, 285, 10, 0, 10, 12, 1, 11, 1, 0, 1, 3,
12, 1, 11, 1, 0, 0, 8, 0, 267, 0, 285, 9, 10, 0, 6,
5, 0, 7616, 8, 0, 307, 0, 297, 9, 10, 11, 0, 0, 113,
2, 12, 0, 0, 317, 10, 11, 0, 0, 119, 2, 12, 0, 0, 317,
10, 0, 22, 2, 0, 14, 3, 0, 97, 8, 0, 339, 0, 332, 9,
10, 11, 0, 0, 44, 3, 12, 0, 12, 1, 11, 1, 0, 8492, 11,
1, 0, 1, 3, 12, 1, 0, 7, 3, 11, 1, 0, 0, 8, 0, 345,
0, 366, 9, 10, 0, 458, 6, 0, 8181, 8, 0, 385, 0, 378,
9, 10, 11, 0, 0, 18, 2, 12, 0, 13]

stack = []
sp = ctx1 = ctx2 = 0

def push(value):
 global sp
 sp += 1
 stack[sp] = value & 0xFFFF

def pop():
 global sp
 sp -= 1
 return stack[sp + 1]

def init_vm():
 global stack, sp, ctx1, ctx2
 stack = [ord(ch) for ch in 'kYwxCbJoLp']
 stack += [0,0,0,0]
 sp = 9
 ctx1 = ctx2 = 0

def exec_vm():
 global ctx1, ctx2
 ip = 0

 while ip < 386:
  #print 'loc_%d' %ip
  opcode = instructions[ip]
  
  if opcode == 0: # ins_load
   operand = instructions[ip + 1]
   push(operand)
   ip += 2

  elif opcode == 1: # ins_dec_sp
   pop()
   ip += 1

  elif opcode == 2: # ins_add
   v0 = pop()
   v1 = pop()
   push(v0 + v1)
   ip += 1

  elif opcode == 3: # ins_sub
   v0 = pop()
   v1 = pop()
   push(v1 - v0)
   ip += 1  

  elif opcode == 4: # ins_rotr
   v0 = pop()
   v1 = pop();
   push((v1 << (16 - v0)) | (v1 >> v0))
   ip += 1

  elif opcode == 5: # ins_rotl
   v0 = pop()
   v1 = pop();
   push((v1 >> (16 - v0)) | (v1 << v0))
   ip += 1

  elif opcode == 6: # ins_xor
   v0 = pop()
   v1 = pop();
   push(v1 ^ v0)
   ip += 1

  elif opcode == 7: # ins_not
   v0 = pop()
   push(~v0)
   ip += 1  

  elif opcode == 8: # ins_cmp
   v0 = pop()
   if v0 == pop():
    push(1)
   else:
    push(0)
   ip += 1    

  elif opcode == 9: # ins_cload
   v1 = pop()
   v0 = pop()
   if 1 == pop():
    push(v1)
   else:
    push(v0)
   ip += 1 

  elif opcode == 10: # ins_jmp
   ip = pop()

  elif opcode == 11: # ins_load_ctx
   operand = instructions[ip + 1]
   if operand == 0:
    push(ctx1)
   elif operand == 1:
    push(ctx2)
   ip += 2

  elif opcode == 12: # ins_set_ctx
   operand = instructions[ip + 1]
   v1 = pop()
   if operand == 0:
    ctx1 = v1
   elif operand == 1:
    ctx2 = v1
   ip += 2 

  elif opcode == 13: # ins_inc_ip
   ip += 1    


def main():
 global stack
 start = ord('A') - 1
 end = ord('z') + 1

 for pos in range(10):
  ret_vals = [None for i in xrange(start, end)]
  for i in range(start, end):
   init_vm()
   stack[pos] = i
   exec_vm()
   ret_vals[i-start] = tuple([i, ctx1])

  for e in ret_vals:
   if e[1] != ret_vals[0][1]:
    print chr(e[0]),
    break 


if __name__ == '__main__':
 main()

Challenge #6 - khaki

The challenge presents a piece of obfuscated python bytecode and by far this is best challenge. The file provided is a py2exe'd executable which can be easily unpacked to get the embedded pyc file. This pyc is obfuscated and cannot be easily decompiled. The reason for this is it has been sprinkled with NOPs , two POP_TOP, two ROT_TWO, and three ROT_THREE instructions. I developed a peephole optimizer to remove these instructions and make the file decompile-able using the bytecode-graph library developed by fireeye.
import bytecode_graph
import marshal
import opcode

def remove_nops(bcg, nodes):
 for i in xrange(len(nodes) - 1):
  node = nodes[i]
  if node.opcode == opcode.opmap['NOP']:
   bcg.delete_node(node)
   return True
 return False


def peephole_load_const(bcg, nodes):
 for i in xrange(len(nodes) - 1):
  node = nodes[i]
  # Peephole optimization (remove sequence of load and pop instructions)  
  if node.opcode == opcode.opmap['LOAD_CONST'] and nodes[i+1].opcode == opcode.opmap['POP_TOP']:
   bcg.delete_node(node)
   bcg.delete_node(nodes[i+1])
   return True
 return False   

def peephole_rot_two(bcg, nodes):
 for i in xrange(len(nodes) - 1):
  node = nodes[i]

  # Peephole optimization (remove two consecutive ROT_TWO)  
  if node.opcode == opcode.opmap['ROT_TWO'] and nodes[i+1].opcode == opcode.opmap['ROT_TWO']:
   bcg.delete_node(node)
   bcg.delete_node(nodes[i+1])
   return True
 return False

def peephole_rot_three(bcg, nodes):
 for i in xrange(len(nodes) - 2):
  node = nodes[i]

  # Peephole optimization (remove two consecutive ROT_THREE)  
  if node.opcode == opcode.opmap['ROT_THREE'] and nodes[i+1].opcode == opcode.opmap['ROT_THREE'] and nodes[i+2].opcode == opcode.opmap['ROT_THREE']:
   bcg.delete_node(node)
   bcg.delete_node(nodes[i+1]) 
   bcg.delete_node(nodes[i+2]) 
   return True

 return False  


def main():
 pyc_file = open('poc.pyc', 'rb').read()
 pyc = marshal.loads(pyc_file[8:])
 bcg = bytecode_graph.BytecodeGraph(pyc)

 nodes = [x for x in bcg.nodes()]

 while remove_nops(bcg, nodes) == True:
  nodes = [x for x in bcg.nodes()]

 while peephole_load_const(bcg, nodes) == True:
  nodes = [x for x in bcg.nodes()]
 
 while peephole_rot_two(bcg, nodes) == True:
  nodes = [x for x in bcg.nodes()]


 while peephole_rot_three(bcg, nodes) == True:
  nodes = [x for x in bcg.nodes()]

 deobf_code = bcg.get_code()
 f = open('poc-deobf.pyc', 'wb')
 f.write('\x03\xf3\x0d\x0a\0\0\0\0')
 marshal.dump(deobf_code, f)
 f.close()


if __name__ == '__main__':
 main()

Using this we can obtain the following deobfuscated code.
# Embedded file name: poc.py
import sys, random
__version__ = 'Flare-On ultra python obfuscater 2000'
target = random.randint(1, 101)
count = 1
error_input = ''
while True:
    print '(Guesses: %d) Pick a number between 1 and 100:' % count,
    input_num = sys.stdin.readline()
    try:
        input_num = int(input_num, 0)
    except:
        error_input = input_num
        print 'Invalid input: %s' % error_input
        continue

    if target == input_num:
        break
    if input_num < target:
        print 'Too low, try again'
    else:
        print 'Too high, try again'
    count += 1

if target == input_num:
    win_msg = 'Wahoo, you guessed it with %d guesses\n' % count
    sys.stdout.write(win_msg)
if count == 1:
    print 'Status: super guesser %d' % count
    #sys.exit(1)
if count > 25:
    print 'Status: took too long %d' % count
    sys.exit(1)
else:
    print 'Status: %d guesses' % count

if error_input != '':
    tmp = ''.join((chr(ord(x) ^ 66) for x in error_input)).encode('hex')
    if tmp != '312a232f272e27313162322e372548':
        sys.exit(0)
    stuffs = [67,139,119,165,232,86,207,61,
    import hashlib
    stuffer = hashlib.md5(win_msg + tmp).digest()
    for x in range(len(stuffs)):
        print chr(stuffs[x] ^ ord(stuffer[x % len(stuffer)])),

    print

Another python script to brute force the flag.
import hashlib

for i in xrange(100):
 win_msg = 'Wahoo, you guessed it with %d guesses\n' %i
 tmp = '312a232f272e27313162322e372548'

 stuffs = [67,139,119,165,232,86,207,61,79,67,45,58,230,190,181,74,65,148,71,243,246,67,142,60,61,92,58,115,240,226,171]
 stuffer = hashlib.md5(win_msg + tmp).digest()

 s = ''
 for x in range(len(stuffs)):
  s += chr(stuffs[x] ^ ord(stuffer[x % len(stuffer)]))
 if s.endswith('.com'):
  print s
  break
Flag 1mp0rt3d_pygu3ss3r@flare-on.com

Challenge #7 - hashes

The challenge is a x86 ELF (linux binary) developed in the go language. However unlike the standard go compiler gc, this has been compiled with gccgo and requires libgo.so.7 in order to be able to run. Now my local linux vm is ubuntu 14.04 and libgo7 is only available for ubuntu 16.04 and above. However I was not willing to download and install a complete new distro just for running this single binary. Hence a workaround was necessary. I powered on cloud9 vm, wgetted the deb directly bypassing the package manager. Although dpkg could not install the package, I got the much needed file libgo.so.7. Using it I could debug the binary in my local ubuntu 14.04 vm.

Fig 7 - Satisfying the dependencies
With that out of the picture, the objective of the challenge is to crack the SHA1 hash of the flag applied three times recursively. Since we know, that the flag ends in @flare-on.com, all that is required is to bruteforce the first few characters. Taking the good boy message "You have hashed the hashes" as a cue, I quickly brute forced the flag h4sh3d_th3_h4sh3s@flare-on.com

Challenge #8 - chimera

The name of the challenge immediately reminded me of the movie Mission: Impossible II wherein IMF agent Ethan Hunt must track and destroy a biological weapon Chimera along with its anti-dote Bellerophon and prevent it from being misused. While the actual challenge had nothing to do with the movie but certainly it was equally engrossing. Instead of the chimera virus, here we have an PE executable with a the relevant code hidden up the sleeves in the DOS stub. Once this is figured out, all that is left to disassemble the obfuscated 16 bit code to understand its workings. Dosbox along with its debugger proved much helpful in solving this problem. To get the flag I used the following script.
table = [255, 21, 116, 32, 64, 0, 137, 236, 93, 195, 66, 70,
192, 99, 134, 42, 171, 8, 191, 140, 76, 37, 25, 49,
146, 176, 173, 20, 162, 182, 103, 221, 57, 216, 95,
63, 123, 92, 194, 178, 246, 46, 117, 155, 97, 148, 207,
206, 106, 152, 80, 242, 91, 240, 69, 48, 14, 56, 235,
59, 108, 102, 127, 36, 61, 223, 136, 151, 185, 179,
241, 203, 131, 153, 26, 13, 239, 177, 3, 85, 158, 154,
122, 16, 224, 54, 232, 211, 228, 50, 193, 120, 7, 183,
107, 199, 112, 201, 44, 160, 145, 53, 109, 254, 115,
94, 244, 164, 217, 219, 67, 105, 245, 141, 238, 68,
125, 72, 181, 220, 75, 2, 161, 227, 210, 166, 33, 62,
47, 163, 215, 187, 132, 90, 251, 143, 18, 28, 65, 40,
197, 118, 89, 156, 247, 51, 6, 39, 10, 11, 175, 113,
22, 74, 233, 159, 79, 111, 226, 15, 190, 43, 231, 86,
213, 83, 121, 45, 100, 23, 149, 167, 189, 124, 29, 88,
147, 165, 101, 248, 24, 19, 234, 188, 229, 243, 55,
4, 150, 168, 30, 1, 41, 130, 81, 60, 104, 31, 142, 218,
138, 5, 34, 114, 73, 250, 135, 169, 84, 98, 198, 170,
9, 180, 253, 214, 209, 172, 133, 17, 71, 58, 157, 230,
77, 27, 204, 82, 128, 35, 252, 237, 139, 126, 96, 205,
110, 87, 186, 222, 174, 202, 196, 119, 12, 78, 212,
208, 200, 225, 184, 249, 38, 144, 129, 52]

target = [56, 225, 74, 27, 12, 26, 70, 70, 10, 150, 41, 115, 115, 164, 105, 3, 0, 27, 168, 248, 184, 36, 22, 214, 9, 203]

flag = map(ord, list('A'*26))

def rol(n):
 b = (n >> 7) & 1
 n = ((n << 1) | b) & 0xFF
 return n

def ror(n):
 b = n & 1
 n = ((n >> 1) | (b << 7)) & 0xFF
 return n 


def calc():
 for i in xrange(len(flag)-1, -1, -1):
  if i == len(flag) - 1:
   v1 = rol(rol(rol(0x97)))
  else:
   v1 = rol(rol(rol(flag[i+1])))

  v2 = table[v1]
  v2 = table[v2]

  flag[i] ^= v2  

 for i in xrange(len(flag)):
  if i == 0:
   flag[i] ^= 0xC5
  else:
   flag[i] ^= flag[i-1]

 print map(hex, flag)


def reverse():
 for i in xrange(len(target)-1, -1, -1):
  if i == 0:
   target[i] ^= 0xC5
  else:
   target[i] ^= target[i-1]

 for i in xrange(len(target)-1, -1, -1):
  if i == len(target) - 1:
   v1 = rol(rol(rol(0x97)))
  else:
   v1 = rol(rol(rol(save)))

  v2 = table[v1]
  v2 = table[v2]
  save = target[i]
  target[i] ^= v2 

 print ''.join(map(chr, target))


if __name__ == '__main__':
 reverse()
flag retr0_hack1ng@flare-on.com 


Challenge #9 - GUI

The challenge consists of a .net executable with ConfuserEx thrown in for a change. DnSpy along with NoFuserEx is sufficient to extract all the necessary strings for reconstructing back the shared secret.

Share:1-d8effa9e8e19f7a2f17a3b55640b55295b1a327a5d8aebc832eae1a905c48b64
Share:2-f81ae6f5710cb1340f90cd80d9c33107a1469615bf299e6057dea7f4337f67a3
Share:3-523cb5c21996113beae6550ea06f5a71983efcac186e36b23c030c86363ad294
Share:4-04b58fbd216f71a31c9ff79b22f258831e3e12512c2ae7d8287c8fe64aed54cd
Share:5-5888733744329f95467930d20d701781f26b4c3605fe74eefa6ca152b450a5d3
Share:6-a003fcf2955ced997c8741a6473d7e3f3540a8235b5bac16d3913a3892215f0a

Flag Shamir_1s_C0nfused@flare-on.com

Challenge #10 - flava

This was the final challenge, and is composed of many sub challenges. The first part requires to get through three layers of obfuscated javascript with an obfuscated Diffie Hellman (courtesy of Angler EK) for more distress. So unless, one figures out what the heck is with all the obfuscated javascript it is a dead end. Even if one manages to guess that, breaking the Diffie Hellman is more pain. Luckily, Kaspersky researches have already done the hard work before and it requires a bit of Googling to locate the code necessary to break the diffie hellman.
After three layers of javascript there are three more layers of actionscript. While the first layer is straightforward the second and third layers are obfuscated. The challenge in this part is to identify that the RC4 key is reused.  Once we know that, we can simply xor the plain text and ciphertext to get the keystream, and xor the resultant keystream with the second ciphertext to get back the plain text. The third actionscript layer simply prints the flag angl3rcan7ev3nprim3@flare-on.com

Final Words

Overall, the challenges this year were certainly more difficult than those of the preceding year. Some parts required bruteforcing hashes and guesswork which I detest. Another point of notice is that there were no 64 bit binaries. There were also no challenges involving kernel drivers. Finally, I would like to extend my thanks to everyone who helped me through the course of the challenges.