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:

Thursday, March 21, 2013

Introduction.This is the second part of the article about binary instrumentation for exploit analysis purposes and this time we will discuss a real pdf exploit: a Stack-based buffer overflow in CoolType.dll (CVE-2010-2883). You can retrieve it from the metasploit module exploit/windows/fileformat/adobe_cooltype_sing .In order to bypass DEP, this exploit makes use of Heap Spraying to run its ROP shellcode. On the other hand, our goal is to come closer to the point where the vulnerability occurs, so one clever thing to do is to use Pintool to detect the ROP itself.

To do that, we can simply check if the instruction executed after a RET is located after a CALL, but be aware that performing this test alone could lead to false positives. A better test would be to control wether this check works for three times in a row, but this gives rise to some Pintool's problems that we will discuss later.Another method to detect ROP is to control the ESP register and look for the "0c0c0c0c" value, but inspecting the register with Pin is very slow and will degrade the performance of your Pintool. So we won't implement this one.Finally, one last check is to log the "pop ESP" instruction, that is a common ROP gadget employed right before the ROP shellcode itself.Detecting the ROP with a Pintool.Here is the function to detect the ROP:

in the "DetectEip()" function (where specified by the comments).Now a brief description of what the code does. Basically, this Pintool looks for two opcodes: the one corresponding to RET (Pin code 557) and the one corresponding to POP (Pin code 486).If a RET is encountered, the Pintool follows it and checks if the previous opcode is a CALL, looking for the E8 opcode or the ones provided in the "OpcCheck[].Opcode" array (the list may not be complete, but while testing it was reasonably accurate). In case it's not, it notifies the user with the message: "*Address* RETurned here, but not after call".If a POP is encountered, it checks if it is a "POP ESP" and, in case it is, it notifies the user by printing "*Adress* POP ESP DETECTED!!" and dumps the last executed instructions on file.That's it. You are finally ready to compile the Pintool and run it within Adobe Acrobat Reader to analyse the PDF exploit.Analyzing the outputHere is an excerpt from the output produced by the Pintool:Exception handler address: 7C91EAEC Starting PintoolLoading module C:\Programmi\Adobe\Reader 9.0\Reader\AcroRd32.exe Main exe Base: 00400000 End: 00453FFFLoading module C:\WINDOWS\system32\kernel32.dll Module Base: 7C800000 Module end: 7C8FEFFF Loading module C:\WINDOWS\system32\ntdll.dll Module Base: 7C910000 Module end: 7C9C5FFF Starting thread 0...0D6D8192 RETurned here, but not after call02D43FA5 RETurned here, but not after call22326DB0 RETurned here, but not after call5B18174F RETurned here, but not after call08171CF0 RETurned here, but not after call08171D47 RETurned here, but not after call06066EED RETurned here, but not after call0633DE6B RETurned here, but not after call...4A82A714 RETurned here, but not after call4A82A714 POP ESP DETECTED!!Dumping list of previously executed EIPs 0803DDC60803DDCA0803DDCC0803DDCD...0808B3040808B3050808B3070808B3084A80CB384A80CB3E4A80CB3F4A82A714

From the log above we can see all the modules being loaded and threads being created. Then, we notice some false positives: these are legitimate RETs, which don't return to an instruction after a CALL.Finally, we get to the part where both checks are detected: the code returns to an instruction not located after a call and a "POP ESP" instruction is executed.In particular, the last logged EIPs correspond to following ROP gadgets: 4A80CB38 81C5 94070000 ADD EBP,794 4A80CB3E C9 LEAVE 4A80CB3F C3 RETN 4A82A714 5C POP ESP(4A82A715 C3 RETN)So we have located where the exploit occurs (i.e. the address "0808B308"): not bad!Note that the last instruction reported here (the RETN between parentheses) is not logged by the Pintool because a crash happened right after its execution... but......Why???

As I said before, this exploit makes use of Heap Spraying. In particular, we can see it by debugging Adobe Acrobat Reader while Pin is not instrumenting it and setting a breakpoint on address "0808B308". Now, if we open the PDF exploit and leave the debugger running, we can inspect the memory when the code hits the breakpoint:

This is exactly what we were expecting: you can notice the ROP shellcode at "0c0c0c0c" and the Heap Spraying all around. On the other hand, if we debug the Adobe Acrobat Reader while Pin is instrumenting it, we obtain:

So... no ROP, nor Heap Spraying... but the blocks of memory are still allocated. Who has allocated them?

To get the answer we need to look inside the code window:

... It's Pin itself!

Pin allocates a lot of memory to perform binary instrumentation, occupying also the addresses usually employed by the Heap Spraying. This means that when the ROP shellcode is executed, it's not located where it is supposed to be and this will result in Adobe Acrobat Reader crashing.

Another problem I ran into, is that even when I modified the Pintool in order to force the exploit to work with the shellcode that was placed at a different address than 0x0C0C0C0C, the exploit still crashed.

This time I could see it run all the ROP shellcode, which allocates a block of executable memory, copies itself to it and then jumps to it.

I haven't investigated the problem yet, but it seems that the instrumented shellcode is placed in an area that is read only, therefore the self decryption failed when writing the decrypted bytes back to the shellcode memory.

Sunday, March 10, 2013

