Challenge 1

This is the first challenge of Flare-On 2015. As the program says itself, it is an easy start. But we will still go step by step, because the same steps will help us in the harder challenges later.

The Files

In the challenge folder, we have two files:

File Size MD5
Flare-On_start_2015.exe 186,880 bytes F812BF4E535409E60EA95213421DB3AB
i_am_happy_you_are_to_playing_the_flareon_challenge.exe 1,536 bytes 7C0F16DE595AE03E2928D3FA6B73B235

The first one is only the starter. We run it and it extracts the real challenge for us. The second one is the binary we will analyze. And look at the size: only 1,536 bytes. This is very small for a Windows executable. A normal “Hello World” program compiled with Visual Studio is much bigger than this, because the compiler adds the C runtime code into it. So, when we see a file this small, we can already guess that it is probably written directly in assembly.

Triage

First Look with DiE

First, we put the binary into DiE (Detect It Easy) to see the general structure.

DiE overview of the binary

DiE gives us a lot of information in one screen:

  • File type: PE32. This is a 32-bit Windows executable.
  • Architecture: I386, Mode: 32-bit, Endianness: LE. So, it is x86 and little endian.
  • Type: Console. It is a console program, not a GUI program.
  • Base address: 0x00400000, Entry point: 0x00401000.
  • Sections: only 2.
  • Size of image: 0x3000. This is the size of the program in memory. It is three pages of 0x1000: one for the headers, one for .text, and one for .data.
  • Time date stamp: 1970-01-01 03:00:00. This is just 0 in the header. DiE shows it in local time (UTC+3), so we see 03:00 and not 00:00. The author set it to zero, or the assembler did not write it.
  • Language: ASMx86. DiE also thinks that the program is written in assembly. This matches our guess from the file size.

Sections

Let’s look at the sections in DiE:

Section table in DiE

The sizes look normal and there are no strange section names. So, we don’t see any sign of a packer.

But there are two small strange things:

  • .text is RWE, so it is readable, writable, and executable. Compilers normally make the code section only RE. A writable code section is something we see in packers and self-modifying code. Here, the code is very short and we will see that it does not modify itself. The author probably just used loose flags.
  • There is no .rdata section. Imports and strings are all in .data. A normal compiler usually does not do this. This is another sign that the binary is hand-written.

Imports

Import table in DiE

The only imported DLL is kernel32.dll, and it has 8 functions.

Strings

Program strings in DiE

At the end, we have the real strings of the program:

0x4020F2  Let's start out easy
0x402108  Enter the password>
0x40211C  You are success
0x40212E  You are failure

So, the program asks for a password and tells us if it is correct or not. Classic crackme.

Analysis with Ghidra

The code is very small, so we can open the binary in Ghidra and go directly to the entry point. There is only one real function, entry at 0x401000. Here is the decompiled code:

Decompiled entry function in Ghidra

Let’s go through it.

hFile = GetStdHandle(0xfffffff6);
hFile_00 = GetStdHandle(0xfffffff5);

GetStdHandle gives us a handle for the standard input, output, or error. The argument 0xfffffff6 is -10 in two’s complement, and this is STD_INPUT_HANDLE. 0xfffffff5 is -11, and this is STD_OUTPUT_HANDLE. So:

hFile    = stdin
hFile_00 = stdout
WriteFile(hFile_00,s_Let_s_start_out_easy_Enter_the_p_004020f2,0x2a,&local_8,(LPOVERLAPPED)0x0);
ReadFile(hFile,&DAT_00402158,0x32,&local_8,(LPOVERLAPPED)0x0);

WriteFile is not only for files. It can also write to a console handle. Here, it writes 0x2A (42) bytes from 0x4020F2 to stdout. As we saw in the strings, 0x4020F2 is "Let's start out easy\r\nEnter the password>".

Then, ReadFile reads at most 0x32 (50) bytes from stdin and puts them at 0x402158. So, DAT_00402158 is our input buffer.

local_8 is just a DWORD that receives the number of bytes written or read. The program never checks it.

The Check Loop

This is the important part:

iVar1 = 0;
do {
  if (((&DAT_00402158)[iVar1] ^ 0x7d) != (&DAT_00402140)[iVar1]) {
    WriteFile(hFile_00,s_You_are_failure_0040212e,0x12,&local_8,(LPOVERLAPPED)0x0);
    return;
  }
  iVar1 = iVar1 + 1;
} while (iVar1 < 0x18);

