[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M71FWAD2YN34WDGTD96Y4Z42":3,"skill-same:01M71FWAD2YN34WDGTD96Y4Z42":60},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":28,"linkOnly":29,"markdownContent":30,"markdownBody":31,"frontMatter":32,"refName":33,"commitSha":34,"skillDirectory":35,"forksCount":14,"repositoryHtmlUrl":36,"repositoryHomepageUrl":6,"ownerHtmlUrl":37,"ownerBlogUrl":6,"ownerDescription":38,"updatedAt":39,"install":40,"resources":53},"01M71FWAD2YN34WDGTD96Y4Z42","offensive-mitigations",null,"- Supports Secure Boot and firmware integrity checking.","DCx7C5\u002Fai-marketplace","DCx7C5","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F42419559?v=4","01M71C01G2AZV3NTNGWAWSHJPP","DC","01M71C01GQW6G50S2BYMS7PP3E",0,"MIT","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Foffensive-mitigations\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27],"offensive mitigations","offensive","secure boot","firmware","cybersecurity","firmware integrity","secure","integrity","boot","2026-11-10 10:12:30",false,"---\nname: offensive-mitigations\ndescription: \"- Supports Secure Boot and firmware integrity checking.\"\ndomain: cybersecurity\n---\n\n## Full Methodology\n\n# Modern Kernel Exploit Mitigations\n\n## Memory-safety & Isolation\n\n### Kernel Address Space Layout Randomization (KASLR)\n\n- Randomizes memory addresses where the kernel and its components are loaded.\n- Makes it difficult for attackers to predict kernel code and data locations.\n\n#### Bypass Techniques\n\n- **Information Leaks:** Exploiting vulnerabilities (e.g., uninitialized memory, side-channels) to leak kernel pointers and calculate the base address.\n- **Side-Channel Attacks:** Using timing, cache, or other microarchitectural side channels to infer memory layout.\n  - **Prefetch Cache Timing:** Measures access speed across the kASLR range (0xfffff80000000000 to 0xfffff80800000000, ~0x8000 iterations with 0x100000 alignment). The fastest access indicates a cached address, revealing the actual kernel base. Uses `rdtscp` for timing, `mfence` for memory barriers, and `prefetchnta`\u002F`prefetcht2` for cache manipulation.\n- **Targeting Non-Randomized Regions:** Exploiting data or code segments that are not fully randomized.\n- **Brute-Force:** Feasible in environments with limited entropy (e.g., some 32-bit systems or specific configurations).\n- **Intel LAM:** Linear Address Masking support exists on recent kernels\u002FCPUs but may be disabled by default. Verify with kernel config, boot params, and CPU flags on your target.\n\n### Kernel Page Table Isolation (KPTI)\n\n- Linux:\n  - Separates user-space and kernel-space page tables.\n  - Mitigates the Meltdown vulnerability by preventing user-space access to kernel memory.\n\n#### Bypass Techniques\n\n- **Side-Channel Attacks:** Exploiting microarchitectural side channels (e.g., TLB timing, cache attacks) that leak information across the isolation boundary.\n- **Hardware Vulnerabilities:** Exploiting CPU vulnerabilities (e.g., L1TF, MDS) that can bypass page table separation.\n- **Implementation Flaws:** Bugs in the KPTI implementation itself.\n\n#### Practitioner\n\n- Linux: check status via `\u002Fsys\u002Fdevices\u002Fsystem\u002Fcpu\u002Fvulnerabilities\u002F*` and `dmesg | grep -i kpti`.\n- Windows: verify meltdown\u002FKVA shadowing with `Get-SpeculationControlSettings` PowerShell script from Microsoft.\n\n### Supervisor Mode Access Prevention (SMAP)\n\n- Linux:\n  - Hardware feature preventing unintended kernel access to user-space memory.\n  - Protects against attacks exploiting improper memory accesses.\n\n#### Bypass Techniques\n\n- **ROP\u002FJOP Gadgets:** Finding instruction sequences (gadgets) within kernel code that disable SMAP temporarily (e.g., via `stac` instruction) before accessing user memory.\n- **Data-Only Attacks:** Attacks that achieve their goal without directly accessing user-space data from the kernel inappropriately.\n- **Kernel Information Leaks:** Combining with KASLR bypasses to find suitable gadgets.\n\n#### Practitioner\n\n- Linux: confirm with `grep smap \u002Fproc\u002Fcpuinfo` and `cat \u002Fproc\u002Fcpuinfo | grep 'smep\\|smap'`.\n- Check CR4 at runtime with `rdmsr`\u002F`wrmsr` tools or `lscpu -e` on supported systems.\n\n### Supervisor Mode Execution Protection (SMEP)\n\n- Linux\u002FWindows:\n  - Hardware feature preventing execution of user-space code when in supervisor mode.\n  - Located in bit 20 of the CR4 control register.\n  - Blocks certain privilege escalation attacks that rely on executing shellcode in user-mode memory.\n\n#### Bypass Techniques\n\n- **ROP\u002FJOP Chains:** Constructing code reuse chains entirely from existing kernel code, avoiding execution of user-space code.\n- **Data-Only Attacks:** Exploiting vulnerabilities without needing to execute shellcode (e.g., overwriting kernel data structures).\n- **Disabling SMEP:** Finding gadgets or techniques to modify the CR4 control register to disable SMEP.\n- **Type Confusion Exploits:** Using type confusion vulnerabilities to gain control flow and build ROP chains for SMEP bypass.\n- **Page Table Manipulation:** Modifying page table entries (PTEs) to change user pages to supervisor pages, making user-space code executable in kernel context.\n- **Write-What-Where Primitives:** Using arbitrary write vulnerabilities to modify CR4 register or page table structures.\n\n#### Practitioner\n\n- Linux: `grep smep \u002Fproc\u002Fcpuinfo`; verify effective state via `dmesg | grep -i smep`.\n- Windows: SMEP is enforced when Memory Integrity\u002FHVCI is enabled on modern systems.\n\n### Kernel Data Protection (KDP)\n\n- Windows:\n  - Marks certain kernel memory regions as read-only.\n  - Prevents unauthorized modification of critical kernel data structures.\n\n#### Practitioner\n\n- Check with `Get-CimInstance -ClassName Win32_DeviceGuard` and `System Information → Device Guard properties` for KDP\u002FHVCI\u002FVBS.\n\n### Memory Integrity (Core Isolation)\n\n- Windows:\n  - Uses virtualization and HVCI to prevent malicious code alteration.\n  - Guards against code injection or execution in kernel mode.\n\n#### Practitioner\n\n- Enable\u002Fverify: Windows Security → Device Security → Core isolation details.\n- PowerShell: `Get-ItemProperty -Path HKLM:\\SYSTEM\\CurrentControlSet\\Control\\DeviceGuard\\Scenarios\\HypervisorEnforcedCodeIntegrity | Select-Object Enabled`.\n\n### Read-Only Data Sections (RODATA)\n\n- Linux:\n  - Marks specific kernel memory regions as read-only.\n  - Prevents modification of critical data structures and code.\n\n### Hardened Usercopy\n\n- Linux:\n  - Adds boundary checks to memory copy operations between user and kernel space.\n  - Prevents buffer overflows and memory corruption during copy operations.\n\n### Memory Tagging Extension (MTE)\n\n- Linux (ARM):\n  - Hardware-assisted memory safety feature to detect memory corruption bugs.\n  - Mitigates use-after-free and buffer overflows at a hardware level.\n  - Adopted as a production security feature in **Android 16 (March 2025)** with both asynchronous and synchronous detection modes available for apps.\n\n#### How MTE Works\n\n- **4-bit Tags:** Each 16-byte memory allocation receives a random 4-bit tag (values 0-15)\n- **Pointer Tagging:** Upper bits of pointers store the allocation tag\n- **Tag Checking:** Hardware validates pointer tag matches memory tag on every dereference\n- **Fault on Mismatch:** Invalid access triggers `SIGSEGV` (sync mode) or logs asynchronously (async mode)\n\n#### Bypass Techniques\n\n- Tag Collision (Probabilistic): With only 4-bit tags (16 possible values), collision probability is high\n  - Increase entropy with larger allocation pools; Android 16 uses tag rotation heuristics.\n- Untagged Memory Regions: Not all memory is MTE-protected\n  - Enable MTE on stack via `prctl(PR_MTE_TCF_SYNC, PR_TAGGED_ADDR_ENABLE)`.\n- Asynchronous Mode Exploitation: Android's async mode delays fault reporting for performance\n  - Use synchronous mode (`MTE_mode=sync`) for security-critical apps.\n- Integer Overflow in Tag Calculation: MTE tags are derived from allocation size; overflow can corrupt tags\n- Kernel-Space Bypass: MTE only protects userspace by default\n  - Kernel allocations (`kmalloc`, `vmalloc`) don't use MTE (Android 16, Linux 6.8)\n  - Kernel exploit primitives (KASLR leak, arbitrary write) unaffected\n  - Syscall buffer handling may not validate tags\n- JIT Code Execution: JIT-compiled code can bypass MTE checks\n\n```asm\n; Assembly gadget to create untagged pointer\nmov x0, xzr          ; Zero out tag bits\norr x0, x0, #0x1000  ; Set address without tag\nldr x1, [x0]         ; Load from untagged pointer (no MTE check)\n```\n\n#### Exploitation Workflow:\n\n1. Leak a tagged pointer\n2. Strip tag bits (mask upper 8 bits)\n3. Use untagged pointer for memory operations\n4. MTE doesn't validate untagged accesses in some contexts\n\n#### Practitioner\n\n- Android: enable per‑app via Developer Options or `adb shell setprop persist.device_config.runtime_native_boot.mte_mode sync` (device‑specific).\n- Linux: compile with `CONFIG_ARM64_MTE` and use `prctl(PR_SET_TAGGED_ADDR_CTRL, ...)` from user space.\n- Verify MTE status: `cat \u002Fproc\u002Fcpuinfo | grep mte` and check `HWCAP2_MTE` in `getauxval(AT_HWCAP2)`\n- Android 16+ apps: opt-in via manifest `\u003Capplication android:memtagMode=\"sync\">`\n\n### Intel Linear Address Masking (LAM)\n\nIntel allows software to use upper address bits for metadata, similar to ARM's Top Byte Ignore (TBI).\n\n#### How LAM Works\n\n- **LAM57:** Uses bits 62:57 (6 bits) for tags in 5-level paging\n- **LAM48:** Uses bits 62:48 (15 bits) for tags in 4-level paging\n- **Hardware Masking:** CPU ignores tagged bits during address translation\n- **Use Cases:** Memory tagging, capability systems, garbage collection metadata\n- **Vulnerability Classes:**\n\n1. **Pointer Forge:** Attackers can craft tagged pointers without validation\n2. **Info Leak Bypass:** Some sanitizers only check canonical addresses; LAM-tagged pointers pass checks\n3. **Address Confusion:** Software assuming canonical addresses may mishandle LAM pointers\n\n### Memory Sealing\n\n- Linux:\n  - `mseal()` permanently seals selected VMAs so permissions\u002Fmappings can no longer change—even by the owner (verify kernel version and libc support on your target).\n  - Adopted by projects such as Chrome\u002Fglibc\u002FBPF tool‑chains to seal JIT pages, locking down GOT\u002FPLT and eBPF JIT regions (version‑specific; verify).\n\n#### Bypass Techniques\n\n- **Time‑of‑use Window:** Exploits must succeed before sealing.\n- **Data‑only Abuse:** Still possible if the mapping remains writable.\n- **Kernel Flaws:** Bugs in the `mseal()` path could bypass a seal.\n\n#### Practitioner\n\n- Verify `mseal` availability via `grep -R sys_mseal \u002Fproc\u002Fkallsyms` or kernel `symbols`.\n- Userland: `prctl(PR_MSEAL, ...)` (glibc 2.41+ headers), check errno for `ENOSYS` on older kernels.\n\n### Privileged Access Never (PAN)\n\n- Linux (ARM):\n  - Hardware feature preventing direct kernel access to user-space memory.\n  - Similar concept to SMAP on x86, prevents certain data leakage\u002Fcorruption bugs.\n\n### Kernel DMA Protection\n\n- Windows:\n  - Uses IOMMU\u002FVT-d to protect against malicious peripherals performing DMA attacks.\n  - Prevents unauthorized memory access via hardware devices.\n\n### Pluton Security Processor\n\n- Windows:\n  - Microsoft Pluton is increasingly deployed with newer platforms, replacing or augmenting discrete TPM 2.0 and hardware‑binding BitLocker keys, Secure Boot, and HVCI policies. Check OEM\u002FSKU documentation for Copilot+ requirements.\n\n#### Practitioner\n\n- Check Pluton state in Device Manager → Security devices, or `tpm.msc` shows Pluton‑backed TPM if present.\n\n### Memory Protection Keys (MPK)\n\n- Linux:\n  - Provides per-page memory permissions using hardware keys.\n  - Allows fine-grained control over memory access rights.\n\n#### Bypass Techniques\n\n- **PKRU Register Manipulation**: Using gadgets to modify the Protection Key Rights Register.\n- **Unprotected Memory**: Targeting memory regions not protected by MPK.\n- **Implementation Bugs**: Exploiting flaws in the MPK implementation.\n- **Side-Channel Attacks**: Using side channels to infer protected memory contents.\n\n### Protection Keys for Supervisor (PKS)\n\n- Linux\u002FIntel:\n  - Extends PKU to supervisor pages; the kernel flips page permissions via `wrmsr PKS_MSC*` without TLB flushes (Sapphire‑Rapids+).\n  - Landed upstream in Linux 6.12.\n\n#### Bypass Techniques\n\n- **ROP\u002FJOP `WRMSR` Gadgets** that flip PKS bits.\n- **Unprotected Regions** outside a PKS domain.\n- **CPU Errata** undermining isolation.\n\n#### Practitioner\n\n- Linux: enable with `CONFIG_X86_PKS`; verify via `dmesg | grep -i pks` and `\u002Fproc\u002Fcpuinfo` flags.\n\n### Zero-Page Memory Allocation\n\n- Linux\u002FWindows:\n  - Ensures memory pages are zeroed before allocation.\n  - Prevents leakage of residual data.\n\n### Zero-Page Mapping Removal\n\n- Linux:\n  - Removes zero page mapping to prevent NULL pointer dereference exploits.\n  - Enhances memory safety.\n\n### Init-On-Alloc and Init-On-Free and Init-Stack-All-Zero\n\n- Linux:\n  - Automatically zeroes memory when allocated or freed.\n  - Prevents use-after-free and information leakage.\n\n### TPM Bus Encryption\n\n- Linux:\n  - Recent kernels add support for stronger TPM transports over SPI\u002FI²C on some platforms. Feature availability and defaults vary; verify in `dmesg` and driver configs for your device.\n\n#### Practitioner\n\n- Verify with `dmesg | grep -i tpm` and kernel config `CONFIG_TCG_TIS_SPI`\u002F`_I2C` options; firmware must expose supported transports.\n\n## Memory Safety Initiatives\n\n### Rust in the Linux Kernel\n\n- First‑class Rust support landed in Linux 6.1 (December 2022) and was declared production‑ready with Linux 6.6 (October 2023).\n- In‑tree Rust drivers (e.g., NVMe, DRM simple‑display, Wi‑Fi) have so far exhibited zero memory‑safety bugs under continuous fuzzing, demonstrating the practical security benefit of memory‑safe languages.\n- Ongoing work aims to extend Rust usage into networking, Android GKI modules, and scheduler subsystems, further shrinking the kernel's attack surface.\n\n### Safer Windows Drivers with C++20 and Rust\n\n- Starting in Windows 11 23H2, the Windows Driver Framework (WDF) officially supports both modern C++20 and a Rust projection (`windows‑drivers‑rs`) that wrap KMDF\u002FWDF APIs with lifetime‑safe abstractions.\n- Hardware vendors can now obtain WHQL signatures for C++20 or Rust kernels drivers, eliminating common lifetime and IRQL‑misuse bugs without sacrificing performance.\n\n### CHERI \u002F Morello (Experimental Capability Hardware)\n\n- Arm's Morello evaluation platform (2022‑2025) runs a CHERI‑enabled Linux kernel that enforces pointer capabilities in user and kernel space, providing hardware‑enforced spatial and temporal memory safety.\n- Although experimental, CHERI demonstrates a plausible post‑2025 path toward fundamentally safer C\u002FC++ code with architectural support.\n\n### memfd_secret (userland secret memory)\n\n- Linux:\n  - `memfd_secret` (Linux 5.14+) provides user‑mode pages hidden from other processes and the kernel direct mappings\n  - Useful for protecting keys and ROP staging from accidental exposure; verify support via kernel config and `memfd_secret(2)`\n\n## Virtualization-Based Security Enhancements\n\n### Virtualization-Based Security (VBS)\n\n- Windows:\n  - Creates an isolated, secure memory region using hardware virtualization.\n  - Protects sensitive system components and data from malware and exploits.\n\n#### Bypass Techniques\n\n- **Hypervisor Vulnerabilities:** Exploiting bugs in the underlying hypervisor (Hyper-V) to escape the VBS container.\n- **Misconfiguration:** Weaknesses in VBS configuration or deployment.\n- **Physical Access:** Hardware-level attacks (e.g., DMA attacks if not mitigated by Kernel DMA Protection).\n- **Compromised Signed Components:** Exploiting vulnerabilities in trusted components running within VBS.\n\n#### Practitioner\n\n- Confirm VBS\u002FHVCI: `Core isolation` settings or PowerShell `Get-CimInstance -ClassName Win32_DeviceGuard` (look for `VirtualizationBasedSecurityStatus` and `SecurityServicesConfigured`).\n\n### AMD Secure Encrypted Virtualization – Secure Nested Paging (SEV‑SNP)\n\n- Linux guest support since 6.11; provides full memory encryption + integrity with an SVSM.\n- Shipping today in major cloud \"confidential VM\" SKUs.\n\n### Intel Trust Domain Extensions (TDX)\n\n- Guest driver landed in 6.11; host enablement queued for 6.16.\n- Protects guest memory against a compromised hypervisor.\n\n#### Practitioner\n\n- Cloud: verify TDX\u002FSEV‑SNP instance type (`Azure DCasv5\u002FECasv5`, `GCP C3`, `AWS C7g` variants); attest via platform‑specific tools (e.g., `az confcom attestation`).\n\n### Arm Confidential Compute Architecture (CCA) Realms\n\n- Realm VM support merged in 6.13 for Arm v9 CPUs, giving encrypted, isolated guest environments.\n\n### Hypervisor-Enforced Code Integrity (HVCI)\n\n- Windows:\n  - Uses VBS to enforce code integrity checks on kernel-mode drivers and binaries.\n  - Ensures only signed and verified code can execute in kernel mode.\n\n#### Bypass Techniques\n\n- **Signed Malicious Drivers:** Obtaining signing certificates (stolen or illicitly acquired) to sign malicious code.\n- **Exploiting Allowed Drivers:** Finding vulnerabilities in legitimate, signed drivers already running on the system (\"Bring Your Own Vulnerable Driver\" - BYOVD).\n- **Hypervisor Vulnerabilities:** Exploiting the underlying hypervisor (see VBS bypasses).\n- **Configuration Issues:** Weaknesses in Code Integrity policies.\n\n### Mode Based Execution Control (MBEC)\n\n- Windows:\n  - Ensures driver code can only be executed in kernel mode.\n  - Available in hardware and software (emulated) forms.\n  - Prevents user-mode execution of kernel code.\n\n### Kernel Mode Code Integrity (KMCI)\n\n- Windows:\n  - Ensures kernel pages can only become executable with proper signing.\n  - Enforces driver signing enforcement and vulnerable driver blocklists.\n  - Implements software SMEP (Supervisor Mode Execution Prevention).\n  - `DriverSiPolicy.p7b` now refreshes **weekly** via Windows Update and MEM Configuration Manager, accelerating the BYOVD blocklist cadence.\n\n### User Mode Code Integrity (UMCI)\n\n- Windows:\n  - Ensures user mode pages can only become executable with proper signing.\n  - CI validates the signaturees of EXE and DLL before allowing them to load.\n  - Enforces protected processes and protected process light signature requirements\n  - Enforces `\u002FINTEGRITYCHECK` for `FIPS 140-2` modules\n  - Exposed to consumers as _Smart App Control_ and businesses as _App Control for Business_.\n  - Part of the Device Guard technology stack.\n\n### Windows Defender System Guard\n\n- Windows:\n  - Monitors system integrity during boot and runtime.\n  - Protects against rootkits and bootkits by verifying system integrity.\n\n### Windows Defender Application Guard\n\n- Windows:\n  - Runs untrusted content in isolated containers.\n  - Protects the host from potentially malicious websites and documents.\n\n### Credential Guard\n\n- Windows:\n  - Uses VBS to isolate and protect credentials.\n  - Prevents attacks like Pass-the-Hash or Pass-the-Ticket.\n\n### Device Guard\n\n- Windows:\n  - Combines WDAC and virtualization-based security to lock down devices.\n  - Ensures only trusted applications can run.\n\n## OS Loader and Hotpatching Changes (Windows 11 24H2+)\n\n- Recent Windows versions (24H2 and later) introduced changes that impact classic process injection techniques like Process Hollowing (RunPE).\n- **Status:** Client Hotpatching availability and cadence depend on SKU\u002Fservicing channel. Validate GA status in current Microsoft documentation.\n- Windows Server 2025 requires an Azure Arc subscription for hotpatch servicing.\n\n### Impact on Process Hollowing (MEM_PRIVATE Payloads)\n\n- **Root Cause 1 (Error `0xC0000141`):** Native Hotpatching support added a new function `RtlpInsertOrRemoveScpCfgFunctionTable` during process initialization (`LdrpInitializeProcess -> LdrpProcessMappedModule`). This function calls `ZwQueryVirtualMemory` with a new `MemoryImageExtensionInformation` class, which _only_ works on `MEM_IMAGE` memory regions.\n  - Classic Process Hollowing stores the payload in `MEM_PRIVATE` memory (either by unmapping the original PE or allocating a new region).\n  - The `ZwQueryVirtualMemory` call fails with `STATUS_INVALID_ADDRESS` for the `MEM_PRIVATE` payload region, causing process loading to terminate.\n- **Root Cause 2 (Error `0xC00004AC`, Memory Integrity Enabled):** If Memory Integrity (HVCI) is enabled, another check occurs later in the loading process.\n  - `LdrpQueryCurrentPatch` is called on the payload's memory region.\n  - This leads to a call to `NtManageHotPatch`, which fails with `STATUS_CONFLICTING_ADDRESSES` for the `MEM_PRIVATE` payload.\n  - This error also terminates the process loading.\n\n### Solutions and Bypasses\n\n1.  **Use Alternative Techniques (Recommended):** Employ methods that map the payload as `MEM_IMAGE`, which are unaffected by these specific checks.\n    - Examples: Process Doppelganging, Process Ghosting, Process Herpaderping, Transacted Hollowing, Ghostly Hollowing, Herpaderply Hollowing, Process Overwriting.\n    - These techniques generally interact more naturally with the loader and newer OS features.\n2.  **Patch NTDLL (If sticking to Classic RunPE):**\n    - **For `0xC0000141`:** Hook `ZwQueryVirtualMemory`.\n      - Check if the OS is Win11 24H2+ (64-bit).\n      - If the `MemoryInformationClass` is `MemoryImageExtensionInformation` AND the query targets the base address of the `MEM_PRIVATE` payload:\n        - Return a benign error like `STATUS_NOT_SUPPORTED` instead of calling the original function.\n      - Otherwise, call the original `ZwQueryVirtualMemory`.\n      - [Implementation Example](https:\u002F\u002Fgithub.com\u002Fhasherezade\u002Flibpeconv\u002Fblob\u002Fmaster\u002Frun%5Fpe\u002Fpatch%5Fntdll.cpp#L91)\n    - **For `0xC00004AC` (Memory Integrity):** Hook `NtManageHotPatch`.\n      - Patch the function to immediately return a benign error like `STATUS_NOT_SUPPORTED`.\n      - Apply this patch early in the process creation, for both 32-bit and 64-bit.\n      - Ensure `FlushInstructionCache` is called if patching after the function might have been cached.\n      - [32-bit Example](https:\u002F\u002Fgithub.com\u002Fhasherezade\u002Flibpeconv\u002Fblob\u002Fmaster\u002Frun%5Fpe\u002Fpatch%5Fntdll.cpp#L4)\n      - [64-bit Example](https:\u002F\u002Fgithub.com\u002Fhasherezade\u002Flibpeconv\u002Fblob\u002Fmaster\u002Frun%5Fpe\u002Fpatch%5Fntdll.cpp#L43)\n\n## Control Flow Integrity and Execution Protections\n\n### Data Execution Prevention (DEP)\n\n- Windows\u002FLinux:\n  - Marks certain memory regions as non-executable.\n  - Prevents execution of code from data pages, mitigating buffer overflow attacks.\n\n#### Bypass Techniques\n\n- **Return-oriented Programming (ROP)**: Using existing code fragments to create attack chains without injecting code.\n- **ret2libc**: Jump directly to code in libc.\n- **ret2data**: Place shellcode in the data section.\n- **ret2strcpy**: Place shellcode on the stack and use strcpy to move it somewhere executable.\n- **ret2gets**: Read from stdin to gain control.\n- **VirtualProtect\u002FVirtualAlloc**: Call these functions to change memory permissions.\n- **JIT Spraying**: Leverage Just-In-Time compilation to get executable memory.\n\n#### Practitioner\n\n- use `!vprot rip` or `!vpro rsp` to check for protections inside WinDbg\n- `.scriptload G:\\Projects\\narly.js; !nmod` also helps you to see which modules have DEP protection\n- `Data Execution Prevention` settings inside `Windows Exploit Guard` can be used to force DEP protection on an executable\n- pivot with `VirtualProtect` \u002F `NtProtectVirtualMemory` (or pre‑ACG RWX section) from a ROP\u002FJOP chain.\n- Modern Windows 10\u002F11 enforce **CET (Shadow Stack)** and **XFG (Cross‑Function Guard)**, which break classic ROP; successful chains must first disable CET (for example with `SetProcessMitigationPolicy`) or switch to JOP\u002FSCS gadgets.\n- an example would be `pop rcx; retn; pop rcx; retn; mov [rcx], rax; pop rbp; retn;`\n- we can use `IAT` to identify and call `WriteProcessMemory` which can be used to circumvent DEP protection through `NtProtectVirtualMemory` API\n- [Ropper 2.0](https:\u002F\u002Fgithub.com\u002Fsashs\u002FRopper) **or Rizin‑ropper** — both support CET\u002FXFG‑aware gadget filtering.\n\n### Control Flow Integrity (CFI)\n\n- Windows:\n  - Ensures kernel execution follows legitimate paths.\n  - Thwarts control-flow hijacking attacks like function pointer overwrites.\n\n#### Bypass Techniques\n\n- **Similar Function Prototypes**: For XFG (Extreme Flow Guard), functions with similar prototypes may be exploitable.\n- **Data-Only Attacks**: Manipulating program state without violating CFI constraints.\n- **Implementation Weaknesses**: Exploiting gaps in the implementation of CFI.\n- **JIT Compilation**: Just-in-time compiled code may bypass CFI checks.\n\n#### Practitioner\n\n- Windows build: enable CFG\u002FXFG via `\u002Fguard:cf \u002Fguard:xfg` and `\u002FQspectre` where applicable; inspect PE `LoadConfig` for CFG\u002FXFG metadata.\n- Linux build: Clang `-fsanitize=cfi` (user space) or `CONFIG_CFI_CLANG=y` (kernel), with LTO; verify symbols contain CFI jump tables.\n\n### kCFI\n\n- Linux\n  - Clang-based forward-edge Control-Flow Integrity that verifies indirect function calls at runtime in the kernel.\n  - Enabled by default in Android GKI kernels and ChromeOS since early 2024; available upstream via `CONFIG_CFI_CLANG`.\n  - Complements FineIBT and hardware CET by protecting software-only control-flow edges.\n  - **BHI Hardening (Linux 6.9\u002F6.10):** FineIBT now incorporates indirect‑branch serialization to mitigate Branch History Injection.\n\n### Control Flow Guard (CFG)\n\n- Windows:\n  - Ensures indirect calls go only to valid, predefined locations.\n  - Helps prevent control-flow hijacking attacks.\n\n#### Bypass Techniques\n\n- **JIT Code Execution**: Using Just-In-Time compiled code which may not be properly protected.\n- **Import Address Table (IAT) Manipulation**: Inserting entries in IAT since these aren't checked.\n- **Data-only Attacks**: Modifying program data to influence control flow without redirecting execution.\n- **Type Confusion**: Exploiting type confusion to bypass CFG checks.\n\n#### Practitioner\n\n- Check process mitigation: `Get-ProcessMitigation -Name process.exe` (PowerShell) → CFG\u002FstrictCFG\u002FXFG states.\n- PE inspection: `dumpbin \u002Floadconfig` shows GuardCFFunctionTable and flags.\n\n### Stack Canaries\n\n- Linux\u002FWindows:\n  - Inserts random values before return addresses on the stack.\n  - Detects stack buffer overflows before they overwrite return addresses.\n\n#### Bypass Techniques\n\n- **Leaking Canary Values**: Using format string or other information disclosure vulnerabilities.\n- **Overwriting Non-return Variables**: Attacking function pointers or other control flow variables not protected by canaries.\n- **Brute Force**: On systems with low entropy canaries or predictable generation.\n- **Exception Handler Attacks**: Targeting exception registration records which may not be protected.\n- **Unprotected Functions**: Exploiting functions not protected by canaries (often due to performance considerations).\n\n### Stack Clash Protection\n\n- Linux\u002FGCC:\n  - Prevents stack and heap collisions by probing stack pages during large allocations.\n  - Mitigates privilege escalation attacks that rely on stack\u002Fheap layout manipulation.\n  - Enabled with `-fstack-clash-protection` compiler flag.\n\n#### Bypass Techniques\n\n- **Precise Heap Layout**: Carefully crafting heap allocations to avoid clash detection.\n- **Small Allocations**: Using allocations smaller than the probe size to avoid triggering protection.\n- **Alternative Memory Regions**: Targeting other memory regions not protected by stack clash detection.\n- **Implementation Gaps**: Exploiting edge cases in the probing logic.\n\n### Hardware‑Enforced Stack Protection\n\n- Windows:\n  - Utilizes Intel CET (specifically the Shadow Stack feature, referred to as Kernel Mode Hardware-enforced Stack Protection or KCET) and AMD Shadow Stack features.\n  - Requires Hypervisor-Enforced Code Integrity (HVCI) \u002F Virtualization-Based Security (VBS) to be enabled.\n  - Provides a hardware-backed shadow stack to protect return addresses against ROP\u002FJOP attacks.\n  - Applies to kernel-mode stacks, including those associated with user-mode threads executing in kernel mode (e.g., during system calls).\n  - Hardware-Enforced Stack Protection is enabled by default on compatible hardware with Windows 11, version 24H2, when VBS\u002FHVCI is active. The `IMAGE_GUARD_SHADOW_STACK` PE flag indicates compatibility and is increasingly adopted for key binaries, with Windows components widely enabling it.\n\n#### Bypass Techniques\n\n- **Increased Difficulty with HVCI:** When combined with Hypervisor-Enforced Code Integrity (HVCI), bypassing hardware-enforced shadow stacks becomes significantly more challenging. HVCI leverages virtualization (Hyper-V) to protect the shadow stack's integrity via the Secure Kernel (VTL1). The Secure Kernel manages the shadow stack pointer (`VMX_GUEST_SSP` in the VMCS for VTL0) through hypercalls, preventing even kernel-mode code (VTL0) from directly tampering with it.\n- **Return Address Protection:** The hardware compares the return address on the main stack with the one stored on the protected shadow stack before executing a `RET` instruction. Mismatches typically cause a fault (system crash for KCET), mitigating standard ROP\u002FJOP attacks that rely on overwriting the return address on the main stack.\n- **Secure Kernel Validation:** The Secure Kernel is involved in validating and restoring shadow stack context (e.g., during exception handling via functions like `nt!KeKernelShadowStackRestoreContext` and secure system calls like `securekernel!SkmmNtKernelShadowStackAssist`), adding another layer of integrity checking.\n- **Potential (Difficult) Vectors:** Bypasses would likely require exploiting vulnerabilities in the hypervisor (Hyper-V) or the Secure Kernel itself, finding flaws in the hardware CET implementation, or developing sophisticated data-only attacks that achieve control without corrupting the stack's return addresses. These are considerably harder than bypassing software-based or unprotected hardware stack protections.\n- **Limited Scope:** Like other CFI mechanisms, attacks targeting non-control data or logic bugs may still be possible if they don't violate the protected control flow.\n\n### Pointer Authentication (ARM64)\n\n- Linux\u002FiOS:\n  - Uses cryptographic signatures to protect pointers.\n  - Mitigates attacks like Return-Oriented Programming (ROP).\n\n#### Bypass Techniques\n\n- **Unprotected Assembly Code**: Assembly code often lacks PAC protection.\n- **Raw Function Pointers**: Recovery handlers and other mechanisms that use raw pointers.\n- **Signing Gadgets**: Using existing code that signs pointers.\n- **Switch Case Branches**: Unprotected indirect branches in switch case implementations.\n- **Authentication Failure Handling**: Exploiting cases where authentication failures don't trigger exceptions.\n- **Thread State Manipulation**: Incorrect handling of thread state during context switches.\n\n### Intel Control‑flow Enforcement Technology (CET)\n\n- Hardware feature providing protections against control-flow hijacking.\n- Includes Shadow Stack and Indirect Branch Tracking.\n- Enabled by default starting with Windows 11 build 26100 (Win11 24H2+). Any stack pivot or `ret` without a valid shadow‑stack token raises `STATUS_STACK_BUFFER_OVERRUN` (0xC0000409).\n- **Detect CET:** Read the `IMAGE_DLLCHARACTERISTICS_GUARD_CF` flag in the PE header or `PEB→LdrDataTableEntry.GuardFlags`.\n  - Windows: `Get-ProcessMitigation -System` shows `UserShadowStack` and `UserCetEnabled`.\n  - Linux: check `cet_ss` in `\u002Fproc\u002Fcpuinfo` and `prctl(PR_SET_SHADOW_STACK_STATUS, ...)`.\n- **Bypass tips for CET in shellcode:**\n  1. Align the shellcode entry to a valid call target and emit `ENDBR64`\u002F`SETSSP` before the first `ret`.\n  2. Use ROP‑less staging (queued APC, `NtContinue`, or `NtTestAlert`) so the kernel performs the first return.\n\n### Intel Indirect Branch Tracking (IBT)\n\n- Linux\u002FWindows:\n  - Part of Intel CET that enforces legitimate indirect branch targets.\n  - Requires `ENDBR32` or `ENDBR64` instructions at valid indirect call\u002Fjump destinations.\n  - Prevents JOP (Jump-Oriented Programming) attacks by validating branch targets.\n  - Available on Tiger Lake+ CPUs, enabled via `CET_IBT` bit in MSR.\n\n#### Bypass Techniques\n\n- **ENDBR Gadgets**: Finding existing code sequences that start with valid `ENDBR32\u002F64` instructions.\n- **ENDBR Spraying**: Injecting or finding multiple `ENDBR` instructions to create gadget chains.\n- **Unprotected Modules**: Targeting libraries or code not compiled with IBT support.\n- **Legacy Code Paths**: Exploiting code paths that bypass IBT checks (e.g., signal handlers, exception contexts).\n- **Hardware Quirks**: Exploiting CPU-specific implementation differences or errata.\n\n#### Practitioner\n\n- Check IBT status: `cat \u002Fproc\u002Fcpuinfo | grep cet_ibt` (Linux) or inspect `cr4.cet` bit\n- Compile with IBT: `-fcf-protection=branch` (GCC) or `-mcet` flag\n- Binary analysis: Look for `ENDBR64` (0xF3 0x0F 0x1E 0xFA) or `ENDBR32` (0xF3 0x0F 0x1E 0xFB) instructions\n\n### Shadow Call Stack (SCS)\n\n- Linux:\n  - Compiler-based CFI mechanism using a shadow stack to protect return addresses.\n  - Helps prevent ROP attacks.\n  - Ensures only signed and verified code can execute in kernel mode.\n  - Blocks RWX pages and unsigned kernel callbacks when **Memory Integrity** is ON (default on 2024‑hardware).\n  - Common allocation pattern for executable memory: `PAGE_READWRITE` → write payload → `NtProtectVirtualMemory` → `PAGE_EXECUTE_READ`.\n  - WoW64 heaven‑gate patches to `WOW64CFG` are rejected by HVCI; favour direct 64‑bit syscalls (e.g., via `wow64log`).\n\n#### Bypass Techniques\n\n- **Data‑only Attacks** (no return‑address writes).\n- **Hypervisor\u002FKernel Bugs** that corrupt GCS state.\n\n### Guarded Control Stack (GCS)\n\n- Linux\u002FARM64:\n  - Hardware user‑space shadow stack on Armv9‑A CPUs, merged in Linux 6.13 and on by default in modern Android.\n  - Complements KCET\u002FCET on x86.\n\n#### PAN‑GCS Dual Enforcement (Android 16, Armv9 Realms)\n\n- From Android 16, GCS (shadow stack) plus Privileged Access Never (PAN) are **mandatory** for all Play‑targetSdk 34+ apps running on Armv9 Realms hardware, providing dual hardware + software enforcement.\n\n#### Bypass Techniques\n\n- **Data‑only Attacks** (no return‑address writes).\n- **Hypervisor\u002FKernel Bugs** that corrupt GCS state.\n\n### FineIBT\n\n- Linux:\n  - Enhanced CFI mechanism for indirect branch targets.\n  - Provides finer-grained control flow protection than basic CFI.\n  - The initial implementation was vulnerable to Branch History Injection (BHI). Hardened FineIBT with serialising `INT3` fences landed upstream in Linux 6.14\n\n### Arbitrary Code Guard (ACG)\n\n- Windows:\n  - Prevents processes from allocating or modifying memory to be executable.\n  - Mitigates attacks relying on dynamic code generation or modification.\n\n#### Practitioner\n\n- Check ACG: `Get-ProcessMitigation -Name process.exe | Select-Object -ExpandProperty DynamicCode`.\n- WDAC policy can enforce ACG: audit with `Get-CIPolicy` and `CodeIntegrity` logs.\n\n### Code Integrity Guard (CIG)\n\n- Windows:\n  - Restricts loading of DLLs to only those signed by Microsoft or WHQL.\n  - Prevents loading of potentially malicious or untrusted libraries.\n\n#### Practitioner\n\n- PowerShell: `Get-ProcessMitigation -Name process.exe | Select-Object -ExpandProperty BinarySignature`.\n- Event Logs: `Microsoft-Windows-CodeIntegrity\u002FOperational` for blocked DLL loads.\n\n### Kernel Control-Flow Guard (kCFG)\n\n- Windows:\n  - Kernel-specific implementation and enforcement of Control Flow Guard.\n  - Protects against control-flow hijacking within the kernel itself.\n\n### eXtended Flow Guard (XFG)\n\n- Windows:\n  - Debuted with Windows 11 23H2. Adds strict function‑prototype hashing to CFG, blocking many type‑confusion escapes.\n\n#### Bypass Techniques\n\n- **Prototype Collisions** (extremely rare).\n- **Modules Without XFG** (legacy or JIT code).\n\n### Export Address Filtering (EAF) \u002F Import Address Filtering (IAF)\n\n- Windows:\n  - Protects module export and import tables from tampering.\n  - Prevents attacks that redirect function calls by modifying these tables.\n\n### Structured Exception Handling Overwrite Protection (SEHOP)\n\n- Windows:\n  - Protects the integrity of exception handler chains on the stack.\n  - Prevents exploits that overwrite exception handlers to gain control flow.\n\n#### Bypass Techniques\n\n- **Modules Without SafeSEH**: A single module without protection breaks the chain.\n- **ROP Chains**: Building ROP chains that don't rely on exception handlers.\n- **Alternative Attack Vectors**: Targeting other vulnerable components not protected by SEHOP.\n- **Unprotected Exception Handlers**: Finding handlers that are still vulnerable.\n\n### Exploit Address Table Filtering (EAF & EAF+)\n\n- Windows:\n  - Blocks access to Export Address Tables of critical DLLs like kernel32.dll and ntdll.dll.\n  - EAF+ allows specifying modules not permitted to access the EAT, particularly targeting UAF bugs.\n  - Uses hardware breakpoints to filter access attempts.\n\n#### Bypass Techniques\n\n- **Alternative Discovery Methods**: Using different techniques to locate functions.\n- **Unprotected Modules**: Targeting modules not covered by EAF protection.\n\n### Import Address Filtering (IAF)\n\n- Windows:\n  - Ensures all functions listed in a DLL's IAT exist within the image's load address range.\n  - Prevents IAT overwrite attacks.\n\n### Virtual Table Guard\n\n- Windows:\n  - Ensures virtual function table pointers point to valid guard pages.\n  - Terminates execution if invalid vptrs are detected.\n  - Protects against C++ virtual function table overwrites.\n\n### MemGC\n\n- Windows:\n  - Replacement for MemProtect technology.\n  - Specifically targets mitigation of use-after-free exploitation.\n\n### Kernel Text Read-only Region (KTRR)\n\n- iOS:\n  - Prevents modification of the iOS kernel at runtime.\n  - Implements hardware-enforced read-only memory for kernel code.\n\n#### KTRR‑v2 & FastPAC (iOS 18, A18\u002FA19)\n\n- Hardware‑enforced cache‑colouring prevents pointer‑authentication re‑spray, complementing traditional KTRR for stricter kernel integrity.\n\n### Intel Memory Protection Extensions (MPX)\n\n> [!NOTE]\n> Support was removed from Linux 5.6 (April 2020) and GCC 9.1; no mainstream OS or compiler ships MPX today.\n\n## Heap Protections\n\n### Heap Cookies\n\n- Windows:\n  - Places a 1-byte value in the metadata of heap chunks.\n  - Detects heap metadata corruption before exploitation.\n\n### AMSI Heap Scanning (Jan 2025)\n\n- Windows:\n  - AMSI (Antimalware Scan Interface) scans newly committed **writable** heap pages _before_ they are flipped to `PAGE_EXECUTE_READ` or `PAGE_EXECUTE_WRITECOPY`.\n  - **Safer allocation pattern to avoid AMSI heap scanning:** Reserve memory with `PAGE_NOACCESS`, decrypt\u002Fdeobfuscate payload in‑place, then change protection to `PAGE_EXECUTE_READ`.\n  - The classic \"patch the `AMSI` ASCII tag in `amsi.dll`\" trick no longer works reliably; consider patching the COM VTable entry for `IAmsiStream::QueryInterface` or using a proxy‑DLL hook instead.\n\n### Low Fragmentation Heap (LFH)\n\n- Windows:\n  - First 32-bit of metadata gets XORed with canary to ensure integrity.\n  - Allocates blocks in predetermined size ranges by organizing blocks into buckets.\n  - Reduces heap predictability and exploitation potential.\n\n### Safe Unlink\n\n- Windows\u002FLinux:\n  - Checks integrity of pointers before freeing memory chunks.\n  - Prevents unlink exploitation in heap management.\n\n#### Bypass Techniques\n\n- **Heap Overflow**: Using malloc maleficarum techniques.\n- **Chunk-on-Lookaside Overwrite**: Targeting specific heap management structures.\n\n### Heap and Stack Protections\n\n- Windows:\n  - Implements guard pages and heap allocation randomization.\n  - Detects and prevents buffer overflows and stack smashing.\n\n## Randomization Techniques\n\n### Address Space Layout Randomization (ASLR)\n\n- Linux & Windows:\n  - Randomizes memory addresses used by executables and libraries.\n  - Makes it harder for attackers to predict target addresses.\n\n#### Bypass Techniques\n\n- **Information Leaks**: Exploiting vulnerabilities to leak addresses of loaded modules.\n- **ROP with PLT\u002FGOT**: Using the Procedure Linkage Table to leak addresses and calculate base addresses.\n- **Low Entropy**: Exploiting systems with limited randomization bits.\n- **Heap Spraying**: Filling memory with copies of shellcode to increase hit probability.\n- **Local Privilege Escalation**: Using local exploits to bypass protection.\n- **Partial Overwrite**: Overwriting only part of an address to maintain alignment.\n- **Statically Linked Code**: Targeting code that doesn't use ASLR.\n\n#### Practitioner\n\n- you probably first need an information leak to identify the correct memory address and then use it to circumvent ASLR and DEP\n- format string bugs also helps trigger an information leak, so you can use them alongside `ropchains` to bypass ASLR and DEP\n- information leaks are often happen through logical errors or memory corruption bugs\n\n### Position Independent Executables (PIE)\n\n- Linux\u002FWindows:\n  - Compiles executables as position-independent code, enabling ASLR for the main executable.\n  - Without PIE, the main executable loads at a fixed base address, providing attackers a reliable target.\n  - Essential for full ASLR coverage across all memory regions.\n\n#### Bypass Techniques\n\n- **Information Leaks**: Same techniques as ASLR bypass - leak addresses to calculate base.\n- **Partial Overwrites**: Overwriting only the lower bytes of addresses to maintain relative offsets.\n- **Non-PIE Dependencies**: Targeting linked libraries that aren't position-independent.\n- **GOT\u002FPLT Attacks**: Exploiting Global Offset Table entries before they're resolved.\n\n#### Practitioner\n\n- Check PIE status: `file \u002Fpath\u002Fto\u002Fbinary` or `readelf -h \u002Fpath\u002Fto\u002Fbinary | grep Type`\n- Compile with PIE: `-fPIE -pie` (GCC) or `-fPIC -shared` for libraries\n- Detect at runtime: `\u002Fproc\u002FPID\u002Fmaps` shows randomized executable base addresses\n- **checksec**: `checksec --file=\u002Fpath\u002Fto\u002Fbinary` shows PIE status\n\n### ASCII Armored Address Space\n\n- Windows:\n  - Loads all shared libraries in addresses starting with `0x00`.\n  - Prevents string manipulation exploits that terminate at null bytes.\n\n#### Bypass Techniques\n\n- **Partial Injection**: Still possible to inject one null byte.\n- **Main Executable Attacks**: Main executable is not moved, so attackers can target it instead.\n\n### Function Granular KASLR (FGKASLR)\n\n- Linux:\n  - Randomizes kernel functions at a finer granularity.\n  - Enhances address space randomization effectiveness.\n\n### Kernel Stack Randomization\n\n- Linux:\n  - Randomizes the kernel stack base address per process.\n  - Makes stack-based attacks more challenging.\n\n### Mandatory ASLR (MASLR)\n\n- Windows:\n  - Forces the rebasing of modules even when they were compiled without ASLR support.\n  - Enhances protection against code reuse attacks.\n\n### Bottom-Up ASLR (BASLR)\n\n- Windows:\n  - Works alongside MASLR to randomize allocation patterns.\n  - Blocks 64KB allocations from requested base address up to a randomly selected number.\n  - Repeats randomization each time the process restarts.\n\n## Side-Channel Attack Mitigations\n\n### Speculative Execution Mitigations\n\n- Linux\u002FWindows:\n  - Addresses vulnerabilities like Spectre and Meltdown.\n  - Includes microcode updates and patches to prevent speculative execution attacks.\n\n### Recent Spectre Mitigations\n\n- **IBPB (Indirect Branch Prediction Barrier)**:\n  - Intel\u002FAMD feature that flushes indirect branch predictors.\n  - Prevents cross-privilege domain speculation leakage.\n  - Controlled via `MSR_IA32_PRED_CMD`.\n\n- **IBRS (Indirect Branch Restricted Speculation)**:\n  - Restricts speculation of indirect branches when in higher privilege levels.\n  - Mitigates Spectre v2 by preventing user-space speculation attacks on kernel.\n  - Performance overhead led to adoption of retpolines as primary mitigation.\n\n- **STIBP (Single Thread Indirect Branch Predictors)**:\n  - Prevents sibling threads from controlling each other's indirect branch prediction.\n  - Mitigates cross-hyperthread Spectre attacks.\n  - Particularly important for SMT (Simultaneous Multi-Threading) environments.\n\n- **SSBD (Speculative Store Bypass Disable)**:\n  - Prevents speculative execution of loads that bypass older stores.\n  - Mitigates Spectre v4 (Speculative Store Bypass).\n  - Can be controlled per-process via `prctl()` on Linux.\n\n#### Bypass Techniques\n\n- **Microarchitectural Timing**: Using cache timing, TLB timing, or other side channels.\n- **Cross-Process Leakage**: Exploiting shared microarchitectural state between processes.\n- **Hardware Implementation Gaps**: CPU-specific vulnerabilities in mitigation implementations.\n- **Performance Optimization Exploitation**: Targeting cases where mitigations are disabled for performance.\n\n#### Practitioner\n\n- Check mitigations: `cat \u002Fproc\u002Fcpuinfo | grep -E \"(ibpb|ibrs|stibp|ssbd)\"`\n- Runtime controls: `\u002Fsys\u002Fdevices\u002Fsystem\u002Fcpu\u002Fvulnerabilities\u002F` directory\n- Per-process SSBD: `prctl(PR_SET_SPECULATION_CTRL, PR_SPEC_STORE_BYPASS, ...)`\n- Performance impact: Use `perf` to measure mitigation overhead\n\n### Kernel Memory Sanitizer (KMSAN)\n\n- Linux:\n  - Detects use of uninitialized memory in the kernel.\n  - Helps find and fix initialization bugs.\n\n### Linux Kernel Runtime Guard (LKRG)\n\n- Linux (Module):\n  - Loadable kernel module performing runtime integrity checks on critical kernel structures.\n  - Aims to detect and prevent various exploits in real-time.\n\n### Spectre-BHB Mitigations\n\n- Linux:\n  - Addresses Branch History Injection vulnerabilities on ARM.\n  - Prevents certain speculative execution attacks.\n\n## Dynamic Analysis and Detection Tools\n\n### Kernel Address Sanitizer (KASAN)\n\n- Linux:\n  - Dynamic memory error detector for the kernel.\n  - Identifies use-after-free and out-of-bounds bugs.\n\n### eBPF Verification Enhancements\n\n- Linux:\n  - Strengthens verification of eBPF programs loaded into the kernel.\n  - Prevents exploitation via the eBPF subsystem.\n\n## Windows Defender Security Features\n\n### Windows Defender Application Control (WDAC)\n\n- Windows:\n  - Controls which drivers and applications are allowed to run.\n  - Uses code integrity policies to prevent unauthorized code execution.\n\n#### Practitioner\n\n- Enumerate policies: `Get-CIPolicy -Effective` and `Get-ComputerInfo | Select WindowsProductName, WindowsVersion`.\n- Validate blocklists: ensure `DriverSiPolicy.p7b` is current; check with `gpresult \u002Fr` or MEM policies.\n\n### Exploit Protection\n\n- Windows:\n  - System-wide mitigation settings against common exploit techniques.\n  - Includes heap spray allocation prevention, mandatory ASLR, etc.\n\n#### Practitioner\n\n- Export\u002Fimport settings via `Export-ProcessMitigation` \u002F `Set-ProcessMitigation`.\n- Audit per‑process: `Get-ProcessMitigation` for DEP\u002FASLR\u002FSEHOP\u002FCFG\u002FXFG.\n\n### Attack Surface Reduction (ASR) Rules\n\n- Windows:\n  - Part of Windows Defender Exploit Guard, providing configurable rules.\n  - Blocks specific behaviors often associated with malware or exploits (e.g., Office macro execution, script obfuscation).\n\n#### Practitioner\n\n- Query ASR state: `Get-MpPreference | Select -ExpandProperty AttackSurfaceReductionRules_Ids, AttackSurfaceReductionRules_Actions`.\n- Enable common rules in audit first; deploy in enforced after tuning.\n\n### Smart Screen\n\n- Windows:\n  - Analyzes files and websites for suspicious characteristics.\n  - Warns or blocks potentially malicious content.\n\n### Controlled Folder Access\n\n- Windows:\n  - Protects files and folders from unauthorized changes.\n  - Helps prevent ransomware from encrypting or deleting data.\n\n## File System and Data Protections\n\n### Filesystem Protections (fs-verity & fscrypt)\n\n- Linux:\n  - fs-verity: Provides integrity protection for read-only files.\n  - fscrypt: Enables filesystem-level encryption for data at rest.\n\n### BitLocker Drive Encryption\n\n- Windows:\n  - Full disk encryption to protect data at rest.\n  - Uses TPM and user credentials for encryption keys.\n\n### Integrity Measurement Architecture (IMA) \u002F Extended Verification Module (EVM)\n\n- Linux:\n  - Provides runtime integrity checking for files and metadata based on stored hashes.\n  - Ensures files haven't been tampered with post-boot.\n\n## Access Control and Attack Surface Reduction\n\n### Strict Syscall Filtering (Seccomp)\n\n- Linux:\n  - Allows applications to restrict system calls they can invoke.\n  - Reduces the kernel's attack surface from user-space applications.\n- Seccomp user‑notifier:\n  - Enables broker‑style decisions in userspace; defend against confused‑deputy by strict validation and time‑bounded decisions\n  - Attackers may abuse notifier latency for TOCTOU races; keep policies minimal and deterministic\n\n#### Practitioner\n\n- Inspect running process seccomp: `grep Seccomp \u002Fproc\u002F\u003Cpid>\u002Fstatus` (0=disabled, 1=strict, 2=filter).\n- Use `seccomp-tools dump \u003Cpid>` to view filters; in containers, inspect OCI seccomp profile.\n\n### Container Security Mitigations\n\n- **User Namespaces**:\n  - Isolates user and group IDs between host and container.\n  - Provides privilege isolation without requiring root on the host.\n  - Maps container root (UID 0) to unprivileged user on host.\n\n- **PID Namespaces**:\n  - Isolates process IDs, preventing container processes from seeing host processes.\n  - Container init process becomes PID 1 within its namespace.\n\n- **Network Namespaces**:\n  - Provides isolated network stack (interfaces, routing tables, firewall rules).\n  - Prevents network-based container escape attacks.\n\n- **Mount Namespaces**:\n  - Isolates filesystem view, preventing access to host filesystem.\n  - Combined with chroot-like restrictions and read-only mounts.\n\n- **Capability Dropping**:\n  - Removes dangerous Linux capabilities from container processes.\n  - Examples: `CAP_SYS_ADMIN`, `CAP_NET_ADMIN`, `CAP_SYS_MODULE`.\n\n- **Seccomp Profiles**:\n  - Restricts system calls available to containerized processes.\n  - Default Docker\u002FPodman profiles block ~44 dangerous syscalls.\n\n- **AppArmor\u002FSELinux Profiles**:\n  - Mandatory Access Control for container processes.\n  - Restricts file access, network operations, and capabilities.\n\n#### Container hardening quick test\n\n```bash\ndocker inspect \u003Cctr> | jq '.[0].HostConfig.SecurityOpt, .[0].HostConfig.CapDrop'\ncapsh --print\nlsns | grep \" $(cat \u002Fproc\u002Fself\u002Fns\u002Fpid) \\|net\\|mnt\\|user\\|ipc\\|uts\"\ngrep Seccomp \u002Fproc\u002F$$\u002Fstatus\nid -Z 2>\u002Fdev\u002Fnull || echo \"No SELinux context\"\n```\n\n#### Bypass Techniques\n\n- **Namespace Escapes**: Exploiting kernel bugs in namespace implementations.\n- **Capability Abuse**: Leveraging remaining capabilities (e.g., `CAP_DAC_OVERRIDE`) for privilege escalation.\n- **Seccomp Bypasses**: Finding allowed syscalls that can be chained for exploitation.\n- **Container Runtime Exploits**: Targeting Docker\u002Fcontainerd\u002Frunc vulnerabilities.\n- **Host Resource Access**: Exploiting mounted host resources (sockets, devices, filesystems).\n- **Privileged Containers**: Targeting containers running with `--privileged` flag.\n\n#### Practitioner\n\n- Check container mitigations: `docker inspect \u003Ccontainer>` or `podman inspect \u003Ccontainer>`\n- Audit capabilities: `capsh --print` inside container\n- List namespaces: `lsns` or `ls -la \u002Fproc\u002F$$\u002Fns\u002F`\n- Seccomp status: `grep Seccomp \u002Fproc\u002F$$\u002Fstatus`\n- SELinux context: `id -Z` (if SELinux enabled)\n- **Container security scanning**: Tools like `docker-bench-security`, `kube-bench`\n\n### Lockdown Mode\n\n- Linux:\n  - Restricts access to kernel features that could allow code execution.\n  - Enhances security, especially with Secure Boot enabled.\n  - **Linux 6.14** extends lockdown to cover kexec‑file pinning and loads the built‑in module blocklists earlier, further closing BYOVD avenues.\n\n### Executable‑policy Securebits\n\n- **Linux 6.14:** Introduces `SECBIT_EXEC_RESTRICT_FILE` and `SECBIT_EXEC_DENY_INTERACTIVE` securebits together with the `AT_EXECVE_CHECK` flag, allowing interpreters to delegate final execution‑permission checks to the kernel and tightening script\u002Floader abuse paths.\n\n### NTSYNC Driver Hardening\n\n- **Linux 6.14:** The new `ntsync` driver offers an `io_uring`‑based fast‑path that removes classic futex primitives from reachable attack surface, reducing user→kernel synchronization abuse.\n\n### Landlock LSM\n\n- Linux:\n  - Unprivileged sandboxing framework allowing processes to restrict their own access rights.\n  - Reduces the impact of compromised user-space applications.\n\n### AppContainer and User Account Control (UAC)\n\n- Windows:\n  - AppContainer: Application isolation for modern apps.\n  - UAC: Limits application privileges, prompting for elevation when necessary.\n\n### PatchGuard (KPP)\n\n- Windows:\n  - Protects the kernel from modifications of critical structures and registers.\n  - Periodically checks for unauthorized modifications to kernel structures.\n  - Asynchronously monitors critical structures: IDT, GDT, SSDT, MSRs, kernel stacks\n  - Triggers `CRITICAL_STRUCTURE_CORRUPTION` BSOD (0x109) when tampering detected\n  - **Modern impact**: Blocks classic SSDT\u002FIDT hooking on Windows 10\u002F11\n\n#### Bypass Techniques\n\n- **Bootkit Deployment**: Bypassing protection at boot time before PatchGuard initializes.\n- **Debugging Bypass**: PatchGuard doesn't run if a debugger is attached at boot.\n- **Timing Attacks**: Taking advantage of the periodic nature of PatchGuard checks.\n- **Memory Manipulation**: Modifying kernel memory without triggering detection mechanisms.\n- **Hypervisor-based**: Type 1 hypervisor using EPT to hide kernel modifications\n\n### Windows Sandbox\n\n- Windows:\n  - Provides a disposable virtual environment.\n  - Runs untrusted software isolated from the host system.\n\n### Module Signing Enforcement\n\n- Linux\u002FWindows:\n  - Code signing for kernel modules\n  - Prevents loading of unsigned or maliciously modified kernel components\n\n### Block Remote Images\n\n- Windows:\n  - Prevents loading DLLs from UNC file paths (e.g., \\\\\\\\evilsite\\\\bad.dll).\n  - Blocks attackers from bypassing ASLR by loading non-rebased modules.\n\n### Block Untrusted Fonts\n\n- Windows:\n  - Only loads fonts from trusted locations.\n  - Prevents attacks like Stuxnet that exploit font rendering vulnerabilities in kernel mode.\n\n### Validate Handle Usage\n\n- Windows:\n  - Checks handle references to ensure they are valid.\n  - Prevents exploitation of handle misuse.\n\n### Disable Extension Points\n\n- Windows:\n  - Blocks registry-based extension points like AppInit_DLL.\n  - Prevents hooking or extending applications through known extension mechanisms.\n\n### Disable Win32k System Calls\n\n- Windows:\n  - Disables unused system calls to reduce attack surface.\n  - Particularly effective against kernel exploits.\n\n### Do Not Allow Child Processes\n\n- Windows:\n  - Blocks the ability for a process to call the CreateProcess function.\n  - Prevents malware from spawning additional processes (also known as \"Calc Killer\").\n\n### Validate Image Dependency\n\n- Windows:\n  - Requires any DLL loaded by a process to be signed by Microsoft.\n  - Prevents DLL side-loading attacks.\n\n### Block Low Integrity Images\n\n- Windows:\n  - Blocks processes running at low or untrusted integrity levels from loading downloaded files.\n  - Enhances sandbox security.\n\n### Usermode Helper (UMH) Mitigations\n\n- Linux:\n  - CONFIG_STATIC_USERMODEHELPER: Forces all usermode helper calls through a static binary.\n  - CONFIG_STATIC_USERMODEHELPER_PATH: Sets the path to the static usermode helper binary.\n  - Prevents attackers from abusing kernel-to-userspace execution paths.\n  - Requires userspace support.\n\n### SMB Signing\n\n- Windows:\n  - Adds cryptographic signatures to Server Message Block (SMB) packets.\n  - Prevents man-in-the-middle attacks against network file sharing.\n\n## Hardware-Assisted Security Features\n\n### Trusted Platform Module (TPM) 2.0\n\n- Windows\u002FLinux:\n  - Secure crypto-processor enhancing hardware security.\n  - Used for secure boot, disk encryption, and credentials.\n\n### Secure Boot\n\n- Windows\u002FLinux:\n  - Ensures only trusted, signed software loads during boot.\n  - Prevents boot-level malware from starting before the OS.\n\n### UEFI Firmware Security\n\n- Windows\u002FLinux:\n  - Provides a secure pre-OS environment.\n  - Supports Secure Boot and firmware integrity checking.\n\n## Diagrams\n\n### Modern Security Architecture\n\n```mermaid\nflowchart TB\n    System[\"System Security\"]\n\n    subgraph \"Memory Protection\"\n        KASLR[\"Kernel ASLR\"]\n        KPTI[\"Kernel Page Table Isolation\"]\n        SMAP[\"Supervisor Mode Access Prevention\"]\n        SMEP[\"Supervisor Mode Execution Prevention\"]\n        KDP[\"Kernel Data Protection\"]\n        RODATA[\"Read-Only Data Sections\"]\n    end\n\n    subgraph \"Virtualization Security\"\n        VBS[\"Virtualization-Based Security\"]\n        HVCI[\"Hypervisor-Enforced Code Integrity\"]\n        MBEC[\"Mode-Based Execution Control\"]\n        KMCI[\"Kernel Mode Code Integrity\"]\n    end\n\n    subgraph \"Control Flow Protection\"\n        CFG[\"Control Flow Guard\"]\n        CET[\"Control-Flow Enforcement Technology\"]\n        KCFG[\"Kernel Control Flow Guard\"]\n    end\n\n    System --> KASLR\n    System --> KPTI\n    System --> SMAP\n    System --> SMEP\n    System --> KDP\n    System --> RODATA\n    System --> VBS\n    System --> HVCI\n    System --> MBEC\n    System --> KMCI\n    System --> CFG\n    System --> CET\n    System --> KCFG\n```\n\n### Virtualization-Based Security Stack\n\n```mermaid\nflowchart TB\n    Hardware[\"Hardware (CPU with Virtualization Support)\"]\n    Hypervisor[\"Hypervisor (Hyper-V)\"]\n    VTL1[\"VTL1 (Secure Kernel)\"]\n    VTL0[\"VTL0 (Normal Windows Kernel)\"]\n    Apps[\"User Applications\"]\n\n    Hardware --> Hypervisor\n    Hypervisor --> VTL1\n    Hypervisor --> VTL0\n    VTL0 --> Apps\n\n    subgraph \"Secure World\"\n        VTL1\n        SecureServices[\"Secure Services\"]\n        CredGuard[\"Credential Guard\"]\n        KMCI[\"Kernel Mode Code Integrity\"]\n    end\n\n    VTL1 --> SecureServices\n    VTL1 --> CredGuard\n    VTL1 --> KMCI\n```\n\n### Exploit Mitigation Evolution\n\n```mermaid\nflowchart LR\n    ClassicMitigations[\"Classic Mitigations\"]\n    ModernMitigations[\"Modern Mitigations\"]\n    FutureMitigations[\"Future Mitigations\"]\n\n    subgraph \"2000s\"\n        DEP[\"DEP\u002FNX\"]\n        ASLR[\"ASLR\"]\n        Stack[\"Stack Cookies\"]\n        SafeSEH[\"SafeSEH\"]\n    end\n\n    subgraph \"2010s\"\n        CFG[\"Control Flow Guard\"]\n        VBS[\"Virtualization-Based Security\"]\n        HVCI[\"HVCI\"]\n        WDAC[\"WDAC\"]\n    end\n\n    subgraph \"2020s+\"\n        CET[\"CET Shadow Stack\"]\n        MTE[\"Memory Tagging\"]\n        CFI[\"Full CFI\"]\n    end\n\n    ClassicMitigations --> DEP\n    ClassicMitigations --> ASLR\n    ClassicMitigations --> Stack\n    ClassicMitigations --> SafeSEH\n\n    ModernMitigations --> CFG\n    ModernMitigations --> VBS\n    ModernMitigations --> HVCI\n    ModernMitigations --> WDAC\n\n    FutureMitigations --> CET\n    FutureMitigations --> MTE\n    FutureMitigations --> CFI\n```\n","## Full Methodology\n\n# Modern Kernel Exploit Mitigations\n\n## Memory-safety & Isolation\n\n### Kernel Address Space Layout Randomization (KASLR)\n\n- Randomizes memory addresses where the kernel and its components are loaded.\n- Makes it difficult for attackers to predict kernel code and data locations.\n\n#### Bypass Techniques\n\n- **Information Leaks:** Exploiting vulnerabilities (e.g., uninitialized memory, side-channels) to leak kernel pointers and calculate the base address.\n- **Side-Channel Attacks:** Using timing, cache, or other microarchitectural side channels to infer memory layout.\n  - **Prefetch Cache Timing:** Measures access speed across the kASLR range (0xfffff80000000000 to 0xfffff80800000000, ~0x8000 iterations with 0x100000 alignment). The fastest access indicates a cached address, revealing the actual kernel base. Uses `rdtscp` for timing, `mfence` for memory barriers, and `prefetchnta`\u002F`prefetcht2` for cache manipulation.\n- **Targeting Non-Randomized Regions:** Exploiting data or code segments that are not fully randomized.\n- **Brute-Force:** Feasible in environments with limited entropy (e.g., some 32-bit systems or specific configurations).\n- **Intel LAM:** Linear Address Masking support exists on recent kernels\u002FCPUs but may be disabled by default. Verify with kernel config, boot params, and CPU flags on your target.\n\n### Kernel Page Table Isolation (KPTI)\n\n- Linux:\n  - Separates user-space and kernel-space page tables.\n  - Mitigates the Meltdown vulnerability by preventing user-space access to kernel memory.\n\n#### Bypass Techniques\n\n- **Side-Channel Attacks:** Exploiting microarchitectural side channels (e.g., TLB timing, cache attacks) that leak information across the isolation boundary.\n- **Hardware Vulnerabilities:** Exploiting CPU vulnerabilities (e.g., L1TF, MDS) that can bypass page table separation.\n- **Implementation Flaws:** Bugs in the KPTI implementation itself.\n\n#### Practitioner\n\n- Linux: check status via `\u002Fsys\u002Fdevices\u002Fsystem\u002Fcpu\u002Fvulnerabilities\u002F*` and `dmesg | grep -i kpti`.\n- Windows: verify meltdown\u002FKVA shadowing with `Get-SpeculationControlSettings` PowerShell script from Microsoft.\n\n### Supervisor Mode Access Prevention (SMAP)\n\n- Linux:\n  - Hardware feature preventing unintended kernel access to user-space memory.\n  - Protects against attacks exploiting improper memory accesses.\n\n#### Bypass Techniques\n\n- **ROP\u002FJOP Gadgets:** Finding instruction sequences (gadgets) within kernel code that disable SMAP temporarily (e.g., via `stac` instruction) before accessing user memory.\n- **Data-Only Attacks:** Attacks that achieve their goal without directly accessing user-space data from the kernel inappropriately.\n- **Kernel Information Leaks:** Combining with KASLR bypasses to find suitable gadgets.\n\n#### Practitioner\n\n- Linux: confirm with `grep smap \u002Fproc\u002Fcpuinfo` and `cat \u002Fproc\u002Fcpuinfo | grep 'smep\\|smap'`.\n- Check CR4 at runtime with `rdmsr`\u002F`wrmsr` tools or `lscpu -e` on supported systems.\n\n### Supervisor Mode Execution Protection (SMEP)\n\n- Linux\u002FWindows:\n  - Hardware feature preventing execution of user-space code when in supervisor mode.\n  - Located in bit 20 of the CR4 control register.\n  - Blocks certain privilege escalation attacks that rely on executing shellcode in user-mode memory.\n\n#### Bypass Techniques\n\n- **ROP\u002FJOP Chains:** Constructing code reuse chains entirely from existing kernel code, avoiding execution of user-space code.\n- **Data-Only Attacks:** Exploiting vulnerabilities without needing to execute shellcode (e.g., overwriting kernel data structures).\n- **Disabling SMEP:** Finding gadgets or techniques to modify the CR4 control register to disable SMEP.\n- **Type Confusion Exploits:** Using type confusion vulnerabilities to gain control flow and build ROP chains for SMEP bypass.\n- **Page Table Manipulation:** Modifying page table entries (PTEs) to change user pages to supervisor pages, making user-space code executable in kernel context.\n- **Write-What-Where Primitives:** Using arbitrary write vulnerabilities to modify CR4 register or page table structures.\n\n#### Practitioner\n\n- Linux: `grep smep \u002Fproc\u002Fcpuinfo`; verify effective state via `dmesg | grep -i smep`.\n- Windows: SMEP is enforced when Memory Integrity\u002FHVCI is enabled on modern systems.\n\n### Kernel Data Protection (KDP)\n\n- Windows:\n  - Marks certain kernel memory regions as read-only.\n  - Prevents unauthorized modification of critical kernel data structures.\n\n#### Practitioner\n\n- Check with `Get-CimInstance -ClassName Win32_DeviceGuard` and `System Information → Device Guard properties` for KDP\u002FHVCI\u002FVBS.\n\n### Memory Integrity (Core Isolation)\n\n- Windows:\n  - Uses virtualization and HVCI to prevent malicious code alteration.\n  - Guards against code injection or execution in kernel mode.\n\n#### Practitioner\n\n- Enable\u002Fverify: Windows Security → Device Security → Core isolation details.\n- PowerShell: `Get-ItemProperty -Path HKLM:\\SYSTEM\\CurrentControlSet\\Control\\DeviceGuard\\Scenarios\\HypervisorEnforcedCodeIntegrity | Select-Object Enabled`.\n\n### Read-Only Data Sections (RODATA)\n\n- Linux:\n  - Marks specific kernel memory regions as read-only.\n  - Prevents modification of critical data structures and code.\n\n### Hardened Usercopy\n\n- Linux:\n  - Adds boundary checks to memory copy operations between user and kernel space.\n  - Prevents buffer overflows and memory corruption during copy operations.\n\n### Memory Tagging Extension (MTE)\n\n- Linux (ARM):\n  - Hardware-assisted memory safety feature to detect memory corruption bugs.\n  - Mitigates use-after-free and buffer overflows at a hardware level.\n  - Adopted as a production security feature in **Android 16 (March 2025)** with both asynchronous and synchronous detection modes available for apps.\n\n#### How MTE Works\n\n- **4-bit Tags:** Each 16-byte memory allocation receives a random 4-bit tag (values 0-15)\n- **Pointer Tagging:** Upper bits of pointers store the allocation tag\n- **Tag Checking:** Hardware validates pointer tag matches memory tag on every dereference\n- **Fault on Mismatch:** Invalid access triggers `SIGSEGV` (sync mode) or logs asynchronously (async mode)\n\n#### Bypass Techniques\n\n- Tag Collision (Probabilistic): With only 4-bit tags (16 possible values), collision probability is high\n  - Increase entropy with larger allocation pools; Android 16 uses tag rotation heuristics.\n- Untagged Memory Regions: Not all memory is MTE-protected\n  - Enable MTE on stack via `prctl(PR_MTE_TCF_SYNC, PR_TAGGED_ADDR_ENABLE)`.\n- Asynchronous Mode Exploitation: Android's async mode delays fault reporting for performance\n  - Use synchronous mode (`MTE_mode=sync`) for security-critical apps.\n- Integer Overflow in Tag Calculation: MTE tags are derived from allocation size; overflow can corrupt tags\n- Kernel-Space Bypass: MTE only protects userspace by default\n  - Kernel allocations (`kmalloc`, `vmalloc`) don't use MTE (Android 16, Linux 6.8)\n  - Kernel exploit primitives (KASLR leak, arbitrary write) unaffected\n  - Syscall buffer handling may not validate tags\n- JIT Code Execution: JIT-compiled code can bypass MTE checks\n\n```asm\n; Assembly gadget to create untagged pointer\nmov x0, xzr          ; Zero out tag bits\norr x0, x0, #0x1000  ; Set address without tag\nldr x1, [x0]         ; Load from untagged pointer (no MTE check)\n```\n\n#### Exploitation Workflow:\n\n1. Leak a tagged pointer\n2. Strip tag bits (mask upper 8 bits)\n3. Use untagged pointer for memory operations\n4. MTE doesn't validate untagged accesses in some contexts\n\n#### Practitioner\n\n- Android: enable per‑app via Developer Options or `adb shell setprop persist.device_config.runtime_native_boot.mte_mode sync` (device‑specific).\n- Linux: compile with `CONFIG_ARM64_MTE` and use `prctl(PR_SET_TAGGED_ADDR_CTRL, ...)` from user space.\n- Verify MTE status: `cat \u002Fproc\u002Fcpuinfo | grep mte` and check `HWCAP2_MTE` in `getauxval(AT_HWCAP2)`\n- Android 16+ apps: opt-in via manifest `\u003Capplication android:memtagMode=\"sync\">`\n\n### Intel Linear Address Masking (LAM)\n\nIntel allows software to use upper address bits for metadata, similar to ARM's Top Byte Ignore (TBI).\n\n#### How LAM Works\n\n- **LAM57:** Uses bits 62:57 (6 bits) for tags in 5-level paging\n- **LAM48:** Uses bits 62:48 (15 bits) for tags in 4-level paging\n- **Hardware Masking:** CPU ignores tagged bits during address translation\n- **Use Cases:** Memory tagging, capability systems, garbage collection metadata\n- **Vulnerability Classes:**\n\n1. **Pointer Forge:** Attackers can craft tagged pointers without validation\n2. **Info Leak Bypass:** Some sanitizers only check canonical addresses; LAM-tagged pointers pass checks\n3. **Address Confusion:** Software assuming canonical addresses may mishandle LAM pointers\n\n### Memory Sealing\n\n- Linux:\n  - `mseal()` permanently seals selected VMAs so permissions\u002Fmappings can no longer change—even by the owner (verify kernel version and libc support on your target).\n  - Adopted by projects such as Chrome\u002Fglibc\u002FBPF tool‑chains to seal JIT pages, locking down GOT\u002FPLT and eBPF JIT regions (version‑specific; verify).\n\n#### Bypass Techniques\n\n- **Time‑of‑use Window:** Exploits must succeed before sealing.\n- **Data‑only Abuse:** Still possible if the mapping remains writable.\n- **Kernel Flaws:** Bugs in the `mseal()` path could bypass a seal.\n\n#### Practitioner\n\n- Verify `mseal` availability via `grep -R sys_mseal \u002Fproc\u002Fkallsyms` or kernel `symbols`.\n- Userland: `prctl(PR_MSEAL, ...)` (glibc 2.41+ headers), check errno for `ENOSYS` on older kernels.\n\n### Privileged Access Never (PAN)\n\n- Linux (ARM):\n  - Hardware feature preventing direct kernel access to user-space memory.\n  - Similar concept to SMAP on x86, prevents certain data leakage\u002Fcorruption bugs.\n\n### Kernel DMA Protection\n\n- Windows:\n  - Uses IOMMU\u002FVT-d to protect against malicious peripherals performing DMA attacks.\n  - Prevents unauthorized memory access via hardware devices.\n\n### Pluton Security Processor\n\n- Windows:\n  - Microsoft Pluton is increasingly deployed with newer platforms, replacing or augmenting discrete TPM 2.0 and hardware‑binding BitLocker keys, Secure Boot, and HVCI policies. Check OEM\u002FSKU documentation for Copilot+ requirements.\n\n#### Practitioner\n\n- Check Pluton state in Device Manager → Security devices, or `tpm.msc` shows Pluton‑backed TPM if present.\n\n### Memory Protection Keys (MPK)\n\n- Linux:\n  - Provides per-page memory permissions using hardware keys.\n  - Allows fine-grained control over memory access rights.\n\n#### Bypass Techniques\n\n- **PKRU Register Manipulation**: Using gadgets to modify the Protection Key Rights Register.\n- **Unprotected Memory**: Targeting memory regions not protected by MPK.\n- **Implementation Bugs**: Exploiting flaws in the MPK implementation.\n- **Side-Channel Attacks**: Using side channels to infer protected memory contents.\n\n### Protection Keys for Supervisor (PKS)\n\n- Linux\u002FIntel:\n  - Extends PKU to supervisor pages; the kernel flips page permissions via `wrmsr PKS_MSC*` without TLB flushes (Sapphire‑Rapids+).\n  - Landed upstream in Linux 6.12.\n\n#### Bypass Techniques\n\n- **ROP\u002FJOP `WRMSR` Gadgets** that flip PKS bits.\n- **Unprotected Regions** outside a PKS domain.\n- **CPU Errata** undermining isolation.\n\n#### Practitioner\n\n- Linux: enable with `CONFIG_X86_PKS`; verify via `dmesg | grep -i pks` and `\u002Fproc\u002Fcpuinfo` flags.\n\n### Zero-Page Memory Allocation\n\n- Linux\u002FWindows:\n  - Ensures memory pages are zeroed before allocation.\n  - Prevents leakage of residual data.\n\n### Zero-Page Mapping Removal\n\n- Linux:\n  - Removes zero page mapping to prevent NULL pointer dereference exploits.\n  - Enhances memory safety.\n\n### Init-On-Alloc and Init-On-Free and Init-Stack-All-Zero\n\n- Linux:\n  - Automatically zeroes memory when allocated or freed.\n  - Prevents use-after-free and information leakage.\n\n### TPM Bus Encryption\n\n- Linux:\n  - Recent kernels add support for stronger TPM transports over SPI\u002FI²C on some platforms. Feature availability and defaults vary; verify in `dmesg` and driver configs for your device.\n\n#### Practitioner\n\n- Verify with `dmesg | grep -i tpm` and kernel config `CONFIG_TCG_TIS_SPI`\u002F`_I2C` options; firmware must expose supported transports.\n\n## Memory Safety Initiatives\n\n### Rust in the Linux Kernel\n\n- First‑class Rust support landed in Linux 6.1 (December 2022) and was declared production‑ready with Linux 6.6 (October 2023).\n- In‑tree Rust drivers (e.g., NVMe, DRM simple‑display, Wi‑Fi) have so far exhibited zero memory‑safety bugs under continuous fuzzing, demonstrating the practical security benefit of memory‑safe languages.\n- Ongoing work aims to extend Rust usage into networking, Android GKI modules, and scheduler subsystems, further shrinking the kernel's attack surface.\n\n### Safer Windows Drivers with C++20 and Rust\n\n- Starting in Windows 11 23H2, the Windows Driver Framework (WDF) officially supports both modern C++20 and a Rust projection (`windows‑drivers‑rs`) that wrap KMDF\u002FWDF APIs with lifetime‑safe abstractions.\n- Hardware vendors can now obtain WHQL signatures for C++20 or Rust kernels drivers, eliminating common lifetime and IRQL‑misuse bugs without sacrificing performance.\n\n### CHERI \u002F Morello (Experimental Capability Hardware)\n\n- Arm's Morello evaluation platform (2022‑2025) runs a CHERI‑enabled Linux kernel that enforces pointer capabilities in user and kernel space, providing hardware‑enforced spatial and temporal memory safety.\n- Although experimental, CHERI demonstrates a plausible post‑2025 path toward fundamentally safer C\u002FC++ code with architectural support.\n\n### memfd_secret (userland secret memory)\n\n- Linux:\n  - `memfd_secret` (Linux 5.14+) provides user‑mode pages hidden from other processes and the kernel direct mappings\n  - Useful for protecting keys and ROP staging from accidental exposure; verify support via kernel config and `memfd_secret(2)`\n\n## Virtualization-Based Security Enhancements\n\n### Virtualization-Based Security (VBS)\n\n- Windows:\n  - Creates an isolated, secure memory region using hardware virtualization.\n  - Protects sensitive system components and data from malware and exploits.\n\n#### Bypass Techniques\n\n- **Hypervisor Vulnerabilities:** Exploiting bugs in the underlying hypervisor (Hyper-V) to escape the VBS container.\n- **Misconfiguration:** Weaknesses in VBS configuration or deployment.\n- **Physical Access:** Hardware-level attacks (e.g., DMA attacks if not mitigated by Kernel DMA Protection).\n- **Compromised Signed Components:** Exploiting vulnerabilities in trusted components running within VBS.\n\n#### Practitioner\n\n- Confirm VBS\u002FHVCI: `Core isolation` settings or PowerShell `Get-CimInstance -ClassName Win32_DeviceGuard` (look for `VirtualizationBasedSecurityStatus` and `SecurityServicesConfigured`).\n\n### AMD Secure Encrypted Virtualization – Secure Nested Paging (SEV‑SNP)\n\n- Linux guest support since 6.11; provides full memory encryption + integrity with an SVSM.\n- Shipping today in major cloud \"confidential VM\" SKUs.\n\n### Intel Trust Domain Extensions (TDX)\n\n- Guest driver landed in 6.11; host enablement queued for 6.16.\n- Protects guest memory against a compromised hypervisor.\n\n#### Practitioner\n\n- Cloud: verify TDX\u002FSEV‑SNP instance type (`Azure DCasv5\u002FECasv5`, `GCP C3`, `AWS C7g` variants); attest via platform‑specific tools (e.g., `az confcom attestation`).\n\n### Arm Confidential Compute Architecture (CCA) Realms\n\n- Realm VM support merged in 6.13 for Arm v9 CPUs, giving encrypted, isolated guest environments.\n\n### Hypervisor-Enforced Code Integrity (HVCI)\n\n- Windows:\n  - Uses VBS to enforce code integrity checks on kernel-mode drivers and binaries.\n  - Ensures only signed and verified code can execute in kernel mode.\n\n#### Bypass Techniques\n\n- **Signed Malicious Drivers:** Obtaining signing certificates (stolen or illicitly acquired) to sign malicious code.\n- **Exploiting Allowed Drivers:** Finding vulnerabilities in legitimate, signed drivers already running on the system (\"Bring Your Own Vulnerable Driver\" - BYOVD).\n- **Hypervisor Vulnerabilities:** Exploiting the underlying hypervisor (see VBS bypasses).\n- **Configuration Issues:** Weaknesses in Code Integrity policies.\n\n### Mode Based Execution Control (MBEC)\n\n- Windows:\n  - Ensures driver code can only be executed in kernel mode.\n  - Available in hardware and software (emulated) forms.\n  - Prevents user-mode execution of kernel code.\n\n### Kernel Mode Code Integrity (KMCI)\n\n- Windows:\n  - Ensures kernel pages can only become executable with proper signing.\n  - Enforces driver signing enforcement and vulnerable driver blocklists.\n  - Implements software SMEP (Supervisor Mode Execution Prevention).\n  - `DriverSiPolicy.p7b` now refreshes **weekly** via Windows Update and MEM Configuration Manager, accelerating the BYOVD blocklist cadence.\n\n### User Mode Code Integrity (UMCI)\n\n- Windows:\n  - Ensures user mode pages can only become executable with proper signing.\n  - CI validates the signaturees of EXE and DLL before allowing them to load.\n  - Enforces protected processes and protected process light signature requirements\n  - Enforces `\u002FINTEGRITYCHECK` for `FIPS 140-2` modules\n  - Exposed to consumers as _Smart App Control_ and businesses as _App Control for Business_.\n  - Part of the Device Guard technology stack.\n\n### Windows Defender System Guard\n\n- Windows:\n  - Monitors system integrity during boot and runtime.\n  - Protects against rootkits and bootkits by verifying system integrity.\n\n### Windows Defender Application Guard\n\n- Windows:\n  - Runs untrusted content in isolated containers.\n  - Protects the host from potentially malicious websites and documents.\n\n### Credential Guard\n\n- Windows:\n  - Uses VBS to isolate and protect credentials.\n  - Prevents attacks like Pass-the-Hash or Pass-the-Ticket.\n\n### Device Guard\n\n- Windows:\n  - Combines WDAC and virtualization-based security to lock down devices.\n  - Ensures only trusted applications can run.\n\n## OS Loader and Hotpatching Changes (Windows 11 24H2+)\n\n- Recent Windows versions (24H2 and later) introduced changes that impact classic process injection techniques like Process Hollowing (RunPE).\n- **Status:** Client Hotpatching availability and cadence depend on SKU\u002Fservicing channel. Validate GA status in current Microsoft documentation.\n- Windows Server 2025 requires an Azure Arc subscription for hotpatch servicing.\n\n### Impact on Process Hollowing (MEM_PRIVATE Payloads)\n\n- **Root Cause 1 (Error `0xC0000141`):** Native Hotpatching support added a new function `RtlpInsertOrRemoveScpCfgFunctionTable` during process initialization (`LdrpInitializeProcess -> LdrpProcessMappedModule`). This function calls `ZwQueryVirtualMemory` with a new `MemoryImageExtensionInformation` class, which _only_ works on `MEM_IMAGE` memory regions.\n  - Classic Process Hollowing stores the payload in `MEM_PRIVATE` memory (either by unmapping the original PE or allocating a new region).\n  - The `ZwQueryVirtualMemory` call fails with `STATUS_INVALID_ADDRESS` for the `MEM_PRIVATE` payload region, causing process loading to terminate.\n- **Root Cause 2 (Error `0xC00004AC`, Memory Integrity Enabled):** If Memory Integrity (HVCI) is enabled, another check occurs later in the loading process.\n  - `LdrpQueryCurrentPatch` is called on the payload's memory region.\n  - This leads to a call to `NtManageHotPatch`, which fails with `STATUS_CONFLICTING_ADDRESSES` for the `MEM_PRIVATE` payload.\n  - This error also terminates the process loading.\n\n### Solutions and Bypasses\n\n1.  **Use Alternative Techniques (Recommended):** Employ methods that map the payload as `MEM_IMAGE`, which are unaffected by these specific checks.\n    - Examples: Process Doppelganging, Process Ghosting, Process Herpaderping, Transacted Hollowing, Ghostly Hollowing, Herpaderply Hollowing, Process Overwriting.\n    - These techniques generally interact more naturally with the loader and newer OS features.\n2.  **Patch NTDLL (If sticking to Classic RunPE):**\n    - **For `0xC0000141`:** Hook `ZwQueryVirtualMemory`.\n      - Check if the OS is Win11 24H2+ (64-bit).\n      - If the `MemoryInformationClass` is `MemoryImageExtensionInformation` AND the query targets the base address of the `MEM_PRIVATE` payload:\n        - Return a benign error like `STATUS_NOT_SUPPORTED` instead of calling the original function.\n      - Otherwise, call the original `ZwQueryVirtualMemory`.\n      - [Implementation Example](https:\u002F\u002Fgithub.com\u002Fhasherezade\u002Flibpeconv\u002Fblob\u002Fmaster\u002Frun%5Fpe\u002Fpatch%5Fntdll.cpp#L91)\n    - **For `0xC00004AC` (Memory Integrity):** Hook `NtManageHotPatch`.\n      - Patch the function to immediately return a benign error like `STATUS_NOT_SUPPORTED`.\n      - Apply this patch early in the process creation, for both 32-bit and 64-bit.\n      - Ensure `FlushInstructionCache` is called if patching after the function might have been cached.\n      - [32-bit Example](https:\u002F\u002Fgithub.com\u002Fhasherezade\u002Flibpeconv\u002Fblob\u002Fmaster\u002Frun%5Fpe\u002Fpatch%5Fntdll.cpp#L4)\n      - [64-bit Example](https:\u002F\u002Fgithub.com\u002Fhasherezade\u002Flibpeconv\u002Fblob\u002Fmaster\u002Frun%5Fpe\u002Fpatch%5Fntdll.cpp#L43)\n\n## Control Flow Integrity and Execution Protections\n\n### Data Execution Prevention (DEP)\n\n- Windows\u002FLinux:\n  - Marks certain memory regions as non-executable.\n  - Prevents execution of code from data pages, mitigating buffer overflow attacks.\n\n#### Bypass Techniques\n\n- **Return-oriented Programming (ROP)**: Using existing code fragments to create attack chains without injecting code.\n- **ret2libc**: Jump directly to code in libc.\n- **ret2data**: Place shellcode in the data section.\n- **ret2strcpy**: Place shellcode on the stack and use strcpy to move it somewhere executable.\n- **ret2gets**: Read from stdin to gain control.\n- **VirtualProtect\u002FVirtualAlloc**: Call these functions to change memory permissions.\n- **JIT Spraying**: Leverage Just-In-Time compilation to get executable memory.\n\n#### Practitioner\n\n- use `!vprot rip` or `!vpro rsp` to check for protections inside WinDbg\n- `.scriptload G:\\Projects\\narly.js; !nmod` also helps you to see which modules have DEP protection\n- `Data Execution Prevention` settings inside `Windows Exploit Guard` can be used to force DEP protection on an executable\n- pivot with `VirtualProtect` \u002F `NtProtectVirtualMemory` (or pre‑ACG RWX section) from a ROP\u002FJOP chain.\n- Modern Windows 10\u002F11 enforce **CET (Shadow Stack)** and **XFG (Cross‑Function Guard)**, which break classic ROP; successful chains must first disable CET (for example with `SetProcessMitigationPolicy`) or switch to JOP\u002FSCS gadgets.\n- an example would be `pop rcx; retn; pop rcx; retn; mov [rcx], rax; pop rbp; retn;`\n- we can use `IAT` to identify and call `WriteProcessMemory` which can be used to circumvent DEP protection through `NtProtectVirtualMemory` API\n- [Ropper 2.0](https:\u002F\u002Fgithub.com\u002Fsashs\u002FRopper) **or Rizin‑ropper** — both support CET\u002FXFG‑aware gadget filtering.\n\n### Control Flow Integrity (CFI)\n\n- Windows:\n  - Ensures kernel execution follows legitimate paths.\n  - Thwarts control-flow hijacking attacks like function pointer overwrites.\n\n#### Bypass Techniques\n\n- **Similar Function Prototypes**: For XFG (Extreme Flow Guard), functions with similar prototypes may be exploitable.\n- **Data-Only Attacks**: Manipulating program state without violating CFI constraints.\n- **Implementation Weaknesses**: Exploiting gaps in the implementation of CFI.\n- **JIT Compilation**: Just-in-time compiled code may bypass CFI checks.\n\n#### Practitioner\n\n- Windows build: enable CFG\u002FXFG via `\u002Fguard:cf \u002Fguard:xfg` and `\u002FQspectre` where applicable; inspect PE `LoadConfig` for CFG\u002FXFG metadata.\n- Linux build: Clang `-fsanitize=cfi` (user space) or `CONFIG_CFI_CLANG=y` (kernel), with LTO; verify symbols contain CFI jump tables.\n\n### kCFI\n\n- Linux\n  - Clang-based forward-edge Control-Flow Integrity that verifies indirect function calls at runtime in the kernel.\n  - Enabled by default in Android GKI kernels and ChromeOS since early 2024; available upstream via `CONFIG_CFI_CLANG`.\n  - Complements FineIBT and hardware CET by protecting software-only control-flow edges.\n  - **BHI Hardening (Linux 6.9\u002F6.10):** FineIBT now incorporates indirect‑branch serialization to mitigate Branch History Injection.\n\n### Control Flow Guard (CFG)\n\n- Windows:\n  - Ensures indirect calls go only to valid, predefined locations.\n  - Helps prevent control-flow hijacking attacks.\n\n#### Bypass Techniques\n\n- **JIT Code Execution**: Using Just-In-Time compiled code which may not be properly protected.\n- **Import Address Table (IAT) Manipulation**: Inserting entries in IAT since these aren't checked.\n- **Data-only Attacks**: Modifying program data to influence control flow without redirecting execution.\n- **Type Confusion**: Exploiting type confusion to bypass CFG checks.\n\n#### Practitioner\n\n- Check process mitigation: `Get-ProcessMitigation -Name process.exe` (PowerShell) → CFG\u002FstrictCFG\u002FXFG states.\n- PE inspection: `dumpbin \u002Floadconfig` shows GuardCFFunctionTable and flags.\n\n### Stack Canaries\n\n- Linux\u002FWindows:\n  - Inserts random values before return addresses on the stack.\n  - Detects stack buffer overflows before they overwrite return addresses.\n\n#### Bypass Techniques\n\n- **Leaking Canary Values**: Using format string or other information disclosure vulnerabilities.\n- **Overwriting Non-return Variables**: Attacking function pointers or other control flow variables not protected by canaries.\n- **Brute Force**: On systems with low entropy canaries or predictable generation.\n- **Exception Handler Attacks**: Targeting exception registration records which may not be protected.\n- **Unprotected Functions**: Exploiting functions not protected by canaries (often due to performance considerations).\n\n### Stack Clash Protection\n\n- Linux\u002FGCC:\n  - Prevents stack and heap collisions by probing stack pages during large allocations.\n  - Mitigates privilege escalation attacks that rely on stack\u002Fheap layout manipulation.\n  - Enabled with `-fstack-clash-protection` compiler flag.\n\n#### Bypass Techniques\n\n- **Precise Heap Layout**: Carefully crafting heap allocations to avoid clash detection.\n- **Small Allocations**: Using allocations smaller than the probe size to avoid triggering protection.\n- **Alternative Memory Regions**: Targeting other memory regions not protected by stack clash detection.\n- **Implementation Gaps**: Exploiting edge cases in the probing logic.\n\n### Hardware‑Enforced Stack Protection\n\n- Windows:\n  - Utilizes Intel CET (specifically the Shadow Stack feature, referred to as Kernel Mode Hardware-enforced Stack Protection or KCET) and AMD Shadow Stack features.\n  - Requires Hypervisor-Enforced Code Integrity (HVCI) \u002F Virtualization-Based Security (VBS) to be enabled.\n  - Provides a hardware-backed shadow stack to protect return addresses against ROP\u002FJOP attacks.\n  - Applies to kernel-mode stacks, including those associated with user-mode threads executing in kernel mode (e.g., during system calls).\n  - Hardware-Enforced Stack Protection is enabled by default on compatible hardware with Windows 11, version 24H2, when VBS\u002FHVCI is active. The `IMAGE_GUARD_SHADOW_STACK` PE flag indicates compatibility and is increasingly adopted for key binaries, with Windows components widely enabling it.\n\n#### Bypass Techniques\n\n- **Increased Difficulty with HVCI:** When combined with Hypervisor-Enforced Code Integrity (HVCI), bypassing hardware-enforced shadow stacks becomes significantly more challenging. HVCI leverages virtualization (Hyper-V) to protect the shadow stack's integrity via the Secure Kernel (VTL1). The Secure Kernel manages the shadow stack pointer (`VMX_GUEST_SSP` in the VMCS for VTL0) through hypercalls, preventing even kernel-mode code (VTL0) from directly tampering with it.\n- **Return Address Protection:** The hardware compares the return address on the main stack with the one stored on the protected shadow stack before executing a `RET` instruction. Mismatches typically cause a fault (system crash for KCET), mitigating standard ROP\u002FJOP attacks that rely on overwriting the return address on the main stack.\n- **Secure Kernel Validation:** The Secure Kernel is involved in validating and restoring shadow stack context (e.g., during exception handling via functions like `nt!KeKernelShadowStackRestoreContext` and secure system calls like `securekernel!SkmmNtKernelShadowStackAssist`), adding another layer of integrity checking.\n- **Potential (Difficult) Vectors:** Bypasses would likely require exploiting vulnerabilities in the hypervisor (Hyper-V) or the Secure Kernel itself, finding flaws in the hardware CET implementation, or developing sophisticated data-only attacks that achieve control without corrupting the stack's return addresses. These are considerably harder than bypassing software-based or unprotected hardware stack protections.\n- **Limited Scope:** Like other CFI mechanisms, attacks targeting non-control data or logic bugs may still be possible if they don't violate the protected control flow.\n\n### Pointer Authentication (ARM64)\n\n- Linux\u002FiOS:\n  - Uses cryptographic signatures to protect pointers.\n  - Mitigates attacks like Return-Oriented Programming (ROP).\n\n#### Bypass Techniques\n\n- **Unprotected Assembly Code**: Assembly code often lacks PAC protection.\n- **Raw Function Pointers**: Recovery handlers and other mechanisms that use raw pointers.\n- **Signing Gadgets**: Using existing code that signs pointers.\n- **Switch Case Branches**: Unprotected indirect branches in switch case implementations.\n- **Authentication Failure Handling**: Exploiting cases where authentication failures don't trigger exceptions.\n- **Thread State Manipulation**: Incorrect handling of thread state during context switches.\n\n### Intel Control‑flow Enforcement Technology (CET)\n\n- Hardware feature providing protections against control-flow hijacking.\n- Includes Shadow Stack and Indirect Branch Tracking.\n- Enabled by default starting with Windows 11 build 26100 (Win11 24H2+). Any stack pivot or `ret` without a valid shadow‑stack token raises `STATUS_STACK_BUFFER_OVERRUN` (0xC0000409).\n- **Detect CET:** Read the `IMAGE_DLLCHARACTERISTICS_GUARD_CF` flag in the PE header or `PEB→LdrDataTableEntry.GuardFlags`.\n  - Windows: `Get-ProcessMitigation -System` shows `UserShadowStack` and `UserCetEnabled`.\n  - Linux: check `cet_ss` in `\u002Fproc\u002Fcpuinfo` and `prctl(PR_SET_SHADOW_STACK_STATUS, ...)`.\n- **Bypass tips for CET in shellcode:**\n  1. Align the shellcode entry to a valid call target and emit `ENDBR64`\u002F`SETSSP` before the first `ret`.\n  2. Use ROP‑less staging (queued APC, `NtContinue`, or `NtTestAlert`) so the kernel performs the first return.\n\n### Intel Indirect Branch Tracking (IBT)\n\n- Linux\u002FWindows:\n  - Part of Intel CET that enforces legitimate indirect branch targets.\n  - Requires `ENDBR32` or `ENDBR64` instructions at valid indirect call\u002Fjump destinations.\n  - Prevents JOP (Jump-Oriented Programming) attacks by validating branch targets.\n  - Available on Tiger Lake+ CPUs, enabled via `CET_IBT` bit in MSR.\n\n#### Bypass Techniques\n\n- **ENDBR Gadgets**: Finding existing code sequences that start with valid `ENDBR32\u002F64` instructions.\n- **ENDBR Spraying**: Injecting or finding multiple `ENDBR` instructions to create gadget chains.\n- **Unprotected Modules**: Targeting libraries or code not compiled with IBT support.\n- **Legacy Code Paths**: Exploiting code paths that bypass IBT checks (e.g., signal handlers, exception contexts).\n- **Hardware Quirks**: Exploiting CPU-specific implementation differences or errata.\n\n#### Practitioner\n\n- Check IBT status: `cat \u002Fproc\u002Fcpuinfo | grep cet_ibt` (Linux) or inspect `cr4.cet` bit\n- Compile with IBT: `-fcf-protection=branch` (GCC) or `-mcet` flag\n- Binary analysis: Look for `ENDBR64` (0xF3 0x0F 0x1E 0xFA) or `ENDBR32` (0xF3 0x0F 0x1E 0xFB) instructions\n\n### Shadow Call Stack (SCS)\n\n- Linux:\n  - Compiler-based CFI mechanism using a shadow stack to protect return addresses.\n  - Helps prevent ROP attacks.\n  - Ensures only signed and verified code can execute in kernel mode.\n  - Blocks RWX pages and unsigned kernel callbacks when **Memory Integrity** is ON (default on 2024‑hardware).\n  - Common allocation pattern for executable memory: `PAGE_READWRITE` → write payload → `NtProtectVirtualMemory` → `PAGE_EXECUTE_READ`.\n  - WoW64 heaven‑gate patches to `WOW64CFG` are rejected by HVCI; favour direct 64‑bit syscalls (e.g., via `wow64log`).\n\n#### Bypass Techniques\n\n- **Data‑only Attacks** (no return‑address writes).\n- **Hypervisor\u002FKernel Bugs** that corrupt GCS state.\n\n### Guarded Control Stack (GCS)\n\n- Linux\u002FARM64:\n  - Hardware user‑space shadow stack on Armv9‑A CPUs, merged in Linux 6.13 and on by default in modern Android.\n  - Complements KCET\u002FCET on x86.\n\n#### PAN‑GCS Dual Enforcement (Android 16, Armv9 Realms)\n\n- From Android 16, GCS (shadow stack) plus Privileged Access Never (PAN) are **mandatory** for all Play‑targetSdk 34+ apps running on Armv9 Realms hardware, providing dual hardware + software enforcement.\n\n#### Bypass Techniques\n\n- **Data‑only Attacks** (no return‑address writes).\n- **Hypervisor\u002FKernel Bugs** that corrupt GCS state.\n\n### FineIBT\n\n- Linux:\n  - Enhanced CFI mechanism for indirect branch targets.\n  - Provides finer-grained control flow protection than basic CFI.\n  - The initial implementation was vulnerable to Branch History Injection (BHI). Hardened FineIBT with serialising `INT3` fences landed upstream in Linux 6.14\n\n### Arbitrary Code Guard (ACG)\n\n- Windows:\n  - Prevents processes from allocating or modifying memory to be executable.\n  - Mitigates attacks relying on dynamic code generation or modification.\n\n#### Practitioner\n\n- Check ACG: `Get-ProcessMitigation -Name process.exe | Select-Object -ExpandProperty DynamicCode`.\n- WDAC policy can enforce ACG: audit with `Get-CIPolicy` and `CodeIntegrity` logs.\n\n### Code Integrity Guard (CIG)\n\n- Windows:\n  - Restricts loading of DLLs to only those signed by Microsoft or WHQL.\n  - Prevents loading of potentially malicious or untrusted libraries.\n\n#### Practitioner\n\n- PowerShell: `Get-ProcessMitigation -Name process.exe | Select-Object -ExpandProperty BinarySignature`.\n- Event Logs: `Microsoft-Windows-CodeIntegrity\u002FOperational` for blocked DLL loads.\n\n### Kernel Control-Flow Guard (kCFG)\n\n- Windows:\n  - Kernel-specific implementation and enforcement of Control Flow Guard.\n  - Protects against control-flow hijacking within the kernel itself.\n\n### eXtended Flow Guard (XFG)\n\n- Windows:\n  - Debuted with Windows 11 23H2. Adds strict function‑prototype hashing to CFG, blocking many type‑confusion escapes.\n\n#### Bypass Techniques\n\n- **Prototype Collisions** (extremely rare).\n- **Modules Without XFG** (legacy or JIT code).\n\n### Export Address Filtering (EAF) \u002F Import Address Filtering (IAF)\n\n- Windows:\n  - Protects module export and import tables from tampering.\n  - Prevents attacks that redirect function calls by modifying these tables.\n\n### Structured Exception Handling Overwrite Protection (SEHOP)\n\n- Windows:\n  - Protects the integrity of exception handler chains on the stack.\n  - Prevents exploits that overwrite exception handlers to gain control flow.\n\n#### Bypass Techniques\n\n- **Modules Without SafeSEH**: A single module without protection breaks the chain.\n- **ROP Chains**: Building ROP chains that don't rely on exception handlers.\n- **Alternative Attack Vectors**: Targeting other vulnerable components not protected by SEHOP.\n- **Unprotected Exception Handlers**: Finding handlers that are still vulnerable.\n\n### Exploit Address Table Filtering (EAF & EAF+)\n\n- Windows:\n  - Blocks access to Export Address Tables of critical DLLs like kernel32.dll and ntdll.dll.\n  - EAF+ allows specifying modules not permitted to access the EAT, particularly targeting UAF bugs.\n  - Uses hardware breakpoints to filter access attempts.\n\n#### Bypass Techniques\n\n- **Alternative Discovery Methods**: Using different techniques to locate functions.\n- **Unprotected Modules**: Targeting modules not covered by EAF protection.\n\n### Import Address Filtering (IAF)\n\n- Windows:\n  - Ensures all functions listed in a DLL's IAT exist within the image's load address range.\n  - Prevents IAT overwrite attacks.\n\n### Virtual Table Guard\n\n- Windows:\n  - Ensures virtual function table pointers point to valid guard pages.\n  - Terminates execution if invalid vptrs are detected.\n  - Protects against C++ virtual function table overwrites.\n\n### MemGC\n\n- Windows:\n  - Replacement for MemProtect technology.\n  - Specifically targets mitigation of use-after-free exploitation.\n\n### Kernel Text Read-only Region (KTRR)\n\n- iOS:\n  - Prevents modification of the iOS kernel at runtime.\n  - Implements hardware-enforced read-only memory for kernel code.\n\n#### KTRR‑v2 & FastPAC (iOS 18, A18\u002FA19)\n\n- Hardware‑enforced cache‑colouring prevents pointer‑authentication re‑spray, complementing traditional KTRR for stricter kernel integrity.\n\n### Intel Memory Protection Extensions (MPX)\n\n> [!NOTE]\n> Support was removed from Linux 5.6 (April 2020) and GCC 9.1; no mainstream OS or compiler ships MPX today.\n\n## Heap Protections\n\n### Heap Cookies\n\n- Windows:\n  - Places a 1-byte value in the metadata of heap chunks.\n  - Detects heap metadata corruption before exploitation.\n\n### AMSI Heap Scanning (Jan 2025)\n\n- Windows:\n  - AMSI (Antimalware Scan Interface) scans newly committed **writable** heap pages _before_ they are flipped to `PAGE_EXECUTE_READ` or `PAGE_EXECUTE_WRITECOPY`.\n  - **Safer allocation pattern to avoid AMSI heap scanning:** Reserve memory with `PAGE_NOACCESS`, decrypt\u002Fdeobfuscate payload in‑place, then change protection to `PAGE_EXECUTE_READ`.\n  - The classic \"patch the `AMSI` ASCII tag in `amsi.dll`\" trick no longer works reliably; consider patching the COM VTable entry for `IAmsiStream::QueryInterface` or using a proxy‑DLL hook instead.\n\n### Low Fragmentation Heap (LFH)\n\n- Windows:\n  - First 32-bit of metadata gets XORed with canary to ensure integrity.\n  - Allocates blocks in predetermined size ranges by organizing blocks into buckets.\n  - Reduces heap predictability and exploitation potential.\n\n### Safe Unlink\n\n- Windows\u002FLinux:\n  - Checks integrity of pointers before freeing memory chunks.\n  - Prevents unlink exploitation in heap management.\n\n#### Bypass Techniques\n\n- **Heap Overflow**: Using malloc maleficarum techniques.\n- **Chunk-on-Lookaside Overwrite**: Targeting specific heap management structures.\n\n### Heap and Stack Protections\n\n- Windows:\n  - Implements guard pages and heap allocation randomization.\n  - Detects and prevents buffer overflows and stack smashing.\n\n## Randomization Techniques\n\n### Address Space Layout Randomization (ASLR)\n\n- Linux & Windows:\n  - Randomizes memory addresses used by executables and libraries.\n  - Makes it harder for attackers to predict target addresses.\n\n#### Bypass Techniques\n\n- **Information Leaks**: Exploiting vulnerabilities to leak addresses of loaded modules.\n- **ROP with PLT\u002FGOT**: Using the Procedure Linkage Table to leak addresses and calculate base addresses.\n- **Low Entropy**: Exploiting systems with limited randomization bits.\n- **Heap Spraying**: Filling memory with copies of shellcode to increase hit probability.\n- **Local Privilege Escalation**: Using local exploits to bypass protection.\n- **Partial Overwrite**: Overwriting only part of an address to maintain alignment.\n- **Statically Linked Code**: Targeting code that doesn't use ASLR.\n\n#### Practitioner\n\n- you probably first need an information leak to identify the correct memory address and then use it to circumvent ASLR and DEP\n- format string bugs also helps trigger an information leak, so you can use them alongside `ropchains` to bypass ASLR and DEP\n- information leaks are often happen through logical errors or memory corruption bugs\n\n### Position Independent Executables (PIE)\n\n- Linux\u002FWindows:\n  - Compiles executables as position-independent code, enabling ASLR for the main executable.\n  - Without PIE, the main executable loads at a fixed base address, providing attackers a reliable target.\n  - Essential for full ASLR coverage across all memory regions.\n\n#### Bypass Techniques\n\n- **Information Leaks**: Same techniques as ASLR bypass - leak addresses to calculate base.\n- **Partial Overwrites**: Overwriting only the lower bytes of addresses to maintain relative offsets.\n- **Non-PIE Dependencies**: Targeting linked libraries that aren't position-independent.\n- **GOT\u002FPLT Attacks**: Exploiting Global Offset Table entries before they're resolved.\n\n#### Practitioner\n\n- Check PIE status: `file \u002Fpath\u002Fto\u002Fbinary` or `readelf -h \u002Fpath\u002Fto\u002Fbinary | grep Type`\n- Compile with PIE: `-fPIE -pie` (GCC) or `-fPIC -shared` for libraries\n- Detect at runtime: `\u002Fproc\u002FPID\u002Fmaps` shows randomized executable base addresses\n- **checksec**: `checksec --file=\u002Fpath\u002Fto\u002Fbinary` shows PIE status\n\n### ASCII Armored Address Space\n\n- Windows:\n  - Loads all shared libraries in addresses starting with `0x00`.\n  - Prevents string manipulation exploits that terminate at null bytes.\n\n#### Bypass Techniques\n\n- **Partial Injection**: Still possible to inject one null byte.\n- **Main Executable Attacks**: Main executable is not moved, so attackers can target it instead.\n\n### Function Granular KASLR (FGKASLR)\n\n- Linux:\n  - Randomizes kernel functions at a finer granularity.\n  - Enhances address space randomization effectiveness.\n\n### Kernel Stack Randomization\n\n- Linux:\n  - Randomizes the kernel stack base address per process.\n  - Makes stack-based attacks more challenging.\n\n### Mandatory ASLR (MASLR)\n\n- Windows:\n  - Forces the rebasing of modules even when they were compiled without ASLR support.\n  - Enhances protection against code reuse attacks.\n\n### Bottom-Up ASLR (BASLR)\n\n- Windows:\n  - Works alongside MASLR to randomize allocation patterns.\n  - Blocks 64KB allocations from requested base address up to a randomly selected number.\n  - Repeats randomization each time the process restarts.\n\n## Side-Channel Attack Mitigations\n\n### Speculative Execution Mitigations\n\n- Linux\u002FWindows:\n  - Addresses vulnerabilities like Spectre and Meltdown.\n  - Includes microcode updates and patches to prevent speculative execution attacks.\n\n### Recent Spectre Mitigations\n\n- **IBPB (Indirect Branch Prediction Barrier)**:\n  - Intel\u002FAMD feature that flushes indirect branch predictors.\n  - Prevents cross-privilege domain speculation leakage.\n  - Controlled via `MSR_IA32_PRED_CMD`.\n\n- **IBRS (Indirect Branch Restricted Speculation)**:\n  - Restricts speculation of indirect branches when in higher privilege levels.\n  - Mitigates Spectre v2 by preventing user-space speculation attacks on kernel.\n  - Performance overhead led to adoption of retpolines as primary mitigation.\n\n- **STIBP (Single Thread Indirect Branch Predictors)**:\n  - Prevents sibling threads from controlling each other's indirect branch prediction.\n  - Mitigates cross-hyperthread Spectre attacks.\n  - Particularly important for SMT (Simultaneous Multi-Threading) environments.\n\n- **SSBD (Speculative Store Bypass Disable)**:\n  - Prevents speculative execution of loads that bypass older stores.\n  - Mitigates Spectre v4 (Speculative Store Bypass).\n  - Can be controlled per-process via `prctl()` on Linux.\n\n#### Bypass Techniques\n\n- **Microarchitectural Timing**: Using cache timing, TLB timing, or other side channels.\n- **Cross-Process Leakage**: Exploiting shared microarchitectural state between processes.\n- **Hardware Implementation Gaps**: CPU-specific vulnerabilities in mitigation implementations.\n- **Performance Optimization Exploitation**: Targeting cases where mitigations are disabled for performance.\n\n#### Practitioner\n\n- Check mitigations: `cat \u002Fproc\u002Fcpuinfo | grep -E \"(ibpb|ibrs|stibp|ssbd)\"`\n- Runtime controls: `\u002Fsys\u002Fdevices\u002Fsystem\u002Fcpu\u002Fvulnerabilities\u002F` directory\n- Per-process SSBD: `prctl(PR_SET_SPECULATION_CTRL, PR_SPEC_STORE_BYPASS, ...)`\n- Performance impact: Use `perf` to measure mitigation overhead\n\n### Kernel Memory Sanitizer (KMSAN)\n\n- Linux:\n  - Detects use of uninitialized memory in the kernel.\n  - Helps find and fix initialization bugs.\n\n### Linux Kernel Runtime Guard (LKRG)\n\n- Linux (Module):\n  - Loadable kernel module performing runtime integrity checks on critical kernel structures.\n  - Aims to detect and prevent various exploits in real-time.\n\n### Spectre-BHB Mitigations\n\n- Linux:\n  - Addresses Branch History Injection vulnerabilities on ARM.\n  - Prevents certain speculative execution attacks.\n\n## Dynamic Analysis and Detection Tools\n\n### Kernel Address Sanitizer (KASAN)\n\n- Linux:\n  - Dynamic memory error detector for the kernel.\n  - Identifies use-after-free and out-of-bounds bugs.\n\n### eBPF Verification Enhancements\n\n- Linux:\n  - Strengthens verification of eBPF programs loaded into the kernel.\n  - Prevents exploitation via the eBPF subsystem.\n\n## Windows Defender Security Features\n\n### Windows Defender Application Control (WDAC)\n\n- Windows:\n  - Controls which drivers and applications are allowed to run.\n  - Uses code integrity policies to prevent unauthorized code execution.\n\n#### Practitioner\n\n- Enumerate policies: `Get-CIPolicy -Effective` and `Get-ComputerInfo | Select WindowsProductName, WindowsVersion`.\n- Validate blocklists: ensure `DriverSiPolicy.p7b` is current; check with `gpresult \u002Fr` or MEM policies.\n\n### Exploit Protection\n\n- Windows:\n  - System-wide mitigation settings against common exploit techniques.\n  - Includes heap spray allocation prevention, mandatory ASLR, etc.\n\n#### Practitioner\n\n- Export\u002Fimport settings via `Export-ProcessMitigation` \u002F `Set-ProcessMitigation`.\n- Audit per‑process: `Get-ProcessMitigation` for DEP\u002FASLR\u002FSEHOP\u002FCFG\u002FXFG.\n\n### Attack Surface Reduction (ASR) Rules\n\n- Windows:\n  - Part of Windows Defender Exploit Guard, providing configurable rules.\n  - Blocks specific behaviors often associated with malware or exploits (e.g., Office macro execution, script obfuscation).\n\n#### Practitioner\n\n- Query ASR state: `Get-MpPreference | Select -ExpandProperty AttackSurfaceReductionRules_Ids, AttackSurfaceReductionRules_Actions`.\n- Enable common rules in audit first; deploy in enforced after tuning.\n\n### Smart Screen\n\n- Windows:\n  - Analyzes files and websites for suspicious characteristics.\n  - Warns or blocks potentially malicious content.\n\n### Controlled Folder Access\n\n- Windows:\n  - Protects files and folders from unauthorized changes.\n  - Helps prevent ransomware from encrypting or deleting data.\n\n## File System and Data Protections\n\n### Filesystem Protections (fs-verity & fscrypt)\n\n- Linux:\n  - fs-verity: Provides integrity protection for read-only files.\n  - fscrypt: Enables filesystem-level encryption for data at rest.\n\n### BitLocker Drive Encryption\n\n- Windows:\n  - Full disk encryption to protect data at rest.\n  - Uses TPM and user credentials for encryption keys.\n\n### Integrity Measurement Architecture (IMA) \u002F Extended Verification Module (EVM)\n\n- Linux:\n  - Provides runtime integrity checking for files and metadata based on stored hashes.\n  - Ensures files haven't been tampered with post-boot.\n\n## Access Control and Attack Surface Reduction\n\n### Strict Syscall Filtering (Seccomp)\n\n- Linux:\n  - Allows applications to restrict system calls they can invoke.\n  - Reduces the kernel's attack surface from user-space applications.\n- Seccomp user‑notifier:\n  - Enables broker‑style decisions in userspace; defend against confused‑deputy by strict validation and time‑bounded decisions\n  - Attackers may abuse notifier latency for TOCTOU races; keep policies minimal and deterministic\n\n#### Practitioner\n\n- Inspect running process seccomp: `grep Seccomp \u002Fproc\u002F\u003Cpid>\u002Fstatus` (0=disabled, 1=strict, 2=filter).\n- Use `seccomp-tools dump \u003Cpid>` to view filters; in containers, inspect OCI seccomp profile.\n\n### Container Security Mitigations\n\n- **User Namespaces**:\n  - Isolates user and group IDs between host and container.\n  - Provides privilege isolation without requiring root on the host.\n  - Maps container root (UID 0) to unprivileged user on host.\n\n- **PID Namespaces**:\n  - Isolates process IDs, preventing container processes from seeing host processes.\n  - Container init process becomes PID 1 within its namespace.\n\n- **Network Namespaces**:\n  - Provides isolated network stack (interfaces, routing tables, firewall rules).\n  - Prevents network-based container escape attacks.\n\n- **Mount Namespaces**:\n  - Isolates filesystem view, preventing access to host filesystem.\n  - Combined with chroot-like restrictions and read-only mounts.\n\n- **Capability Dropping**:\n  - Removes dangerous Linux capabilities from container processes.\n  - Examples: `CAP_SYS_ADMIN`, `CAP_NET_ADMIN`, `CAP_SYS_MODULE`.\n\n- **Seccomp Profiles**:\n  - Restricts system calls available to containerized processes.\n  - Default Docker\u002FPodman profiles block ~44 dangerous syscalls.\n\n- **AppArmor\u002FSELinux Profiles**:\n  - Mandatory Access Control for container processes.\n  - Restricts file access, network operations, and capabilities.\n\n#### Container hardening quick test\n\n```bash\ndocker inspect \u003Cctr> | jq '.[0].HostConfig.SecurityOpt, .[0].HostConfig.CapDrop'\ncapsh --print\nlsns | grep \" $(cat \u002Fproc\u002Fself\u002Fns\u002Fpid) \\|net\\|mnt\\|user\\|ipc\\|uts\"\ngrep Seccomp \u002Fproc\u002F$$\u002Fstatus\nid -Z 2>\u002Fdev\u002Fnull || echo \"No SELinux context\"\n```\n\n#### Bypass Techniques\n\n- **Namespace Escapes**: Exploiting kernel bugs in namespace implementations.\n- **Capability Abuse**: Leveraging remaining capabilities (e.g., `CAP_DAC_OVERRIDE`) for privilege escalation.\n- **Seccomp Bypasses**: Finding allowed syscalls that can be chained for exploitation.\n- **Container Runtime Exploits**: Targeting Docker\u002Fcontainerd\u002Frunc vulnerabilities.\n- **Host Resource Access**: Exploiting mounted host resources (sockets, devices, filesystems).\n- **Privileged Containers**: Targeting containers running with `--privileged` flag.\n\n#### Practitioner\n\n- Check container mitigations: `docker inspect \u003Ccontainer>` or `podman inspect \u003Ccontainer>`\n- Audit capabilities: `capsh --print` inside container\n- List namespaces: `lsns` or `ls -la \u002Fproc\u002F$$\u002Fns\u002F`\n- Seccomp status: `grep Seccomp \u002Fproc\u002F$$\u002Fstatus`\n- SELinux context: `id -Z` (if SELinux enabled)\n- **Container security scanning**: Tools like `docker-bench-security`, `kube-bench`\n\n### Lockdown Mode\n\n- Linux:\n  - Restricts access to kernel features that could allow code execution.\n  - Enhances security, especially with Secure Boot enabled.\n  - **Linux 6.14** extends lockdown to cover kexec‑file pinning and loads the built‑in module blocklists earlier, further closing BYOVD avenues.\n\n### Executable‑policy Securebits\n\n- **Linux 6.14:** Introduces `SECBIT_EXEC_RESTRICT_FILE` and `SECBIT_EXEC_DENY_INTERACTIVE` securebits together with the `AT_EXECVE_CHECK` flag, allowing interpreters to delegate final execution‑permission checks to the kernel and tightening script\u002Floader abuse paths.\n\n### NTSYNC Driver Hardening\n\n- **Linux 6.14:** The new `ntsync` driver offers an `io_uring`‑based fast‑path that removes classic futex primitives from reachable attack surface, reducing user→kernel synchronization abuse.\n\n### Landlock LSM\n\n- Linux:\n  - Unprivileged sandboxing framework allowing processes to restrict their own access rights.\n  - Reduces the impact of compromised user-space applications.\n\n### AppContainer and User Account Control (UAC)\n\n- Windows:\n  - AppContainer: Application isolation for modern apps.\n  - UAC: Limits application privileges, prompting for elevation when necessary.\n\n### PatchGuard (KPP)\n\n- Windows:\n  - Protects the kernel from modifications of critical structures and registers.\n  - Periodically checks for unauthorized modifications to kernel structures.\n  - Asynchronously monitors critical structures: IDT, GDT, SSDT, MSRs, kernel stacks\n  - Triggers `CRITICAL_STRUCTURE_CORRUPTION` BSOD (0x109) when tampering detected\n  - **Modern impact**: Blocks classic SSDT\u002FIDT hooking on Windows 10\u002F11\n\n#### Bypass Techniques\n\n- **Bootkit Deployment**: Bypassing protection at boot time before PatchGuard initializes.\n- **Debugging Bypass**: PatchGuard doesn't run if a debugger is attached at boot.\n- **Timing Attacks**: Taking advantage of the periodic nature of PatchGuard checks.\n- **Memory Manipulation**: Modifying kernel memory without triggering detection mechanisms.\n- **Hypervisor-based**: Type 1 hypervisor using EPT to hide kernel modifications\n\n### Windows Sandbox\n\n- Windows:\n  - Provides a disposable virtual environment.\n  - Runs untrusted software isolated from the host system.\n\n### Module Signing Enforcement\n\n- Linux\u002FWindows:\n  - Code signing for kernel modules\n  - Prevents loading of unsigned or maliciously modified kernel components\n\n### Block Remote Images\n\n- Windows:\n  - Prevents loading DLLs from UNC file paths (e.g., \\\\\\\\evilsite\\\\bad.dll).\n  - Blocks attackers from bypassing ASLR by loading non-rebased modules.\n\n### Block Untrusted Fonts\n\n- Windows:\n  - Only loads fonts from trusted locations.\n  - Prevents attacks like Stuxnet that exploit font rendering vulnerabilities in kernel mode.\n\n### Validate Handle Usage\n\n- Windows:\n  - Checks handle references to ensure they are valid.\n  - Prevents exploitation of handle misuse.\n\n### Disable Extension Points\n\n- Windows:\n  - Blocks registry-based extension points like AppInit_DLL.\n  - Prevents hooking or extending applications through known extension mechanisms.\n\n### Disable Win32k System Calls\n\n- Windows:\n  - Disables unused system calls to reduce attack surface.\n  - Particularly effective against kernel exploits.\n\n### Do Not Allow Child Processes\n\n- Windows:\n  - Blocks the ability for a process to call the CreateProcess function.\n  - Prevents malware from spawning additional processes (also known as \"Calc Killer\").\n\n### Validate Image Dependency\n\n- Windows:\n  - Requires any DLL loaded by a process to be signed by Microsoft.\n  - Prevents DLL side-loading attacks.\n\n### Block Low Integrity Images\n\n- Windows:\n  - Blocks processes running at low or untrusted integrity levels from loading downloaded files.\n  - Enhances sandbox security.\n\n### Usermode Helper (UMH) Mitigations\n\n- Linux:\n  - CONFIG_STATIC_USERMODEHELPER: Forces all usermode helper calls through a static binary.\n  - CONFIG_STATIC_USERMODEHELPER_PATH: Sets the path to the static usermode helper binary.\n  - Prevents attackers from abusing kernel-to-userspace execution paths.\n  - Requires userspace support.\n\n### SMB Signing\n\n- Windows:\n  - Adds cryptographic signatures to Server Message Block (SMB) packets.\n  - Prevents man-in-the-middle attacks against network file sharing.\n\n## Hardware-Assisted Security Features\n\n### Trusted Platform Module (TPM) 2.0\n\n- Windows\u002FLinux:\n  - Secure crypto-processor enhancing hardware security.\n  - Used for secure boot, disk encryption, and credentials.\n\n### Secure Boot\n\n- Windows\u002FLinux:\n  - Ensures only trusted, signed software loads during boot.\n  - Prevents boot-level malware from starting before the OS.\n\n### UEFI Firmware Security\n\n- Windows\u002FLinux:\n  - Provides a secure pre-OS environment.\n  - Supports Secure Boot and firmware integrity checking.\n\n## Diagrams\n\n### Modern Security Architecture\n\n```mermaid\nflowchart TB\n    System[\"System Security\"]\n\n    subgraph \"Memory Protection\"\n        KASLR[\"Kernel ASLR\"]\n        KPTI[\"Kernel Page Table Isolation\"]\n        SMAP[\"Supervisor Mode Access Prevention\"]\n        SMEP[\"Supervisor Mode Execution Prevention\"]\n        KDP[\"Kernel Data Protection\"]\n        RODATA[\"Read-Only Data Sections\"]\n    end\n\n    subgraph \"Virtualization Security\"\n        VBS[\"Virtualization-Based Security\"]\n        HVCI[\"Hypervisor-Enforced Code Integrity\"]\n        MBEC[\"Mode-Based Execution Control\"]\n        KMCI[\"Kernel Mode Code Integrity\"]\n    end\n\n    subgraph \"Control Flow Protection\"\n        CFG[\"Control Flow Guard\"]\n        CET[\"Control-Flow Enforcement Technology\"]\n        KCFG[\"Kernel Control Flow Guard\"]\n    end\n\n    System --> KASLR\n    System --> KPTI\n    System --> SMAP\n    System --> SMEP\n    System --> KDP\n    System --> RODATA\n    System --> VBS\n    System --> HVCI\n    System --> MBEC\n    System --> KMCI\n    System --> CFG\n    System --> CET\n    System --> KCFG\n```\n\n### Virtualization-Based Security Stack\n\n```mermaid\nflowchart TB\n    Hardware[\"Hardware (CPU with Virtualization Support)\"]\n    Hypervisor[\"Hypervisor (Hyper-V)\"]\n    VTL1[\"VTL1 (Secure Kernel)\"]\n    VTL0[\"VTL0 (Normal Windows Kernel)\"]\n    Apps[\"User Applications\"]\n\n    Hardware --> Hypervisor\n    Hypervisor --> VTL1\n    Hypervisor --> VTL0\n    VTL0 --> Apps\n\n    subgraph \"Secure World\"\n        VTL1\n        SecureServices[\"Secure Services\"]\n        CredGuard[\"Credential Guard\"]\n        KMCI[\"Kernel Mode Code Integrity\"]\n    end\n\n    VTL1 --> SecureServices\n    VTL1 --> CredGuard\n    VTL1 --> KMCI\n```\n\n### Exploit Mitigation Evolution\n\n```mermaid\nflowchart LR\n    ClassicMitigations[\"Classic Mitigations\"]\n    ModernMitigations[\"Modern Mitigations\"]\n    FutureMitigations[\"Future Mitigations\"]\n\n    subgraph \"2000s\"\n        DEP[\"DEP\u002FNX\"]\n        ASLR[\"ASLR\"]\n        Stack[\"Stack Cookies\"]\n        SafeSEH[\"SafeSEH\"]\n    end\n\n    subgraph \"2010s\"\n        CFG[\"Control Flow Guard\"]\n        VBS[\"Virtualization-Based Security\"]\n        HVCI[\"HVCI\"]\n        WDAC[\"WDAC\"]\n    end\n\n    subgraph \"2020s+\"\n        CET[\"CET Shadow Stack\"]\n        MTE[\"Memory Tagging\"]\n        CFI[\"Full CFI\"]\n    end\n\n    ClassicMitigations --> DEP\n    ClassicMitigations --> ASLR\n    ClassicMitigations --> Stack\n    ClassicMitigations --> SafeSEH\n\n    ModernMitigations --> CFG\n    ModernMitigations --> VBS\n    ModernMitigations --> HVCI\n    ModernMitigations --> WDAC\n\n    FutureMitigations --> CET\n    FutureMitigations --> MTE\n    FutureMitigations --> CFI\n```\n",{"name":5,"domain":23,"description":7},"main","a91f1293287ffa9f4f1b8f486cd6e835a1568c84","skills\u002Foffensive-mitigations","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace","https:\u002F\u002Fgithub.com\u002FDCx7C5","#Python","2026-09-01 11:21:00",{"source":8,"skillName":5,"commands":41,"prompt":51,"zipAvailable":52},[42,45,48],{"tool":43,"command":44},"npx","npx skills add DCx7C5\u002Fai-marketplace --skill offensive-mitigations",{"tool":46,"command":47},"bunx","bunx skills add DCx7C5\u002Fai-marketplace --skill offensive-mitigations",{"tool":49,"command":50},"pnpm","pnpm dlx skills add DCx7C5\u002Fai-marketplace --skill offensive-mitigations","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Foffensive-mitigations\u002FSKILL.md",true,[54],{"path":55,"resourceType":56,"resourceTypeDesc":57,"sizeBytes":58,"sourceHtmlUrl":59},"index.json","REFERENCE","参考文档",517,"https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Foffensive-mitigations\u002Findex.json",[61,86,109,131,153,169],{"skillNo":62,"name":63,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":28},"01M71HAPZ01KQ30RKTB0FFSQ05","services-wmi-persistence-detect","Detect WMI event subscription persistence by enumerating ActiveScriptEventConsumer, CommandLineEventConsumer, and permanent subscriptions in the WMI repository.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fservices\u002Fwmi\u002Fpersistence\u002Fdetect\u002FSKILL.md",[],[68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,23,85],"services","detect","services wmi persistence detect","wmi","persistence","de","cm","process","activescript","event","subscriptions","commandline-consumer","repository","subscription","event-subscription","t1546.003","forensics","process-forensics",{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":28},"01M71HAK6JTTTS229T17WJMMCG","services-wmi-exec-exploit","Perform lateral movement across Windows networks using WMI-based remote execution techniques including Impacket wmiexec.py, CrackMapExec, and native WMI commands for stealthy post-exploitation during red team engagements.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fservices\u002Fwmi\u002Fexec\u002Fexploit\u002FSKILL.md",[],[93,68,94,71,95,96,97,23,98,99,100,101,102,103,73,104,105,106,107,108],"exploit","services wmi exec exploit","exec","remote","traffic","Bash","analysis","team","across","crackmapexec","native","command","lateral movement","read","lateral-movement","Impacket",{"skillNo":110,"name":111,"nameZh":6,"description":112,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":113,"categories":114,"keywords":115,"publishedAt":28},"01M71HAG6MHKNQV8KDZKMT4886","registry-artifact-extract","Extract and analyze Windows Registry hives to uncover user activity, installed software, autostart entries, and evidence of system compromise.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fregistry\u002Fartifact\u002Fextract\u002FSKILL.md",[],[116,117,118,119,120,121,23,98,122,99,123,124,73,106,125,126,127,128,129,130],"artifact","registry","registry artifact extract","extract","evidence-collection","artifact-analysis","collection","analyze","uncover","software","activity","digital-forensics","windows-registry","regripper","sonnet",{"skillNo":132,"name":133,"nameZh":6,"description":134,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":135,"categories":136,"keywords":137,"publishedAt":28},"01M71HACR4A8XTWTTSXK4124AA","processes-token-impersonate-detect","Detect Windows token impersonation and privilege abuse including SeImpersonatePrivilege exploitation via Potato attacks and token stealing techniques.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fprocesses\u002Ftoken\u002Fimpersonate\u002Fdetect\u002FSKILL.md",[],[69,138,139,140,141,142,143,74,144,23,85,145,146,147,148,149,150,151,152,73],"processes token impersonate detect","token","processes","attacks","windows","escalation","techniques","privilege-escalation","seimpersonate","token-impersonation","printspoofer","exploitation","potato","impersonation","via",{"skillNo":154,"name":155,"nameZh":6,"description":156,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":157,"categories":158,"keywords":159,"publishedAt":28},"01M71HAABSB4Z6QFSXEG00R4RK","processes-thread-injection-detect","Detect Windows thread injection techniques including CreateRemoteThread, QueueUserAPC, NtCreateThreadEx, and thread hijacking via process memory analysis.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fprocesses\u002Fthread\u002Finjection\u002Fdetect\u002FSKILL.md",[],[160,161,69,162,140,142,163,74,164,144,23,85,99,165,166,167,168,152,73,75],"thread","processes thread injection detect","injection","memory","process-injection","api","apc-injection","thread-injection","nt-api",{"skillNo":170,"name":171,"nameZh":6,"description":172,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":173,"categories":174,"keywords":175,"publishedAt":28},"01M71HA7H311V5G14WMX58HQSS","processes-hollow-technique-detect","Detect process hollowing (RunPE) by identifying processes with mismatched image paths between PEB and VAD tree, or unmapped PE headers in memory.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fprocesses\u002Fhollow\u002Ftechnique\u002Fdetect\u002FSKILL.md",[],[176,69,140,177,163,74,178,179,23,85,180,181,182,183,184,185,73,75,186,187],"processes hollow technique detect","tree","memory-forensics","process-hollow","peb","runpe","image","pe-header","in memory","with","mismatched","headers"]