This article is about binary instrumentation over various exploit scenarios. In particular, we are going to use Pin, a software developed by Intel, to show how this approach can help with the analysis.Pin is employed to create dynamic program analysis tools, the so called "Pintools". Once executed, a Pintool acts almost like a virtual machine that runs the code from a target executable image and rebuilds it by adding the code you need to perform your own analysis. For example, you can: install a callback that is invoked every time a single instruction is executed; inspect registers; alter the context and so on.Note: I've tested the whole work using Windows XP 32 bit and Visual Studio 2010.How to compile and execute a Pintool.The simplest way to compile a Pintool is to use the Visual Studio project provided by Intel, located in the Pin folder at: \source\tools\MyPinTool .To run it, simply type: pin -t <your_pintool.dll> -- <application_path>.In this way your Pintool will be executed within the application you want to test.

How to code a Pintool: a (very) short description.

A Pintool begins with a standard initialization of the Pin engine by using the "PIN_Init()" function; then, you need to register the callbacks for the events you want to handle. For instance, you can use:

"INS_AddInstrumentFunction()" to register a callback that is invoked at every executed instruction;

"IMG_AddInstrumentFunction()" to register a callback that notifies you every time an executable module is loaded;

"PIN_AddThreadStartFunction()" and "PIN_AddThreadFiniFunction()" to handle thread creation and ending.

In particular, if you register a callback with "INS_AddInstrumentFunction()", you can then use the "INS_InsertCall()" function from it and register other callbacks.These callbacks have a special property: they can be invoked before or after an instruction is executed. Also, you can pass to them any kind of data, including the value of specific registers (the instruction pointer, for instance), memory addresses and so on.Finally, you'll have to use "PIN_AddFiniFunction()" to register the callback that is invoked when the application quits.Once all the callbacks are registered, you can start the instrumented program by calling "PIN_StartProgram()".Your Pintool can filter specific conditions with an incredibly accurate resolution, but bear in mind that the performances may degrade badly depending on what kind of actions you choose to do.As an example, let's consider again the "INS_AddInstrumentFunction()", and suppose that we are going to register a callback that logs every executed instruction to a file: if you are distracted, you might generate a file I/O for every single instruction, which is very inefficient. Another operation that will reduce your Pintool's performances, if called frequently, is the disassembler functionality.So be careful: your instrumented application can run almost at realtime speed if your Pintool is well written, but a bad implementation may slow down your application up to the point where it will take minutes to run.

A basic Pintool.

Here is a very basic Pintool to which we will add more specific functions later.

It basically logs to a file: the address of each instruction being executed; all the exceptions occurred; the name of each module being loaded, including the base and the end address.I have also put a comment in the "DetectEip()" function, to specify where you can call the functions we will add later.First exploit scenario: stack overflow.As a first case study, we are going to consider a specially crafted sample:

Before compiling and linking it (I used Visual Studio 10), be sure to disable all the security options (stack canaries, DEP, ASLR) and to set the Base Address to 0x41410000.I know it might sound a little unreal, and in fact... it is! But don't worry, as I said before, this is just the simplest example that crossed my mind and we are going to use it as a first test. Anyway the methodology I'm proposing is very effective and we will see a real case study later.First, we need to "exploit" this little test: I'll be quick. We can open the executable with Ollydbg and debug it until we find the "getchar" function, that grabs an input string. Then, we enter the following (in my case at least, you should check the parameters explained later if you want to be 100% sure!): "123456789abcAAAA 0AABBBBBBBBBBBBBBBBBBB" (remove the " ").

What's the meaning of it? We are going to fill all the 12 required bytes, and because of the lack of control over the size of the input, we also type:

"AAAA", that is the padding added by the compiler;

" 0AA", that corresponds to the 0x41413020 address (= "AA0 ", because of the endianness) where the "JMP ESP" instruction (= "0xFF 0xE4" as an opcode) is located --- this will overwrite the return address of the "main" function;

a bunch of "B", that corresponds to the "INC EDX" instruction --- this is where you will usually put the shellcode, but as a test every valid instruction will be fine!

Now that you have tested that the string I provided works also in your case, or you have built your own valid string, we are ready to analyze our first exploit scenario: a simple stack overflow. How can we detect that?The most natural idea is to perform a check over EIP to see whether its value corresponds to a non-executable area (the stack in this case).The Pintool maintains two variables containing the base and end address of the module being executed.If the value of the EIP isn't in the range specified by these two addresses, Pintool accesses the modules list maintained by Pin, looking for a new executable module in which the value of EIP resides (for instance, after an API call). When such a module is found, the variables containing the base and end address are updated (making it the current module).If the value of EIP isn't located within any of the modules, the Pintool reports it as suspicious and logs the list of the last 1000 executed values of EIP.Here is the code to do that:

it jumps to the overwritten return address, that is the address "0x41413020", where a "JMP ESP" is located;

Pintool successfully detects that we are trying to execute code within a non executable module (that is the "0x0012FF84" address, belonging to the stack).

Conclusions

This was an introductory article on binary instrumentation for exploit analysis purposes and I really hope you liked it! See you for the second part in a few days, where I will discuss another scenario: a real pdf exploit, that makes use of ROP and Heap Spraying.