iVar1 is our loop counter i. In every round:

  1. It takes one byte of our input, input[i].
  2. It XORs this byte with 0x7D.
  3. It compares the result with the byte at 0x402140 + i.
  4. If they are not equal, it prints "You are failure" and returns.
  5. If they are equal, it increments i and continues while i < 0x18 (24).

If all 24 bytes match, the loop ends and the program prints "You are success".

Let’s rename the variables to make the code easier to read:

stdin_h  = GetStdHandle(STD_INPUT_HANDLE);
stdout_h = GetStdHandle(STD_OUTPUT_HANDLE);
WriteFile(stdout_h, "Let's start out easy\r\nEnter the password>", 0x2A, &n, NULL);
ReadFile(stdin_h, input, 0x32, &n, NULL);

for (i = 0; i < 24; i++) {
    if ((input[i] ^ 0x7D) != encoded[i]) {
        WriteFile(stdout_h, "You are failure\r\n", 0x12, &n, NULL);
        return;
    }
}
WriteFile(stdout_h, "You are success\r\n", 0x12, &n, NULL);

The Encoded Password

Now we need to know what is at 0x402140. When we double-click DAT_00402140 in Ghidra, it takes us to the .data section. There are 24 bytes there:

00402140  1F 08 13 13 04 22 0E 11 4D 0D 18 3D 1B 11 1C 0F
00402150  18 50 12 13 53 1E 12 10

These are not printable characters. That is why we did not see them in the strings list. This is the encoded password. Let’s call it blob.

Decoding the Password

The check is:

input[i] ^ 0x7D == blob[i]

XOR has a nice property: if a ^ k = b, then b ^ k = a. So, XOR is its own inverse, and we can get the password like this:

input[i] = blob[i] ^ 0x7D

Let’s do it for the first few bytes:

0x1F ^ 0x7D = 0x62 -> 'b'
0x08 ^ 0x7D = 0x75 -> 'u'
0x13 ^ 0x7D = 0x6E -> 'n'
0x13 ^ 0x7D = 0x6E -> 'n'
0x04 ^ 0x7D = 0x79 -> 'y'
...

Doing this by hand for 24 bytes is boring, so a small Python script does the job:

blob = bytes.fromhex("1f08131304220e114d0d183d1b111c0f18501213531e1210")
print("".join(chr(b ^ 0x7D) for b in blob))

Output:

bunny_sl0pe@flare-on.com

Testing the Flag

Let’s give it to the program:

Correct password accepted

That was it!

Challenge 2

Now, we will solve the second challenge of Flare-On 2015. The file name is very_success. It is a very small file, but it has some nice tricks inside. We will look at the binary, understand the assembly code line by line, and then write a small script to get the password.

First Look

The challenge comes in a zip file. After we extract it, we get one file: very_success. It has no extension. Its size is only 1536 bytes.

Let’s put it into DiE to see the general structure.

DiE overview of very_success.exe

It is a 32-bit (i386) PE file and it is a console program. DiE does not show any compiler or packer. It says the language is ASMx86. This is normal, because the file is so small, it is probably written directly in assembly.

Sections

PE section table in DiE

There are only two sections.

One interesting thing is that .text is also writable (RWX). Normally, the code section is only readable and executable. In this challenge it is not used for anything bad, but in other challenges, RWX code can mean self-modifying code. So it is good to remember it.

Imports

Import table in DiE

All imports come from kernel32.dll.

Strings

Program strings in DiE

You crushed that last one! Let's up the game.
Enter the password>
You are success
You are failure

So the program asks for a password and prints “success” or “failure”. Our goal is to find the correct password.

Running the Program

Let’s run it and give a wrong password. Because the file has no extension, I copied it as very_success.exe first.

Wrong password rejected

Finding the Entry Point

Let’s open the file in Ghidra. The entry point is at 0x4010DF.

Misdisassembled entry point in Ghidra

Ghidra shows some strange instructions after the call. We will see why below. The real code is like this. The entry point has only one instruction:

004010DF    call    0x401000
004010E4    db AF AA AD EB AE AA EC A4 BA AF AE AA 8A C0 A7 B0
            db BC 9A BA A5 A5 BA AF B8 9D B8 F9 AE 9D AB B4 BC
            db B6 B3 90 9A A8

After the call, there is no more code. There are 37 bytes that look like random data. This is interesting. Let’s remember what call does:

call 0x401000

; is the same as:

push 0x4010E4      ; address of the next "instruction" (return address)
jmp  0x401000

So call pushes 0x4010E4 to the stack. But 0x4010E4 is not code, it is our 37 bytes of data. Now let’s look at the first instruction of the function at 0x401000:

00401000    pop     eax

It pops the return address into EAX. So now EAX = 0x4010E4, which is the address of the 37 bytes. This is a classic call/pop trick. It is a common way to get the address of some data without writing that address directly in the code. You can see it often in shellcode, because shellcode does not know where it will be loaded in memory.

Ghidra Gets Confused

Ghidra does not know about this trick. It thinks call 0x401000 will return to 0x4010E4, so it tries to disassemble our 37 bytes as code. The bytes AF AA AD EB AE become this garbage:

004010E4    scasd
004010E5    stosb
004010E6    lodsd
004010E7    jmp     0x401097

To fix it, we tell Ghidra the truth:

  1. Mark the function at 0x401000 as No Return (Edit Function Signature, then check “No Return”). Now Ghidra knows that the code does not continue after the call.
  2. Clear the wrong instructions at 0x4010E4 (right click, then Clear Flow and Repair).
  3. Define the 37 bytes at 0x4010E4 as a byte[37] array. We don’t know what these bytes are yet, so we don’t give them a name for now.

Entry point after the fix

After this, Ghidra shows the 37 bytes as data, and the functions look correct.

The Main Function (0x401000)

Ghidra names this function FUN_00401000. It is the first function that runs, and as we will see, it does all the main work of the program. So I will call it the main function.

This function is simple, so this time we will follow the decompiler output. We will look at the assembly only for the strange parts.

Main function in Ghidra

Let’s go step by step.

unaff_retaddr

In the variable list, we see int unaff_retaddr;. But this variable is never set in the code. It is used only as the first argument of FUN_00401084.

unaff_retaddr means “unaffected return address”. Ghidra uses this name when a function uses the return address on the stack as a value. This is our call/pop trick. The decompiler hides the pop eax line, but in the listing on the left we can still see it:

00401000    pop     eax                     ; EAX = 0x4010E4 (address of the 37 bytes)
00401001    push    ebp
00401002    mov     ebp, esp
00401004    sub     esp, 0x10               ; 4 local variables (4 bytes each)
00401007    mov     [ebp-0x10], eax         ; save address of the 37 bytes

So unaff_retaddr is 0x4010E4, the address of our 37 bytes.

GetStdHandle

hFile = GetStdHandle(0xfffffff6);
hFile_00 = GetStdHandle(0xfffffff5);

GetStdHandle gives us the handle of the console input or output. 0xfffffff6 is -10 and it means STD_INPUT_HANDLE. 0xfffffff5 is -11 and it means STD_OUTPUT_HANDLE.

WriteFile and ReadFile

