Rereading 0day Security (3), SEH Hijacking, Plus GS, SafeSEH and SEHOP

3410 words
17 minutes
Rereading 0day Security (3), SEH Hijacking, Plus GS, SafeSEH and SEHOP
This post is also available in 简体中文.

Part three of “Rereading 0day Security”, lab notes from 0day Security: Software Vulnerability Analysis Techniques, 2nd edition (by failwest and others), written in 2020 and tidied up in 2026. This post folds four or five of my exception-handling notes into one. First, how to overwrite SEH to hijack the program, then the three protections aimed at it, GS, SafeSEH and SEHOP, how each works and how each can be bypassed. Several of the book’s popups use the shellcode from part one that finds APIs dynamically, so I won’t paste it all again here.

What SEH is#

  • SEH is the Structured Exception Handler, an important data structure in Windows exception handling. Each SEH record holds two DWORDs, one pointing at the next SEH record and one holding the address of the handler function, 8 bytes in total
  • SEH records live on the stack
  • When a thread starts, an SEH is automatically installed on its stack as the thread’s default handler
  • If the source uses exception handling like try-except, the compiler implements it by installing an SEH in the current function’s stack frame
  • There are usually several SEH records on the stack at once
  • They’re chained into a singly linked list through their “next” pointers, from the top of the stack toward the bottom. The one at the head of the list (closest to the top of the stack) is pointed to by the pointer at offset 0 in the TEB
  • When an exception happens, the system takes the SEH closest to the top of the stack from offset 0 of the TEB and uses its handler
  • If the handler closest to the scene fails, it tries the next ones down the list
  • If none of the handlers the program installed can deal with it, the system uses its default handler, which shows an error dialog and kills the program

The idea behind overwriting SEH#

  • SEH lives on the stack, so data overflowing a buffer can flood it
  • Change the handler address in the SEH record to the start of the shellcode
  • After the overflow, the corrupted stack frame or heap data triggers an exception
  • Once the system starts handling it, it runs the shellcode as the exception handler

The nice thing is obvious. You don’t have to wait for the function to ret, you just need to cause an exception. A divide by zero like the one below is enough.

Overwriting SEH on the stack#

The lab is on Windows 2000. First I used an all-NOP “shellcode” to see how far the overwrite reaches.

void test(char* input)
{
char buf[200];
int zero = 0;
__asm int 3 // break for debug
__try
{
strcpy(buf, input); // overrun the stack
zero = 4 / zero; // generate an exception
}
__except(MyExceptionhandler()){}
}

Here’s what I saw while debugging:

  • 0x0012FE98 is where the shellcode starts
  • The current thread has 3 SEH records installed. The one closest to the top of the stack is at 0x0012FF68, and it’s the first to be called
  • What we need to overwrite is 0x0012FF6C, its handler address. Put the shellcode start address 0x0012FE98 there and that’s it

Then swap the input for “real shellcode + a tail that reaches the SEH”. The popup shellcode from part one goes first, and the end looks like this:

... (popup shellcode before this, omitted) ...
90 90 90 90 ; next SEH record, anything goes
98 FE 12 00 ; SEH handler address = 0x0012FE98, points at the shellcode

The strcpy overflow overwrites the SEH, zero = 4 / zero raises a divide-by-zero exception, the system goes off to “handle” it with our shellcode, and the popup shows up.

Overwriting SEH on the heap#

The same idea works for heap overflows. Put the shellcode on the heap, use a DWORD SHOOT to point the SEH record at it, then cause an exception. The setup is the same DWORD SHOOT as in part two, only the target changes from the PEB function pointer to the SEH.


A closer look at exception dispatch#

Walking the whole path once gives us something to refer back to when we get to the bypasses.

Exception handling at different levels#

  • The smallest scope for exception handling is the thread. Each thread has its own SEH chain and tries it first when something goes wrong
  • A process can have many threads, and the process also has a handler for everything. When a thread’s own SEH can’t fix it, it goes to the process handler
  • The system also catches everything for every program. When all the handlers fail, the system’s default handler is called, which usually just shows a crash dialog

Thread-level callbacks and unwind#

