Dive into exceptions: caution, this may be hard



Suppose that you are facing a practical task that requires a full implementation of exception handling in a code embedded in someone else’s process, or you are creating your next PE packer/cryptor to ensure the functionality of exceptions in an unpacked image. In any case, it all comes down to the fact that the code using the exceptions is executed outside the image projected by the system boot loader, which will be the main cause of your problems.

To demonstrate the problem, consider a simple example of code that copies its own image to a new area within the current AP process:

In the ‘exceptions_test’ procedure, the attempt to access a null pointer is wrapped in ‘try-except’, an MSVC extension, instead of exception filter, there is a stub that returns ‘EXCEPTION_EXECUTE_HANDLER’, which should immediately lead to the execution of code in ‘except’ block. In the first call, ‘exceptions_test’ works as expected: the exception is intercepted, and the system displays a message box. But after copying the code to a new place and calling up a copy of ‘exceptions_test’, the exception handling stops, and the application simply “crashes” with an unhandled exception message, so characteristic for this version of OS. The specific reason of such behavior will depend on the platform used for the test and, to identify it, we need to understand the exception dispatching mechanism.

Exception Dispatching

Exception Dispatching

Regardless of the platform and the exception type, the dispatching for user mode always starts from ‘KiUserExceptionDispatcher’ in ‘ntdll’ module, the control of which is handed over from ‘KiDispatchException’, a core dispatcher (if the exception was called from user mode and has not been handled by debugger). In this example, the control is handed over for both cases of exception (during the execution of ‘exceptions_test’ and its copy in the new address), you can verify this by setting the breakpoint on ‘ntdll!KiUserExceptionDispatcher’. The code of ‘KiUserExceptionDispatcher’ is very simple and similar to the following:

where ‘EXCEPTION_RECORD’ is the structure with information about the exception, and ‘CONTEXT’ is structure of the thread context state at the time of exception. Both structures are documented in MSDN, but you are probably already familiar with them. Pointers to these data are sent to ‘ntdll!RtlDispatchException’, where the real dispatching actually takes place. In 32-bit and 64-bit systems, the mechanics of exception handling are different.


The main mechanism for x86-platform is Structured Exception Handling (SEH) based on a singly linked list of exception handlers located in the stack and always available from ‘NT_TIB.ExceptionList’. The basics of this mechanism have been described many times in various papers (see Useful Resources box). So I will not repeat all this but only focus your attention to those points that intersect with our task.

SEH chain dump

SEH chain dump


The fact is that, in SEH, all items of the handler list must be in the stack, which means that they are potentially exposed to overwriting in case of buffer overflow in the stack. This was successfully used by the creators of exploits — the pointer to the handler was overwritten by an address required to execute the shell code, and this was also accompanied by overwriting the pointer to the next list item, which violated the integrity of the handler chain. To increase the resilience to attacks against the programs that use SEH, Microsoft developed such mechanisms as SafeSEH (a table with addresses of “safe” handlers located in ‘IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG’ of PE file), SEHOP (a simple integrity check for the frame chain) and integrated the checks under DEP system policy to be conducted in the process of exception dispatching.

A simplified pseudocode for basic dispatching procedure ‘RtlDispatchException’ for x86-version of ‘ntdll.dll’ in Windows 8.1 can be represented (with certain assumptions) as follows:

The presented pseudocode allows you to conclude that a successful transfer of control to SEH handler during the dispatching of an exception requires meeting the following conditions:

  1. The chain of SEH frames must be correct (end with the handler ‘ntdll!FinalExceptionHandler’). The test is performed with SEHOP enabled for the process.
  2. SEH frame must be located in the stack.
  3. SEH frame must contain a pointer to a “valid” handler.
The call stack for exception filter

The call stack for exception filter