WriteFile(hFile_00,s_You_crushed_that_last_one!_Let's_004020f2,0x43,&local_4,(LPOVERLAPPED)0x0);

This prints the prompt string to stdout. 0x43 (67) is the length of the string. The number of written bytes goes into local_4.

ReadFile(hFile,&DAT_00402159,0x32,&local_4,(LPOVERLAPPED)0x0);

This reads our input from stdin. It reads max 50 (0x32) bytes into the buffer at 0x402159 (DAT_00402159).

The Result

lpOverlapped = (LPOVERLAPPED)0x0;
lpNumberOfBytesWritten = &local_4;
nNumberOfBytesToWrite = 0x11;
iVar1 = FUN_00401084(unaff_retaddr,&DAT_00402159,local_4);
if (iVar1 == 0) {
  lpBuffer = s_You_are_failure_00402147;
}
else {
  lpBuffer = s_You_are_success_00402135;
}
WriteFile(hFile_00,lpBuffer,nNumberOfBytesToWrite,lpNumberOfBytesWritten,lpOverlapped);

FUN_00401084 gets 3 arguments: the address of the 37 bytes (unaff_retaddr), our input (DAT_00402159) and the length of our input (local_4). If it returns 0, the program selects “You are failure”. If not, it selects “You are success”. Then it prints the selected string with WriteFile.

After that, the function returns. This ret goes back to Windows, not to the entry point, because the entry point’s return address was popped at the beginning.

Giving Names

Now we know enough to give some names:

  • FUN_00401084 gets the 37 bytes and our input, and the program prints “success” only if it returns a non-zero value. So it checks the password. I renamed it to CheckPassword.
  • The 37 bytes are given to the check function together with our input. So they are probably the correct password in an encoded form. We will confirm this at the end, when we get the password from these bytes. I renamed them to g_abEncodedKey, and unaff_retaddr to pEncodedKey.
  • The buffer at 0x402159 holds our input. I renamed it to g_szInputBuffer.
  • hFile and hFile_00 became hStdin and hStdout. local_4 became bytes_read, iVar1 became is_valid and lpBuffer became result_msg.
  • FUN_00401000 reads the password and checks it. I renamed it to main_ReadAndCheckPassword.

After renaming, the decompiled main function is much easier to read:

Main function after renaming

The Check Function (0x401084)

This is the most important part of the challenge.

From the main function, we already know the 3 arguments of this function:

param_1  -> address of the 37 bytes (0x4010E4)
param_2  -> our input (0x402159)
param_3  -> length of our input (bytes read by ReadFile)

So before we start, let’s rename them in Ghidra to make the code easier to read:

  • param_1 -> encoded_key
  • param_2 -> input
  • param_3 -> input_len

CheckPassword function after renaming

This looks quite complicated. There are XORs, rotations, a sum that changes in every step, and the key is read from the end to the start. Following all of this by hand and writing the reverse code takes time, and it is easy to make a small mistake.

For this kind of work, I got help from an LLM. LLMs are really good at scripting. I gave it the decompiler output and asked it to explain the check and write a script that reverses it. This saved me a lot of time.

I think using an LLM is a good idea for jobs like this: unpacking, decrypting data, decoding encoded values, or reversing a small check function like this one. You understand the general logic with the decompiler, and the LLM helps you to write the script quickly. But don’t trust it blindly. Always test the result, for example by giving the result to the program.

The Solve Script

The 37 bytes are at 0x4010E4. We can copy them from Ghidra.

Here is the script. It calculates the password from the 37 bytes:

# The 37 bytes at 0x4010E4 (g_abEncodedKey)
key = bytes.fromhex(
    "afaaadebaeaaeca4baafaeaa8ac0a7b0"
    "bc9abaa5a5baafb89db8f9ae9dabb4bc"
    "b6b3909aa8"
)

# The check in CheckPassword, for each character i:
#   v = ((input[i] ^ 0xC7) + (1 << (rolling_sum & 3)) + 1) & 0xFF
#   v must be equal to key[36 - i]
#   rolling_sum += v
#
# rolling_sum is bVar4 and v is cVar2 in the decompiler output.
# For the correct password, v is always key[36 - i], so we can
# calculate rolling_sum from the key and reverse each step.

rolling_sum = 0
password = ""
for i in range(37):
    k = key[36 - i]
    password += chr(((k - (1 << (rolling_sum & 3)) - 1) & 0xFF) ^ 0xC7)
    rolling_sum += k

print(password)

Output:

a_Little_b1t_harder_plez@flare-on.com

Testing the Password

Let’s give the password to the program:

Correct password accepted

So we also solved this challenge.

Challenge 3

First Look

The binary name is elfie. The name makes us think about ELF, which is the executable format of Linux. But we should not trust the name. A file name is only a name. Let’s look at the first bytes of the file.

elfie.exe PE header in HxD

  • MZ (4D 5A) is the DOS header magic. Every PE file starts with it.
  • At offset 0x3C, we have D8 00 00 00. This is the offset of the PE header. When we go to 0xD8, we see PE\0\0.

So, this is not an ELF file. It is a 32-bit Windows PE file. The file command also says the same thing:

elfie: PE32 executable (console) Intel 80386, for MS Windows

Now we know it is a Windows executable. So, let’s rename it to elfie.exe and run it once in our VM, just to see what it does.

elfie.exe goat window on launch

There is no button and no text box. There is nothing to click. Only a picture and two hints. “Look inside!” probably tells us to look inside the binary.

Let’s put it into DiE.

DiE overview of elfie.exe

The file is about 12 MB. This is strange, because when we look at the sections, the code section is very small:

Section table in DiE

If we sum all the raw sizes, it is around 0x30600 bytes, which is about 194 KB. But the file is 0xBAA980 bytes. So, where is the rest?

The answer is the overlay. The overlay is the data appended at the end of a PE file, after the last section. The Windows loader does not map it into memory. It only maps the sections that are written in the section table. So, if a program wants to use the overlay, it must open its own file and read it manually.

overlay start = 0x30600
file size     = 0xBAA980
overlay size  = ~11.9 MB

So, almost all of the file is in the overlay. This is a common thing for installers and packers. The small .text is only a “stub” that reads the overlay and does something with it.

Let’s check the imports and strings to understand what this stub does.

Import table in DiE

Some imports from KERNEL32.dll:

GetModuleFileNameW     -> get the path of its own file
GetTempPathW           -> get the %TEMP% folder
CreateDirectoryA       -> create a folder
LoadLibraryExA         -> load a DLL
GetProcAddress         -> find a function inside that DLL
CreateProcessW         -> start a new process
SetEnvironmentVariableA

Now, let’s look at the strings. The most interesting ones are at the very end of the file, inside the overlay. Let’s scroll to the bottom of the Strings tab in DiE:

PyInstaller strings in the overlay

Remember, the overlay is not part of any section. The Windows loader doesn’t even load it into memory. So, it is not really a part of the program. It is more like another file that is appended to the end of the executable.

And when we look at the strings in this “other file”, we see file names: python27.dll, PySide.QtCore.pyd, QtGui4.dll, out00-PYZ.pyz, elfie… It looks like the overlay is an archive that holds many files, and these files are all related to Python.

So, our guess is this: the small PE part is only a launcher, and the real program is a Python 2.7 program that is packed inside the overlay, together with its interpreter and libraries.

Actually, DiE already told us this at the beginning. Go back to the first DiE screenshot. It says Language: Python and Packer: PyInstaller[custom].

Understanding PyInstaller

PyInstaller is a tool that converts a Python script into a single executable. The user doesn’t need to install Python. But how does it do this? Python is an interpreted language, so somebody must run the script.

The trick is simple. PyInstaller puts everything into the executable:

program.exe (PE file)
├── PE part (.text, .rdata, ...)   -> small C program, the "bootloader"
└── overlay (CArchive)
    ├── pythonXY.dll               -> the Python interpreter itself
    ├── *.dll                      -> other DLLs the program needs
    ├── *.pyd                      -> compiled Python extensions
    ├── *.pyz                      -> zipped Python libraries
    ├── pyi* scripts               -> PyInstaller's own startup scripts
    ├── <script name>              -> the main script of the program
    └── cookie                     -> small structure at the very end

When we run it, it works like this:

Windows loader
    ↓
PE entry point (bootloader)
    ↓
open its own file, read the overlay
    ↓
extract the DLLs to %TEMP%\_MEIxxxxx
    ↓
LoadLibrary("pythonXY.dll")
    ↓
run the main script with the interpreter

This is why we saw GetModuleFileNameW, GetTempPathW, LoadLibraryExA and GetProcAddress in the imports. The bootloader doesn’t link to Python statically. It finds the functions at runtime with GetProcAddress.

Extracting the Archive

There is a well-known tool for PyInstaller executables: pyinstxtractor (PyInstaller Extractor). It is a single Python script. Let’s run it on our file:

pyinstxtractor extracting elfie.exe

The tool created a folder named elfie.exe_extracted:

Extracted PyInstaller archive contents

elfie.pyc                     4,053,584   -> main script
_pyi_bootstrap.pyc                4,236   -> PyInstaller startup script
pyi_carchive.pyc                 13,150   -> PyInstaller startup script
pyi_archive.pyc, pyi_importers.pyc, pyi_os_path.pyc, struct.pyc
out00-PYZ.pyz                   995,801   -> zipped Python libraries
python27.dll                  2,449,920   -> Python interpreter
QtCore4.dll, QtGui4.dll, PySide.QtCore.pyd, PySide.QtGui.pyd, ...
msvcr90.dll, msvcp90.dll, msvcm90.dll, ...

This is exactly the structure we drew above. The small PE part only carries these files and runs elfie with python27.dll.

Looking at elfie.pyc

The tool says “You can now use a python decompiler on the pyc files”. So, let’s put elfie.pyc into a decompiler. FLARE VM has pycdc (Decompyle++), which supports Python 2.7:

pycdc fails on elfie.pyc

It fails with Got unsupported type 0x4F. To understand why, let’s open the file in a text editor, like Notepad++:

elfie.pyc in Notepad++

Surprise. We can read it! A real .pyc file is bytecode, and in a text editor it looks like garbage. But this one is readable text. So, this PyInstaller version keeps the main script as plain Python source code, not as bytecode. The decompiler expected bytecode, but it found text. This is why it failed, and we don’t need a decompiler at all. But the code doesn’t look very friendly…

The First Layer of Obfuscation

Let’s look at the file:

Base64 exec at the end

O0OO0OO00000OOOO0OOOOO0O00O0O0O0 = 'IRGppV0FJM3BRRlNwWGhNNG'
OO0O0O00OO00OOOOOO0O0O0OOO0OOO0O = 'UczRkNZZ0JVRHJjbnRJUWlJV3FRTkpo'
OOO0000O0OO0OOOOO000O00O0OO0O00O = 'xTStNRDJqZG9nRCtSU1V'
OOO0000O0OO0OOOOO000O00O0OO0O00O += 'Rbk51WXI4dmRaOXlwV3NvME0ySGp'
OOO0OOOOOOOO0000O000O00O0OOOO00O = 'ZnJvbSBQeVNpZGUgaW1wb3J'
...
(about 56,000 lines)
...
O00OO00OOO0OOOO0OOOO0OO00000OOO0 += 'nNocTB'
import base64
exec(base64.b64decode(OOO0OOOOOOOO0000O000O00O0OOOO00O + O0O00OO0OO00OO00OO00O000OOO0O000 + ...))

So, what is happening here?

  • Variable names contain only O (the letter) and 0 (zero). For a human, they all look the same. This is a cheap but annoying trick.
  • Each variable holds a small piece of a base64 string. Some of them are extended with +=.
  • At the end, the last line joins the variables in the correct order, decodes the base64, and runs the result with exec.

exec takes a string and runs it as Python code. So, the real program is hidden inside this base64 string.

We don’t need to join these pieces ourselves. The script already does it for us. We only need to change one thing: instead of running the decoded code with exec, we will print it. So, let’s make a copy of elfie.pyc, name it layer1.py, and edit it in Notepad++:

  1. Delete the strange characters at the very beginning (ETX, ó and the four NULs). They are not Python code. The tool added them. The file must start with O0OO0OO....
  2. Delete the NUL byte on the last line of the file. Python 3 doesn’t accept null bytes in source code, and it gives SyntaxError: source code cannot contain null bytes.
  3. On the last line, change exec( to print(. We also add .decode() at the end, because in Python 3, b64decode returns bytes. Without it, we would see the output as b'...'.

The last line becomes this:

print(base64.b64decode(OOO0OOOOOOOO0000O000O00O0OOOO00O + ... + O00OO00OOO0OOOO0OOOO0OO00000OOO0).decode())

Now, let’s run it and save the output to a file:

> python layer1.py > stage2.py

That’s it. stage2.py is the code that exec would run.

The Second Layer

The output, stage2.py, is about 1.38 MB, but it is only 49 lines. Two of these lines are huge. Let’s look at the first lines:

from PySide import QtGui, QtCore
import base64
OOO00O00OO0OO000OOOO00000000OOO0 = ''.join((x for x in reversed('CCmQuSkTFlEAAAAA86w1BWpR...')))
OO0O00000OO0O0O0OOOO0OO0OOO000O0 = ''.join((x for x in reversed('==gggJkrE5URJBAAAAwVKkxU...')))

Second-stage obfuscated code

The two huge lines are reversed strings. When we look at the end of them, we see ...BVi. Reversed, it is iVB.... And iVBORw0KGgo is the base64 of the PNG magic bytes (\x89PNG\r\n\x1a\n). So, these two variables are two PNG images, base64 encoded and reversed. We will see later where they are used.

The obfuscator also uses another trick. Many names are written in reverse:

getattr(QtGui, 'tidEtxeTQ'[::-1])

'tidEtxeTQ'[::-1] reverses the string, so it becomes 'QTextEdit'. And getattr(QtGui, 'QTextEdit') is the same as QtGui.QTextEdit. So, this line is only a hidden way of writing QtGui.QTextEdit.

Deobfuscating the Code

Now, let’s clean the code. I renamed the variables and reversed all the strings by hand. The original version is first, and my cleaned version is after it.

The bottom part of the script is the “main”:

# original
OOO00O000O0000OO000OO0000O000000 = getattr(QtGui, 'noitacilppAQ'[::-1])(['000000000000000000000000'[::-1]])
OO0000OOOOO000000OO0OOO00OO00OOO = getattr(QtGui, 'wodniWniaMQ'[::-1])()
...
getattr(OO0000OOOOO000000OO0OOO00OO00OOO, 'eltiTwodniWtes'[::-1])('!ereht eno dnif nac uoy !edisni kooL'[::-1])
# cleaned
app    = QtGui.QApplication(['000000000000000000000000'])
window = QtGui.QMainWindow()

img_normal  = QtGui.QPixmap()
img_normal.loadFromData(base64.b64decode(IMAGE_1))
img_success = QtGui.QPixmap()
img_success.loadFromData(base64.b64decode(IMAGE_2))

width  = img_normal.width()
height = img_normal.height()

window.setWindowTitle('Look inside! you can find one there!')
window.setFixedSize(width, height)

editor = SecretTextEdit(window, img_normal, img_success)
window.setCentralWidget(editor)
window.show()
app.exec_()

So, the program creates a window. The size of the window is the size of the first image. And the window title is a hint: “Look inside! you can find one there!” :)

Then, there is a class. Its parent is QTextEdit, so it is a text box where we can type something:

# cleaned
class SecretTextEdit(QtGui.QTextEdit):
    def __init__(self, window, img_normal, img_success):
        super(SecretTextEdit, self).__init__(window)
        self.window      = window
        self.img_normal  = img_normal
        self.img_success = img_success
        self.solved      = False

    def check(self):
        text = self.toPlainText()
        if text == ''.join(c for c in reversed('moc.no-eralf@OOOOY.sev0000L.eiflE')):
            self.window.setWindowTitle('great success!')
            self.solved = True
            self.window.setVisible(False)
            self.window.setVisible(True)

    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_Enter or event.key() == QtCore.Qt.Key_Return:
            self.check()
        else:
            super(SecretTextEdit, self).keyPressEvent(event)

    def paintEvent(self, event):
        painter = QtGui.QPainter(self.viewport())
        if self.solved:
            painter.drawPixmap(self.rect(), self.img_success)
        else:
            painter.drawPixmap(self.rect(), self.img_normal)
        super(SecretTextEdit, self).paintEvent(event)

Let’s go through it:

  • keyPressEvent is called by Qt for every key press. If the key is Enter or Return, it calls check(). Otherwise, it gives the key to the normal QTextEdit, so the character is written into the box.
  • check() gets the text in the box with toPlainText() and compares it with a string. The string is written backwards, and it is reversed at runtime with reversed().
  • If they are equal, the title becomes "great success!", and solved becomes True. Then, the window is hidden and shown again. This forces Qt to repaint the window.
  • paintEvent draws the background image. If solved is True, it draws the second image. If not, it draws the first one.

Now we understand what we saw when we ran the program. There was no text box, but in fact, the goat picture is the text box. The QTextEdit covers the whole window, and paintEvent draws the picture on it. So, we can click on the picture and type, and the text is written on top of the goat. And the “magical keys” hint was about this: the program is waiting for the correct keys and the Enter key.

Getting the Flag

Let’s reverse the string:

>>> 'moc.no-eralf@OOOOY.sev0000L.eiflE'[::-1]
'Elfie.L0000ves.YOOOO@flare-on.com'

And here is our flag:

Elfie.L0000ves.YOOOO@flare-on.com

Now, let’s run the program again to confirm it. We click on the goat picture, type the flag, and press Enter.

Flag accepted: "great success!"

The title changes to “great success!”, and the background image changes. Now the goat says “You the best!! YA!” :). That was it.