Saturday, 28 October 2017

CTF Writeup - Flare-On 2017 - 07: zsud.exe


  • Name - zsud.exe
  • Category - Reverse Engineering
  • Points - 1
  • Binary - Download here

The 7th Flare-On challenge is an x86 single-user dungeon game:


The game allows you to move around, interact with objects, pick them up, equip them, drop them and even talk to a guy called Kevin.

Loading the binary in IDA and looking at the strings tab we notice a few interesting ones:
  • M:\\whiskey_tango_flareon.dll
  • flareon.dll
  • !This program cannot be run in DOS mode.
  • .text
  • .rsrc
  • .reloc

All of these strings point towards an embedded DLL that starts at location 0x148AB0:


Following the xrefs for this memory region we are directed to function sub_F7170() from which we can identify the size of the embedded DLL:


Extract 0x1200 bytes starting from 0x148AB0, dump them into a file, rename to flareon.dll and open it using dnSpy:

using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Management.Automation;
using System.Security.Cryptography;
using System.Text;

namespace flareon
{
    public class four
    {
        private static string Decrypt2(byte[] cipherText, string key)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(key);
            byte[] array = new byte[16];
            byte[] iV = array;
            string result = null;
            using (RijndaelManaged rijndaelManaged = new RijndaelManaged())
            {
                rijndaelManaged.Key = bytes;
                rijndaelManaged.IV = iV;
                ICryptoTransform transform = rijndaelManaged.CreateDecryptor(rijndaelManaged.Key, rijndaelManaged.IV);
                using (MemoryStream memoryStream = new MemoryStream(cipherText))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Read))
                    {
                        using (StreamReader streamReader = new StreamReader(cryptoStream))
                        {
                            result = streamReader.ReadToEnd();
                        }
                    }
                }
            }
            return result;
        }

        public static int Smth(string arg)
        {
            using (PowerShell powerShell = PowerShell.Create())
            {
                try
                {
                    byte[] cipherText = Convert.FromBase64String(arg);
                    string script = four.Decrypt2(cipherText, "soooooo_sorry_zis_is_not_ze_flag");
                    powerShell.AddScript(script);
                    Collection collection = powerShell.Invoke();
                    foreach (PSObject current in collection)
                    {
                        Console.WriteLine(current);
                    }
                }
                catch (Exception var_5_70)
                {
                    Console.WriteLine("Exception received");
                }
            }
            return 0;
        }
    }
}

The DLL accepts a Base64 string, decodes it, AES decrypts it using the key 'soooooo_sorry_zis_is_not_ze_flag' and runs the resultant PowerShell script. Let's try and extract the PS1 script from the binary.

At the beginning of function sub_12523D0(), a region in memory is Base64'd and then passed to flareon.dll after this has been loaded into memory. The following image shows the resultant base64 string pointed at by EAX right after it has been encoded:


Extract the base64 string and create a C# program, based on the .NET flareon.dll, to recover the PS1 script:


[ ... snip ... ]

public static int Smth(string arg)
{
    byte[] cipherText = Convert.FromBase64String(arg);
    string script = Program.Decrypt2(cipherText, "soooooo_sorry_zis_is_not_ze_flag");
    System.IO.StreamWriter file = new System.IO.StreamWriter("zsud.ps1");
    file.WriteLine(script);
    file.Close();
    return 0;
}

public static void Main()
{
    string base64encoded = "Sbogppc38m/yviiq2 … [snip] … AyyAEQ2IwZPNoPEzE=";
    Smth(base64encoded);
    Console.ReadKey();
}

[ ... snip ... ]

The decrypted script can be viewed/downloaded here. If we run the powershell script on its own, we get the same UI depicted in the first image above.

First thing to notice in the script is the string 'http://127.0.0.1:9999/some/thing.asp' on line 814 which hints that the script communicates with a local web server embedded in the binary. This is confirmed by the following netstat result when zsud.exe is open:

Command Prompt
C:\>netstat -antp tcp | findstr 9999 TCP 127.0.0.1:9999 0.0.0.0:0 LISTENING InHost C:\>


Let's go back to the PS1 script and try to uncover what it's doing. The following is an excerpt of the important sections:


[ ... snip ... ]

$key = New-Thing "a key" "You BANKbEPxukZfP2EikF8jN04 ... [snip] ... PtEVBhQ==" @("key")

[ ... snip ... ]