While everything is absolutely clear for the first two points and no further steps are needed to implement them, the procedure for checking the handler for its “validity” requires a more detailed explanation. The handler is checked by using ‘ntdll! RtlIsValidHandler’, the pseudocode of which for Vista SP1 version was for the first time presented to the public back in 2008 at the Black Hat conference in the United States. Even though it contained some inaccuracies, this did not prevent it from roaming through ‘copy-paste’ from one resource to another for several years. Since then, the code of this function did not change significantly, and the analysis of its version for Windows 8.1 allowed to generate the following pseudocode:

The above pseudocode has a modified procedure for checking the conditions (in the original version, some conditions are checked twice, some are checked in nested functions). After analyzing the pseudocode, you can see that, for a successful validation, it is necessary to fulfill one set of conditions where the handler belongs:

  • Image with no ‘SafeSEH’, no ‘NO_SEH’ flag, no ‘ILonly’ flag;
  • Image with SafeSEH, no ‘NO_SEH’ flag, no ‘ILonly’ flag, the image must be registered in ‘LdrpInvertedFunctionTable’ (not required if the exception occurred at the time of process initialization);
  • Non-executable area of memory, ‘ExecuteDispatchEnable (ExecuteOptions)’ flag must be enabled (will work only with disabled ‘No Execute’ for the process);
  • Executable area of the memory, ‘ImageDispatchEnable’ flag must be enabled.

In this case, the area of memory is considered as an image, if the region attributes have a ‘MEM_IMAGE’ flag enabled for it (you can get the attributes by using ‘NtQueryVirtualMemory’), and the content corresponds to PE structure. You can get the process flags by using ‘NtQueryInformationProces’ from ‘KPROCESS.KEXECUTE_OPTIONS’. Based on the obtained information, we can suggest at least three ways to implement the support for exceptions in dynamically loaded code on x86 platform:

  1. Enabling/substituting ‘ImageDispatchEnable’ flag for the process.
  2. Substituting the memory region type for ‘MEM_IMAGE’ (for PE image with no SafeSEH).
  3. Implementing your own exception dispatcher to bypass all checks.

Now, let’s examine in detail each of these options. Separately, it is worth mentioning the support for SafeSEH that you may need when writing, for example, a usual legal PE packer or protector. To implement it, you will need to think about adding manually a mapped image record (with a pointer to SafeSEH) to global table ‘ntdll!LdrpInvertedFunctionTable’. In this case, the functions that work directly with this table are not exported by ‘ntdll.dll’ and it doesn’t make much sense to search for them manually, because, in the older OS, they still require a pointer to the table. After somehow finding the pointer, you should also think about blocking the access to the table in order to safely make changes. An alternative option may be to unpack the file into a section of the unpacker and transfer ‘SafeSEH’ table from the unpacked file into the main image. Unfortunately, a detailed discussion of these and other techniques is beyond the scope of this article, as here we review the options that do not imply the support for SafeSEH (by the way, you can always simply set the values in this table to zero).

Substituting ‘ExecuteOptions’ of the Process

ExecuteOptions (‘KEXECUTE_OPTIONS’) is a part of kernel structure ‘KPROCESS’, which contains the DEP settings for the process. The structure has the following form:

At the user level, you can obtain the values of these settings (flags) by using ‘NtQueryInformationProcess’ with the information class parameter equal to 0x22 (ProcessExecuteFlags). The flags are set similarly by using ‘NtSetInformationProcess’. Starting with Vista SP1, the processes with enabled DEP, by default, have enabled ‘Permanent’ flag that bans any change to the settings after initializing the process. This is confirmed by the fragment of ‘KeSetExecuteOptions’ procedure called in kernel mode from ‘NtSetInformationProcess’:

Therefore, while in the user mode, you cannot modify ‘ExecuteOptions’ with enabled DEP. But you still have an option just to “cheat” ‘RtlIsValidHandler’ by setting a hook on ‘NtQueryInformationProcess’, where the flags will be substituted by those that you need. Setting up such interception would make workable the exceptions in the code outside the modules loaded by the system. Here’s an example of interceptor code:

This method for exceptions is suitable when injecting the entire PE image or for manually mapped images. Moreover, this option is somewhat more preferable than the previous one, because it does not diminish the security of the process by partially disabling DEP (you do not need more malware, right?). As a bonus, this method allows you to pass an internal check of the handler in modern versions of CRT when using ‘try-except’ and ‘try-finally’ structures (these structures can be used without CRT, for more details, see the relevant box). In CRT, the check is performed by ‘ __ValidateEH3RN’ called from ‘_except_handler3’, it assumes that the type ‘MEM_IMAGE’ is set for the region and correct PE structure.

Using Your Own Exception Dispatcher

If the options that involve setting up a hook are not suitable for any reason or you simply do not like them, you can go even further and fully replace SEH dispatching by your own code after implementing all required SEH dispatcher logic inside the vector handler. The above pseudocode of ‘RtlDispatchException’ shows that VEH is called before the system starts to process SEH chain. Nothing prevents you from seizing control over the exception by using the vector handler and then deciding on your own what to do with it and what handlers to call. You can set VEH handler just with one line of code:

where ‘VectoredSEH’ is a handler which, in fact, is SEH dispatcher. The complete chain of calls for this handler will look like this: KiUserExceptionDispatcher -> RtlDispatchException -> RtlpCallVectoredHandlers -> VectoredSEH. In this case, you may not return the control of the calling function, and to call on your own ‘NtContinue’ or ‘NtRaiseException’ depending on the success of dispatching. For complete source code of implementing SEH through VEH, see the materials accompanying this article or go to [GitHub] (https://github.com/Teq2/SEH-Over-VEH). The implementation code is fully workable, and the dispatching logic corresponds to the system logic.

SEH dispatcher inside the vector handler

SEH dispatcher inside the vector handler

x64 and IA64

64-bit versions of Windows for x64 and Itanium-based platforms use a completely different method to handle exceptions than in x86 versions. This method is based on tables that contain all information necessary for exception dispatching, including the offsets for the beginning and end of a code block, for which the exception is handled. Therefore, the code compiled for these platforms has no operations to set and remove the handler for each ‘try-except’ block. The static table of exceptions is in the ‘Exception Directory’ of PE file and represents an array of elements from structures of ‘RUNTIME_FUNCTION’ that look as follows:

It is nice to note that, at the system level, there is support provided for dynamic code exceptions. If the code is in an area of memory which is not an image or this image has no exception table generated by the compiler, the information for exception handling is taken from dynamic tables of exceptions (DynamicFunctionTable). A pointer to the list is stored in ‘ tdll!RtlpDynamicFunctionTable’ and several functions for working with this list are exported from ‘ntdll.dll’. A cursory review of the listings for these functions allowed to obtain the following structure of list items in ‘DynamicFunctionTable’:

RUNTIME_FUNCTION' lookup algorithm

RUNTIME_FUNCTION’ lookup algorithm

The items are added by ‘RtlAddFunctionTable’ and ‘RtlInstallFunctionTableCallback’, and deleted by ‘RtlDeleteFunctionTable’. All these functions are well documented in MSDN and are very easy to use. Here’s an example of adding a dynamic table for the image that has been just displayed manually:

That’s all, there are no hooks or your own exception dispatchers, and there is no need to bypass the system checks. I would only like to note that ‘DynamicFunctionTable’ is global for the process. So, if the code for which an entry has been added did its job and has to be removed, it is better also to remove the corresponding entry from the table. Instead of adding a table, you can set a callback for specific range of addresses in AP that will receive control each time when the ‘RUNTIME_FUNCTION’ entry is needed for the code from that area. For a version with callback, see the source codes accompanying this article.

Exception is handled

Exception is handled


The low-level programming under Windows that involves the use of native API does not impose exceptions as a method for handling errors, and the developers of “special software” often either simply neglect them or limit themselves just to setting an unhandled exception filter or to simply using VEH. Nevertheless, the exceptions remain a powerful tool that enables you to extract more gain from a more complex architecture of your program. The methods described in this article will allow you to use exceptions even in the most unusual circumstances.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">