Tuesday, March 4, 2014

DEFKTHON CTF 2014 - Reversing 300 WriteUp

Hi Again,
The CTF just ended (less than 15 min) and here's the write-up , actually I prepared it yesterday.
Yesterday was a hard day at university , but I was happy to see that a CTF was taking place that night and there were some reversing tasks.
The CTF was DEFKTHON 2014 CTF , I was able to solve Reverse300 , and the challenge was quite cool.
They offered 'me' a 32-bit executable (300.exe) which will display "Password!!" when opening it
(I figured later that you can provide a command line argument and hope to get the flag if you have the right key : D which is really hard to predict btw).


The first step I took was to figure out where exactly the process will write to the console and I figured that it will create a child process that will do the job. Before that , and while stepping I saw that the parent will create a temporary folder under %temp% in which multiple "dll"s and "pyd" files will be stored (python27.dll for example) that folder name looks like _MEIxxxx where "x"s are random numbers . This gave me a clear idea about what this challenge is for, the executable was actually generated from a Py2Exe software and sooner or later the python source code will be in memory or in disk.

Now that I knew that the child process is the one that will execute the interpreted code, I tried to debug that child process. It is actually possible to do this under WinDbg (if you know a way to do it under Olly/Immunity please leave a comment below).
To switch the debugger to the Child Process whenever it's created all you have to do is type this command " .childdbg 1 " this will enable child process debugging for the current session.

eax=00000000 ebx=00000000 ecx=a1240000 edx=0009e138 esi=fffffffe edi=00000000
eip=776e103b esp=0036f9f8 ebp=0036fa24 iopl=0         nv up ei pl zr na pe nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000246
ntdll!LdrVerifyImageMatchesChecksum+0x96c:
776e103b cc              int     3
1:001> |
   0    id: 2fa8    create    name: image01340000
   1    id: 1e30    child    name: image01340000
(After Calling CreateProcess by the parent here we are breaking before executing the child proc)


Now all I had to do is determine what API is used to write to the console , so I've put a breakpoint on kernel32!WriteFile and kernel32!WriteConsole (there are high odds that would be one of these two), And It was WriteFile which writes the message to the console.
Now I'm at WriteFile and I need to go to the call from the child process right ? So I have kept returning from a function to its caller until reaching the original call from the ChildProcess.

Stack Trace :
============
0036d89c 729699ad kernel32!WriteFile
0036f3a8 72969d37 MSVCR90!lseeki64+0x56b
0036f3ec 7292f4c6 MSVCR90!write+0x9f
0036f410 729313ff MSVCR90!flsbuf+0x143
0036f438 729314ac MSVCR90!fwrite_nolock+0x11b
0036f47c 1e0b1ad8 MSVCR90!fwrite+0x61
0036f4a8 1e0abd64 python27!PyString_InsertThousandsGrouping+0x2c8
0036f4c8 1e0abdb6 python27!PyTrash_thread_destroy_chain+0x144
0036f4dc 1e094a55 python27!PyObject_Print+0x16
[...]
[...]
0036f638 0134352c python27!PyRun_SimpleString+0xc
00000000 00000000 image01340000+0x352c


And here's the call to the function from python27.dll (in the folder under %temp%)

01343525 53              push    ebx
01343526 ff1564c23501    call    dword ptr [image01340000+0x1c264 (0135c264)]


The function is supplied one argument in EBX. And You can see from the way the function is called (the function pointer is accessed from a memory location) that this call could be used to call different functions from python27.dll depending on the task that the file needs to do.
Let's rerun the crackme switch to the child proc and put a breakpoint at (push ebx) , you'll notice that we'll hit the breakpoint many times.
Taking a further look to this function I found that it's always copying each character of the interpreted script filename to the stack, leaving the target file to be executed visible for us. So each time after hitting the breakpoint at <push ebx> , we can display the stack and look for our file which is obviously (challenge1.py). There's a manifest file at the folder in the %temp% giving us a little hint about the filename.
Here's a snippet showing the stack just before starting to execute the interpreted code of challenge1.py :
Now after recognizing the file, we'll need the source to it so maybe it is stored on disk and maybe in memory . I tried to look at the folder stored at %temp% but there was no trace , hopefully the argument passed to the function in EBX is a pointer to a string (in other words pointer to the python source code) so if you dump EBX you'll see the source code right there :)


So the python source is :
==============================================
#AJIN ABRAHAM | OPENSECURITY.IN
from passlib.hash import cisco_pix as pix
import sys,base64
user=""
xx=""
if(len(sys.argv)>1):
     x=sys.argv[1]
     hashus = pix.encrypt("DEFCON14-CTF-IS", user=x)
     z=[89,86,69,121,100,82,69,103,98,47,48,103,80,71,77,121]
     for zz in z:
          xx+= chr(zz+(275*100001-275*1000-27225274))
     hashgen = pix.encrypt("DEFCON14-CTF-IS", user=base64.decodestring(xx))
     if(hashgen==hashus):
          print "Oh Man You got it! But :( ===>    " + str(base64.encodestring(base64.decodestring(xx)))
     else:
          print "Naaaaaaa !! You are screweD"
else:
     print "Password !!"
==============================================
As it seems to be "Password!!" is written to the console because no command line arguments were given when executing the file.
I made simple changes to the code to be able to see the flag directly :) as it will be generated only based on the array "z" (so no need for the passlib.hash) :==============================================
import sys,base64
xx=""
z=[89,86,69,121,100,82,69,103,98,47,48,103,80,71,77,121]
for zz in z:
    xx+= chr(zz+(275*100001-275*1000-27225274))
print "The Flag : " + str((base64.decodestring(xx)))
==============================================
This will print the flag to validate on the platform.
And there it is :  300 points + fun.
See you soon,
Souhail Hammou.

Sunday, February 23, 2014

CodeGate CTF 2014 - Reverse 250 Clone Technique Write-up

Hi,
The concept of this Crackme is really simple but reaching the right Track took me hours and hours because I was looking deeper into it and the answer was right in front of me :) ...
The challenge is named "Clone Technique" used in Naruto Manga ,  the process creates many instances of it (using CreateProcessW) with different command line arguments (3 values).
Example :
2nd process : clone_technique.exe 3026539702 3580248161 2
3rd process : clone_technique.exe 466510610 2867152813 3
4th process : clone_technique.exe 2580226910 609694577 4


The wrong way that I took was fortunately of some benefit because what I did is analyze how the values are generated and I also simulated the algorithm in ASM (check links below).
In the first place I didn't know how the flag would be and I couldn't get any hints so I tried to look and look until I found this weird string in the .data section :
I've put a breakpoint on access to this string and ran the program, then the debugger breaks at a function at : 00401070 (you can also check all the references to this string and you'll find the "push 00407030" to our function).
This function takes 3 arguments : - the first value in the cmdline , the second value and a pointer to the string.
The function will use both values in a loop to decrypt each byte alone of the string and store it in a seperated memory location pointed by EDX using the instruction :
004010E8  |. 8802           |MOV BYTE PTR DS:[EDX],AL
The function returns a pointer to the decrypted string in EAX (the decryption result will be non-ASCII until the used values -keys- are right).

If you have a clear idea now , you will notice that each process will be created with its own cmd line arguments , thus different keys to decrypt the string , thus different result. So we'll need to show the final decrypted string for each process until finding a readable ASCII string.
We'll need to patch the executable and create a code cave which will pop up a MessageBox whenever the string is decrypted (we can also display only the ASCII compatible string which will only be the flag) . I was lazy and tired so , I just put a MessageBox call and kept pressing enter until seeing the flag :

Jump to code cave

 We don't have to forget to NOP a "REP STOS" instruction that will cause an access violation after redirecting the execution to our cave code.
Now save the executable , run it and you should see MessageBoxes with total gibberish (invalid key decrypting the string) , keep clicking and clicking and clicking until this will popup :

The Flag.

Script which will generate the same values passed in the command line (complete waste of time :) ) : http://pastebin.com/tcRdpEKF

Regards.

Saturday, February 1, 2014

Anti-debugging trick - Checking for the Low Fragmentation Heap

Hi everyone,

I'll introduce you today a Anti-debugging trick which the idea came across my mind while debugging Windows Heap, I don't know if it was used before anywhere but here I am showing it today.

Check the C/C++ source code : http://pastebin.com/pacrKh0z

Short introduction to the Windows front end allocator :

Yesterday I promised writing something related to the windows heap manager and an opportunity came now to discuss some of the front end allocator aspects.
First of all let me define what a LFH (low fragmentation heap) is :
The LFH was introduced in Windows XP and Windows Server 2003 but it wasn't used as a default front end allocator until Windows Vista. The default front end allocator were the lookaside lists (LAL) , each of these 2 is a singly linked list with 128 lists.