The callback used for exception handling takes 4 arguments:

  • pExcept: points at the EXCEPTION_RECORD, with the exception type, where it happened and so on
  • pFrame: points at the SEH structure in the stack frame
  • pContext: points at the CONTEXT, with the state of every register
  • pDispatch: the dispatcher context

The callback can return one of two values:

  • 0 (ExceptionContinueExecution): the exception was handled, go back to where it happened and carry on
  • 1 (ExceptionContinueSearch): handling failed, look further down the chain

There’s also an UNWIND step. Once the system finds a handler that can deal with the exception, it calls all the SEH records it walked past earlier (the ones that failed) one more time, to tell them “you’ve been given up on, clean up and release your resources”, and then takes them off the list. During unwind, ExceptionFlags in EXCEPTION_RECORD is set to EH_UNWINDING(0x2), and it’s implemented by RtlUnwind in ntdll. Also, before calling any callback, the system checks whether the process is being debugged, and if so hands the exception to the debugger first.

Process level and the UEF#

When the thread’s chain has failed, it goes to the process exception handler (registered with SetUnhandledExceptionFilter). If that fails too, it reaches the system’s default UnhandledExceptionFilter(), the top-level handler called the UEF (Unhandled Exception Filter). On 2000/XP this function reads the registry key HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug, where the Auto value decides whether to show a dialog and the Debugger value names the default debugger.

The whole flow#

  • The CPU catches the exception and the kernel takes over for the kernel-mode part
  • When the kernel is done, it hands things back to user mode
  • The first thing in user mode to handle the exception is KiUserExceptionDispatcher() in ntdll
  • It checks whether the process is being debugged, and if so hands it to the debugger
  • Then it goes through VEH (vectored exception handling)
  • If not being debugged, it calls RtlDispatchException() to walk the thread’s SEH chain, and unwinds once it finds a handler
  • If every SEH on the stack fails, it calls the process exception handler
  • If that fails, it calls the UEF

A few other places to strike#

  • VEH, vectored exception handling, new since XP. It’s per process, registered through an API, chained into a doubly linked list and stored on the heap, and it runs before SEH. Use a heap overflow DWORD SHOOT to change the pointer to the VEH head node, and once an exception starts you can steer it into the shellcode
  • Attack the SEH head pointer in the TEB, that is, change the TEB’s first DWORD. The catch is that in a multithreaded program the TEB is hard to locate (the first TEB is at 0x7FFDE000, and each one after that is 0x1000 lower), so this is usually only used on single-threaded programs
  • Attack the UEF. Point the DWORD SHOOT target at the UEF entry and put the shellcode entry in the data, then cause an exception that only the UEF can handle. When the exception happens, EDI often points somewhere on the heap not far from the shellcode, so overwriting the UEF handler with the address of a CALL DWORD PTR [EDI + 0x78] instruction (or [ESI + 0x4C], [EBP + 0x74]) often gets you in
  • Attack a function pointer in the PEB. When ExitProcess cleans up it has to enter a critical section to synchronize, which ends up calling RtlEnterCriticalSection, and before XP SP2 the PEB address never changed, so it’s easier to use than the TEB (see part two)

Off-by-one#

Exploitation techniques come in rough layers, from basic stack overflows (overwriting the return address), to advanced stack overflows (you can only reach part of EBP and not the return address, like the off-by-one from misusing strncpy), to heap overflows and format strings.

void off_by_one(char * input)
{
char buf[200];
int i = 0, len = 0;
len = sizeof(buf);
for(i = 0; input[i] && (i <= len); i++) // i <= len goes one step too far
{
buf[i] = input[i];
}
}

This function is trying to avoid overflowing, but i <= len is off by one at the boundary, so it can overflow by a single byte. That’s just enough to overwrite the lowest byte of EBP and control EBP within a certain range.


Everything so far has been about attacking. After XP SP2, Microsoft added three protections against these routes, GS, SafeSEH and SEHOP. Let’s go through them one at a time.

