Monday, June 10, 2013

Malwares are a never-ending source of obfuscation tricks: some of them are accurately crafted, whereas others just happen to be there. Sometimes it depends on the compiler itself: how it deals with optimizations, how it translates some language specific constructs, and so on. In this case, we are going to discuss how SEH is implemented in Visual C++. After a short low level explanation, I will propose a procedure that exploits this mechanism in order to obfuscate code and I will provide the source code of a working POC too.SEH in Visual Studio: how does it work?Let's begin with a brief description of a little trick that I've found while analyzing a malware detected by ESET as Win32/Rootkit.Avatar. For more information about it you can check this detailed article.In particular, the article mentions a specific behaviour of the malware: "the malware raises an exception to pass control to an installed exception-handler". That is:....text:0040235B push offset sub_402B26.text:00402360 mov eax, large fs:0.text:00402366 push eax.text:00402367 mov large fs:0, esp

...

This is the standard way an exception handler is installed, and it corresponds to a try-catch statement in C++.Anyway, if we keep analyzing the code we'll notice that this isn't the only exception handler being installed. In fact, we are going to see how the malware takes advantage of another one, in the attempt to hide a common debugger check (the PEB one) inside it.Exception handlers have already been extensively documented in the past, but this one is a little bit trickier because it makes use of a Visual Studio specific implementation: the try-except statement. Here is how it is implemented in the malware:....text:00401CC5 push offset dword_4044C8

.text:00401CCA push offset __except_handler3.text:00401CCF mov eax, large fs:0.text:00401CD5 push eax.text:00401CD6 mov large fs:0, esp...This is the installation code for a SEH in Visual Studio, and there are two substantial differences in respect to the previous code: the first one is that it seems to be installing a standard library routine ("__except_handler3") as an exception handler, which doesn't look suspicious; the second one is a little bit confusing if you haven't read the specifications before. However, a closer look will reveal the trick. In fact another value is being pushed, that is:.text:00401CC5 push offset dword_4044C8

We usually wouldn't expect to see this additional "push", and we would think that it isn't related to the SEH, but... it actually is!

In particular, this "push" is putting on the stack the address of a data structure named "scopetable entry", documented by Matt Pietrek, which has the following definition:

typedef struct _SCOPETABLE

{

DWORD previousTryLevel;

DWORD lpfnFilter;

DWORD lpfnHandler;

} SCOPETABLE, *PSCOPETABLE;

It specifies the addresses of the code blocks to be executed for the filter expression ("lpfnFilter")and for the except body ("lpfnHandler"):

__try {

... code

}

__except(filter expression) {

... except body

}

The library routine "__except_handler3" uses this information first to call the code for the filter expression, which will decide if the exception is handled or not, and then to dispatch execution to the except body (in case it's handled). So, actually, the real exception handler installed by the malware is not the library one, but it is the one inside the except body. We can see this structure in the malware:

.rdata:004044C8 dword_4044C8 dd 0FFFFFFFFh

.rdata:004044CC dd offset filter

.rdata:004044D0 dd offset except_body

and the related code:

.text:00401CFA mov [ecx], al ; trigger exception!

.text:00401CFC jmp short loc_401D13

.text:00401CFE ; ----------------------------------------------

.text:00401CFE

.text:00401CFE filter:

.text:00401CFE mov eax, 1

.text:00401D03 retn

.text:00401D04 ; ----------------------------------------------

.text:00401D04

.text:00401D04 except_body:

.text:00401D04 mov esp, [ebp+var_18]

.text:00401D07 mov eax, large fs:30h

.text:00401D0D mov al, [eax+2]

.text:00401D10 mov [ebp+var_1C], eax

.text:00401D13

.text:00401D13 loc_401D13:

.text:00401D13 mov [ebp+var_4], 0FFFFFFFFh

.text:00401D1A mov al, byte ptr [ebp+var_1C]

.text:00401D1D mov ecx, [ebp+var_10]

.text:00401D20 mov large fs:0, ecx

.text:00401D27 pop edi

.text:00401D28 pop esi

.text:00401D29 pop ebx

.text:00401D2A mov esp, ebp

.text:00401D2C pop ebp

.text:00401D2D retn

From this listing you can see that the filter code always returns true, which means that the except body is always executed when an exception happens (and the code triggers one on purpose on line 00401CFA). On execution, the except body checks PEB.BeingDebugged in order to detect a debugger attached to the process, and returns true or false depending on the result. Later, the function that called the above code, will check such a flag and terminate execution in case of debugger detection.A better way to exploit the SEH implementation.

So, all this trouble just to hide the check for the debugger inside a try-except statement and to make it a bit more difficult to trace but, as it is, this trick is not really being effective. Is it possible to do better?Well, if we put the debugger check inside the filter code rather than in the except body, we can make the filter return false in case of debugger detection, which means the library handler "__except_handler3" won't call the except body, and will terminate the execution instead. This would confuse things, because the decision on whether to terminate execution or not is taken inside a library code routine, rather than in the malware code itself. In this case, if someone debugs the malware he will find that the execution always terminates when running the standard Visual Studio exception handler code, and will have to dig into it to understand what's happening.

It would look like this:

__try

{

//...

RaiseException(0, 0, 0, 0);

}

__except(!IsDebuggerPresent())

{

//...

}

Briefly: the code guarded in the try block will cause an exception; the filter routine is the check implemented via the IsDebuggerPresent API, which returns true if the debugger is attached and false otherwise. So, in case a debugger is detected, the filter returns zero, and the except block is never called, causing the process to simply crash.

Of course, you can obfuscate the code in the filter routine and make it not so obvious, and this will leave the analyst puzzling in why is the code crashing inside Visual Studio standard library routine :)."__except_handler4"?!