The LFH as its name describes is implemented to guarantee that heap fragmentation will be reduced and it's strongly recommended to use for application that allocate a big number of small size blocks.
When the LFH is created first, predetermined sizes of memory will be allocated and put into buckets (LFH lists), when the application will call for an allocation the LFH will provide the smallest available block to satisfy the allocation , otherwise the request will be passed into the heap manager then to the Freelists (check explanation later).

When LAL is used as a front end allocator, a block won't reside in a list of its list until it was allocated either from the FreeLists or by committing memory then freed. All that won't apply until a list of the lookaside table can handle the freed block otherwise it will passed to the Heap manager to perform coalescing if two adjacent blocks are free, update the FreeList bitmap values (if necessary), invalidate coalesced blocks entries then insert the coalesced block into its valid list in the FreeLists. If no block coalescing is possible the block is inserted directly in the FreeLists.

Anti-Debugging Trick :

I noticed that when the executable is run under a debugger no Low Fragmentation Heap (LFH) is created for it so the pointer to the LFH equals NULL.
So we'll just have to check if the pointer to LFH is null to detect if the process was created inside a debugger.
I tried after to run the process outside the debugger then attach it and I noticed that a LFH is created for the heap and the pointer to the LFH is valid.
 The pointer to the LFH is located at "heap_handle+0xd4" under Windows 7 for WOW64 executables and at "heap_handle+0x178" for 64-bit executable.

I attached the debugger to the process :
0:001> dt _HEAP 00460000
ntdll!_HEAP
   +0x000 Entry            : _HEAP_ENTRY
   +0x008 SegmentSignature : 0xffeeffee
   +0x00c SegmentFlags     : 0
[...]
   +0x0d0 CommitRoutine    : 0x5b16148e

   +0x0d4 FrontEndHeap     : 0x00468cf0 Void
   +0x0d8 FrontHeapLockCount : 0
   +0x0da FrontEndHeapType : 0x2 <-- Type : LFH
   +0x0dc Counters         : _HEAP_COUNTERS
   +0x130 TuningParameters : _HEAP_TUNING_PARAMETERS


When running the process from the debugger LFH won't be enabled :
0:001> dt _HEAP 00320000
ntdll!_HEAP
   +0x000 Entry            : _HEAP_ENTRY
   +0x008 SegmentSignature : 0xffeeffee
   +0x00c SegmentFlags     : 0

[...] 
   +0x0cc LockVariable     : 0x00320138 _HEAP_LOCK
   +0x0d0 CommitRoutine    : 0x6d58ec0e     long  +6d58ec0e
   +0x0d4 FrontEndHeap     : (null)
   +0x0d8 FrontHeapLockCount : 0
   +0x0da FrontEndHeapType : 0
   +0x0dc Counters         : _HEAP_COUNTERS
   +0x130 TuningParameters : _HEAP_TUNING_PARAMETERS


Remember that, The LFH isn't used by default until Windows Vista and posterior versions , so to implement the anti-debugging technique under Windows XP we'll need to enable the LFH as it's not used by default, to do so you'll simply need to call HeapSetInformation with the HEAP_INFORMATION_CLASS set to 0 and with the pointer to the information buffer pointing to "0x2" which will enable the LFH for the heap passed as the first argument.

A simple way to bypass this technique is simply by attaching the debugger to the application instead of running it from a debugger :) .

More details on the LFH : here

Thanks for your time :)
Souhail Hammou. @Dark_Puzzle

Thursday, January 30, 2014

Creating and using your own 'heap' manager

Hi,
First of all, I didn't want to write a long title so I've put word heap between apostrophes, simply because in this example we're not creating or managing a heap, but a (zeroed) chunk of  memory which we reserve from the virtual address space of our application. (we'll commit from the reserved chunk as needed)

The differences between a heap and our custom heap are huge.
The only thing that you have to keep in mind for now is that a Heap is divided into Segments each segment contains heap blocks within the committed memory range in which the user/application accessible part resides.
Another thing that I want to mention is that the Windows heap manager keeps track of free blocks using the BEA (back-end-allocator or FreeLists) and the LFH/LAL (low fragmentation heap or lookaside lists).
In addition each block in use by the application or that is in the LAL is considered busy (A Flag withing each block describes its status) and each block within a free list is considered Free.
Maybe I'll write a detailed post soon about Windows Heap Management.