How it works#

  • On by default since Visual Studio 2003 (VC7.0) (Buffer Security Check)
  • On every function call, an extra random DWORD is pushed into the stack frame, called the canary or Security Cookie
  • The cookie sits before EBP, and the system also keeps a copy in .data
  • In a stack overflow, the cookie gets overwritten before EBP and the return address
  • Before the function returns, it runs a Security Check comparing the cookie on the stack with the copy in .data. If they differ, there was an overflow, so it goes into exception handling, the function doesn’t return normally and the ret never runs
  • It costs performance, so GS is left out when the function has no buffer, takes variable arguments, is marked with a keyword like naked, starts with inline assembly, or its buffers aren’t 8-byte types and are no bigger than 4 bytes
  • Those exceptions caused problems, so VS2005 SP1 added #pragma strict_gs_check to put a cookie in any function
  • There’s also variable reordering. Local variables get rearranged in the stack frame by type, with strings moved to higher addresses so an overflowing string can’t trash other variables, and pointer and string arguments copied to lower addresses

Here are the cookie details. The first DWORD of .data is the seed (the original cookie), which is different on every run. After the stack frame is set up, ESP is XORed with the seed to get this function’s cookie, for extra randomness, and before returning it XORs with ESP again to recover the seed and compare. The disassembly makes it very clear:

; compute the cookie at the start of the function
mov eax, dword ptr ds:[__security_cookie] ; take the original cookie from .data
xor eax, ebp ; XOR with ebp
mov [ebp-0x4], eax ; store it at ebp-0x4
; check it before the function returns
mov ecx, [ebp-0x4]
xor ecx, ebp
call __security_check_cookie
; __security_check_cookie:
cmp ecx, dword ptr ds:[__security_cookie] ; compare with the .data copy
jnz __report_gsfailure ; report an error if they differ
rep retn

Gaps in GS#

GS only protects the part of the stack frame around the return address, so there are a few places it doesn’t reach:

  1. Overwriting function pointers. GS can hardly stop attacks that overwrite a function pointer
  2. Exception handling. GS doesn’t protect SEH, so you can hijack the program before the cookie check by overwriting SEH and causing an exception. If strcat hits an invalid address and raises an exception, the function never gets to its cookie check on return
  3. Virtual functions. The stack is only checked when the function returns, so hijack it before that. Overwrite a C++ object’s vtable pointer so it points at a pop/pop/ret trampoline, and you jump into the shellcode the moment a virtual function is called. Vtable attacks get the full treatment in part four
  4. Taking it head on. The cookie is the original cookie in .data xor ebp, so if the overflow can change both the cookie on the stack and the original cookie in .data so they still match, the check passes. The book builds an example where a negative i can reach .data to do exactly this

Back then I couldn’t figure out the book’s “break GS through unprotected memory” example (where char arry[4] should have been unprotected but was protected anyway). In theory a 4-byte buffer shouldn’t get GS, but in my test it did. Looking back now, it’s because GS doesn’t decide on size alone. arry is treated as an array, and its address is taken (passed to strcpy), so the compiler’s heuristics flagged it as risky and protected it. So “buffers no bigger than 4 bytes aren’t protected” isn’t a rule you can apply mechanically.


SafeSEH checks the exception handler#

Since GS can’t protect SEH, Microsoft gave SEH its own protection, SafeSEH. When SEH has been overwritten, it checks things before actually calling the handler:

  • Is the exception handler chain on the current stack? If not, stop
  • Does the handler pointer point into the current stack? If so, stop (shellcode is often on the stack, so this one hurts)
  • If both of those pass, it calls RtlIsValidHandler() to check that the handler is valid:
    • If the handler address is inside the memory range of a loaded module:
      • Does that module set IMAGE_DLLCHARACTERISTICS_NO_SEH? If so, the check fails
      • Does that module have a safe SEH table? If so, look the handler address up in the table, and only a match passes
      • Is the module pure IL (.NET)? If so, the check fails
      • Is the handler on a non-executable page? If so, it depends on DEP. Without DEP it passes, with DEP it raises an access violation
    • If the handler address is outside every loaded module:
      • On a non-executable page? Depends on DEP, same as above
      • Does the system allow jumping outside modules? If yes it passes, otherwise it fails

This is a screenshot from back then, the trampoline (CALL [EBP+0xC]) I found while stepping through the RtlIsValidHandler decision:

The CALL [EBP+0xC] trampoline I found
The CALL [EBP+0xC] trampoline I found

Three ways around SafeSEH#

Follow the decision tree above and the gaps show themselves:

  1. Put the shellcode on the heap. Even when the SEH check decides a handler is “invalid”, on some paths it still gets called. The more reliable version is to have the stack overflow only point the SEH at shellcode on the heap, which dodges the check on stack addresses
  2. Use a module without SafeSEH as the trampoline. DLLs built with VC6 don’t have SafeSEH by default. Find a pop/pop/ret in such a module and overwrite the SEH handler with its address. The check sees an address inside “a module with no safe SEH table” and lets it pass, and after the pop/pop/ret, that ret brings us back to the shellcode. (A VC6 DLL’s default load base 0x10000000 contains a 0x00 that strcpy cuts off, so change the base with /base:"0x11120000")
  3. Use an address outside the loaded modules. Find an instruction like call/jmp dword ptr[ebp+N] in memory outside any module and use it as the trampoline, getting around the “must be a valid handler inside a module” check
Warning

There are two traps in actually doing this. One, a function with __try{} built by VS2008 pushes a -2 (VC6 uses -1) at Security Cookie+4 as a marker, and exception handling changes that value, which can break the shellcode, so pad 8 NOPs after the trampoline. Two, where the trampoline’s ret lands is often a few bytes off from the shellcode itself, so you need a short jump (sometimes followed by a long one) to get into the real entry point.

The browser version, bypassing SafeSEH with Flash ActiveX#

This is the browser flavor of route 2. Before 9.0.124, the Flash Player ActiveX control didn’t support SafeSEH, so if you find a suitable trampoline address inside that control, you get around SafeSEH:

  • Write your own MFC ActiveX control with a stack overflow in it, and trigger the overflow by calling it from a web page
  • After the overflow overwrites the SEH, jump to the trampoline you found in the Flash control
  • From the trampoline, jump back to the shellcode on the stack

In my test back then, the overflow string started at 0x01DCF4FC and the handler address closest to the top of the stack was at 0x01DCF610, so 0x114 (276 bytes) of filler reached exactly up to the handler address, and bytes 277-280 held the trampoline. OllyFindAddr’s Find CALL/JMP[EBP+N] found a CALL [EBP+0xC] at 0x300B2D1C (the screenshot above). The trampoline jumps to 4 bytes before that address, so a short jump goes there with the shellcode right after it:

01DCF60C EB 06 jmp short 01DCF614 ; skip 4 bytes to the shellcode
01DCF60E 90 90 nop nop
01DCF610 1C 2D (trampoline address, low half)
01DCF612 0B 30 (trampoline address, high half)
01DCF614 90 ; the shellcode starts here

The POC page uses JavaScript to glue a run of 邐 characters (U+9090, two NOPs each) and the trampoline address into a Unicode string and feeds it to the control’s test(). The divide-by-zero exception fires, it breaks at the trampoline, and it jumps into the shellcode.


SEHOP and the integrity of the whole chain#

SafeSEH checks a single handler. SEHOP comes at it from another angle and checks whether the whole SEH chain has been broken. The core of it is whether the last handler on the chain is the system’s fixed final exception handler. If it is, the chain is intact. If it isn’t, something in the middle was overwritten and an SEH overwrite attack may be happening, so the current handler isn’t run.

if (process_flags & 0x40 == 0) // only check if there are SEH records
{
if (record != 0xFFFFFFFF)
{
do
{
if (record < stack_bottom || record > stack_top) // the record must be on the stack
goto corruption;
if ((char *)record + sizeof(EXCEPTION_REGISTRATION) > stack_top) // entirely on the stack
goto corruption;
if ((record & 3) != 0) // 4-byte aligned
goto corruption;
handler = record->handler;
if (handler >= stack_bottom && handler < stack_top) // the handler can't be on the stack
goto corruption;
record = record->next;
} while (record != 0xFFFFFFFF); // walk the whole chain
}
if ((TEB->word_at_offset_0xFCA & 0x200) != 0)
{
if (handler != &FinalExceptionHandler) // the core check: the last one must be the final handler
goto corruption;
}
}