function Invoke-XformKey([String]$keytext, [String]$desc) {
    $newdesc = $desc 

    Try {
        $split = $desc.Split()
        $text = $split[0..($split.Length-2)]
        $encoded = $split[-1]
        $encoded_urlsafe = $encoded.Replace('+', '-').Replace('/', '_').Replace('=', '%3D')
        $uri = "${script:baseurl}?k=${keytext}&e=${encoded_urlsafe}"
        $r = Invoke-WebRequest -UseBasicParsing "$uri"
        $decoded = $r.Content
        if ($decoded.ToLower() -NotContains "whale") {
            $newdesc = "$text $decoded"
        }
    } Catch {
        Add-ConsoleText "..."
    }
    
    return $newdesc
}

function Invoke-MoveDirection($char, $room, $direction, $trailing) {
    $nextroom = $null
    $movetext = "You can't go $direction."
    $statechange_tristate = $null

    $nextroom = Get-RoomAdjoining $room $direction
    if ($nextroom -ne $null) {
        $key = Get-ThingByKeyword $char 'key'
        if (($key -ne $null) -and ($script:okaystopnow -eq $false)) {
            $dir_short = ([String]$direction[0]).ToLower()

            ${N} = ${sC`Ri`Pt:MS`VcRt}::("{1}{0}" -f'nd','ra').Invoke() % 6

            if ($directions_enum[$dir_short] -eq ($n)) {
                $script:key_directions += $dir_short
                $newdesc = Invoke-XformKey $script:key_directions $key.Desc
                $key.Desc = $newdesc
                if ($newdesc.Contains("@")) {
                    $nextroom = $script:map.StartingRoom
                    $script:okaystopnow = $true
                }
                $statechange_tristate = $true
            } else {
                $statechange_tristate = $false
            }
        }

        $script:room = $nextroom
        $movetext = "You go $($directions_short[$direction.ToLower()])"

        if ($statechange_tristate -eq $true) {
            $movetext += "`nThe key emanates some warmth..."
        } elseif ($statechange_tristate -eq $false) {
            $movetext += "`nHmm..."
        }

        if ($script:autolook -eq $true) {
            $movetext += "`n$(Get-LookText $char $script:room $trailing)"
        }
    } else {
        $movetext = "You can't go that way."
    }

    return "$movetext"
}

[ ... snip ... ]

$baseurl = 'http://127.0.0.1:9999/some/thing.asp'
$directions_enum = @{'n' = 0; 's' = 1; 'e' = 2; 'w' = 3; 'u' = 4; 'd' = 5}

[ ... snip ... ]



The script does the following for each movement we perform in the game:
  1. Calls Invoke-MoveDirection
  2. Generates a random number between 0 and 5 (line 39)
  3. Translates our move to a number (lines 27 & 77)
  4. If these 2 numbers coincide, call Invoke-XformKey (line 43)
  5. Sends the list of directions (k param) and url-encoded key description (e param) to local web server (lines 15 & 16)
  6. If response does not contain 'whale', set it as the new key description (lines 18 & 19)
  7. If response contains '@', warp to starting room and stop game (lines 45 - 47)
The last bullet point hints that if we send the correct GET request to the local web server, it should spit the e-mail address. Using parts of the PS1 script above, we create another PS1 script to try and bruteforce the first 25 directions expected by the server:

iex ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("U0VULWl0RW
[ ... snip ... ]
"Xl9LCAke2ZpRWxkVmFgTGB1YGVzfSAgKTsgIHJldHVybiAke2FgVFRyfTsgICB9")))