Back to our topic : I spent much time in the previous months trying to understand the concepts behind the Windows Heap Manager and also some of its exploitation techniques. Thus, I also added a small security check in the custom manager that does safe unlinking from the FreeList.
Our custom manager will clone only a small part of Windows heap management which is implementing a circular FreeList structure and will also use a singly linked list to keep track of all allocated and free blocks. I programmed it so no new portions will be committed from reserved memory until there are no free blocks to allocate from.
You will be able also to display details about the MAP (singly linked list) and the FreeList used while allocating and freeing to see the changes.

Full commented C++ source here : http://pastebin.com/2LgcByyC

Execution example :
I've allocated some blocks then freed some of them and displayed the map :

And after that displayed the FreeList :
 
P.S : 0x002A4D10 is the FreeList's head.
You can play with allocations and frees as you like then display details :)
See you soon,

Souhail Hammou. @Dark_Puzzle .


Monday, January 27, 2014

HackIM CTF 2014 - Reverse100 write-up

Hey,
The challenge is a 32-bit executable : when executing it displays the following :
   Flag : )T(+,*'))$&T(Y)*#(+&#+)$%'T+&#(T
I found that  ")T(+,*'))$&T(Y)*#(+&#+)$%'T+&#(T" is passed to 3 functions, only one of them is executed when running the program (the one that will concatenate 'Flag :' and the encrypted flag then pass them to WriteFile which will write the output to the console) .
So there might be a piece of code that may decrypt the encrypted flag somewhere and was keeped there but never refered to anywhere.
When I saw where the other pushes are it turned out to be the decryption stub which is never executed.
Disassembly here : http://pastebin.com/sw6DkfPN

As you can see it takes every character from  ")T(+,*'))$&T(Y)*#(+&#+)$%'T+&#(T" then adds "0xD" to it , after that it concatenates the result with another string "5F 41 4E 44 5F 4D 4F 4F 4F 4F" which is  "_AND_MOOOO" in ASCII.

Thus the flag would be : 6a589746613a5f670583086124a8305a_AND_MOOOO
Easy right ? :)
Cheers,

Souhail Hammou.

Sunday, January 26, 2014

Introduction To Windows API Hooking.

Hey,
Today I wrote a piece of code that hooks MessageBoxA API to redirect execution to another function that will call MessageBoxA with different arguments.
This is the traditional way to hook APIs , there are other methods used for instance IAT hooking.

C++ Visual Studio Express 2010 : http://pastebin.com/ny3NGn93

The 1st step was to Hotpatch MessageBoxA function. In other words some functions in Windows DLLs are ready to be hooked that's why a "mov edi,edi" (which represent a 2 bytes NOP) which will be patched to a short jump is the first instruction executed in each of these functions.

The question that you may ask is why not simply using 2 NOPs instead of "mov edi,edi" , the answer is related to performance : each NOP takes 1 clock cycle so 2 NOPs will take 2 clock cycles. But "mov edi,edi" instruction will take only 1 clock cycle.

Each "mov edi,edi" is preceded by 5 NOPs which are never being executed. Hotpatching consists of overwriting "mov edi,edi" by a short 5 bytes jump back. And then inserting our hook by overwriting the 5 NOPs with a long jump instruction that will execute our desired function, this requires us to calculate a relative address.

When the hook is no longer needed it is sufficient to restore only "mov edi,edi" instruction as the 5 bytes before it are never executed.

See you soon :)

Souhail Hammou.

Saturday, January 25, 2014

A Quick Dive Into Windows Kernel-Mode Debugging - Protected Processes.

Hey :) ,
This is maybe a first write-up of many which will discuss windows kernel debugging.
I've mentioned in my previous post "protected processes" and I decided to share with you this writeup discussing them and showing some applied kernel debugging.
Protected processes are digitally signed processes that were first introduced in Windows Vista in order to protect Media contents (HD/Blu-ray).
The use of Protected processes wasn't hindered by Media use only . Processes such as System and Werfault.exe (Displays information about crashes and needs access to protected processes in case one of them crashes) are protected. So you can see that protected processes can interact with each other normally. In addition, even a normal process has the ability to create a Protected process BUT it will certainly fail because a special digital signature isn't present in the created process
Another point is that Protected Processes forbid users even with an administrator account to debug them,dump memory,edit memory. Furthermore, access rights to a protected process are limited for instance PROCESS_QUERY_LIMITED_INFORMATION / PROCESS_SUSPEND_RESUME / PROCESS_TERMINATE accesses are granted while PROCESS_ALL_ACCESS is not.

As you may know, each process has an executive process (EPROCESS) structure that resides in Kernel mode and which can be accessed only from it. The EPROCESS structure contains detailed information about the process and points to many other structures like KTHREAD structures list, and it also contains structures like pcb which is a KPROCESS structure and the first element of EPROCESS.

