Rereading 0day Security (3), SEH Hijacking, Plus GS, SafeSEH and SEHOP
- 1Getting Started with Windows Kernel Drivers, a Debugging Setup and the Basics
- 2Rereading 0day Security (1), Stack Overflows and Shellcode Basics
- 3Rereading 0day Security (2), the NT5 Heap, DWORD SHOOT and the First Heap Protections
- 4Rereading 0day Security (3), SEH Hijacking, Plus GS, SafeSEH and SEHOPThis article
- 5Rereading 0day Security (4), Early Ways Around DEP and ASLR
- 6A Short History of Windows Exploit Mitigations (2000–2026)
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:
0x0012FE98is 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 address0x0012FE98there 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 goes98 FE 12 00 ; SEH handler address = 0x0012FE98, points at the shellcodeThe 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 theEXCEPTION_RECORD, with the exception type, where it happened and so onpFrame: points at the SEH structure in the stack framepContext: points at theCONTEXT, with the state of every registerpDispatch: 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 on1 (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()inntdll - 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 is0x1000lower), 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.
GS and the cookie on the stack
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
canaryorSecurity 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 Checkcomparing 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 theretnever 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_checkto 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 functionmov eax, dword ptr ds:[__security_cookie] ; take the original cookie from .dataxor eax, ebp ; XOR with ebpmov [ebp-0x4], eax ; store it at ebp-0x4
; check it before the function returnsmov ecx, [ebp-0x4]xor ecx, ebpcall __security_check_cookie; __security_check_cookie:cmp ecx, dword ptr ds:[__security_cookie] ; compare with the .data copyjnz __report_gsfailure ; report an error if they differrep retnGaps 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:
- Overwriting function pointers. GS can hardly stop attacks that overwrite a function pointer
- 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
strcathits an invalid address and raises an exception, the function never gets to its cookie check on return - 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/rettrampoline, and you jump into the shellcode the moment a virtual function is called. Vtable attacks get the full treatment in part four - Taking it head on. The cookie is the original cookie in
.dataxorebp, so if the overflow can change both the cookie on the stack and the original cookie in.dataso they still match, the check passes. The book builds an example where a negativeican reach.datato 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.arryis 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
- Does that module set
- 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
- If the handler address is inside the memory range of a loaded module:
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](/images/DNAHQe.png)
Three ways around SafeSEH
Follow the decision tree above and the gaps show themselves:
- 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
- Use a module without SafeSEH as the trampoline. DLLs built with VC6 don’t have SafeSEH by default. Find a
pop/pop/retin 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 thepop/pop/ret, thatretbrings us back to the shellcode. (A VC6 DLL’s default load base0x10000000contains a0x00that strcpy cuts off, so change the base with/base:"0x11120000") - 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
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 shellcode01DCF60E 90 90 nop nop01DCF610 1C 2D (trampoline address, low half)01DCF612 0B 30 (trampoline address, high half)01DCF614 90 ; the shellcode starts hereThe 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/MinorLinkerVersionin its PE header (Microsoft turned it off for some packers like Armadillo). Set those two to0x53and0x52and 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/retfrom 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_DATAis KernelBase, so the shellcode from part one that “takes the second node as kernel32” needs an extramov 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!




