How to Defeat SEH Anti-Debugging

There are much better articles that describe what Structured Exception Handling(SEH) is and honestly, I'm still trying to wrap my head around it so don't take what I write as gospel. If you have a better understanding and I get something wrong, please correct me. I really want to understand this. With that being said, I couldn't find an easy way to circumvent/defeat it so this is what I came up with.

Structured Exception Handling is a Windows mechanism to allow programs to handle exceptions/interrupts. This is accomplished by adding handlers to a linked list of exception handlers. This linked list is stored in the Thread Environment Block(TEB) structure. It can be referenced by fs:[0] on x86 binaries or gs:[0] on x64 binaries.

 The TIB struct:

 
Note that TEB is just an extended TIB structure. The EXCEPTION_REGISTRATION_RECORD struct:

 

These two structures were talked about ad nauseam when I was doing my research but I couldn't get it to function how other articles wrote about it. Instead, I was running into the undocumented exception handling used by the Microsoft C runtime library. 

Before we proceed further, this is the code we will be analyzing:

 
The code should hopefully be self-explanatory. Inside of the try block, I'm de-referencing an invalid pointer which will lead to an exception being thrown. If you execute this outside of a debugger, you will see, "Execute real logic" but if you execute it inside of a debugger, you will get an exception access violation.

 
So this here is what I was looking to solve when I originally began to research. I wanted to know how to get my debugger to execute the exception handler. Sure you could just nop out code indiscriminately but what if you nopped out too much or too little? I wanted to know for sure that the code I was executing was the code that should be getting executed. Again, if you know of a better way, please reach out. But what I realized was that before pushing __except_handler4, a structure was being pushed onto the stack. 

 
If you look at the 7th element(28 bytes in), you have the address for the finally block. After you encounter the exception, you can modify EIP and point it to this address. You'll then be able to continue the intended execution flow. Two instructions down from where the error is throw you see a call to this address. After the call the stack is cleaned up. If you try and return back to main after the normal logic path is taken, you will get another error. Just modify EIP to jump to the clean up and done. 

Comments

Popular posts from this blog

Crackme: antilagvip's medium crackme

Crackme: git's simple crackme medium-hard

Crackme: atherusti's First C program