Speaking about Protected Processes , EPROCESS has a special bit that defines the nature of a process (protected or not).
In our example we will try to attach (audiodg.exe) which is a protected process to OllyDbg. The result is the following:
We have 2 choices here , the first is to make Ollydbg a protected process and then Attach it to audiodg.exe or zeroing the bit in audiodg.exe EPROCESS structure to make it unprotected then attach it normally.

We'll do the first one, we can similarly do this with "Task Manager" to create a dump of audiodg.exe or any protected process then examine that dump.
So let's set up the kernel debugger and display the EPROCESS structure for ollydbg.exe :

lkd> dt _EPROCESS 846d8030
nt!_EPROCESS
   +0x000 Pcb              : _KPROCESS
   +0x098 ProcessLock      : _EX_PUSH_LOCK
   +0x0a0 CreateTime       : _LARGE_INTEGER 0x01cf1a21`239824ec
   +0x0a8 ExitTime         : _LARGE_INTEGER 0x0
   +0x0b0 RundownProtect   : _EX_RUNDOWN_REF
   [...CUT __ CUT...]
   +0x26c Flags2           : 0x2d014
   +0x26c JobNotReallyActive : 0y0
   +0x26c AccountingFolded : 0y0
   +0x26c NewProcessReported : 0y1
   +0x26c ExitProcessReported : 0y0
   +0x26c ReportCommitChanges : 0y1
   +0x26c LastReportMemory : 0y0
   +0x26c ReportPhysicalPageChanges : 0y0
   +0x26c HandleTableRundown : 0y0
   +0x26c NeedsHandleRundown : 0y0
   +0x26c RefTraceEnabled  : 0y0
   +0x26c NumaAware        : 0y0
   +0x26c ProtectedProcess : 0y0        <-- bit in which we are interested.
   +0x26c DefaultPagePriority : 0y101
   +0x26c PrimaryTokenFrozen : 0y1
   +0x26c ProcessVerifierTarget : 0y0
   +0x26c StackRandomizationDisabled : 0y1
   +0x26c AffinityPermanent : 0y0
   +0x26c AffinityUpdateEnable : 0y0
   +0x26c PropagateNode    : 0y0
   +0x26c ExplicitAffinity : 0y0
   [...CUT __ CUT...]
   +0x2b0 RequestedTimerResolution : 0
   +0x2b4 ActiveThreadsHighWatermark : 5
   +0x2b8 SmallestTimerResolution : 0
   +0x2bc TimerResolutionStackRecord : (null)


So all we need to do now is set that bit , in order to so we'll need to edit Flags2.
You can see that the "Protected Process" bit is the 12th bit and we'll need to set it to 1.
0x2d014 -> 101101  0  00000010100
Setting this bit will need us to set Flags2 to 0x2d814 ->101101  1  00000010100 .

lkd> ed 846d8030+0x26c 0x2d814
lkd> dt _EPROCESS 846d8030
nt!_EPROCESS
   +0x000 Pcb              : _KPROCESS
   +0x098 ProcessLock      : _EX_PUSH_LOCK

   [...]
   +0x26c Flags2           : 0x2d814
   +0x26c JobNotReallyActive : 0y0
   +0x26c AccountingFolded : 0y0
   +0x26c NewProcessReported : 0y1
   +0x26c ExitProcessReported : 0y0
   +0x26c ReportCommitChanges : 0y1
   +0x26c LastReportMemory : 0y0
   +0x26c ReportPhysicalPageChanges : 0y0
   +0x26c HandleTableRundown : 0y0
   +0x26c NeedsHandleRundown : 0y0
   +0x26c RefTraceEnabled  : 0y0
   +0x26c NumaAware        : 0y0
   +0x26c ProtectedProcess : 0y1
       <-- Ollydbg.exe is a protected process now
   +0x26c DefaultPagePriority : 0y101
   +0x26c PrimaryTokenFrozen : 0y1
   +0x26c ProcessVerifierTarget : 0y0
   +0x26c StackRandomizationDisabled : 0y1
   +0x26c AffinityPermanent : 0y0
   +0x26c AffinityUpdateEnable : 0y0
   +0x26c PropagateNode    : 0y0
   +0x26c ExplicitAffinity : 0y0


Now we'll simply try to attach audiodg.exe and it will work as expected :

I hope you enjoyed reading this short writeup.
See you later :).

Regards,

Souhail Hammou . @Dark_Puzzle