.("{0}{1}{2}"-f 'SEt-IT','E','M') VariaBLE:q21s 
[ ... snip ...]
 ${T`ype`BU`IldEr}.("{2}{0}{1}"-f 'teTy','pe','Crea').Invoke(); }


[STring]::joIN( '', ('35h88w112_119}81r74r77h100J94<5
[ ... snip ...]
|%{[CHAR]($_ -BXoR  0x03  ) } ) )|.( $ShelliD[1]+$SheLLID[13]+'X')


$key = New-Thing "a key" "You BANKbEPxukZfP2EikF8jN04 ... [snip] ... PtEVBhQ==" @("key")

$baseurl = 'http://127.0.0.1:9999/some/thing.asp'

function Invoke-XformKey([String]$keytext, [String]$desc) {
    $newdesc = $desc 

    Try {
        $split = $desc.Split()
        $text = $split[0..($split.Length-2)]
        $encoded = $split[-1]
        $encoded_urlsafe = $encoded.Replace('+', '-').Replace('/', '_').Replace('=', '%3D')
        $uri = "${script:baseurl}?k=${keytext}&e=${encoded_urlsafe}"
        $r = Invoke-WebRequest -UseBasicParsing "$uri"
        $decoded = $r.Content

        # If response is different than previous one, set as new description
        if ($decoded.ToLower() -ne $encoded.ToLower()) {
            $newdesc = "$text $decoded"
            return $newdesc
        }
    } Catch {}
}

$directions_enum = @{0 = "n"; 1 = "s"; 2 = "e"; 3 = "w"; 4="u"; 5 = "d"}
$cumulativekey = ""

for ($i=0; $i -lt 25; $i++){
    for ($j=0; $j -lt 6; $j++){
        $testingchar = $directions_enum[$j]
        if ($newkey = Invoke-XformKey $cumulativekey$testingchar $key){
            $key = $newkey
            $cumulativekey += $testingchar
            break
        }
    }
}

echo "Directions: $cumulativekey"
echo "Key: $key"

Running the script:

Command Prompt
C:\>powershell -file bruteforcer.ps1 Directions: wnneesssnewne Key: You can start to make out some words but you need to follow the ZipRg2+UxcDPJ8T iemKk7Z9bUOfPf7VOOalFAepISztHQNEpU4kza+IMPAh84PlNxwYEQ1IODlkrwNXbGXcx/Q== C:\>


We notice 3 important things when we run the script:
  1. The key is incompletely decoded
  2. Only the first 13 direction attempts out of the 25 were executed
  3. Multiple runs produce the same output even though the expected input is decided by rand()
The first 2 happen because the server is bruteforce resistant and is expecting the right directions to spit out the answer. The 3rd bullet point is answered by looking at lines 431 - 433 of the extracted PS1 script:

if (($thing.Keywords -Contains "key") -and ($container_new -eq $script:char)){
    ${Msv`c`RT}::("{1}{0}"-f 'rand','s').Invoke(42)
}

When we pick up the 'key' in the game, srand(42) is executed, which explains why the rand() function always produces the same result and hence the server always expects the same directions. If we factor in the srand(42) though we notice that the output of 'rand() % 6' still does not match 'wnneesssnewne', which has been proven to be right else we would've never decoded parts of the key.

During the challenge it took me ages to realise the trick: both the rand() and srand() function are hooked in the binary and replaced with a custom implementation! This happens in function sub_1336530():


In the image we can see that the pointer to the real rand() is being hooked by new_rand() whilst srand() is being hooked by new_srand(). Let's take a look at both of these new functions. The following is the new_srand():


Recall that srand() is called from the PS1 when we collect the key. When this happens, it sets the global variable dword_138BD28 to 1, as displayed in the image above.

Let us take a look at the new implementation of rand(), i.e. new_rand():


If the global variable dword_138BD28 has been set to 1, i.e. new_srand() has been called, then it will end up in the green basic block which takes the expected direction from the array dword_1389CB8. This is NOT random at all!

Let's create a python script to extract all the expected directions:

import sys

directions_enum = {0:"n", 1:"s", 2 : "e", 3 : "w", 4:"u", 5 : "d"}

dword_1389CB8 = [0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00]

dword_138BD24 = 0

for x in range(200):
    result = dword_1389CB8[dword_138BD24 * 4]
    dword_138BD24 = (dword_138BD24 + 1) % 0x35
    sys.stdout.write(directions_enum[result])

Running the script:

Command Prompt
C:\>python direction_extractor.py wnneesssnewneewwwdundundunsuneunsewdunsewsewsewsewdunwnneesssnewneewwwdundundun suneunsewdunsewsewsewsewdunwnneesssnewneewwwdundundunsuneunsewdunsewsewsewsewdu nwnneesssnewneewwwdundundunsuneunsewdunsew C:\>


Sw33t! Let's modify the PS1 script now to specifically send these rather than trying to bruteforce our way:


[ ... snip ... ]

$solutions = "wnneesssnewneewwwdundundunsuneunsewdunsewsewsewsewdunwnneesssnewneewwwdundundunsuneunsewdunsewsewse"

for ($j=1; $j -lt 54; $j++){
    $tempSolution = $solutions.substring(0,$j)
 if ($newkey = Invoke-XformKey $tempSolution $key){
        $key = $newkey
    }
}

echo "Directions: $cumulativekey"
echo "Key: $key"

And this time:

Command Prompt
C:\>powershell -file send_right_directions.ps1 Directions: wnneesssnewneewwwdundundunsuneunsewdunsewsewsewsewdun Key: You can start to make out some words but you need to follow the RIGHT_PATH!@66696e646b6576696e6d616e6469610d0a C:\>


Not exactly what we want by close enough. The long hex string at the end translated to 'findkevinmandia'. So let's go and find Kev ... nahh, let's extract the logic directly from the script.

The decrypter to this output can be found in the original PS1 file on lines 463 - 477 which are invoked when we talk to Kevin Mandia whilst wearing a helmet and the key is dropped in the room. Extracting the logic from the script and putting our response from the server we end up with the following script:

$key = "You can start to make out some words but you need to follow the RIGHT_PATH!@66696e646b6576696e6d616e6469610d0a"

$md5 = New-Object System.Security.Cryptography.MD5CryptoServiceProvider
$utf8 = New-Object System.Text.UTF8Encoding
$hash = [System.BitConverter]::ToString($md5.ComputeHash($utf8.GetBytes($key)))


$Data = [System.Convert]::FromBase64String("EQ/Mv3f/1XzW4FO8N55+DIOkeWuM70Bzln7Knumospan")
$Key = [System.Text.Encoding]::ASCII.GetBytes($hash)

# Adapated from the gist by harmj0y et al
$R={$D,$K=$Args;$H=$I=$J=0;$S=0..255;0..255|%{$J=($J+$S[$_]+$K[$_%$K.Length])%256;$S[$_],$S[$J]=$S[$J],$S[$_]};$D|%{$I=($I+1)%256;$H=($H+$S[$I])%256;$S[$I],$S[$H]=$S[$H],$S[$I];$_-bxor$S[($S[$I]+$S[$H])%256]}}
$x = (& $r $data $key | ForEach-Object { "{0:X2}" -f $_ }) -join ' '
$resp = "`nKevin says, with a nod and a wink: '$x'."
$resp += "`n`nBet you didn't know he could speak hexadecimal! :-)"

echo $resp

The output:

Command Prompt
C:\>powershell -file kevin_mandia.ps1 Kevin says, with a nod and a wink: '6D 75 64 64 31 6E 67 5F 62 79 5F 79 30 75 72 35 33 6C 70 68 40 66 6C 61 72 65 2D 6F 6E 2E 63 6F 6D'. Bet you didn't know he could speak hexadecimal! :-) C:\>


Converting the hex to ascii: mudd1ng_by_y0ur53lph@flare-on.com

Monday, 23 October 2017

CTF Writeup - Flare-On 2017 - 06: payload.dll


  • Name - payload.dll
  • Category - Reverse Engineering
  • Points - 1
  • Binary - Download here

The next challenge on the list is a 64-bit windows DLL. We create a small 64-bit program that loads the DLL and calls the only exported function by its ordinal number:

#include <windows.h>
#include <stdio.h>

int main(int argc, char* argv[])
{
    FARPROC func;

    HINSTANCE dllHandle = LoadLibraryA("payload.dll");

    if (dllHandle == NULL)
        return 0;

    printf("Loading payload.dll\n");
    func = GetProcAddress(dllHandle, 1);
    func();

    printf("Press Any Key to Continue\n");
    getchar();
    return 0;
}

Running the binary we get the following message box:


Interesting. It tells us to insert a clever message, yet the exported function doesn't accept any parameters. Let's take a look at function sub_7FEFAB95A50() which has an xref to this message:


If we put a break point on the JNZ instruction in the basic block at the top and manually alter the execution flow to the yellow basic blocks by flipping the Zero Flag, we reveal a single character from the key:


As already annotated in the previous image, the yellow basic blocks set a region as RWX, decrypt the memory region with key orphanedirreproducibleconfidences and call it to reveal a single of the character of the key.

The question now is, how do we force the DLL into revealing the other characters of the key when it doesn't accept any input? The answer lies in function sub_7FEFAA24710():

__int64 sub_7FEFAA24710()
{
    struct _SYSTEMTIME SystemTime; // [rsp+20h] [rbp-28h]

    GetSystemTime(&SystemTime);
    return (unsigned int)((SystemTime.wYear + SystemTime.wMonth) % 26);
}

If this function returns 0x19 (25), as it does in this case, it will use the 25th key to decrypt the 25th region and reveals the 25th character of the key. Manually setting the output of this function between 0 and 13, and manually forcing the execution to the yellow blocks as we have done before, we reveal the first 14 characters:

  • key[0] = 0x77
  • key[1] = 0x75
  • key[2] = 0x75
  • key[3] = 0x75
  • key[4] = 0x74
  • key[5] = 0x2d
  • key[6] = 0x65
  • key[7] = 0x78
  • key[8] = 0x79
  • key[9] = 0x30
  • key[10] = 0x72
  • key[11] = 0x74
  • key[12] = 0x73
  • key[13] = 0x40

As we reach the '@' character we can stop since we know that the email has to end with @flare-on.com.

The final key is therefore wuuut-exp0rts@flare-on.com.

CTF Writeup - Flare-On 2017 - 05: pewpewboat.exe


  • Name - pewpewboat.exe
  • Category - Reverse Engineering
  • Points - 1
  • Binary - Download here

The challenge is a 64-bit ELF binary, despite it's file extension. Launching it we get a Battleship game!


The goal is to beat the game by sinking all the ships, which we have no visibility of, in each level by inputting coordinate values. Completing the first level we are greeted with:


Note that the solution spells out the letter 'F'! We try to input the Md5 hash of the 4-char string to no avail. At this point we're not sure what's meant by NotMD5Hash so let's look at the binary under IDA. The main() function starts by loading some stack strings and initializes some stuff for the game; it then goes into a main loop which has 2 important functions (green basic block): sub_403047() which sets up the next level and sub_403C05() where we get to actually play the level:


The function sub_403C05() further contains another loop which iterates for each coordinate we supply:


Each time we input a coordinate, the loop displayed above does the following:
  1. Sets up the curses text-based user interface (sub_4031E1)
  2. Displays the grid (sub_403263)
  3. Processes the coordinate to determine if we've hit a ship or not, checks if we have completed the level and displays the appropriate messages (sub_4038D6)
  4. Asks the user to input the next coordinate (sub_40377D)
The first objective is to find what is meant by NotMd5Hash so we can progress further into the game. The function that deals with this is sub_403530(); the stack string NotMd5Hash("%s") at the beginning gives it away. Let's look at the first part of this function:


The green basic block is looped over 4 times and randomly generates the 4 characters for the NotMd5Hash string. It then goes to the yellow basic block which computes the MD5 hash of the 4-char string (whattt!???), prints out the NotMd5Hash string and waits for our input. But we've already tried the MD5 and it didn't work! Let's check what comes next:


The blue basic block loops over each byte of the 16-byte Md5 output, NOT's the value and stores the hex representation of it. The result is then compared to our input in the purple basic block. So this is what is meant by NotMd5Hash! The values of the output are NOT'd. The following is a python script to compute this:

import md5

m = md5.new("GHND").digest()
print ''.join(["%02X" % (256 + ~ord(x)) for x in m])

At this point we can continue playing the game and try to beat each level by guessing the coords. Of course we're not doing that as it is very time consuming and painful. So, the next step is to find a way to reveal where the ships are for each level. A good way to checking this is to trace what happens to our input coord and how a HIT or MISS is determined based on this input.

Our input is read in sub_40377D():

unsigned __int64 __fastcall sub_40377D(__int64 a1)
{

    [ .. snip .. ]

    printf(format, &v6);
    if ( fgets(&s, 17, stdin) )
    {
        row = (char)(s & 0xDF) - 0x41;
        col = v5 - 0x31;
        if ( row < 0 || row > 7 || col < 0 || col > 7 )
        {
            sub_403411(&s, 17LL);
        }
        else
        {
            *(_QWORD *)(a1 + 8) |= 1LL << (8 * (unsigned __int8)row + col);
            *(_BYTE *)(a1 + 28) = s & 0xDF;
            *(_BYTE *)(a1 + 29) = v5;
        }
    }
    return __readfsqword(0x28u) ^ v28;
}

The function reads our input at line 7 and maps the row and column to a number between 0 and 7 on lines 9 and 10. For example, 'B6' translates to row = 1 & col = 5 whilst 'E2' translates to row = 4 & col = 1. Both values are then validated on line 11 to ensure they're on the board. Finally, at line 17, the values are combined into a single value that represents the input coordinate. This is the important part as it will be used to determine a HIT or a MISS. The following is a python 1-liner, which we'll use later on, to compute this value:

singlify = 1 << (row * 8 + col)

We now move onto the part where a HIT or MISS is determined. This happens in sub_4038D6() which also decides what message is displayed to the user based on their coord input:


The decision happens in the yellow basic block. On the 4th line of this block, RAX holds a level configuration number which determines the location of all the ships. This value is AND'd with our coord number. If the number remains the same, then it goes to the green basic block which signifies a HIT, if not it goes to the red basic block which displays the message 'You missed :('. If we put a breakpoint and collect the configuration number for the first level we get: 0x0008087808087800.

We now combine everything we know. The following is a python script which, given a configuration number, determines all the hits and also displays them on a grid:

def draw_ships(input):    
    hits = []

    for row in range(8):
        for col in range(8):
            singlify = 1 << (row * 8 + col)
            if singlify & input == singlify:
                hits.append(chr(row + 0x41) + chr(col + 0x31))
                print "X",
            else:
                print "_",
        print
    print
    return hits
    
ship_config = 0x0008087808087800

print draw_ships(ship_config)

Running the script gives us:

Command Prompt
C:\>python solution.py _ _ _ _ _ _ _ _ _ _ _ X X X X _ _ _ _ X _ _ _ _ _ _ _ X _ _ _ _ _ _ _ X X X X _ _ _ _ X _ _ _ _ _ _ _ X _ _ _ _ _ _ _ _ _ _ _ _ ['B4', 'B5', 'B6', 'B7', 'C4', 'D4', 'E4', 'E5', 'E6', 'E7', 'F4', 'G4'] C:\>


Notice that this coincides perfectly with what we've gotten when we played the game manually (check 2nd image from above). With these 2 scripts we're now guaranteed to hit all the ships before running out of ammo and also solve the NotMd5hash challenge each time. Make sure to put a break point to collect the configuration number at each level and get a list of HIT coords from the script.

Going through the 10 levels, we collect the string 'FHGUZREJVO' from the solutions, and the game displays the following message:


Removing the PEWs we get:

Aye! You found some letters did ya? To find what you're looking for, you'll want to re-order them: 9, 1, 2, 7, 3, 5, 6, 5, 8, 0, 2, 3, 5, 6, 1, 4. Next you let 13 ROT in the sea! THE FINAL SECRET CAN BE FOUND WITH ONLY THE UPPER CASE.

This is referring to the string 'FHGUZREJVO'. After we do what we're told we end up with 'BUTWHEREISTHERUM'. Feeding this to the game instead of a coordinate:


Saturday, 21 October 2017

CTF Writeup - Flare-On 2017 - 04: notepad.exe


  1. Name - notepad.exe
  2. Category - Reverse Engineering
  3. Points - 1
  4. Binary - Download here

Running the binary notepad.exe we get:


Expected anything else from a binary called notepad.exe? When the binary is loaded into IDA, we even get the prompt to apply MS symbols to it! Interesting, so what's different from the normal notepad.exe? For starters, the Entry Point points at an executable .rsrc section at the bottom of the PE which also contains other functions. Additionally, the binary loads several strings onto the stack in the start() function, usually an indication that it is trying to hide some functionality:


The start() function looks a bit daunting so I've decided to take a different approach with this challenge and use ProcMon to deduce (guess?) it's inner workings. Filtering on notepad.exe and File System Activity we get the following:


The executable searches for path C:\Users\<user>\flareon2016challenge which is not present on the machine. Create the folder and put a dummy file in, say an empty text file called testing.txt. The function that searches for this file path is sub_1013F30() which does the following:
  1. Constructs the string 'C:\Users\<user>\flareon2016challenge'
  2. Calls FindFirstFileA on the path
  3. For each file found in the folder, invokes sub_1014E20() on it's file path
The first bit of function sub_1014E20() does some validation on the input file:


It performs the following:
  1. Checks that the file starts with 'MZ' (Green)
  2. Ensures that 'PE' offset is less than the size of the binary (Red)
  3. Checks that the file has 'PE' in the right place (Yellow)
  4. Ensures that the Target Machine is for Intel 386 and later (Blue)
  5. Passes the binary mapping to sub_10146C0()
The function sub_10146C0() then takes the timestamp of the input file and the timestamp of notepad.exe and branches the execution flow depending on these 2 values:


The blue basic blocks deal with notepad.exe whilst the yellow ones deal with the input file. Depending on these 2 variables, the execution flow will take 1 of the 5 relevant paths shown below:


Notice that 4 of them are very similar to each other. Let's go through one of them taking the 1st one (left most) as an example. The basic block does the following:
  1. Sub_1014350 converts 0x57D1B2A2 into the Date and Time: 2016/09/08 18:49:06 UTC
  2. Call ECX pops a message box with the resultant Date and Time
  3. Sub_10145B0 takes first 8 bytes from binary at offset 0x400 and writes them to key.bin
The other basic block (2nd from the right) reads the contents of key.bin, checks if it is 32 bytes long and XOR's it with another 32 bytes. The big question at this point is, what should key.bin contain? And hence what should the 4 PE files in 'C:\Users\<user>\flareon2016challenge' be?

The hint is in the folder name 'flareon2016challenge'. Download last year's Flare-On challenges and notice that challenge1.exe has a Date Modified of 08/09/2016 19:49 which matches with the timestamp we've analysed. Copying the challenge1.exe binary in the flareon2016challenge folder and running notepad.exe again we get the following Message Box and the first 8 bytes of the key in key.bin:


Cutting to the chase, the following are the 4 binaries from last year's challenge that match the 4 timestamps required by notepad.exe:
  1. challenge1.exe
  2. DudeLocker.exe
  3. khaki.exe
  4. unknown
We can now complete the challenge by placing these 4 binaries in the flareon2016challenge folder and run notepad.exe. Note that this requires us to change the timestamp of notepad.exe or to change the control flow during execution to ensure that all the branches are taken in the right order.

Alternatively we can extract the 8 bytes key from each binary at offsets 0x400, 0x410, 0x420 and 0x430 respectively (refer to image above). This will give us the key and we can create a small python script to print the solution:

key1 = '\x55\x8b\xec\x8b\x4d\x0c\x56\x57\x8B\x55\x08\x52\xFF\x15\x30\x20\xC0\x40\x50\xFF\xD6\x83\xC4\x08\x00\x83\xC4\x08\x5D\xC3\xCC\xCC'
key2 = '\x37\xE7\xd8\xbe\x7a\x53\x30\x25\xbb\x38\x57\x26\x97\x26\x6f\x50\xf4\x75\x67\xbf\xb0\xef\xa5\x7a\x65\xae\xab\x66\x73\xa0\xa3\xa1'

print ''.join([chr(ord(a) ^ ord(b)) for a,b in zip(key2,key1)])

Running the script:

Command Prompt
C:\>python solution.py bl457_fr0m_th3_p457@flare-on.com C:\>

Friday, 20 October 2017

CTF Writeup - Flare-On 2017 - 03: greek_to_me.exe


  • Name - greek_to_me.exe
  • Category - Reverse Engineering
  • Points - 1
  • Binary - Download here


Launching the binary greek_to_me.exe, we don't get any output nor the option to supply any input. It gets stuck waiting for us to do something or maybe it's doing something computationally intensive. Let's look at the first part of the main function sub_401008():



The function first calls sub_401121(), in the blue basic block above, which contains the following code:

SOCKET __cdecl sub_401121(char *buf)
{
    SOCKET v2; // esi
    SOCKET v3; // eax
    SOCKET v4; // edi
    struct WSAData WSAData; // [esp+0h] [ebp-1A0h]
    struct sockaddr name; // [esp+190h] [ebp-10h]
    
    if ( WSAStartup(0x202u, &WSAData) )
        return 0;
    v2 = socket(2, 1, 6);
    if ( v2 != -1 )
    {
        name.sa_family = 2;
        *(_DWORD *)&name.sa_data[2] = inet_addr("127.0.0.1");
        *(_WORD *)name.sa_data = htons(0x2222u);
        if ( bind(v2, &name, 16) != -1 && listen(v2, 0x7FFFFFFF) != -1 )
        {
            v3 = accept(v2, 0, 0);
            v4 = v3;
            if ( v3 != -1 )
            {
                if ( recv(v3, buf, 4, 0) > 0 )
                    return v4;
                closesocket(v4);
            }
        }
        closesocket(v2);
    }
    WSACleanup();
    return 0;
}


The function opens a local socket on port 2222 and accepts a buffer of 4 bytes. Going back to the image of sub_401121(), the green basic block shows that ECX is loaded with 0x40107C + 0x79, EAX is loaded with 0x40107C and DL takes the first byte of the buffer. The yellow basic block then loops from memory position EAX to memory position ECX, each time computing a simple decryption routine (XOR memory byte with first byte of input and add 0x22) and overwriting the previous values. As location 0x40107C points to code in the binary, the loop modifies the binary whilst running. This is how location 0x40107C looks before it has been modified:


The trick to this challenge is that the decryption algorithm is dependent on a single byte ONLY. As this search space is tiny we create a python script that runs the binary, connects to it, sends it a single character and writes the response:

import socket
import subprocess

for x in range(128,255):
    subprocess.Popen(['greek_to_me.exe'], close_fds=True, creationflags=0x00000008)
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(("127.0.0.1", 2222))
    s.send(chr(x)) 
    data = s.recv(1024).decode()
    print x, data
    s.close ()

Running the script:

Command Prompt
C:\>python brute_force.py 128 Nope, that's not it. 129 Nope, that's not it. 130 Nope, that's not it. [... snip ...] 160 Nope, that's not it. 161 Nope, that's not it. 162 Congratulations! But wait, where's my flag? 163 Nope, that's not it. 164 Nope, that's not it. [... snip ...] C:\>

We now know that the right key is 0xA2, but were is the flag? If we send the right key straight away and go through the decryption algorithm, we notice that the bottom part of sub_401121(), specifically at location 0x40107C, has been modified:


Collecting the bytes above the congratulations message we get: et_tu_brute_force@flare-on.com

Wednesday, 18 October 2017

CTF Writeup - Flare-On 2017 - 02: IgniteMe.exe


  • Name - IgniteMe.exe
  • Category - Reverse Engineering
  • Points - 1
  • Binary - Download here

Running the binary and giving it 'somerandomstuff' as input:

Command Prompt
C:\>IgniteMe.exe G1v3 m3 t3h fl4g: somerandomstuff N0t t00 h0t R we? 7ry 4ga1nz plzzz! C:\>


Looking at the start() function of the binary IgniteMe.exe:


The green basic box is the area we would like our execution to go to whilst the red displays the fail message 'N0t t00 h0t R we? 7ry 4ga1nz plzzz!'.

Starting from the top of the graph, after the message is displayed, the program executes sub_4010F0() which reads our input and makes a copy of it (less chars 0xA and 0xD) in global variable byte_403078. The magic happens in subsequent function sub_401050():

signed int sub_401050()
{
    int v0; // ST04_4
    int i; // [esp+4h] [ebp-8h]
    unsigned int j; // [esp+4h] [ebp-8h]
    char v4; // [esp+Bh] [ebp-1h]

    v0 = strlen(byte_403078);
    v4 = sub_401000();

    for ( i = v0 - 1; i >= 0; --i )
    {
        byte_403180[i] = v4 ^ byte_403078[i];
        v4 = byte_403078[i];
    }

    for ( j = 0; j < 0x27; ++j )
    {
        if ( byte_403180[j] != (unsigned __int8)byte_403000[j] )
            return 0;
    }

    return 1;
}

On line 8, the string length of our input (less 0xA and 0xD) is computed and stored in v0. The next line executes sub_401000() which is a very simple function:

__int16 sub_401000()
{
    return (unsigned __int16)__ROL4__(-2147024896, 4) >> 1;
}

This function returns the value 0x04, which is stored in v4. Lines 11 - 15 iterate over the input string in reverse order, XOR'ing each char with the result of the previous computation. In the first loop it XOR's 0x04 (value of v4) with the last character of our input. The result is then XOR'd with the second from last char, and it keeps on going. Each time, the resultant computations are stored in global variable byte_403180.

Lines 17 - 21 compare the resultant array from the previous algorithm with global variable byte_403000. Each char has to match else the function returns 0 and we end up in the red basic block (refer to 1st image).

Reversing the logic and translate it to a python script:

byte_403000 = '\x0D\x26\x49\x45\x2A\x17\x78\x44\x2B\x6C\x5D\x5E\x45\x12\x2F\x17\x2B\x44\x6F\x6E\x56\x09\x5F\x45\x47\x73\x26\x0A\x0D\x13\x17\x48\x42\x01\x40\x4D\x0C\x02\x69'
xor_value = '\x04'
result = ""

for x in byte_403000[::-1]:
    xor_value = chr(ord(x) ^ ord(xor_value))
    result += xor_value
 
print result[::-1]

Testing out the result:

Command Prompt
C:\>IgniteMe.exe G1v3 m3 t3h fl4g: R_y0u_H0t_3n0ugH_t0_1gn1t3@flare-on.com G00d j0b! C:\>


CTF Writeup - Flare-On 2017 - 01: login.html


  • Name - login.html
  • Category - Reverse Engineering
  • Points - 1
  • Binary - Download here

This year's Flare-On challenge started with a very simple RE(?) challenge, an HTML page which asks for a key.


If we look at the HTML code it becomes apparent that it uses client-side authentication:
    <!DOCTYPE Html />
    <html>
        <head>
            <title>FLARE On 2017</title>
        </head>
        <body>
            
            
            
        </body>
    </html>

The javascript takes our input, operates on it and compares it with the string PyvragFvqrYbtvafNerRnfl@syner-ba.pbz. The algorithm is easy enough to recognize: ROT13. At this point we could either use online solutions such as www.rot13.com or a simple python script such as the one below:

import codecs

print codecs.getencoder("rot-13")("PyvragFvqrYbtvafNerRnfl@syner-ba.pbz")[0]


The key is: ClientSideLoginsAreEasy@flare-on.com