"__except_handler3" is the standard library code, but it was susceptible to corruption in case of stack overflow, and this caused security problems. So with new versions of Visual Studio, the function was updated to "__except_handler4", which is essentially the same routine with additional features. In particular, it uses canaries to protect the SEH data, in order to make sure that the pointers to the exception handlers have not been overwritten: .text:004010C5 @__security_check_cookie@4 proc near ; DATA XREF: __except_handler4+11 o.text:004010C5 cmp ecx, ___security_cookie.text:004010CB jnz short loc_4010CF.text:004010CD rep retn.text:004010CF.text:004010CF loc_4010CF: ; CODE XREF: __security_check_cookie(x)+6 j.text:004010CF jmp ___report_gsfailure.text:004010CF @__security_check_cookie@4 endp

Now that we know all the details related to the SEH implementation in Visual Studio, I would like to propose a simple yet powerful idea to obfuscate algorithms.Briefly, you can:

Create a set of basic virtualized opcodes, each one represented by a different function.

Use these opcodes to write an algorithm encoding it in a data structure (each opcode will be associated to a particular "id number").

Execute each instruction of the program through a different filter expression. This means that if your algorithm consists of "n" opcodes, you will have "n" try-except blocks (that is, "n" filter expressions) and you will have to generate "n" exceptions as well.

Here is the source code of a working POC that implements the RC4 algorithm:

Following this idea, you can easily implement any other algorithm and this bears several advantages in term of obfuscation. In fact, in order to understand the code, you have to analyze the array containing all the opcodes, that is dynamically generated:...

.text:00401678 mov [ebp+var_160], ebx

.text:0040167E mov [ebp+var_15C], 1

.text:00401688 mov [ebp+var_158], 2020113h

.text:00401692 mov [ebp+var_154], ebx

.text:00401698 mov [ebp+var_150], 100h

.text:004016A2 mov [ebp+var_14C], 14h

.text:004016AC mov [ebp+var_148], 0Ah

.text:004016B6 xor ebx, ebx

.text:004016B8 mov [ebp+var_144], ebx

.text:004016BE mov [ebp+var_140], 16h

.text:004016C8 mov [ebp+var_13C], ebx

.text:004016CE mov [ebp+var_138], ebx

.text:004016D4 mov [ebp+var_44C], eax

.text:004016DA lea ebx, [ebp+var_458]

.text:004016E0 mov [ebp+var_448], ebx

.text:004016E6 mov [ebp+var_444], 0

.text:004016F0 mov [ebp+var_440], eax

.text:004016F6 lea ebx, [ebp+var_464]

.text:004016FC mov [ebp+var_43C], ebx

.text:00401702 mov [ebp+var_438], 0

.text:0040170C mov [ebp+var_434], eax

.text:00401712 lea ebx, [ebp+var_460]

.text:00401718 mov [ebp+var_430], ebx

.text:0040171E mov [ebp+var_42C], 0

.text:00401728 mov [ebp+var_428], eax

...

Moreover, the opcodes aren't referenced by any direct call, because they are executed only due to the "RaiseException" API, which is guarded within various nested try-except blocks. This results in a chain of filter expressions and except bodies (which constitute an additional layer above the opcode routines) that are triggered by the scopetable mechanism: