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

Thursday, January 23, 2014

DLL injection - Injecting a DLL into a running process.

Hey,

Today I had some free time and decided to write a piece of code that will inject a DLL into a running process. In this blog entry I'll be briefly explaining the injection process.

DLL injection is wildly used by normal software, malware , game cheats. For example , game trainers will inject a DLL in order to hook certain functions inside the game or simply patch them in order to get a certain cheat to work. There are many techniques to inject a DLL into a process and today I'll be introducing one of them to you.

The C++ source code can be found here : http://pastebin.com/wW81nApT
(Tested on win 7 64-bit)

The concept is simple , we will walk through all running processes list until finding the target process in which we want to inject the DLL.
After getting the process id we have to get a Handle to it , that's why we'll use the OpenProcess function.
The only important thing that you need to be aware of is trying to inject a DLL into a protected process which will certainly fail .
Protected processes are processes which are required to be signed .Injecting a dll , a thread , accessing their virtual memory or debugging them is prohibited. So the PROCESS_ALL_ACCESS won't work in this case. Only few Accesses are allowed like SYNCHRONIZE.

After getting the HANDLE we'll try to allocate some memory in the target process and make write/read access possible to it. Thus, we'll be able to copy the dll name into the process's virtual address space (VAS) using WriteProcessMemory.
We're copying the DLL name into the target process for the simple reason that a process can't load a DLL if its name/directory isn't in its VAS.
The next thing is injecting the DLL so we'll need the address of LoadLibraryA function which we'll pass to CreateRemoteThread and as an argument to it we'll pass the pointer to where our DLL name is in the target process VAS.

Now our DLL is successfully injected into the process , we'll be in our DllMain as soon as the CALL to LoadLibrary is made.After that I used CloseHandle to close the handle to the process.

Cheers :) and see you soon.

Souhail Hammou.