Ways around it#

  • Go straight for the return address or a virtual function. If a function has SEHOP but not GS (or just happens to be missing GS), attack the return address directly. SEHOP doesn’t protect vtables either, so attacking virtual functions still works
  • Use a module without SEHOP. The system decides whether to turn SEHOP off for a program based on MajorLinkerVersion/MinorLinkerVersion in its PE header (Microsoft turned it off for some packers like Armadillo). Set those two to 0x53 and 0x52 and the program passes as Armadillo-packed, which turns SEHOP off
  • Fake the whole SEH chain (as long as ASLR is off). SEHOP only looks at “is the last one the final handler”, so build a fake chain that ends exactly at the system’s final handler address, and it looks like the chain is intact. Combined with a pop/pop/ret from a module without SafeSEH, it fools SafeSEH and SEHOP at the same time

One implementation detail. Starting with Win7, the second module in PEB_LDR_DATA is KernelBase, so the shellcode from part one that “takes the second node as kernel32” needs an extra mov ecx, [ecx] (machine code \x8B\x09) in the middle to step one more node before it gets kernel32 on Win7.


Looking at it again today#

This whole post looks very different in the 64-bit era.

The most fundamental change is that on x64, SEH no longer lives on the stack. 64-bit Windows uses table-based exception handling. Each function’s unwind info and exception handlers are registered in the PE’s .pdata/.xdata, which are read-only, so at runtime there’s no SEH chain on the stack for an overflow to overwrite at all. That means this entire class of “overwrite the SEH record” attacks, together with SafeSEH and SEHOP above, only matters in 32-bit processes. The places you still meet 32-bit SEH overwrites today are mostly old 32-bit programs and some embedded or industrial control software.

The GS cookie is still around and keeps getting stronger, but it was never a defense on its own, just one layer in a deeper stack. What really makes “overwrite the return address” a dead end in modern 64-bit processes is the hardware-enforced shadow stack (Intel CET / Windows Hardware-enforced Stack Protection). On ret, the CPU checks the return address against its copy on the shadow stack, and if they don’t match you get an exception right away, so changing the return address on the stack does nothing.

And the gap in point 3, “GS can’t protect virtual function pointers”, is exactly where modern exploitation happens. That’s why Microsoft added CFG (Control Flow Guard) and the stricter XFG to police the targets of indirect calls. That part, together with vtable attacks, continues in the next post on DEP and ASLR.

Share Article

If this article helped you, please share it with others!

Rereading 0day Security (3), SEH Hijacking, Plus GS, SafeSEH and SEHOP
https://blog.lumysia.net/posts/reread-0day-3-seh-gs-safeseh-sehop/
Author
Livia
Published at
2020-10-25
Related PostsSmart
1
Rereading 0day Security (1), Stack Overflows and Shellcode Basics
My first round of labs from the book 0day Security, covering PE address conversion, overwriting a return address with a stack overflow, the jmp esp trampoline, finding kernel32 through the PEB, encoding shellcode, plus a little format string bug at the end.
2
Rereading 0day Security (2), the NT5 Heap, DWORD SHOOT and the First Heap Protections
Debugging the free lists and lookaside lists on Windows 2000, using unlink for a DWORD SHOOT that overwrites a function pointer in the PEB, then a look at safe unlink, heap cookies and metadata encoding from XP SP2 on.
3
Rereading 0day Security (4), Early Ways Around DEP and ASLR
Turning DEP off with ret2libc, making memory executable with VirtualProtect/VirtualAlloc, beating ASLR with partial overwrites, heap spraying to land on 0x0C0C0C0C, vtable hijacking, and how those ideas grew into today's ROP and info leaks.
4
A Short History of Windows Exploit Mitigations (2000–2026)
Taking that old XP→Win7 table of GS, DEP, ASLR, SafeSEH and SEHOP all the way to Win11, adding CFG, XFG, the CET shadow stack, ACG, CIG, VBS/HVCI and KDP. Every generation of defense answers the attacks of the one before.
5
Taking Apart a Cracked iMazing Package That Defender Flagged, SFX, Batch Files and AutoIt Obfuscation
Peeling the TNT cracked iMazing package layer by layer, a WinRAR self-extractor, encrypted batch files, an AutoIt runner and a decompiled obfuscated script, until the two obfuscated strings finally decode and show what it's really doing.
Random PostsRandom

Comments

Table of Contents