diff --git a/.env.example b/.env.example index 841a36b..dcd234e 100755 --- a/.env.example +++ b/.env.example @@ -111,3 +111,43 @@ TYPESAFE_API_KEY= # # (For blind classes β€” SSRF/XXE/blind RCE β€” pass an out-of-band domain you # control with the --oob-domain flag; without it those are reported as leads.) + +# ------------------------------------------------------------------ +# Run logs β†’ OpenSearch (OPTIONAL). One index per project/customer/domain. +# `docker compose -f docker-compose.opensearch.yml up -d` then: +# neurosploit logs ping +# neurosploit logs push --project acme +#OPENSEARCH_URL=http://127.0.0.1:9200 +#OPENSEARCH_USERNAME= +#OPENSEARCH_PASSWORD= +# Index template; {project} and {date} are substituted. +#OPENSEARCH_INDEX=ns-{project} +# Set to 0 only for a self-signed local endpoint. +#OPENSEARCH_VERIFY_TLS=1 +# Default project label when --project is omitted. +#NS_LOG_PROJECT= + +# ------------------------------------------------------------------ +# Public tunnel for OOB callbacks and webshells (OPTIONAL). ngrok only needs +# the authtoken; `neurosploit tunnel --port 8080` starts the tunnel and a +# local HTTP sink that records callbacks. +#NGROK_AUTHTOKEN= +#NEUROSPLOIT_TUNNEL_PORT=8080 +#NEUROSPLOIT_TUNNEL_BIND=127.0.0.1 + +# ------------------------------------------------------------------ +# Output budgets. These are ceilings, not usage. Raise/lower per provider. +#NEUROSPLOIT_MAX_TOKENS= +#NEUROSPLOIT_CMD_CAP=1048576 +#NEUROSPLOIT_C2_OUTPUT_CAP=524288 + +# ------------------------------------------------------------------ +# Universal completion cache (ON by default). Identical prompts to the same +# model are served from memory/disk instead of paid again. +#NEUROSPLOIT_CACHE=on +#NEUROSPLOIT_CACHE_TTL_SECS=604800 +# Namespace the cache per engagement (default: current directory). +#NEUROSPLOIT_CACHE_SCOPE= + +# Self-improvement review: cheap model used by `neurosploit improve`. +#NEUROSPLOIT_IMPROVE_MODEL=deepseek:deepseek-chat diff --git a/README.md b/README.md index c817d16..6b1391e 100755 --- a/README.md +++ b/README.md @@ -1,247 +1,224 @@ -

🧠 NeuroSploit v4.4.3

+
-

- Stars - Forks - Issues -

+NeuroSploit -

- - - - - -

+# NeuroSploit -

- Website - Docs -

+**Autonomous penetration-testing harness β€” Rust, multi-model, CLI-first.** -

Autonomous, multi-model penetration-testing harness β€” Rust, CLI-first.
-by Joas A Santos & Red Team Leaders

+[![Stars](https://img.shields.io/github/stars/JoasASantos/NeuroSploit?style=for-the-badge&logo=github&color=8b5cf6)](https://github.com/JoasASantos/NeuroSploit/stargazers) +[![Forks](https://img.shields.io/github/forks/JoasASantos/NeuroSploit?style=for-the-badge&logo=github&color=a855f7)](https://github.com/JoasASantos/NeuroSploit/network/members) +[![Issues](https://img.shields.io/github/issues/JoasASantos/NeuroSploit?style=for-the-badge&color=22d3ee)](https://github.com/JoasASantos/NeuroSploit/issues) + +
+ +[![Rust](https://img.shields.io/badge/Rust-tokio%20async-e6b673?style=flat-square&logo=rust)](https://www.rust-lang.org) +[![License](https://img.shields.io/badge/License-MIT-green?style=flat-square)](LICENSE) +[![Agents](https://img.shields.io/badge/MD%20Agents-486-red?style=flat-square)](agents_md/) +[![Modes](https://img.shields.io/badge/Modes-8-9cf?style=flat-square)](#modes) +[![MCP Profiles](https://img.shields.io/badge/MCP%20Profiles-12-f59e0b?style=flat-square)](#mcp-profiles) +[![Providers](https://img.shields.io/badge/LLM%20Providers-19-38bdf8?style=flat-square)](#providers) + +
+ +[**Website**](https://neurosploitai.github.io/) Β· [**Docs & Tutorial**](https://neurosploitai.github.io/docs.html) Β· [**TUTORIAL.md**](TUTORIAL.md) Β· [**BENCHMARK.md**](BENCHMARK.md) + +
--- ## What is NeuroSploit? -**NeuroSploit is an autonomous penetration-testing tool.** You point it at a -target; it does the security assessment on its own and hands you a report β€” -recon, exploitation, chaining findings into real impact, and validation, with no -human driving each step. +Point it at a target. It runs the security assessment autonomously and hands you a report β€” recon, exploitation, chaining, validation β€” no human driving each step. -The key idea: **the harness is the pentester, not the model.** Instead of asking -one LLM to "hack this", a Rust engine runs the methodology β€” it picks the right -specialist agents for what it finds, runs them in parallel, re-sends every claim -over the wire to confirm it's real, and has a second model check each finding -before it's reported. The LLMs are the hands; the harness is the discipline that -keeps them honest. That's why it finds more and invents less than running a model -directly. +**The harness is the pentester, not the model.** A Rust engine runs the methodology: picks specialist agents for what it finds, runs them in parallel, re-sends every claim over the wire to confirm it's real, and has a second model check each finding before reporting. The LLMs are the hands; the harness is the discipline. -It's **CLI-first** (with a web console and a TUI), **open source (MIT)**, and runs -on **your own API keys or a local subscription** β€” nothing about your targets -leaves your machine unless you send it. +``` +recon ─▢ select agents ─▢ exploit in parallel ─▢ wire-check ─▢ cross-model vote ─▢ chain ─▢ report +``` --- -Give NeuroSploit a **URL, a source repo, a running app, or a host/IP**. A Rust -harness (`tokio`) drives a **pool of LLMs** β€” via **API key** or local -**subscription** (Claude Code / Codex / Gemini / Grok) β€” and runs the whole -engagement for you: - -``` -recon ─▢ pick only the agents that fit the surface ─▢ exploit in parallel - ─▢ wire-check every claim ─▢ cross-model vote ─▢ chain into deeper impact ─▢ report -``` - -It won't invent findings: **every claim needs a receipt** (raw tool output or a -`file:line`), is **re-sent by the harness itself** to confirm it reproduces, and -is adjudicated by a **second model** before it reaches the report. - -> ⭐ Useful? **Star the repo.** -> 🌐 Website & live docs: **[neurosploitai.github.io](https://neurosploitai.github.io/)** Β· **[Tutorial & Guide](https://neurosploitai.github.io/docs.html)** -> πŸ“– Deep dive: **[TUTORIAL.md](TUTORIAL.md)** Β· changelog: **[RELEASE.md](RELEASE.md)** Β· honest comparison: **[BENCHMARK.md](BENCHMARK.md)** - ## Install -**Linux / macOS** (x64 & arm64): ```bash +# Linux / macOS (x64 & arm64) curl -fsSL https://raw.githubusercontent.com/JoasASantos/NeuroSploit/main/setup.sh | bash -``` -**Windows** (PowerShell): -```powershell + +# Windows (PowerShell) irm https://raw.githubusercontent.com/JoasASantos/NeuroSploit/main/install.ps1 | iex -``` -The installer sets up Rust if missing, builds the release binary, and links -`neurosploit` onto your PATH. Build by hand instead: -```bash + +# From source git clone https://github.com/JoasASantos/NeuroSploit && cd NeuroSploit/neurosploit-rs cargo build --release # β†’ target/release/neurosploit ``` -## Quick start +## Quick Start ```bash -# just run it β€” the interactive session asks everything, in plain language: +# Interactive wizard (asks everything): neurosploit -# black-box, subscription login (no API key): -neurosploit run http://testphp.vulnweb.com/ --subscription --model anthropic:claude-opus-4-8 -v +# Black-box with subscription: +neurosploit run http://target.com --subscription --model anthropic:claude-opus-4-8 -v -# white-box β€” review a source repo (file:line evidence): +# White-box source review: neurosploit whitebox /path/to/repo --subscription --model anthropic:claude-opus-4-8 -v -# web console β€” a browser UI over the same CLI: -cd web && npm start # β†’ http://localhost:4173 +# Host / AD / infra: +neurosploit host 10.0.0.5 --subscription --model anthropic:claude-opus-4-8 -v + +# Web console: +cd web && npm start # β†’ http://localhost:3000 ``` -No subscription? Use an **API key** for any provider instead β€” see [TUTORIAL.md](TUTORIAL.md#authentication). +--- ## Modes -| Mode | Command | What it does | -|------|---------|-------------| -| **Black-box** | `neurosploit run ` | recon β†’ select β†’ exploit β†’ vote β†’ report | -| **White-box** | `neurosploit whitebox ` | source / SAST review (file:line evidence) | -| **Grey-box** | `neurosploit greybox --url ` | code review **+** live exploitation together | -| **Host / Infra** | `neurosploit host --creds creds.yaml` | Linux / Windows / AD + cloud (AWS/GCP/Azure) | -| **AI / LLM** | `neurosploit aitest ` | jailbreaks, prompt injection, OWASP LLM Top 10 / MCP | -| **Mobile / Binary** | `neurosploit mobile ` | RE a local artifact (Ghidra / MobSF / Frida) | -| **Container** | `neurosploit container ` | OCI image scan + SBOM (trivy/grype/syft) | -| **Mission Control** | `neurosploit tui ` | live TUI panels + a composer you type in mid-run | +| Mode | Command | Surface | +|:-----|:--------|:--------| +| **Black-box** | `neurosploit run ` | Web apps, APIs β€” recon β†’ exploit β†’ vote β†’ report | +| **White-box** | `neurosploit whitebox ` | Source / SAST review (`file:line` evidence) | +| **Grey-box** | `neurosploit greybox --url ` | Code review **+** live exploitation | +| **Host / Infra** | `neurosploit host ` | Linux, Windows, AD, cloud (AWS/GCP/Azure) | +| **AI / LLM** | `neurosploit aitest ` | Jailbreaks, prompt injection, OWASP LLM Top 10 | +| **Mobile** | `neurosploit mobile ` | APK/IPA RE (Ghidra / MobSF / Frida) | +| **Container** | `neurosploit container ` | OCI scan + SBOM (trivy/grype/syft) | +| **Mission Control** | `neurosploit tui ` | Live TUI with mid-run composer | -## Add-ons: Toolbox, MCP tool servers, C2 & WebShells +--- -- **Toolbox (225 tools, opt-in).** Run the right pentest tool instead of only - curl/scripts: nmap, rustscan, httpx, nuclei, ffuf, netexec, impacket, - bloodhound, trivy, apktool, ghidra and more. `neurosploit tools list` / - `run nmap --target 10.0.0.5`; `--tools` gives agents the doctrine and - `--agent-tools` lets API models request cataloged tools in a bounded loop. -- **MCP tool servers.** Curated nmap / Kali / Playwright / Burp / REA templates: - `neurosploit tools mcp add nmap`, then run with `--mcp`. -- **C2 & WebShell management (authorized internal engagements only).** Disabled - by default; enabling requires an authorization reference. Listeners, sessions, - tasks, payloads, persistence/lateral opt-ins, WebShell exec/file ops, and an - append-only audit trail under `.neurosploit/c2/`. +## Architecture -See [`docs/TOOLBOX.md`](docs/TOOLBOX.md) for guardrails and the full surface. +``` +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ NeuroSploit Harness β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ Recon │─▢│ Select │─▢│ Parallel │─▢│ Validate β”‚ β”‚ +β”‚ β”‚ Engine β”‚ β”‚ 486 MDs β”‚ β”‚ Exploit β”‚ β”‚ Wire+Vote β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ +β”‚ β–Ό β–Ό β–Ό β–Ό β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ Attack Knowledge Graph (Neo4j opt.) β”‚ β”‚ +β”‚ β”‚ Host β†’ Service β†’ Finding β†’ Credential β†’ Impact β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β”‚ β”‚ β”‚ β”‚ +β”‚ β–Ό β–Ό β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ Chain β”‚ β”‚ Report β”‚ β”‚ +β”‚ β”‚ Engine β”‚ β”‚ HTMLΒ·PDFΒ·MDβ”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ +β”‚ LLM Pool: Claude Β· GPT Β· Gemini Β· Grok Β· GLM Β· DeepSeek β”‚ +β”‚ Qwen Β· Kimi Β· Mistral Β· Ollama Β· LiteLLM Β· 19 providers β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` -## What makes it different +--- -- **The harness is the pentester.** Agent selection is recon-driven; findings - **chain** (reduce a foothold to a primitive β€” exec / read / write / SSRF / - identity / secret β€” then pivot), each stage proven and non-destructive. -- **Wire-bound evidence** β€” every reported exchange is re-sent through a - scope-guarded replay engine and checked against recorded traffic. A claim the - wire contradicts can't stand as confirmed. -- **Attack knowledge graph (Neo4j optional)** β€” the run is a typed graph of - hosts, services, findings, credentials and impact, spanning **web and internal - network**. It directs the next move during the run and is written to `graph/` - even without a database. -- **Deterministic validation** β€” per-CWE validators judge the measured - request/response bytes, not the model's prose. Grounding gate, POMDP belief and - an anti-hallucination check demote anything the evidence doesn't support. -- **Secrets never leak the report** β€” credentials the agents observe become - `$SECRET_n` in every human-facing report; raw values stay in the run's vault for - re-testing only. -- **Execution resilience** β€” classified error handling (7 error types), exponential - backoff (5 retries, 2s–90s), crash-state salvage (partial findings survive agent - failure), agent lifecycle nudge (3 retries with simplified prompts), progressive - budget warnings (70/85/95%), and run snapshot/resume so interrupted engagements - pick up where they left off. -- **LLM-powered dedup** β€” deterministic fast-path for exact matches, plus a - semantic LLM judge for findings with different wording but the same root cause. -- **486 markdown agents** across web, code (SAST), AI, infra/AD/cloud, chains and - recon β€” each a self-contained playbook you can read, edit or add to. -- **Run via API key or subscription**, 19 providers, including local & CPU-only - (`ollama:` / `llamacpp:`) with no data leaving the host. +## MCP Profiles -## Web console +Built-in profiles swap the tool surface at runtime: + +| Profile | Tools | Use Case | +|:--------|:------|:---------| +| `Web` | Playwright browser automation | Web app testing | +| `MobileAndroid` / `MobileIos` | REA reverse engineering | APK/IPA analysis | +| `BinaryAnalysis` | REA decompiler, call graphs | Native binary RE | +| `BurpSuite` | Burp REST API | Proxy-driven testing | +| `CobaltStrike` | Official CS MCP (team server) | C2 integration | +| `Infra` / `Nmap` | Nmap MCP server | Network discovery | +| `AD` / `Kali` | Kali MCP (80+ tools) | AD / full toolkit | +| `Cloud` | Trivy, Prowler, ScoutSuite | Cloud posture | ```bash -cd web && npm start # β†’ http://localhost:4173 +neurosploit run http://target.com --mcp-profile web +neurosploit host 10.0.0.5 --mcp-profile ad ``` -A browser UI that drives the **same CLI** β€” no second engine. Launch and watch a -run live, then per finding: -- **Attack graph** β€” host β†’ service β†’ finding β†’ credential β†’ impact, every edge - marked confirmed / needs-validation / hypothesis, ordered by kill-chain stage. -- **Wire evidence** β€” the real request/response pairs behind a finding (baseline - vs. attack, the identity pair, matrix probes, the oracle), each tagged with its - wire provenance β€” the proof as bytes, not prose. -- **Re-test one finding** β€” re-run its proof through the replay engine; the dated - history shows a finding drift to "gone" over time. -- **Transcript viewer** β€” any agent's run, split into navigable blocks; search - spans every agent. -- Chains, dependency todolist, recorded traffic, deliverables, PDF export. +--- -## What a run leaves behind +## Toolbox & C2 -Every run is a self-contained folder, `runs/ns--/`: +- **Toolbox (225 tools):** nmap, rustscan, httpx, nuclei, ffuf, netexec, impacket, bloodhound, trivy, apktool, ghidra and more. `neurosploit tools list` +- **MCP servers:** `neurosploit tools mcp add nmap` then `--mcp` +- **C2 & WebShell:** Authorized engagements only. Listeners, sessions, tasks, payloads, audit trail under `.neurosploit/c2/` +- **Pivot Proxy:** Multi-hop tunnel engine through compromised hosts β€” portproxy, chisel, SOCKS. `--pivot-proxy auto` + +--- + +## What Makes It Different + +| Feature | How | +|:--------|:----| +| **Wire-bound evidence** | Every claim re-sent through scope-guarded replay engine | +| **Attack knowledge graph** | Typed graph: hosts, services, findings, credentials, impact | +| **Per-CWE validators** | Deterministic judgment on measured bytes, not prose | +| **Secret redaction** | Credentials become `$SECRET_n` in reports; raw in vault only | +| **Execution resilience** | 7 error types, exponential backoff, crash-state salvage, resume | +| **LLM-powered dedup** | Fast-path exact + semantic judge for same root cause | +| **Multi-hop pivoting** | Auto-detect unreachable subnets, establish tunnel chains | +| **Universal cache** | Identical prompts served from memory/disk β€” token savings | + +--- + +## Providers + +19 LLM providers supported β€” API key or local subscription: + +`anthropic` Β· `openai` Β· `gemini` Β· `azure` Β· `xai` Β· `nvidia_nim` Β· `deepseek` Β· `mistral` Β· `qwen` Β· `zai` Β· `moonshot` Β· `groq` Β· `together` Β· `openrouter` Β· `opencode` Β· `nous` Β· `ollama` Β· `litellm` + +Multi-model voting: `--model anthropic:claude-opus-4-8 --model openai:gpt-5.1 --vote-n 3` + +--- + +## Web Console + +```bash +cd web && npm start # β†’ http://localhost:3000 +``` + +- **Attack graph** β€” host β†’ service β†’ finding β†’ credential β†’ impact, with clickable filters +- **Wire evidence** β€” real request/response pairs with wire provenance +- **Re-test** β€” re-run proof through replay engine +- **Chains & todo** β€” attack chains with validation status +- **Transcript viewer** β€” per-agent run split into navigable blocks +- **PDF export** β€” via Typst + +--- + +## Run Output + +Every run β†’ `runs/ns--/`: | File | Contents | -|------|----------| -| `report.html` Β· `report.pdf` Β· `report.md` | the report (PDF via Typst), secrets redacted | -| `findings.json` / `findings.md` | validated findings (raw, for tools & re-testing) | +|:-----|:---------| +| `report.html` Β· `.pdf` Β· `.md` | Report (PDF via Typst), secrets redacted | +| `findings.json` / `.md` | Validated findings for tooling & 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 | +| `graph/` | Attack chains, todo, Cypher + JSON export | +| `attack-paths.json` Β· `.mmd` | Cross-domain paths (graph + Mermaid) | +| `loot.json` | Credentials, tokens, hosts, endpoints | +| `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`), -`@neurosploit` mention bot, one Jira card per finding, MCP server -(`neurosploit mcp`), compliance mapping (PCI-DSS / HIPAA / SOC 2 / GDPR). See -**[TUTORIAL.md](TUTORIAL.md)**. +GitHub / GitLab PR review gate Β· `@neurosploit` mention bot Β· Jira cards per finding Β· MCP server (`neurosploit mcp`) Β· Compliance mapping (PCI-DSS / HIPAA / SOC 2 / GDPR) Β· Neo4j graph Β· OpenSearch logs + +--- ## Safety -For **authorized** testing only. Agents stay in scope, never run destructive / DoS -actions, and require proof of exploitation. You are responsible for having -permission for every target. +For **authorized** testing only. Agents stay in scope, never run destructive/DoS actions, and require proof of exploitation. You are responsible for having permission for every target. -## Credits & license +--- -**Joas A Santos** & **Red Team Leaders** β€” MIT. +
-> This is the slim, **Rust-only** distribution (`neurosploit-rs/` + `agents_md/`). -> The older Python engine and web GUIs live on the `v3.4.0` branch. +**Joas A Santos** & **Red Team Leaders** β€” MIT License + +
diff --git a/STAGING-upgrades.md b/STAGING-upgrades.md new file mode 100644 index 0000000..e642810 --- /dev/null +++ b/STAGING-upgrades.md @@ -0,0 +1,108 @@ +# NeuroSploit β€” Staged Upgrades (APPLY ONLY AFTER CURRENT RUN CLOSES) + +## PROGRESS (2026-11-21) +- Run 1 `ns-1795270602` CLOSED at round 4/6, ~$36 β€” Forest01 owned (APP-DMZ01 local admin, SQL01 RCE/SeImpersonate, S4U Administratorβ†’FS01, AS-REP/kerberoast, constrained delegation) + DMZ root. **VANGUARD NOT reached** β€” DCSync blocked by double-forward tunnel mangling DRSUAPI. Neo4j 1214 nodes. 44 findings. +- Run 2 (relaunch) `ns-1795288108` RUNNING β€” opus-4-8, seeded creds (svc_deploy+svc_web via /scratchpad/creds.yaml), proxychains installed, focus = DCSync native-from-APP-DMZ01 OR single proxychains SOCKS (NOT double-forward), chain-depth 8. Log: scratchpad/engage2.log. Monitor: bbne0n7bc. +- Branch `feat/validator-chain-graph-stealth-multimodel`, commit `5a3fe4a`, **PR #69** (origin). cargo check 0 errors. +- DONE (#1 chain-expands-needs-review via graph_memory, #2 validator optional + loot-never-rejected, #6 --stealth, #7 --planner-model). Backend only; **NOT yet built into the running binary** β€” build + merge AFTER run 2 closes. +- REMAINING: #3 graph UI extra filters, #4 goal-path-to-objective graph highlight, #5 neo4j consumed by planner (BloodHound shortestPath). Largely partial already (graph_checkpoint feeds next-moves from the graph; Chains tab shows ordered steps+vulns). Best iterated with the user's visual review. +- Disk reclaimed to 11Gi (docker build cache + brew). ~40GB stopped containers + 49GB images still reclaimable with user OK. + +--- + + +**Status:** staged. Do NOT rebuild/restart the engine while the live run is active. +**Live run:** `ns-1795270602-10_0_0_4` Β· model `claude-opus-4-8 --subscription` Β· scope `10.0.0.0/8` Β· neo4j Β· c2 lateral+persist Β· chain-depth 6 Β· log: `/private/tmp/claude-0/-opt-neurosploit-rs/863aed78-9c0f-4bc7-95a7-b9b99c021b04/scratchpad/engage.log` +**Goal (Stop hook):** reach DC01-VANGUARD (10.0.3.4), compromise all DCs, 100% via neurosploit. + +## Lab topology (from user image) +- VPN 10.0.4.0/24 β€” entry 10.0.4.4 +- DMZ 10.0.0.0/24: WEB-PUBLIC01 10.0.0.4 (Ubuntu, ROOTED), APP-DMZ01 10.0.0.5 (Win2016 domain-joined, LOCAL ADMIN owned) +- Forest01 10.0.1.0/24: FS01-AUREON .1.4, SQL01-AUREON .1.5, **DC01-AUREON .1.6** +- Forest02 10.0.2.0/24: **DC01-HELIX 10.0.2.4** +- Forest Root 10.0.3.0/24: **DC01-VANGUARD 10.0.3.4** (final objective) +- domains: aureon.local (Forest01), + helix, vanguard.local (forest root) + +## Loot so far (run ns-1795270602) +- `svc_web:W3bS3rvic3!` = LOCAL ADMIN APP-DMZ01 (nxc Pwn3d!) +- `svc_deploy:D3pl0y#Svc!` (SSH 10.0.0.4) / `aureon\svc_deploy:D3pl0ySvc#2024` (WinRM) +- `jmartinez_id_rsa` (looted key, used for pivot) +- APP-DMZ01$ machine account NTLM + AES keys; local Administrator NTLM; SAM (svc_iis/backup_admin/dev_deploy) +- DAs aureon: adm.roberts, adm.chen, adm.martinez, Administrator +- **d.kim@vanguard.local = forest-root Domain Admin (target identity)** +- Kerberoastable SPNs: svc_sql, svc_backup, svc_sccm, svc_monitor +- .env secrets: MSSQL sa, INTERNAL_API, mail creds +- Pivot: chisel reverse SOCKS 127.0.0.1:1080 + reverse port-forwards to DC ports. APP-DMZ01 reaches DC01-AUREON/FS01/SQL01. + +## Environment fixes already applied (support, not attack) +- VPN: `openvpn --config /Users/joas/Downloads/cadp_laboratory.ovpn` (bg). Endpoint host DNS broken via getaddrinfo (mDNSResponder); fixed with `/etc/hosts`: `3.220.78.132 6c0292d5621b.network.coursestack.com`. +- `proxychains-ng` installed for user joas: `sudo -u joas -H env HOME=/Users/joas brew install proxychains-ng`. + +--- + +# STAGED CHANGES (implement, then build + push) + +## 1. Chain must expand NON-CONFIRMED footholds (needs-review), not only Confirmed +- File: `crates/harness/src/pipeline.rs` +- `attack_chain()` def @2959, called @2505/2788/5875/6708 with `&findings` (already ALL findings β€” confirmed+needs-review+rejected, see "Keep ALL" @3699). Param named `confirmed` is misleading. +- VERIFY + FIX: the frontier (@2983 `frontier=confirmed.to_vec()`) and the `ready`/`prio` from `graph_checkpoint()` (@2977) β€” ensure graph_checkpoint and seed selection do NOT silently drop non-Confirmed status nodes. If `graph_checkpoint`/graph only treats `gm::Status::Confirmed` as a valid foothold (@2943 filters Confirmed), make needs-review-with-receipt also seed chains. +- Rule: a foothold with a concrete receipt (looted cred/key, command output) seeds chain expansion regardless of vote quorum. + +## 2. Validator optional + receipt-bearing never `rejected`; useful key/secret keeps value +- File: `crates/harness/src/pipeline.rs` verdict logic @3636-3708; `main.rs` host flags. +- Add `--no-validate` host flag β†’ skip vote, all findings status `unvalidated`, keep agent severity. Wire into RunConfig. +- In validate(): a finding with `grounded_receipt(&f) || has_http_receipt(&f)` OR a looted credential/key/secret that was REUSED (proven downstream) must become at worst `needs-review`, NEVER `rejected`. Secret/key disclosure + proven reuse = `confirmed` Critical/High. +- Do NOT delete anything (already "Keep ALL" @3699 β€” good). Fix the CAPPING (@3670-3681) so proven-reused secrets aren't severity-capped to Low. +- VOTE_SYS/REFUTE_SYS @1259/1263: add explicit line β€” a leaked long-lived credential/private key/API key that AUTHENTICATES or is REUSED downstream is a confirmed High/Critical finding, not "just a cat on an owned host". + +## 3. Graph UI improvements (frontend) +- Files: `web/public/app.js` (renderGraphMemory ~4440, finding detail ~4480), `web/public/style.css`. +- Better filtering (by entity kind, severity, status, subnet/host), edge-type legend (HAS_* structural vs ESCALATES_TO/IMPACTS/PROVES/CAN_ACCESS attack edges), node/edge path highlighting. + +## 4. FINAL graph shows FULL attack path + all vulns traversed to objective +- The end-of-run graph must render the kill chain: entry (VPN/WEB-PUBLIC01) β†’ every pivot/host β†’ vulns used at each hop β†’ DC01-VANGUARD. +- Backend: `graph_memory.rs` β€” ensure ESCALATES_TO/PROVES/CAN_ACCESS edges link the ordered path; emit a "goal path" (shortestPath/explicit chain) from entry to the objective host. +- Frontend: highlight/overlay that path distinctly (the "road to VANGUARD"), listing the vuln/finding used on each edge. + +## 5. Neo4j graph must be USEFUL for the tests (not just visualization) +- Engine should QUERY the graph to drive decisions (BloodHound-style): shortestPath from owned principals to high-value targets (DCs, DA d.kim), suggest next moves from graph edges. +- Files: `graph_memory.rs` (push + query), planner (`crates/harness/src/planner.rs`, `reactive.rs`) β€” feed graph-derived paths into planner intents. +- Make the graph queryable/actionable: expose "owned β†’ target" path queries the chain phase consumes. + +## 6. Stealth / OPSEC mode (`--stealth`) +- New host flag `--stealth`. When on: + - recon: slow timing (nmap -T2/-T1, no -T4; no rustscan mass-scan), fewer probes, jitter/throttle between actions. + - prefer LOLBins / native tooling over noisy uploads (chisel.exe tripped Defender this run β€” prefer SSH tunnels, native PowerShell, WMI, built-in). Avoid AV-tripping binaries. + - no aggressive brute/spray bursts; lockout-safe, spaced. + - inject an OPSEC preamble into agent system prompts (minimize footprint, avoid detection, clean up). + - MUST NOT reduce test coverage/quality β€” same objectives, quieter path. +- Touch: `main.rs` flag + RunConfig; `pipeline.rs` recon intensity + agent preamble; chain/C2 tool selection. + +## 8. Engagement identifier / marker (`--engagement `) [requested, do later] +- Internal IPs (e.g. 10.0.0.4) collide across different engagements/clients, so grouping/merging runs by IP suffix is unreliable. +- Add `--engagement ` (alias `--test-id`): stamped into RunConfig + each run's metadata (status.json / a tag file in the run dir). +- Used as the GROUP KEY: `merge_runs.py` groups by engagement id, not IP. +- Namespaces Neo4j: set property `engagement=` on every node/edge the run pushes, so separate engagements never mix in the graph even with the same IP. Graph/attack-path queries filter by it. +- Runs stay separate on disk; the marker is what says "same test". +- Files: main.rs flag + RunConfig field; graph_memory.rs push (add the property); merge script group key. + +## 7. `--planner-model` (multi-model role routing) +- Already: `--model a,b,c` builds a multi-model `ModelPool` (pool.rs) + cross-model vote (vote_n). DeepSeek etc. usable now via `--model claude-opus-4-8,deepseek-v4.1`. +- NEW: `--planner-model ` to route the planner/strategist role to a specific model (e.g. deepseek proposes alternative approaches) while executor/validator use others. Wire into planner.rs/reactive.rs model selection. +- TTP customization already via `agents_md/*.md` (editable) + runtime planner synthesis. + +--- + +# APPLY PROCEDURE (after run closes) +1. Confirm run ended: `pgrep -f "neurosploit host"` empty; report final findings + VANGUARD status. +2. `cd /opt/neurosploit-rs/neurosploit-rs && cargo build --release` (binary target/release/neurosploit). Frontend changes are static (no build). +3. Smoke test: `./target/release/neurosploit host --help` lists new flags; quick lab re-run if lab up. +4. Git: branch `feat/validator-chain-graph-stealth-multimodel`, commit per-area. **NO Claude attribution lines** (user memory rule overrides). Push to origin, open PR, merge. +5. Re-launch engagement with new flags if goal (VANGUARD) not yet met: add `--stealth` + `--model claude-opus-4-8,deepseek-v4.1` + `--no-validate` optional. + +# KEY CODE LOCATIONS +- pipeline.rs: attack_chain @2959 (calls 2505/2788/5875/6708); validate verdict @3636-3708 (Keep ALL @3699, cap @3670, receipt path @3659); VOTE_SYS @1259, REFUTE_SYS @1263; graph confirmed-count @2943. +- main.rs: host flags session_environment@51 session_policy@54 transport@61; host cfg build @970-1000; apply_authorization call added ~1187. +- graph_memory.rs: neo4j push, reads NEO4J_PASSWORD ~1976. +- app.js: renderGraphMemory ~4440, finding detail panel ~4480. style.css: .fd-pre, .moves clamp. +- NEO4J creds: user neo4j / pass b6gF1AmPHpuNdTpsd2Z7RFoe / bolt://127.0.0.1:7687 (container neurosploit-neo4j). diff --git a/neurosploit-rs/app/src/main.rs b/neurosploit-rs/app/src/main.rs index 00119b8..8f6013b 100644 --- a/neurosploit-rs/app/src/main.rs +++ b/neurosploit-rs/app/src/main.rs @@ -195,7 +195,8 @@ enum Cmd { /// support MCP fall back to their built-in tools). #[arg(long)] mcp: bool, - /// MCP tool profile: web Β· mobile-android Β· mobile-ios Β· binary Β· burp. + /// MCP tool profile: web Β· mobile-android Β· mobile-ios Β· binary Β· burp Β· + /// cobaltstrike (official team-server HTTP MCP) Β· infra Β· ad Β· cloud Β· kali Β· nmap. /// Auto-registers the right MCP server and tool allowlist for the test type. #[arg(long = "mcp-profile")] mcp_profile: Option, @@ -282,6 +283,34 @@ enum Cmd { #[command(subcommand)] cmd: toolscli::ToolsCmd, }, + /// Ship a run's logs (audit Β· traces Β· findings Β· errors Β· pocs) to + /// OpenSearch, one index per engagement project. + Logs { + #[command(subcommand)] + cmd: LogsCmd, + }, + /// Start an ngrok tunnel plus a local HTTP sink for OOB callbacks and + /// webshell check-ins. Needs NGROK_AUTHTOKEN (or --authtoken). + Tunnel { + /// Local port to forward (the callback sink binds here). + #[arg(long)] + port: Option, + /// ngrok authtoken (defaults to NGROK_AUTHTOKEN). + #[arg(long)] + authtoken: Option, + /// ngrok region (us, eu, ap, au, sa, jp, in). + #[arg(long)] + region: Option, + /// Reserved/custom ngrok domain, when the plan provides one. + #[arg(long)] + domain: Option, + /// Bind address for the local sink (default 127.0.0.1). + #[arg(long)] + bind: Option, + /// Do not start the sink β€” only open the tunnel to an existing service. + #[arg(long = "no-serve")] + no_serve: bool, + }, /// Command & Control for authorized internal engagements: listeners, /// sessions, tasks, payloads, persistence and lateral movement. C2 { @@ -401,6 +430,61 @@ enum Cmd { #[arg(long = "json")] json: bool, }, + /// Turn engagement inputs (IP list Β· OpenAPI/Swagger Β· .ovpn Β· RoE Β· + /// topology image) into targets, a scope YAML and a transport suggestion. + Ingest { + /// File with IPs/hosts/CIDRs, one per line. + #[arg(long)] + ips: Option, + /// OpenAPI/Swagger document (JSON or YAML) β€” base URLs and paths. + #[arg(long)] + swagger: Option, + /// OpenVPN profile; becomes `openvpn:` transport. + #[arg(long)] + ovpn: Option, + /// Rules of Engagement text; `out-of-scope:` / `exclude:` lines become + /// hard exclusions, the rest becomes prompt notes. + #[arg(long)] + roe: Option, + /// Topology image to record with the engagement. + #[arg(long)] + topology: Option, + /// Where to write brief.json and scope.yaml (default `.neurosploit/ingest`). + #[arg(long)] + out: Option, + }, + /// Review a run's friction signals with a cheap model and write an + /// improvement issue (problem Β· evidence Β· proposed fix Β· example patch). + /// Local Markdown by default; `--create --repo` posts it with `gh`. + Improve { + /// Run id (`ns-…`) or path to the run directory. + run: String, + /// Cheap model, e.g. `deepseek:deepseek-chat` (default: NEUROSPLOIT_IMPROVE_MODEL). + #[arg(long)] + model: Option, + /// Print the prompt instead of calling a model. + #[arg(long = "dry-run")] + dry_run: bool, + /// Actually create the GitHub issue (requires --repo and `gh`). + #[arg(long)] + create: bool, + /// GitHub repo for `--create`, as `owner/repo`. + #[arg(long)] + repo: Option, + }, + /// Print a rich, step-by-step reproduction kit for a run's findings. Secrets + /// stay in the vault as `{{REVEALSECRET:name}}` unless --reveal is passed. + Repro { + /// Run id (`ns-…`) or path to the run directory. + run: String, + /// Only this finding id (or exact title). + #[arg(long = "only")] + only: Option, + /// Substitute vault values instead of masked placeholders. Prints real + /// credentials β€” use only on the operator's machine. + #[arg(long = "reveal")] + reveal: bool, + }, /// Assemble/print/verify a run's assurance bundle (P1–P5 in one manifest). Assurance { /// Run id (`ns-…`) or path to the run directory. @@ -1026,6 +1110,16 @@ async fn main() -> anyhow::Result<()> { } } Cmd::Tools { cmd } => { toolscli::handle(cmd).await?; } + Cmd::Logs { cmd } => { handle_logs(&base, cmd).await?; } + Cmd::Tunnel { port, authtoken, region, domain, bind, no_serve } => { + let mut cfg = harness::TunnelConfig::from_env(port); + if authtoken.is_some() { cfg.authtoken = authtoken; } + if region.is_some() { cfg.region = region; } + if domain.is_some() { cfg.domain = domain; } + if let Some(b) = bind { cfg.bind = b; } + cfg.serve = !no_serve; + harness::tunnel::run(cfg).await?; + } Cmd::C2 { cmd } => { c2cli::handle_c2(cmd).await?; } Cmd::Webshell { cmd } => { c2cli::handle_webshell(cmd).await?; } Cmd::Mcp => { mcp::serve()?; } @@ -1050,6 +1144,13 @@ async fn main() -> anyhow::Result<()> { Cmd::Assurance { run, verify } => handle_assurance(&base, &run, verify)?, Cmd::Compliance { run, framework, include_leads } => handle_compliance(&base, &run, &framework, include_leads)?, Cmd::Poc { run, repeats, apply, only, json } => handle_poc(&base, &run, repeats, apply, only, json).await?, + Cmd::Repro { run, only, reveal } => handle_repro(&base, &run, only.as_deref(), reveal)?, + Cmd::Ingest { ips, swagger, ovpn, roe, topology, out } => { + handle_ingest(ips.as_deref(), swagger.as_deref(), ovpn.as_deref(), roe.as_deref(), topology.as_deref(), out.as_deref())? + } + Cmd::Improve { run, model, dry_run, create, repo } => { + handle_improve(&base, &run, model.as_deref(), dry_run, create, repo.as_deref()).await? + } Cmd::Sandbox { cmd } => handle_sandbox(cmd).await?, Cmd::Neo4j { cmd } => handle_neo4j(&base, cmd).await?, Cmd::Capability { cmd } => handle_capability(cmd)?, @@ -1830,6 +1931,31 @@ fn apply_authorization( Ok(()) } +#[derive(Subcommand)] +enum LogsCmd { + /// Check the OpenSearch endpoint, credentials and reachability. + Ping, + /// Ship a run's artifacts (audit Β· traces Β· findings Β· errors Β· usage Β· pocs) + /// to OpenSearch, under one index per engagement project. + Push { + /// Run id (`ns-…`) or path to the run directory. + run: String, + /// Engagement/customer/domain label for the index (defaults to + /// NS_LOG_PROJECT). The index is `ns-` unless OPENSEARCH_INDEX + /// overrides it. + #[arg(long)] + project: Option, + }, + /// Print the events that would be shipped, without sending them. + Preview { + run: String, + #[arg(long)] + project: Option, + #[arg(long, default_value_t = 10)] + limit: usize, + }, +} + #[derive(Subcommand)] enum Neo4jCmd { /// Create/start the Neo4j container (127.0.0.1 only), save the connection, @@ -2205,6 +2331,55 @@ fn handle_sarif(base: &std::path::Path, run: &str, out: Option<&str>) -> anyhow: Ok(()) } +async fn handle_logs(base: &std::path::Path, cmd: LogsCmd) -> anyhow::Result<()> { + let runs = base.join("runs"); + match cmd { + LogsCmd::Ping => { + let cfg = harness::logship::Config::from_env(None) + .ok_or_else(|| anyhow::anyhow!("OPENSEARCH_URL is not set (see docker-compose.opensearch.yml)"))?; + let body = harness::logship::ping(&cfg).await?; + let version = serde_json::from_str::(&body) + .ok() + .and_then(|v| v.get("version").and_then(|x| x.get("number")).and_then(|x| x.as_str()).map(String::from)); + match version { + Some(v) => println!(" \x1b[32mOpenSearch reachable\x1b[0m {} (v{v})", cfg.url), + None => println!(" \x1b[32mOpenSearch reachable\x1b[0m {}", cfg.url), + } + } + LogsCmd::Push { run, project } => { + let cfg = harness::logship::Config::from_env(project.as_deref()) + .ok_or_else(|| anyhow::anyhow!("OPENSEARCH_URL is not set (see docker-compose.opensearch.yml)"))?; + let dir = harness::logship::resolve_run(&runs, &run) + .ok_or_else(|| anyhow::anyhow!("no such run: {run}"))?; + let (report, total) = harness::logship::push_run(&cfg, &dir).await?; + let index = cfg.index_for(&harness::logship::today()); + println!( + " \x1b[32mshipped\x1b[0m {}/{} event(s) β†’ {} ({index})", + report.indexed, total, cfg.url + ); + if report.failed > 0 { + eprintln!(" \x1b[33m⚠ {} document(s) rejected by OpenSearch\x1b[0m", report.failed); + } + if report.indexed == 0 && report.failed > 0 { + anyhow::bail!("OpenSearch rejected every document"); + } + } + LogsCmd::Preview { run, project, limit } => { + let dir = harness::logship::resolve_run(&runs, &run) + .ok_or_else(|| anyhow::anyhow!("no such run: {run}"))?; + let label = project + .or_else(|| std::env::var("NS_LOG_PROJECT").ok()) + .unwrap_or_else(|| "default".to_string()); + let events = harness::logship::collect_run(&dir, &label); + println!("{} event(s) for project '{label}'", events.len()); + for e in events.iter().take(limit) { + println!("{}", serde_json::to_string(e)?); + } + } + } + Ok(()) +} + fn handle_audit(base: &std::path::Path, run: &str, anchor: bool) -> anyhow::Result<()> { let dir = resolve_run(base, run)?; let log = harness::audit::AuditLog::open(dir.join("audit.jsonl")); @@ -2254,6 +2429,106 @@ fn handle_compliance(base: &std::path::Path, run: &str, frameworks: &[String], i Ok(()) } +fn handle_ingest( + ips: Option<&str>, + swagger: Option<&str>, + ovpn: Option<&str>, + roe: Option<&str>, + topology: Option<&str>, + out: Option<&str>, +) -> anyhow::Result<()> { + let brief = harness::ingest::from_files( + ips.map(std::path::Path::new), + swagger.map(std::path::Path::new), + ovpn.map(std::path::Path::new), + roe.map(std::path::Path::new), + topology.map(std::path::Path::new), + )?; + let out_dir = out.map(std::path::PathBuf::from).unwrap_or_else(|| std::path::PathBuf::from(".neurosploit/ingest")); + let (brief_path, scope_path) = harness::ingest::write(&brief, &out_dir)?; + println!("{}", brief.summary()); + for t in brief.targets().iter().take(25) { + println!(" target : {t}"); + } + for e in brief.endpoints.iter().take(25) { + println!(" endpoint: {e}"); + } + println!("\n brief β†’ {}", brief_path.display()); + println!(" scope β†’ {}", scope_path.display()); + if let Some(first) = brief.targets().first() { + let mut cmd = format!("neurosploit run '{first}' --scope-file '{}'", scope_path.display()); + if let Some(t) = &brief.transport { + cmd.push_str(&format!(" --transport '{t}'")); + } + println!("\n next: {cmd}"); + } + Ok(()) +} + +async fn handle_improve( + base: &std::path::Path, + run: &str, + model: Option<&str>, + dry_run: bool, + create: bool, + repo: Option<&str>, +) -> anyhow::Result<()> { + let dir = resolve_run(base, run)?; + let signals = harness::improve::collect(&dir); + let user = harness::improve::prompt(&dir, &signals); + if dry_run { + println!("{user}"); + return Ok(()); + } + let model = model + .map(str::to_string) + .or_else(|| std::env::var("NEUROSPLOIT_IMPROVE_MODEL").ok().filter(|s| !s.trim().is_empty())) + .unwrap_or_else(|| "deepseek:deepseek-chat".to_string()); + let pool = ModelPool::new(vec![ModelRef::parse(&model)], 1); + println!(" reviewing {} signal(s) with {model}…", signals.len()); + let (_m, text) = pool.complete(harness::improve::SYSTEM, &user).await + .map_err(|e| anyhow::anyhow!("improvement model failed: {e}"))?; + let run_id = dir.file_name().and_then(|s| s.to_str()).unwrap_or("run").to_string(); + let path = harness::improve::save(&dir, &run_id, &text)?; + println!("\n{text}\n\n \x1b[2mwritten β†’ {}\x1b[0m", path.display()); + if create { + let repo = repo.ok_or_else(|| anyhow::anyhow!("--create needs --repo owner/repo"))?; + let title = text + .lines() + .find(|l| l.trim_start().starts_with("# ")) + .map(|l| l.trim_start_matches('#').trim().to_string()) + .unwrap_or_else(|| format!("Improve run {run_id}")); + let out = tokio::process::Command::new("gh") + .args(["issue", "create", "--repo", repo, "--title", &title, "--body-file"]) + .arg(&path) + .output() + .await + .map_err(|e| anyhow::anyhow!("could not run gh: {e}"))?; + if !out.status.success() { + anyhow::bail!("gh issue create failed: {}", String::from_utf8_lossy(&out.stderr)); + } + println!(" \x1b[32missue created\x1b[0m {}", String::from_utf8_lossy(&out.stdout).trim()); + } + Ok(()) +} + +fn handle_repro(base: &std::path::Path, run: &str, only: Option<&str>, reveal: bool) -> anyhow::Result<()> { + let dir = resolve_run(base, run)?; + let findings = load_findings(&dir)?; + let store = harness::repro::SecretStore::load(&dir); + let md = harness::repro::markdown(&dir, &findings, &store, reveal, only); + let out = dir.join("reproduction.md"); + std::fs::write(&out, &md)?; + print!("{md}"); + println!("\n \x1b[2mwritten β†’ {}\x1b[0m", out.display()); + if store.is_empty() { + eprintln!(" \x1b[33m⚠ no vault entries found β€” REVEALSECRET tokens stay unresolved\x1b[0m"); + } else if !reveal { + println!(" \x1b[2m{} secret(s) in the vault; pass --reveal to print them\x1b[0m", store.len()); + } + Ok(()) +} + async fn handle_poc(base: &std::path::Path, run: &str, repeats: usize, apply: bool, only: Option, json: bool) -> anyhow::Result<()> { let dir = resolve_run(base, run)?; let mut findings = load_findings(&dir)?; diff --git a/neurosploit-rs/crates/harness/src/c2/manager.rs b/neurosploit-rs/crates/harness/src/c2/manager.rs index 00cf5be..cefa89d 100644 --- a/neurosploit-rs/crates/harness/src/c2/manager.rs +++ b/neurosploit-rs/crates/harness/src/c2/manager.rs @@ -1438,11 +1438,10 @@ impl C2Manager { .bytes() .await .map_err(|e| format!("read response: {e}"))?; - let mut text = String::from_utf8_lossy(&bytes).to_string(); - if text.len() > OUTPUT_CAP { - text.truncate(OUTPUT_CAP); - text.push_str("\n[truncated by NeuroSploit]"); - } + let text = crate::limits::clip( + &String::from_utf8_lossy(&bytes), + crate::limits::env_cap("NEUROSPLOIT_C2_OUTPUT_CAP", OUTPUT_CAP), + ); self.store.audit( "webshell.exec", json!({"id": conn.id, "command": command, "http_status": status, "authorization": state.policy.authorized_by}), diff --git a/neurosploit-rs/crates/harness/src/c2/mod.rs b/neurosploit-rs/crates/harness/src/c2/mod.rs index 343f749..337fa7a 100644 --- a/neurosploit-rs/crates/harness/src/c2/mod.rs +++ b/neurosploit-rs/crates/harness/src/c2/mod.rs @@ -107,12 +107,8 @@ pub(crate) fn unb64(s: &str) -> Option> { .ok() } -pub(crate) fn clip(mut s: String) -> String { - if s.len() > OUTPUT_CAP { - s.truncate(OUTPUT_CAP); - s.push_str("\n[truncated by NeuroSploit C2]"); - } - s +pub(crate) fn clip(s: String) -> String { + crate::limits::clip(&s, crate::limits::env_cap("NEUROSPLOIT_C2_OUTPUT_CAP", OUTPUT_CAP)) } /// Post-exploitation doctrine injected into agent prompts when `--c2` is on. diff --git a/neurosploit-rs/crates/harness/src/cache.rs b/neurosploit-rs/crates/harness/src/cache.rs new file mode 100644 index 0000000..620b2e0 --- /dev/null +++ b/neurosploit-rs/crates/harness/src/cache.rs @@ -0,0 +1,153 @@ +//! Universal completion cache β€” spend a token once. +//! +//! Agents ask the same questions constantly: the same recon page, the same +//! validator prompt, the same "is this reflected?" follow-up across chain +//! rounds and across runs of the same target. Each repeat costs money and time +//! and returns the same answer. This cache keys a completion by the exact +//! (provider, model, backend, system, user, output-budget, temperature) tuple +//! and serves it from memory, then from disk. +//! +//! Safety properties: +//! +//! - **Content-addressed, never fuzzy.** A near-match is not a cache hit; an +//! agent's prompt is its context, and a stale answer to a different prompt is +//! worse than paying again. +//! - **Scoped to a project.** `NEUROSPLOIT_CACHE_SCOPE` (default: the working +//! directory) namespaces the store, so two engagements never share answers. +//! - **Bounded and expirable.** `NEUROSPLOIT_CACHE_TTL_SECS` (default 7 days) +//! and `NEUROSPLOIT_CACHE=off` to disable. Entries are small JSON files; +//! deleting the directory is always safe. +//! - **Does not mask failures.** Only successful completions are stored. + +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::{Mutex, OnceLock}; +use std::time::{SystemTime, UNIX_EPOCH}; + +#[derive(Serialize, Deserialize)] +struct Entry { + created: u64, + model: String, + text: String, +} + +fn mem() -> &'static Mutex> { + static M: OnceLock>> = OnceLock::new(); + M.get_or_init(|| Mutex::new(HashMap::new())) +} + +pub fn enabled() -> bool { + !matches!( + std::env::var("NEUROSPLOIT_CACHE").ok().as_deref().map(str::trim).map(str::to_ascii_lowercase).as_deref(), + Some("0") | Some("false") | Some("off") | Some("no") + ) +} + +fn ttl_secs() -> u64 { + std::env::var("NEUROSPLOIT_CACHE_TTL_SECS") + .ok() + .and_then(|v| v.trim().parse().ok()) + .unwrap_or(7 * 24 * 3600) +} + +fn root() -> PathBuf { + let scope = std::env::var("NEUROSPLOIT_CACHE_SCOPE") + .ok() + .filter(|s| !s.trim().is_empty()) + .map(PathBuf::from) + .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))); + scope.join(".neurosploit").join("cache").join("llm") +} + +fn now() -> u64 { + SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0) +} + +/// Stable key for one completion request. +pub fn key(provider: &str, model: &str, cli: bool, system: &str, user: &str) -> String { + let budget = std::env::var("NEUROSPLOIT_MAX_TOKENS").unwrap_or_default(); + let temp = std::env::var("NEUROSPLOIT_TEMPERATURE").unwrap_or_default(); + let mut h = Sha256::new(); + for part in [provider, model, if cli { "cli" } else { "api" }, &budget, &temp] { + h.update(part.as_bytes()); + h.update([0u8]); + } + h.update(system.as_bytes()); + h.update([0u8]); + h.update(user.as_bytes()); + format!("{:x}", h.finalize()) +} + +pub fn get(k: &str) -> Option { + if !enabled() { + return None; + } + if let Ok(m) = mem().lock() { + if let Some(v) = m.get(k) { + return Some(v.clone()); + } + } + let path = path_for(k); + let text = std::fs::read_to_string(&path).ok()?; + let entry: Entry = serde_json::from_str(&text).ok()?; + if now().saturating_sub(entry.created) > ttl_secs() { + let _ = std::fs::remove_file(&path); + return None; + } + if let Ok(mut m) = mem().lock() { + m.insert(k.to_string(), entry.text.clone()); + if m.len() > 4096 { + m.clear(); + } + } + Some(entry.text) +} + +pub fn put(k: &str, model: &str, text: &str) { + if !enabled() || text.is_empty() { + return; + } + if let Ok(mut m) = mem().lock() { + if m.len() > 4096 { + m.clear(); + } + m.insert(k.to_string(), text.to_string()); + } + let path = path_for(k); + if let Some(dir) = path.parent() { + let _ = std::fs::create_dir_all(dir); + } + let entry = Entry { created: now(), model: model.to_string(), text: text.to_string() }; + if let Ok(json) = serde_json::to_string(&entry) { + let _ = std::fs::write(path, json); + } +} + +fn path_for(k: &str) -> PathBuf { + let shard = &k[..2.min(k.len())]; + root().join(shard).join(format!("{k}.json")) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn key_is_stable_and_sensitive_to_every_input() { + let a = key("p", "m", false, "sys", "user"); + assert_eq!(a, key("p", "m", false, "sys", "user")); + assert_ne!(a, key("p", "m", true, "sys", "user")); + assert_ne!(a, key("p", "m2", false, "sys", "user")); + assert_ne!(a, key("p", "m", false, "sys", "other")); + } + + #[test] + fn roundtrips_in_memory() { + std::env::set_var("NEUROSPLOIT_CACHE", "on"); + let k = key("test", "roundtrip", false, "s", "u"); + put(&k, "test", "hello"); + assert_eq!(get(&k).as_deref(), Some("hello")); + } +} diff --git a/neurosploit-rs/crates/harness/src/improve.rs b/neurosploit-rs/crates/harness/src/improve.rs new file mode 100644 index 0000000..a03e6df --- /dev/null +++ b/neurosploit-rs/crates/harness/src/improve.rs @@ -0,0 +1,145 @@ +//! Self-improvement pass β€” turn a run's friction into a reviewable issue. +//! +//! A pentest harness fails in ways the final report never shows: an agent ran +//! out of output budget mid-JSON, a tool was missing from the sandbox, recon +//! saw a surface the planner never dispatched, a target answered something no +//! validator understood. Those are the signals that make the *next* run better, +//! and they are exactly the ones nobody has time to read. +//! +//! This module collects those signals from a finished run and hands them to a +//! (deliberately cheap) model with one job: write an issue β€” problem, evidence, +//! proposed fix, and an example patch β€” for a human to accept or reject. It +//! never edits code and never opens a PR on its own; `--create` is required to +//! post, so the default is a local Markdown artifact. + +use anyhow::Result; +use serde::{Deserialize, Serialize}; +use std::path::Path; + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Signal { + /// `status` Β· `error` Β· `trace` Β· `coverage` Β· `tool` Β· `parse`. + pub kind: String, + pub detail: String, +} + +const SIGNAL_NEEDLES: &[(&str, &str)] = &[ + ("error", "error"), + ("failed", "failure"), + ("not found", "missing component"), + ("unsupported", "unsupported"), + ("truncated", "truncated output"), + ("parse", "parse issue"), + ("timeout", "timeout"), + ("denied", "policy denial"), + ("no findings", "empty result"), +]; + +/// Collect the run's friction points. Read-only and best-effort. +pub fn collect(dir: &Path) -> Vec { + let mut out = Vec::new(); + + if let Ok(text) = std::fs::read_to_string(dir.join("status.json")) { + if let Ok(v) = serde_json::from_str::(&text) { + let state = v.get("state").and_then(|x| x.as_str()).unwrap_or("unknown"); + let target = v.get("target").and_then(|x| x.as_str()).unwrap_or(""); + out.push(Signal { kind: "status".into(), detail: format!("state={state} target={target}") }); + if let Some(err) = v.get("error").and_then(|x| x.as_str()) { + out.push(Signal { kind: "error".into(), detail: err.to_string() }); + } + } + } + + let findings = std::fs::read_to_string(dir.join("findings.json")) + .ok() + .and_then(|t| serde_json::from_str::(&t).ok()) + .and_then(|v| v.as_array().map(|a| a.len())) + .unwrap_or(0); + out.push(Signal { kind: "coverage".into(), detail: format!("{findings} confirmed finding(s)") }); + + if let Ok(text) = std::fs::read_to_string(dir.join("audit.jsonl")) { + let denied = text.lines().filter(|l| l.contains("\"policy_decision\":\"deny") || l.contains("deny:")).count(); + if denied > 0 { + out.push(Signal { kind: "policy".into(), detail: format!("{denied} denied action(s) in the audit trail") }); + } + let failed = text.lines().filter(|l| l.contains("failed") || l.contains("\"result\":\"error")).count(); + if failed > 0 { + out.push(Signal { kind: "error".into(), detail: format!("{failed} failed action(s) in the audit trail") }); + } + } + + let traces = dir.join("traces"); + if let Ok(rd) = std::fs::read_dir(&traces) { + for e in rd.flatten() { + let name = e.file_name().to_string_lossy().to_string(); + let Ok(text) = std::fs::read_to_string(e.path()) else { continue }; + let low = text.to_lowercase(); + for (needle, label) in SIGNAL_NEEDLES { + if low.contains(needle) { + if let Some(line) = text.lines().find(|l| l.to_lowercase().contains(needle)) { + out.push(Signal { + kind: "trace".into(), + detail: format!("{name}: {label} β€” {}", crate::limits::clip(line.trim(), 240)), + }); + } + } + } + } + } + + // Cap: the issue needs representative evidence, not a dump. + out.truncate(40); + out +} + +pub fn prompt(dir: &Path, signals: &[Signal]) -> String { + let mut s = String::new(); + s.push_str(&format!("Run directory: {}\n\n", dir.display())); + s.push_str("Observed friction (machine-collected, may be noisy):\n"); + for sig in signals { + s.push_str(&format!("- [{}] {}\n", sig.kind, sig.detail)); + } + s +} + +pub const SYSTEM: &str = "You are a senior engineer reviewing a penetration-testing harness's own run. \ +From the friction signals, write ONE GitHub issue that would make the next run materially better. \ +Be concrete and grounded ONLY in the signals provided β€” do not invent facts. \ +Output Markdown with exactly these sections:\n\ +# \n\ +## Problem\n## Evidence\n## Root cause (hypothesis)\n## Proposed fix\n## Example patch (or config change)\n## Acceptance criteria\n\ +Keep it under 700 words. The patch may be a diff or a complete small file; it is a proposal, not a PR."; + +/// Persist the issue next to the run and in the global improvements folder. +pub fn save(dir: &Path, run_id: &str, markdown: &str) -> Result { + let local = dir.join("improvement-issue.md"); + std::fs::write(&local, markdown)?; + let global = Path::new(".neurosploit").join("improvements"); + if std::fs::create_dir_all(&global).is_ok() { + let _ = std::fs::write(global.join(format!("{run_id}.md")), markdown); + } + Ok(local) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn collects_status_and_findings() { + let dir = std::env::temp_dir().join(format!("ns-improve-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("status.json"), r#"{"state":"complete","target":"https://x"}"#).unwrap(); + std::fs::write(dir.join("findings.json"), "[]").unwrap(); + let sig = collect(&dir); + assert!(sig.iter().any(|s| s.kind == "status")); + assert!(sig.iter().any(|s| s.detail.contains("0 confirmed"))); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn prompt_lists_signals() { + let p = prompt(Path::new("/tmp/x"), &[Signal { kind: "error".into(), detail: "boom".into() }]); + assert!(p.contains("boom")); + } +} diff --git a/neurosploit-rs/crates/harness/src/ingest.rs b/neurosploit-rs/crates/harness/src/ingest.rs new file mode 100644 index 0000000..936701b --- /dev/null +++ b/neurosploit-rs/crates/harness/src/ingest.rs @@ -0,0 +1,259 @@ +//! Engagement inputs β€” turn the artifacts an operator already has into targets. +//! +//! A real engagement starts with a pile of files: an IP list from the client, a +//! Swagger/OpenAPI document, an `.ovpn` profile, the Rules of Engagement, a +//! screenshot of the topology. Retyping those into flags is where scope +//! mistakes happen. [`Brief`] reads them once and produces: +//! +//! - the **targets** (base URLs and hosts) to seed recon with, +//! - a **scope YAML** the harness can enforce directly (`--scope-file`), +//! - the **transport** implied by an `.ovpn`, +//! - **exclusions and notes** from the RoE, +//! - a metadata record for a topology image (kept, not interpreted). +//! +//! It is a parser, not a scanner: nothing here sends traffic. Everything it +//! emits is reviewable text, so the operator can correct a bad assumption +//! before the first request. + +use anyhow::Result; +use serde::{Deserialize, Serialize}; +use std::path::{Path, PathBuf}; + +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +pub struct Brief { + /// Hosts/CIDRs from the IP list. + pub ips: Vec, + /// Base URLs from the API document. + pub base_urls: Vec, + /// Endpoint paths from the API document. + pub endpoints: Vec, + /// `openvpn:` when a profile was supplied. + pub transport: Option, + /// Hard exclusions found in the RoE. + pub out_of_scope: Vec, + /// Free-text RoE notes, bounded. + pub notes: Vec, + /// Path to the topology image, recorded for the report. + pub topology: Option, + pub roe: Option, +} + +impl Brief { + pub fn targets(&self) -> Vec { + let mut v: Vec = self.base_urls.clone(); + for ip in &self.ips { + if !v.iter().any(|x| x == ip) { + v.push(ip.clone()); + } + } + v + } + + /// A scope YAML the harness enforces, including the API hosts and the + /// exclusions, with the RoE notes carried as (non-enforced) context. + pub fn scope_yaml(&self) -> String { + let mut s = String::from("hard:\n"); + for t in self.targets() { + let host = if t.contains("://") { + crate::scope::host_of(&t) + } else if t + .split_once('/') + .map(|(_, bits)| !bits.is_empty() && bits.chars().all(|c| c.is_ascii_digit())) + .unwrap_or(false) + { + // A CIDR must keep its prefix length; splitting on '/' would + // quietly widen 10.0.1.0/24 to a single host. + t.clone() + } else { + t.split('/').next().unwrap_or(&t).to_string() + }; + if !host.is_empty() { + s.push_str(&format!(" - {host}\n")); + } + } + if !self.out_of_scope.is_empty() { + s.push_str("exclude:\n"); + for x in &self.out_of_scope { + s.push_str(&format!(" - {x}\n")); + } + } + s.push_str("soft:\n"); + s.push_str(" notes:\n"); + for n in self.notes.iter().take(20) { + s.push_str(&format!(" - {}\n", n.replace('\n', " "))); + } + s + } + + pub fn summary(&self) -> String { + let mut s = String::new(); + s.push_str(&format!( + "targets: {} Β· endpoints: {} Β· exclusions: {} Β· transport: {}\n", + self.targets().len(), + self.endpoints.len(), + self.out_of_scope.len(), + self.transport.as_deref().unwrap_or("direct") + )); + if let Some(t) = &self.topology { + s.push_str(&format!("topology: {t}\n")); + } + for n in &self.notes { + s.push_str(&format!("note: {n}\n")); + } + s + } +} + +pub fn from_files( + ips: Option<&Path>, + swagger: Option<&Path>, + ovpn: Option<&Path>, + roe: Option<&Path>, + topology: Option<&Path>, +) -> Result { + let mut b = Brief::default(); + if let Some(p) = ips { + for line in std::fs::read_to_string(p)?.lines() { + let t = line.split('#').next().unwrap_or("").trim(); + if !t.is_empty() && !b.ips.iter().any(|x| x == t) { + b.ips.push(t.to_string()); + } + } + } + if let Some(p) = swagger { + absorb_api(&mut b, &std::fs::read_to_string(p)?); + } + if let Some(p) = ovpn { + b.transport = Some(format!("openvpn:{}", p.display())); + } + if let Some(p) = roe { + b.roe = Some(p.display().to_string()); + let text = std::fs::read_to_string(p).unwrap_or_default(); + for line in text.lines() { + let t = line.trim(); + let lower = t.to_ascii_lowercase(); + if let Some(rest) = lower.strip_prefix("out-of-scope:").or_else(|| lower.strip_prefix("exclude:")) { + let _ = rest; + let val = t.split_once(':').map(|(_, r)| r.trim()).unwrap_or(""); + if !val.is_empty() { + b.out_of_scope.push(val.to_string()); + } + } else if t.starts_with("- ") && (lower.contains("out of scope") || lower.contains("fora de escopo")) { + b.out_of_scope.push(t.trim_start_matches("- ").to_string()); + } else if !t.is_empty() && b.notes.len() < 40 { + b.notes.push(crate::limits::clip(t, 240)); + } + } + b.notes.truncate(40); + } + if let Some(p) = topology { + if p.is_file() { + b.topology = Some(p.display().to_string()); + } else { + anyhow::bail!("topology file not found: {}", p.display()); + } + } + Ok(b) +} + +/// Extract base URL(s) and paths from an OpenAPI/Swagger document. JSON is +/// parsed properly; YAML is read line-wise (servers/url and path keys), which +/// covers the shapes teams actually hand over. +fn absorb_api(b: &mut Brief, text: &str) { + if let Ok(v) = serde_json::from_str::(text) { + if let Some(servers) = v.get("servers").and_then(|x| x.as_array()) { + for s in servers { + if let Some(u) = s.get("url").and_then(|x| x.as_str()) { + push(&mut b.base_urls, u); + } + } + } + let host = v.get("host").and_then(|x| x.as_str()).unwrap_or(""); + let base = v.get("basePath").and_then(|x| x.as_str()).unwrap_or(""); + if !host.is_empty() { + let scheme = v.get("schemes").and_then(|x| x.as_array()).and_then(|a| a.first()).and_then(|x| x.as_str()).unwrap_or("https"); + push(&mut b.base_urls, &format!("{scheme}://{host}{base}")); + } + if let Some(paths) = v.get("paths").and_then(|x| x.as_object()) { + for k in paths.keys() { + push(&mut b.endpoints, k); + } + } + return; + } + // YAML fallback. + let mut in_servers = false; + let mut in_paths = false; + for raw in text.lines() { + let indent = raw.len() - raw.trim_start().len(); + let t = raw.trim(); + if t.starts_with("servers:") { in_servers = true; in_paths = false; continue; } + if t.starts_with("paths:") { in_paths = true; in_servers = false; continue; } + if indent == 0 && !t.is_empty() && !t.starts_with('-') { in_servers = false; in_paths = false; } + if in_servers { + if let Some(u) = t.strip_prefix("- url:").or_else(|| t.strip_prefix("url:")) { + push(&mut b.base_urls, u.trim().trim_matches(['"', '\''])); + } + } + if in_paths && indent == 2 && t.starts_with('/') { + let key = t.trim_end_matches(':').trim(); + push(&mut b.endpoints, key); + } + } +} + +fn push(v: &mut Vec, s: &str) { + let s = s.trim(); + if !s.is_empty() && !v.iter().any(|x| x == s) { + v.push(s.to_string()); + } +} + +/// Write the brief and the derived scope file, returning both paths. +pub fn write(b: &Brief, out_dir: &Path) -> Result<(PathBuf, PathBuf)> { + std::fs::create_dir_all(out_dir)?; + let brief = out_dir.join("brief.json"); + std::fs::write(&brief, serde_json::to_string_pretty(b)?)?; + let scope = out_dir.join("scope.yaml"); + std::fs::write(&scope, b.scope_yaml())?; + Ok((brief, scope)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_json_openapi() { + let mut b = Brief::default(); + absorb_api(&mut b, r#"{"servers":[{"url":"https://api.example.com/v2"}],"paths":{"/users":{},"/login":{}}}"#); + assert_eq!(b.base_urls, vec!["https://api.example.com/v2"]); + let mut eps = b.endpoints.clone(); eps.sort(); + assert_eq!(eps, vec!["/login", "/users"]); + } + + #[test] + fn parses_yaml_openapi() { + let mut b = Brief::default(); + absorb_api(&mut b, "servers:\n - url: https://y.example.com\npaths:\n /a:\n /b:\n"); + assert!(b.base_urls.contains(&"https://y.example.com".to_string())); + assert!(b.endpoints.contains(&"/a".to_string())); + assert!(b.endpoints.contains(&"/b".to_string())); + } + + #[test] + fn scope_includes_hosts_and_exclusions() { + let b = Brief { + ips: vec!["10.0.0.4".into()], + base_urls: vec!["https://app.example.com/api".into()], + out_of_scope: vec!["payments.example.com".into()], + notes: vec!["test window 02:00".into()], + ..Default::default() + }; + let y = b.scope_yaml(); + assert!(y.contains("10.0.0.4")); + assert!(y.contains("app.example.com")); + assert!(y.contains("payments.example.com")); + assert!(y.contains("test window")); + } +} diff --git a/neurosploit-rs/crates/harness/src/lib.rs b/neurosploit-rs/crates/harness/src/lib.rs index 2453911..622f4a0 100644 --- a/neurosploit-rs/crates/harness/src/lib.rs +++ b/neurosploit-rs/crates/harness/src/lib.rs @@ -16,6 +16,7 @@ pub mod audit; pub mod belief; pub mod browser; pub mod budget; +pub mod cache; pub mod capability; pub mod c2; pub mod chain; @@ -36,13 +37,17 @@ pub mod graph_memory; pub mod graph_reasoning; pub mod grounding; pub mod hygiene; +pub mod improve; pub mod inbox; +pub mod ingest; pub mod integrations; pub mod integrity; pub mod internal; pub mod json_extract; pub mod knowledge; pub mod knowledge_graph; +pub mod limits; +pub mod logship; pub mod mcp_hot_reload; pub mod mcp_profiles; pub mod memory; @@ -54,6 +59,7 @@ pub mod prosecutor; pub mod reactive; pub mod reactive_bridge; pub mod redact; +pub mod repro; pub mod request_analyzer; pub mod provenance; pub mod models; @@ -82,6 +88,7 @@ pub mod types; pub mod usage; pub mod typesafe; pub mod typesafe_agent; +pub mod tunnel; pub mod uncertainty; pub mod validation; pub mod waf; @@ -98,6 +105,9 @@ pub use pipeline::run; pub use reactive_bridge::run_reactive; pub use knowledge_graph::{EdgeKind, KnowledgeGraph, NodeKind}; pub use memory::{Memory, Query as MemoryQuery, Tier as MemoryTier}; +pub use logship::{push_run, ship as ship_logs, Config as LogShipConfig, LogEvent, PushReport}; +pub use limits::{clip as clip_output, env_cap}; +pub use tunnel::TunnelConfig; pub use pool::{ModelPool, Task}; pub use audit::{AuditLog, AuditRecord, KillReason, KillSwitch}; pub use capability::{Capability, TokenError}; diff --git a/neurosploit-rs/crates/harness/src/limits.rs b/neurosploit-rs/crates/harness/src/limits.rs new file mode 100644 index 0000000..b5b5a6b --- /dev/null +++ b/neurosploit-rs/crates/harness/src/limits.rs @@ -0,0 +1,104 @@ +//! Safe string budgets for command output and model payloads. +//! +//! Two failure modes motivated this module: +//! +//! - `String::truncate(n)` **panics** unless `n` is a UTF-8 character +//! boundary. Command output is arbitrary bytes β€” a tool that prints a +//! multi-byte character right at the 256 KiB line was enough to take down a +//! run. Every clip now walks back to a boundary first. +//! - Keeping only the head loses the part operators actually need: a compiler, +//! a scanner or an exploit usually puts the verdict in the **last** lines +//! ("0 rows", "access denied", the stack trace). The clip keeps a head and a +//! tail with an explicit omission marker in between. +//! +//! Limits are configurable (`NEUROSPLOIT_CMD_CAP`, `NEUROSPLOIT_C2_OUTPUT_CAP`, +//! `NEUROSPLOIT_PROMPT_CAP`) and default generously: a truncated log that +//! silently drops evidence is worse than a large one that is stored once. + +/// Largest boundary at or below `i`, so slicing `&s[..i]` is always valid. +pub fn boundary(s: &str, i: usize) -> usize { + if i >= s.len() { + return s.len(); + } + let mut i = i; + while i > 0 && !s.is_char_boundary(i) { + i -= 1; + } + i +} + +/// Clip to at most `max` **bytes**, preserving the head and the tail and +/// marking what was omitted. Never panics on multi-byte input. +pub fn clip(s: &str, max: usize) -> String { + if max == 0 { + return String::new(); + } + if s.len() <= max { + return s.to_string(); + } + let omitted = s.len().saturating_sub(max) + 40; + let marker = format!("\n…[{omitted} bytes omitted]…\n"); + if marker.len() >= max { + let cut = boundary(s, max); + return s[..cut].to_string(); + } + let budget = max - marker.len(); + // Favor the tail slightly: verdicts and errors live there. + let head = budget * 2 / 5; + let tail = budget - head; + let h = boundary(s, head); + let t = boundary(s, s.len().saturating_sub(tail)); + let mut out = String::with_capacity(max); + out.push_str(&s[..h]); + out.push_str(&marker); + out.push_str(&s[t..]); + out +} + +/// A byte cap from the environment, clamped to something sane. +pub fn env_cap(key: &str, default: usize) -> usize { + std::env::var(key) + .ok() + .and_then(|v| v.trim().parse::().ok()) + .filter(|&v| v >= 1024) + .unwrap_or(default) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn clips_on_a_char_boundary_without_panicking() { + // "Γ©" is two bytes; cutting at an odd index would panic with + // String::truncate. + let s = "aaaaaaaaaaéééééééééé"; + for n in 0..s.len() { + let out = clip(s, n); + assert!(out.len() <= n.max(1) + 64, "cap {n}: {}", out.len()); + } + } + + #[test] + fn keeps_head_and_tail() { + let s = format!("HEAD{}TAIL", "x".repeat(10_000)); + let out = clip(&s, 400); + assert!(out.starts_with("HEAD")); + assert!(out.ends_with("TAIL")); + assert!(out.contains("bytes omitted")); + assert!(out.len() <= 400); + } + + #[test] + fn short_input_is_untouched() { + assert_eq!(clip("hello", 100), "hello"); + } + + #[test] + fn boundary_is_valid() { + let s = "aΓ©"; + assert_eq!(boundary(s, 1), 1); + assert_eq!(boundary(s, 2), 1, "index 2 is inside 'Γ©'"); + assert_eq!(boundary(s, 3), 3); + } +} diff --git a/neurosploit-rs/crates/harness/src/logship.rs b/neurosploit-rs/crates/harness/src/logship.rs new file mode 100644 index 0000000..f0e725c --- /dev/null +++ b/neurosploit-rs/crates/harness/src/logship.rs @@ -0,0 +1,460 @@ +//! Optional OpenSearch log shipping β€” one index per engagement/project. +//! +//! Runs already leave a rich trail on disk (`audit.jsonl`, `traces/*.md`, +//! `findings.json`, `status.json`, `usage.json`, toolbox logs). That trail is +//! excellent forensics and terrible operations: it lives in a directory per +//! run, so answering "show me every error this customer's targets produced +//! this week" means walking a filesystem and parsing five formats. +//! +//! This module is the bridge. [`collect_run`] turns a finished run into a flat +//! list of structured [`LogEvent`]s; [`ship`] bulk-indexes them into +//! OpenSearch. Index names are derived from the engagement project, so every +//! customer/domain gets its own `ns-` index and the usual OpenSearch +//! tooling (Kibana-style queries, per-project retention) works without a +//! custom backend. +//! +//! Three rules keep this safe to enable: +//! +//! - It is **opt-in and best-effort**. With `OPENSEARCH_URL` unset every +//! function is a no-op, and a failed shipment never fails the run. +//! - It **never invents** what it indexes: every event is either a parsed line +//! from an existing artifact or counts/status read from one. +//! - It **does not redact on the way in**. The vault already owns secrets; +//! the log store is an operator control plane, and a redacted log cannot +//! reproduce a bug. Access to the index is the control, not mangling the +//! evidence. + +use serde::{Deserialize, Serialize}; +use std::path::{Path, PathBuf}; + +/// Connection + naming settings, resolved from the environment. +#[derive(Clone, Debug)] +pub struct Config { + /// Base URL, e.g. `http://127.0.0.1:9200`. + pub url: String, + pub username: Option, + pub password: Option, + /// Engagement project/company/domain label β€” the index discriminator. + pub project: String, + /// Index template. `{project}` and `{date}` are substituted. + pub index: String, + /// Verify TLS certificates (disable only for a self-signed local install). + pub verify_tls: bool, +} + +impl Config { + /// Resolve from the environment, or `None` when shipping is not configured. + /// + /// `OPENSEARCH_URL` is the switch. `project` (when given) wins over + /// `NS_LOG_PROJECT`; the fallback label is `default`. + pub fn from_env(project: Option<&str>) -> Option { + let url = env_nonempty("OPENSEARCH_URL")?; + let project = project + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) + .or_else(|| env_nonempty("NS_LOG_PROJECT")) + .unwrap_or_else(|| "default".to_string()); + let index = env_nonempty("OPENSEARCH_INDEX").unwrap_or_else(|| "ns-{project}".to_string()); + let verify_tls = env_nonempty("OPENSEARCH_VERIFY_TLS") + .map(|v| !matches!(v.to_ascii_lowercase().as_str(), "0" | "false" | "no" | "off")) + .unwrap_or(true); + Some(Self { + url: url.trim_end_matches('/').to_string(), + username: env_nonempty("OPENSEARCH_USERNAME"), + password: env_nonempty("OPENSEARCH_PASSWORD"), + project, + index, + verify_tls, + }) + } + + /// Concrete index name for a date (`YYYY.MM.DD`), lowercased and sanitized + /// to OpenSearch's index rules (no uppercase, no `\/*?"<>| ,#:`, not + /// starting with `_`, `-`, `+`). + pub fn index_for(&self, date: &str) -> String { + let rendered = self + .index + .replace("{project}", &self.project) + .replace("{date}", date); + sanitize_index(&rendered) + } +} + +fn env_nonempty(key: &str) -> Option { + std::env::var(key).ok().map(|s| s.trim().to_string()).filter(|s| !s.is_empty()) +} + +/// Force a string into a legal OpenSearch index name. +pub fn sanitize_index(raw: &str) -> String { + let mut out = String::with_capacity(raw.len()); + for c in raw.to_ascii_lowercase().chars() { + if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | '+') { + out.push(c); + } else { + out.push('-'); + } + } + let out = out.trim_matches(|c| c == '_' || c == '-' || c == '+').to_string(); + let mut out = if out.is_empty() { "ns-default".to_string() } else { out }; + if out.len() > 200 { + out.truncate(200); + } + out +} + +/// One indexable log record. The field set is deliberately flat and stable so +/// dashboards and saved searches can be shared between evidence classes. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct LogEvent { + /// RFC3339 UTC. + #[serde(rename = "@timestamp")] + pub timestamp: String, + /// Engagement project / customer / domain. + pub project: String, + /// Artifact class: run Β· audit Β· trace Β· finding Β· error Β· usage Β· status Β· poc. + pub kind: String, + /// info Β· low Β· medium Β· high Β· critical Β· error. + pub level: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub run_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub agent: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub target: Option, + /// Human-readable one-liner. + pub message: String, + /// The unmodified source record (or the artifact text), for reproduction. + #[serde(skip_serializing_if = "Option::is_none")] + pub data: Option, +} + +impl LogEvent { + pub fn new(project: &str, kind: &str, level: &str, message: impl Into) -> Self { + Self { + timestamp: now_rfc3339(), + project: project.to_string(), + kind: kind.to_string(), + level: level.to_string(), + run_id: None, + agent: None, + target: None, + message: message.into(), + data: None, + } + } +} + +/// Turn a finished (or in-progress) run directory into flat events. +/// +/// Missing artifacts are skipped β€” a run that died during recon is exactly the +/// kind of run whose partial logs matter β€” so this never errors on a sparse +/// directory. +pub fn collect_run(dir: &Path, project: &str) -> Vec { + let run_id = dir.file_name().and_then(|s| s.to_str()).map(|s| s.to_string()); + let mut events: Vec = Vec::new(); + let mut push = |mut e: LogEvent| { + e.run_id = run_id.clone(); + events.push(e); + }; + + if let Some(meta) = read_json(&dir.join("status.json")) { + let state = meta.get("state").and_then(|v| v.as_str()).unwrap_or("unknown"); + let mut e = LogEvent::new(project, "status", "info", format!("run status: {state}")); + e.target = meta.get("target").and_then(|v| v.as_str()).map(String::from); + e.data = Some(meta); + push(e); + } + + if let Some(arr) = read_json(&dir.join("findings.json")).and_then(|v| v.as_array().cloned()) { + for f in arr { + let severity = f.get("severity").and_then(|v| v.as_str()).unwrap_or("info"); + let title = f.get("title").and_then(|v| v.as_str()).unwrap_or("finding"); + let target = f.get("endpoint").and_then(|v| v.as_str()).map(String::from); + let mut e = LogEvent::new(project, "finding", severity, title.to_string()); + e.target = target; + e.data = Some(f); + push(e); + } + } + + for line in read_lines(&dir.join("audit.jsonl")) { + let Ok(v) = serde_json::from_str::(&line) else { continue }; + let decision = v.get("policy_decision").and_then(|x| x.as_str()).unwrap_or(""); + let level = if decision.starts_with("deny") { "error" } else { "info" }; + let action = v.get("action").and_then(|x| x.as_str()).unwrap_or("action"); + let result = v.get("result").and_then(|x| x.as_str()).unwrap_or(""); + let mut e = LogEvent::new(project, "audit", level, format!("{action}: {result}")); + e.agent = v.get("agent").and_then(|x| x.as_str()).map(String::from); + e.target = v.get("target").and_then(|x| x.as_str()).map(String::from); + e.timestamp = v + .get("timestamp") + .and_then(|x| x.as_str()) + .map(String::from) + .unwrap_or_else(now_rfc3339); + e.data = Some(v); + push(e); + } + + for (name, text) in read_dir_text(&dir.join("traces")) { + let mut e = LogEvent::new( + project, + "trace", + "info", + format!("{name}: {} bytes of agent transcript", text.len()), + ); + e.agent = Some(name.clone()); + e.data = Some(serde_json::json!({ "agent": name, "text": text })); + push(e); + } + + if let Some(v) = read_json(&dir.join("usage.json")) { + let mut e = LogEvent::new(project, "usage", "info", "token/cost usage"); + e.data = Some(v); + push(e); + } + + if let Some(v) = read_json(&dir.join("errors.json")) { + let mut e = LogEvent::new(project, "error", "error", "error report"); + e.data = Some(v); + push(e); + } + for line in read_lines(&dir.join("errors.jsonl")) { + let mut e = LogEvent::new(project, "error", "error", "logged error"); + e.data = serde_json::from_str(&line).ok().or_else(|| Some(serde_json::json!({ "text": line }))); + push(e); + } + for (name, text) in read_dir_text(&dir.join("pocs")) { + if !text.is_empty() { + let mut e = LogEvent::new(project, "poc", "info", format!("poc artifact: {name}")); + e.data = Some(serde_json::json!({ "name": name, "text": text })); + push(e); + } + } + events +} + +fn read_lines(path: &Path) -> Vec { + let Ok(text) = std::fs::read_to_string(path) else { return Vec::new() }; + text.lines().filter(|l| !l.trim().is_empty()).map(String::from).collect() +} + +fn read_json(path: &Path) -> Option { + let text = std::fs::read_to_string(path).ok()?; + serde_json::from_str(&text).ok() +} + +fn read_dir_text(dir: &Path) -> Vec<(String, String)> { + let Ok(rd) = std::fs::read_dir(dir) else { return Vec::new() }; + let mut out: Vec<(String, String)> = rd + .flatten() + .filter(|e| e.path().is_file()) + .filter_map(|e| { + let name = e.file_name().to_string_lossy().to_string(); + let text = std::fs::read_to_string(e.path()).ok()?; + Some((name, text)) + }) + .collect(); + out.sort_by(|a, b| a.0.cmp(&b.0)); + out +} + +/// Bulk-index events. Returns how many documents the cluster accepted. +/// +/// A shipment is chunked at 500 documents. HTTP/transport failures surface as +/// an error for the caller to warn about; individual item failures are counted +/// from the bulk response and reported in the returned [`PushReport`]. +pub async fn ship(cfg: &Config, events: &[LogEvent]) -> anyhow::Result { + if events.is_empty() { + return Ok(PushReport::default()); + } + let mut client = reqwest::Client::builder().user_agent("neurosploit-logship/4.4"); + if !cfg.verify_tls { + client = client.danger_accept_invalid_certs(true); + } + let client = client.build()?; + let index = cfg.index_for(&today()); + + let mut report = PushReport { attempted: events.len(), ..Default::default() }; + for chunk in events.chunks(500) { + let mut body = String::new(); + for e in chunk { + let meta = serde_json::json!({ "index": { "_index": index } }); + body.push_str(&serde_json::to_string(&meta)?); + body.push('\n'); + body.push_str(&serde_json::to_string(e)?); + body.push('\n'); + } + let mut req = client + .post(format!("{}/_bulk", cfg.url)) + .header("Content-Type", "application/x-ndjson") + .body(body); + if let Some(user) = &cfg.username { + req = req.basic_auth(user, Some(cfg.password.clone().unwrap_or_default())); + } + let resp = req.send().await?; + let status = resp.status(); + let text = resp.text().await.unwrap_or_default(); + if !status.is_success() { + anyhow::bail!("OpenSearch _bulk returned {status}: {}", truncate(&text, 400)); + } + if let Ok(v) = serde_json::from_str::(&text) { + if v.get("errors").and_then(|x| x.as_bool()) == Some(true) { + if let Some(items) = v.get("items").and_then(|x| x.as_array()) { + for item in items { + let idx = item.get("index").unwrap_or(item); + if idx.get("error").is_some() { + report.failed += 1; + } else { + report.indexed += 1; + } + } + } + } else { + report.indexed += chunk.len(); + } + } else { + report.indexed += chunk.len(); + } + } + Ok(report) +} + +/// Summarize a shipment. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct PushReport { + pub attempted: usize, + pub indexed: usize, + pub failed: usize, +} + +/// `GET /` β€” proves the URL, credentials and reachability before a run. +pub async fn ping(cfg: &Config) -> anyhow::Result { + let mut client = reqwest::Client::builder().user_agent("neurosploit-logship/4.4"); + if !cfg.verify_tls { + client = client.danger_accept_invalid_certs(true); + } + let client = client.build()?; + let mut req = client.get(format!("{}/", cfg.url)); + if let Some(user) = &cfg.username { + req = req.basic_auth(user, Some(cfg.password.clone().unwrap_or_default())); + } + let resp = req.send().await?; + let status = resp.status(); + let text = resp.text().await.unwrap_or_default(); + if !status.is_success() { + anyhow::bail!("OpenSearch returned {status}: {}", truncate(&text, 400)); + } + Ok(text) +} + +fn truncate(s: &str, n: usize) -> String { + s.chars().take(n).collect() +} + +/// `YYYY.MM.DD` in UTC. +pub fn today() -> String { + let secs = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or(0); + let (y, m, d) = civil_from_days(secs.div_euclid(86_400)); + format!("{y:04}.{m:02}.{d:02}") +} + +/// RFC3339 UTC timestamp for now. +pub fn now_rfc3339() -> String { + let secs = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or(0); + rfc3339_from_unix(secs) +} + +fn rfc3339_from_unix(secs: i64) -> String { + let days = secs.div_euclid(86_400); + let rem = secs.rem_euclid(86_400); + let (y, m, d) = civil_from_days(days); + let (h, min, s) = (rem / 3600, (rem % 3600) / 60, rem % 60); + format!("{y:04}-{m:02}-{d:02}T{h:02}:{min:02}:{s:02}Z") +} + +/// Howard Hinnant's daysβ†’civil conversion (proleptic Gregorian, UTC). +fn civil_from_days(z: i64) -> (i64, u32, u32) { + let z = z + 719_468; + let era = if z >= 0 { z } else { z - 146_096 } / 146_097; + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let y = yoe + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + (y + i64::from(m <= 2), m as u32, d as u32) +} + +/// Convenience: collect and ship one run directory. +pub async fn push_run(cfg: &Config, dir: &Path) -> anyhow::Result<(PushReport, usize)> { + let events = collect_run(dir, &cfg.project); + let n = events.len(); + let report = ship(cfg, &events).await?; + Ok((report, n)) +} + +/// Locate a run directory from a run id (`ns-…`) or a path, against `root`. +pub fn resolve_run(root: &Path, run: &str) -> Option { + let p = PathBuf::from(run); + if p.is_dir() { + return Some(p); + } + let candidate = root.join(run); + candidate.is_dir().then_some(candidate) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn index_is_lowercase_and_legal() { + assert_eq!(sanitize_index("NS-Acme/Prod 01"), "ns-acme-prod-01"); + assert_eq!(sanitize_index("__x__"), "x"); + assert_eq!(sanitize_index(""), "ns-default"); + } + + #[test] + fn template_substitution() { + let cfg = Config { + url: "http://localhost:9200".into(), + username: None, + password: None, + project: "Aureon".into(), + index: "ns-{project}-{date}".into(), + verify_tls: true, + }; + assert_eq!(cfg.index_for("2026.11.22"), "ns-aureon-2026.11.22"); + } + + #[test] + fn date_conversion() { + assert_eq!(rfc3339_from_unix(0), "1970-01-01T00:00:00Z"); + assert_eq!(rfc3339_from_unix(1_700_000_000), "2023-11-14T22:13:20Z"); + } + + #[test] + fn collect_reads_audit_and_traces() { + let dir = std::env::temp_dir().join(format!("ns-logship-test-{}", std::process::id())); + std::fs::create_dir_all(dir.join("traces")).unwrap(); + std::fs::write( + dir.join("audit.jsonl"), + "{\"timestamp\":\"2026-01-01T00:00:00Z\",\"agent\":\"sqli\",\"action\":\"GET /a\",\"target\":\"http://t\",\"policy_decision\":\"allow\",\"result\":\"200\"}\n", + ) + .unwrap(); + std::fs::write(dir.join("traces").join("sqli.md"), "GET /a -> 200").unwrap(); + std::fs::write(dir.join("findings.json"), "[{\"title\":\"XSS\",\"severity\":\"high\",\"endpoint\":\"http://t/x\"}]").unwrap(); + let events = collect_run(&dir, "acme"); + assert!(events.iter().any(|e| e.kind == "audit" && e.agent.as_deref() == Some("sqli"))); + assert!(events.iter().any(|e| e.kind == "trace" && e.agent.as_deref() == Some("sqli.md"))); + assert!(events.iter().any(|e| e.kind == "finding" && e.level == "high")); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/neurosploit-rs/crates/harness/src/mcp_profiles.rs b/neurosploit-rs/crates/harness/src/mcp_profiles.rs index 0f8140e..de50a00 100644 --- a/neurosploit-rs/crates/harness/src/mcp_profiles.rs +++ b/neurosploit-rs/crates/harness/src/mcp_profiles.rs @@ -20,6 +20,7 @@ pub enum Profile { MobileIos, BinaryAnalysis, BurpSuite, + CobaltStrike, Infra, Ad, Cloud, @@ -110,6 +111,26 @@ pub fn profile(p: &Profile) -> McpProfile { "env": {} }), }, + // Official Cobalt Strike MCP (github.com/Cobalt-Strike/cobaltstrike-mcp-server). + // It is an HTTP-transport MCP served by the team server (Cobalt Strike + // 4.13+), not a stdio child β€” point `CS_MCP_URL` at it (default + // http://teamserver:50051/mcp) and keep the credentials in the env. + Profile::CobaltStrike => McpProfile { + name: "Cobalt Strike".into(), + description: "Cobalt Strike team-server C2 via the official HTTP MCP".into(), + server_name: "cobaltstrike".into(), + tools: tool_allowlist(p), + config: json!({ + "transport": "http", + "url": "http://teamserver:50051/mcp", + "env": { + "CS_MCP_URL": "https://localhost:50443", + "CS_MCP_USERNAME": "mcp", + "CS_MCP_PASSWORD": "", + "CS_MCP_VERIFY_SSL": "false" + } + }), + }, Profile::Infra => McpProfile { name: "Infra".into(), description: "Network/infra testing with an Nmap MCP server".into(), @@ -198,6 +219,10 @@ pub fn all_profiles() -> Vec<(Profile, &'static str)> { Profile::BurpSuite, "Burp Suite REST API integration (placeholder)", ), + ( + Profile::CobaltStrike, + "Cobalt Strike team-server C2 via the official HTTP MCP", + ), (Profile::Infra, "Network/infra testing with Nmap MCP"), (Profile::Ad, "Active Directory testing with Kali MCP"), (Profile::Cloud, "Cloud/container tooling via Kali MCP"), @@ -269,6 +294,20 @@ pub fn tool_allowlist(p: &Profile) -> Vec { "proxy_history", "send_to_repeater", ], + Profile::CobaltStrike => &[ + "cs_list_beacons", + "cs_list_commands", + "cs_execute_command", + "cs_list_command_executions", + "cs_read_command_output", + "cs_list_artifacts", + "cs_upload_artifact", + "cs_list_downloads", + "cs_fetch_download", + "cs_list_screenshots", + "cs_fetch_screenshot", + "cs_get_team_server", + ], Profile::Infra | Profile::Nmap => &[ "do-nmap", "nmap_scan", "nmap_service_scan", "nmap_vuln_scan", "nmap_os_detect", "nmap_ping_sweep", @@ -335,6 +374,15 @@ pub fn prompt_context(p: &Profile) -> String { Note: this profile is a placeholder; ensure the Burp REST API \ is running before invoking tools." ), + Profile::CobaltStrike => format!( + "You are operating in COBALT STRIKE mode through the official team-server MCP. \ + Available tools: {tool_list}. Use cs_list_beacons to establish the current session \ + inventory before acting, cs_execute_command to run one authorized command at a time, \ + and cs_read_command_output for the receipt. Every action is attributable to the \ + engagement β€” stay inside the authorized hosts, never run destructive or \ + persistence-changing commands unless the operator explicitly approved them, \ + and put the raw command output into the finding evidence." + ), Profile::Infra => format!( "You are operating in INFRA/NETWORK testing mode. Use the Nmap MCP server for \ host discovery, port/service identification and NSE checks. Available tools: {tool_list}. \ @@ -415,6 +463,7 @@ mod tests { Profile::MobileIos, Profile::BinaryAnalysis, Profile::BurpSuite, + Profile::CobaltStrike, Profile::Infra, Profile::Ad, Profile::Cloud, diff --git a/neurosploit-rs/crates/harness/src/models.rs b/neurosploit-rs/crates/harness/src/models.rs index 7a739f9..765abca 100644 --- a/neurosploit-rs/crates/harness/src/models.rs +++ b/neurosploit-rs/crates/harness/src/models.rs @@ -23,7 +23,7 @@ pub struct Provider { pub fn providers() -> Vec { vec![ Provider { key: "anthropic", label: "Anthropic Claude", base_url: "https://api.anthropic.com/v1", env_key: "ANTHROPIC_API_KEY", kind: "cli", - models: vec!["claude-opus-5-5", "claude-mythos-5-1", "claude-opus-5", "claude-sonnet-5", "claude-fable-5-1", "claude-opus-4-8", "claude-opus-4-6", "claude-sonnet-4-6", "claude-haiku-4-5"] }, + models: vec!["claude-fable-5-2", "claude-mythos-5-2", "claude-opus-5-5", "claude-fable-5-1", "claude-mythos-5-1", "claude-opus-5", "claude-sonnet-5", "claude-opus-4-8", "claude-opus-4-6", "claude-sonnet-4-6", "claude-haiku-4-5"] }, Provider { key: "openai", label: "OpenAI (ChatGPT)", base_url: "https://api.openai.com/v1", env_key: "OPENAI_API_KEY", kind: "cli", models: vec!["gpt-6-astra", "gpt-6-sol", "gpt-6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna", "gpt-5.5", "gpt-5.4", "gpt-5.4-mini", "gpt-5.3-codex", "gpt-5.2", "gpt-5.1", "gpt-5.1-codex", "o4"] }, Provider { key: "xai", label: "xAI Grok", base_url: "https://api.x.ai/v1", env_key: "XAI_API_KEY", kind: "cli", @@ -59,7 +59,7 @@ pub fn providers() -> Vec { Provider { key: "litellm", label: "LiteLLM (proxy)", base_url: "http://localhost:4000/v1", env_key: "LITELLM_API_KEY", kind: "api", models: vec!["gpt-4o", "claude-3-7-sonnet", "gemini/gemini-2.5-pro"] }, Provider { key: "openrouter", label: "OpenRouter", base_url: "https://openrouter.ai/api/v1", env_key: "OPENROUTER_API_KEY", kind: "api", - models: vec!["anthropic/claude-opus-5-5", "anthropic/claude-mythos-5-1", "anthropic/claude-opus-4-8", "z-ai/glm-5.3", "qwen/qwen3.8-max", "deepseek/deepseek-v4.1", "meta-llama/llama-3.3-70b-instruct"] }, + models: vec!["anthropic/claude-fable-5-2", "anthropic/claude-mythos-5-2", "anthropic/claude-opus-5-5", "anthropic/claude-fable-5-1", "anthropic/claude-mythos-5-1", "anthropic/claude-opus-4-8", "z-ai/glm-5.3", "qwen/qwen3.8-max", "deepseek/deepseek-v4.1", "meta-llama/llama-3.3-70b-instruct"] }, // OpenCode Zen β€” the curated OpenAI-compatible gateway behind the // `opencode` CLI (https://opencode.ai/zen). Works two ways, like // anthropic/openai/xai/gemini above: as a plain API-key provider here, @@ -67,7 +67,7 @@ pub fn providers() -> Vec { // `opencode` agentic CLI on the user's own Zen/plan login β€” no key // needed in that mode. `kind: "cli"` reflects the latter. Provider { key: "opencode", label: "OpenCode Zen", base_url: "https://opencode.ai/zen/v1", env_key: "OPENCODE_API_KEY", kind: "cli", - models: vec!["claude-opus-5-5", "claude-mythos-5-1", "claude-opus-5", "claude-sonnet-5", "gpt-6-sol", "gpt-5.6-sol", "gpt-5.5", "gemini-3-pro", "gemini-3.8-flash", "grok-4.7", "grok-4.5", "glm-5.3", "deepseek-v4.1", "deepseek-v4-pro", "qwen3.8-max", "kimi-k3"] }, + models: vec!["claude-fable-5-2", "claude-mythos-5-2", "claude-opus-5-5", "claude-fable-5-1", "claude-mythos-5-1", "claude-opus-5", "claude-sonnet-5", "gpt-6-sol", "gpt-5.6-sol", "gpt-5.5", "gemini-3-pro", "gemini-3.8-flash", "grok-4.7", "grok-4.5", "glm-5.3", "deepseek-v4.1", "deepseek-v4-pro", "qwen3.8-max", "kimi-k3"] }, // Nous Research β€” Hermes models via the Nous Portal. As an API-key // provider here (OpenAI-compatible `inference-api.nousresearch.com`), // or (with --subscription) driven through the `hermes` CLI @@ -77,7 +77,7 @@ pub fn providers() -> Vec { // (`hermes chat -m --provider nous`): `nous:qwen3.8-max` and other // routed models work even though only the Hermes-family defaults are listed. Provider { key: "nous", label: "Nous Research (Hermes)", base_url: "https://inference-api.nousresearch.com/v1", env_key: "NOUS_API_KEY", kind: "cli", - models: vec!["Hermes-4-405B", "Hermes-4-70B", "DeepHermes-3-Mistral-24B-Preview", "claude-mythos-5-1", "qwen3.8-max", "qwen3.8-omni-flash"] }, + models: vec!["Hermes-4-405B", "Hermes-4-70B", "DeepHermes-3-Mistral-24B-Preview", "claude-fable-5-2", "claude-mythos-5-2", "claude-mythos-5-1", "qwen3.8-max", "qwen3.8-omni-flash"] }, // Azure OpenAI (OpenAI-compatible). Set AZURE_OPENAI_ENDPOINT (e.g. // https://.openai.azure.com), optionally AZURE_OPENAI_API_VERSION // (default 2024-10-21), and use `azure:` as the model. @@ -1079,10 +1079,15 @@ 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-"); + // Go big. Output budget is the single most common cause of a truncated + // ReAct chain or a JSON findings block cut mid-object, and a re-run costs + // far more than the extra output tokens. These are ceilings, not usage: + // a model that answers in 800 tokens still bills 800. A provider with a + // lower hard limit can be pinned with NEUROSPLOIT_MAX_TOKENS. if reasoning || claude_large { - 32768 + 131072 } else { - 4096 + 65536 } } @@ -1183,7 +1188,7 @@ mod response_tests { } assert_eq!(cli_binary_for("zai"), Some("claude"), "GLM runs via the claude CLI"); // GLM is reasoning-heavy β†’ gets the larger token ceiling. - assert_eq!(max_tokens_for("glm-5.3"), 32768); + assert_eq!(max_tokens_for("glm-5.3"), 131072); } #[test] @@ -1198,21 +1203,21 @@ mod response_tests { #[test] fn reasoning_models_get_more_headroom() { for m in ["glm-5.3", "glm-4.6", "deepseek-v4.1", "z-ai/glm-5.3", "qwen3.8-max", "kimi-k3", "o3", "gpt-6-sol"] { - assert_eq!(max_tokens_for(m), 32768, "{m} should be treated as reasoning-heavy"); + assert_eq!(max_tokens_for(m), 131072, "{m} should be treated as reasoning-heavy"); } } #[test] fn plain_models_keep_default() { for m in ["gpt-5.5", "gemini-3-pro", "grok-4.7", "meta-llama/llama-3.3-70b-instruct"] { - assert_eq!(max_tokens_for(m), 4096, "{m} should keep the default cap"); + assert_eq!(max_tokens_for(m), 65536, "{m} should keep the default cap"); } } #[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), 32768, "{m} should get 32k for ReAct+JSON output"); + assert_eq!(max_tokens_for(m), 131072, "{m} should get 128k for ReAct+JSON output"); } } diff --git a/neurosploit-rs/crates/harness/src/pool.rs b/neurosploit-rs/crates/harness/src/pool.rs index 03e8c39..a337dd8 100644 --- a/neurosploit-rs/crates/harness/src/pool.rs +++ b/neurosploit-rs/crates/harness/src/pool.rs @@ -310,6 +310,13 @@ impl ModelPool { return Err(anyhow!("cancelled")); } let use_cli = m.use_cli(self.subscription); + let cache_key = crate::cache::key(&m.provider, &m.model, use_cli, system, user); + if let Some(hit) = crate::cache::get(&cache_key) { + if let Some(tx) = self.progress() { + let _ = tx.send(format!("cache hit β†’ {}:{}", m.provider, m.model)); + } + return Ok(hit); + } let progress = self.progress(); let mut last = anyhow::anyhow!("no attempt"); for attempt in 0..MAX_TRANSIENT_RETRIES { @@ -334,7 +341,10 @@ impl ModelPool { r = call => r, }; match r { - Ok(t) => return Ok(t), + Ok(t) => { + crate::cache::put(&cache_key, &m.model, &t); + return Ok(t); + } Err(e) => { let class = classify_error(&format!("{e:#}")); match class { diff --git a/neurosploit-rs/crates/harness/src/reactive_bridge.rs b/neurosploit-rs/crates/harness/src/reactive_bridge.rs index 4dcf813..859b4ae 100644 --- a/neurosploit-rs/crates/harness/src/reactive_bridge.rs +++ b/neurosploit-rs/crates/harness/src/reactive_bridge.rs @@ -117,6 +117,7 @@ pub async fn run_reactive( "mobile-ios" => crate::mcp_profiles::Profile::MobileIos, "binary" => crate::mcp_profiles::Profile::BinaryAnalysis, "burp" => crate::mcp_profiles::Profile::BurpSuite, + "cobaltstrike" | "cobalt" | "cs" | "c2" => crate::mcp_profiles::Profile::CobaltStrike, "infra" | "host" => crate::mcp_profiles::Profile::Infra, "ad" | "internal" => crate::mcp_profiles::Profile::Ad, "cloud" => crate::mcp_profiles::Profile::Cloud, diff --git a/neurosploit-rs/crates/harness/src/report.rs b/neurosploit-rs/crates/harness/src/report.rs index d682159..ccd8453 100644 --- a/neurosploit-rs/crates/harness/src/report.rs +++ b/neurosploit-rs/crates/harness/src/report.rs @@ -349,7 +349,10 @@ pub fn curl_command(f: &Finding) -> String { for (k, v) in &a.request_headers { // Never print a real credential into a document that gets // shared; the reader substitutes their own. - let val = if is_secret_header(k) { "" } else { v.as_str() }; + // A token, not the value: the vault resolves it on demand, so + // a shared report never carries a live credential. + let masked = format!("{{{{REVEALSECRET:{}}}}}", k.to_lowercase()); + let val = if is_secret_header(k) { masked.as_str() } else { v.as_str() }; cmd.push_str(&format!(" \\\n -H '{k}: {val}'")); } if !f.payload.trim().is_empty() && method != "GET" { diff --git a/neurosploit-rs/crates/harness/src/repro.rs b/neurosploit-rs/crates/harness/src/repro.rs new file mode 100644 index 0000000..c15cb12 --- /dev/null +++ b/neurosploit-rs/crates/harness/src/repro.rs @@ -0,0 +1,323 @@ +//! Rich, step-by-step reproduction kits β€” and secrets that stay in the vault. +//! +//! A report that says "SQL injection on /search" is a claim. A reproduction kit +//! that says *run this exact request, expect this exact difference, repeat it +//! twice* is evidence someone else can check. This module turns a finding's +//! recorded exchanges into that kit: +//! +//! 1. **Baseline** β€” the request without the payload, and what it returned. +//! 2. **Attack** β€” the request with the payload, byte for byte. +//! 3. **Verify** β€” the deterministic difference (status, length, marker, +//! repeats) that makes the effect more than a hunch. +//! 4. **Cleanup** β€” when the request changed state, how to undo it. +//! +//! ## Secrets +//! +//! Reproduction often needs the exact credential that proved the bug, but a +//! document is shared far more widely than the vault. So a kit carries a +//! **token** β€” `{{REVEALSECRET:name}}` β€” instead of the value. The vault on +//! disk is the only place the value lives; [`SecretStore::load`] reads it and +//! [`expand`] substitutes on demand (`neurosploit repro --reveal`). Without +//! `--reveal` the token is rendered as a masked placeholder, which is the safe +//! default for anything that leaves the operator's machine. + +use crate::types::Finding; +use std::collections::BTreeMap; +use std::path::Path; + +/// Named secrets read from a run's vault. Lookup is by account name, header +/// label (`authorization`, `cookie`), and any explicit `secrets.json` keys. +#[derive(Clone, Debug, Default)] +pub struct SecretStore { + map: BTreeMap, +} + +impl SecretStore { + pub fn load(run_dir: &Path) -> Self { + let mut map = BTreeMap::new(); + for name in ["secrets.json", "vault.json"] { + if let Ok(text) = std::fs::read_to_string(run_dir.join(name)) { + if let Ok(v) = serde_json::from_str::(&text) { + absorb(&mut map, &v); + } + } + } + if let Ok(text) = std::fs::read_to_string(run_dir.join("vault.jsonl")) { + for line in text.lines().filter(|l| !l.trim().is_empty()) { + if let Ok(v) = serde_json::from_str::(line) { + absorb(&mut map, &v); + } + } + } + SecretStore { map } + } + + pub fn get(&self, key: &str) -> Option<&str> { + self.map.get(key).map(String::as_str) + } + + pub fn insert(&mut self, key: impl Into, value: impl Into) { + let k = key.into().trim().to_lowercase(); + let v = value.into(); + if !k.is_empty() && !v.is_empty() { + self.map.insert(k, v); + } + } + + pub fn len(&self) -> usize { + self.map.len() + } + pub fn is_empty(&self) -> bool { + self.map.is_empty() + } +} + +fn absorb(map: &mut BTreeMap, v: &serde_json::Value) { + match v { + serde_json::Value::Array(items) => { + for it in items { + absorb(map, it); + } + } + serde_json::Value::Object(o) => { + // A vault entry: account + secret (+ optional role/endpoint). + let account = o.get("account").and_then(|x| x.as_str()).unwrap_or(""); + let secret = o.get("secret").or_else(|| o.get("password")).and_then(|x| x.as_str()).unwrap_or(""); + if !account.is_empty() && !secret.is_empty() { + map.insert(account.trim().to_lowercase(), secret.to_string()); + } + // A plain map of name -> value (secrets.json). + for (k, val) in o { + if let Some(s) = val.as_str() { + if k != "account" && k != "secret" { + map.insert(k.trim().to_lowercase(), s.to_string()); + } + } + } + } + _ => {} + } +} + +/// Replace `{{REVEALSECRET:key}}`, `[[REVEALSECRET:key]]` and +/// `REVEALSECRET(key)` with the vault value. When `reveal` is false (or the +/// key is unknown) a masked placeholder is left, so the token itself never +/// leaks the secret. +pub fn expand(text: &str, store: &SecretStore, reveal: bool) -> String { + let mut out = String::with_capacity(text.len()); + let bytes = text.as_bytes(); + let mut i = 0; + while i < bytes.len() { + let (open, close, prefix_len) = if text[i..].starts_with("{{REVEALSECRET:") { + ("{{REVEALSECRET:", "}}", 15) + } else if text[i..].starts_with("[[REVEALSECRET:") { + ("[[REVEALSECRET:", "]]", 15) + } else if text[i..].starts_with("REVEALSECRET(") { + ("REVEALSECRET(", ")", 13) + } else { + let ch = text[i..].chars().next().unwrap_or(' '); + out.push(ch); + i += ch.len_utf8(); + continue; + }; + let _ = open; + let start = i + prefix_len; + let Some(rel_end) = text[start..].find(close) else { + let ch = text[i..].chars().next().unwrap_or(' '); + out.push(ch); + i += ch.len_utf8(); + continue; + }; + let key = text[start..start + rel_end].trim(); + match store.get(key) { + Some(v) if reveal => out.push_str(v), + Some(_) => out.push_str(&format!("β€’β€’β€’β€’β€’β€’ (REVEALSECRET:{key})")), + None => out.push_str(&format!("{{{{REVEALSECRET:{key}}}}}")), + } + i = start + rel_end + close.len(); + } + out +} + +/// Build the ordered, human-runnable steps for one finding. +/// +/// Recorded `repro_steps` win (they are what the agent actually did); this only +/// fills the gaps and expands tokens. Every step is self-contained enough to +/// paste into a shell, because the reader should not have to reconstruct a +/// request from prose. +pub fn steps(f: &Finding, store: &SecretStore, reveal: bool) -> Vec { + let mut out: Vec = Vec::new(); + let push = |out: &mut Vec, s: String| { + let s = expand(&s, store, reveal); + if !s.trim().is_empty() && !out.iter().any(|x| *x == s) { + out.push(s); + } + }; + + if !f.repro_steps.is_empty() { + for s in &f.repro_steps { + push(&mut out, s.clone()); + } + } + + if let Some(ev) = &f.evidence_data { + // 1 β€” baseline. + if let Some(b) = &ev.baseline { + push(&mut out, format!( + "Baseline (no payload) β€” expect HTTP {} ({} bytes):\n{}", + b.status, b.len(), exchange_curl(b) + )); + } + // 2 β€” attack. + if let Some(a) = &ev.attack { + push(&mut out, format!( + "Attack β€” send the payload. Recorded response: HTTP {} ({} bytes, {} ms):\n{}", + a.status, a.len(), a.elapsed_ms, exchange_curl(a) + )); + } + // 3 β€” verification. + if let (Some(b), Some(a)) = (&ev.baseline, &ev.attack) { + let d = crate::validation::diff(b, a); + let mut verify = format!("Verify the difference β€” expected: {}", d.describe()); + if !ev.repeats.is_empty() { + let (ok, hits) = crate::validation::reproducible(b, &ev.repeats, 2); + verify.push_str(&format!( + "\nRepeat the attack {}Γ—; the same difference must appear each time (recorded: {hits}/{}).", + ev.repeats.len() + 1, + ev.repeats.len() + )); + if !ok { + verify.push_str(" Not deterministic β€” treat as needs-review."); + } + } + if !ev.marker.is_empty() { + verify.push_str(&format!( + "\nControlled marker `{}` β€” observed: {}.", + ev.marker, + if ev.marker_observed { "yes" } else { "no" } + )); + } + push(&mut out, verify); + } else if !ev.marker.is_empty() { + push(&mut out, format!( + "Verify the marker `{}` appears in the response (observed: {}).", + ev.marker, + if ev.marker_observed { "yes" } else { "no" } + )); + } + } + + if out.is_empty() { + let curl = crate::report::curl_command(f); + if !curl.is_empty() { + push(&mut out, format!("Send the request:\n{curl}")); + } + if !f.payload.trim().is_empty() { + push(&mut out, format!("Payload:\n{}", f.payload.trim())); + } + } + + // 4 β€” cleanup for state-changing proofs. + let method = f + .evidence_data + .as_ref() + .and_then(|e| e.attack.as_ref()) + .map(|a| a.method.to_uppercase()) + .unwrap_or_default(); + if matches!(method.as_str(), "POST" | "PUT" | "PATCH" | "DELETE") { + push(&mut out, "Cleanup β€” this request changed state. Delete the created object/account or restore the original value before leaving the engagement.".into()); + } + + if out.is_empty() { + out.push("No reproduction steps were recorded for this finding.".into()); + } + out +} + +fn exchange_curl(x: &crate::validation::Exchange) -> String { + let mut cmd = String::from("curl -i -s"); + let method = x.method.to_uppercase(); + if !method.is_empty() && method != "GET" { + cmd.push_str(&format!(" -X {method}")); + } + for (k, v) in &x.request_headers { + let value = if is_secret_header(k) { + format!("{{{{REVEALSECRET:{}}}}}", k.to_lowercase()) + } else { + v.clone() + }; + cmd.push_str(&format!(" \\\n -H '{}: {}'", k, value.replace('\'', "'\\''"))); + } + if !x.body.trim().is_empty() && method != "GET" { + cmd.push_str(&format!(" \\\n --data-raw '{}'", x.body.replace('\'', "'\\''"))); + } + cmd.push_str(&format!(" \\\n '{}'", x.url)); + cmd +} + +fn is_secret_header(k: &str) -> bool { + let k = k.to_lowercase(); + k == "authorization" || k == "cookie" || k == "x-api-key" || k.contains("token") || k.contains("secret") +} + +/// A complete Markdown reproduction kit for a run's findings. +pub fn markdown(run_dir: &Path, findings: &[Finding], store: &SecretStore, reveal: bool, only: Option<&str>) -> String { + let mut s = String::from("# Reproduction kit\n\n"); + s.push_str(&format!( + "Vault: {} secret(s) available. Secrets appear as `{{{{REVEALSECRET:name}}}}`; \ + run `neurosploit repro --reveal` to print the values.\n\n", + store.len() + )); + let mut n = 0; + for f in findings { + if let Some(id) = only { + if f.id != id && !f.title.eq_ignore_ascii_case(id) { + continue; + } + } + n += 1; + s.push_str(&format!("## {}. {} β€” {}\n\n", n, f.title, f.severity)); + s.push_str(&format!("- Endpoint: `{}`\n", if f.endpoint.is_empty() { "(not recorded)" } else { &f.endpoint })); + if !f.cwe.is_empty() { + s.push_str(&format!("- CWE: {}\n", f.cwe)); + } + s.push_str("\n"); + for (i, step) in steps(f, store, reveal).iter().enumerate() { + s.push_str(&format!("### Step {}\n\n```sh\n{}\n```\n\n", i + 1, step)); + } + if !f.evidence.trim().is_empty() { + s.push_str("### Recorded evidence\n\n```\n"); + s.push_str(&expand(f.evidence.trim(), store, reveal)); + s.push_str("\n```\n\n"); + } + s.push_str("---\n\n"); + } + if n == 0 { + s.push_str("_No matching findings._\n"); + } + let _ = run_dir; + s +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn expands_tokens_and_masks_by_default() { + let mut st = SecretStore::default(); + st.insert("alice", "s3cret"); + assert_eq!(expand("pw={{REVEALSECRET:alice}}", &st, false), "pw=β€’β€’β€’β€’β€’β€’ (REVEALSECRET:alice)"); + assert_eq!(expand("pw={{REVEALSECRET:alice}}", &st, true), "pw=s3cret"); + assert_eq!(expand("pw=[[REVEALSECRET:alice]]", &st, true), "pw=s3cret"); + assert_eq!(expand("pw=REVEALSECRET(alice)", &st, true), "pw=s3cret"); + assert_eq!(expand("{{REVEALSECRET:missing}}", &st, true), "{{REVEALSECRET:missing}}"); + } + + #[test] + fn absorbs_vault_array_and_jsonl_shape() { + let mut map = BTreeMap::new(); + absorb(&mut map, &serde_json::json!({"account":"u1","secret":"p1"})); + assert_eq!(map.get("u1").map(String::as_str), Some("p1")); + } +} diff --git a/neurosploit-rs/crates/harness/src/scope.rs b/neurosploit-rs/crates/harness/src/scope.rs index 69e3408..3659228 100644 --- a/neurosploit-rs/crates/harness/src/scope.rs +++ b/neurosploit-rs/crates/harness/src/scope.rs @@ -129,7 +129,7 @@ impl Pattern { // dodged by respelling the same address. See `crate::netguard`. let host = crate::netguard::normalize_host(&host_of(url)); match self { - Pattern::Host(h) => host == crate::netguard::normalize_host(h), + Pattern::Host(h) => same_host(&host, &crate::netguard::normalize_host(h)), Pattern::Wildcard(root) => { let root = crate::netguard::normalize_host(root); host == root || host.ends_with(&format!(".{root}")) } Pattern::Cidr { base, bits } => ipv4_to_u32(&host).map(|ip| ip & mask(*bits) == *base).unwrap_or(false), Pattern::UrlPrefix(p) => { @@ -151,6 +151,26 @@ impl Pattern { } } +/// Loopback spellings are the same host. An engagement authorized against +/// `localhost` must not be blocked when the target resolves itself as +/// `127.0.0.1`, and vice versa. +fn is_loopback(host: &str) -> bool { + matches!(host, "localhost" | "127.0.0.1" | "::1" | "0.0.0.0") +} + +fn same_host(a: &str, b: &str) -> bool { + a == b || (is_loopback(a) && is_loopback(b)) +} + +/// Is `host` a sub-domain of `root`? IPs never have sub-domains, so an IP rule +/// stays exact. +fn host_is_subdomain(host: &str, root: &str) -> bool { + if root.is_empty() || host == root || crate::netguard::parse_ip_any(root).is_some() { + return false; + } + host.ends_with(&format!(".{root}")) +} + fn mask(bits: u8) -> u32 { if bits == 0 { 0 @@ -235,6 +255,13 @@ pub struct SoftScope { /// Requests per minute across the engagement (0 = unlimited). #[serde(default = "default_rate")] pub max_requests_per_minute: u32, + /// Treat a `host` rule as also covering its sub-domains (`api.example.com` + /// under `example.com`). On by default: an engagement against a domain + /// almost always means the domain, and refusing every sub-domain turned a + /// normal test into a stream of false denials. Exclusions still win, and a + /// stricter engagement can turn this off in the scope YAML. + #[serde(default = "yes")] + pub allow_subdomains: bool, /// Payload substrings that are never acceptable, whatever the finding. /// Defaults cover data destruction and resource exhaustion β€” the two /// classes that damage a production target rather than demonstrate a bug. @@ -275,6 +302,7 @@ impl Default for SoftScope { allow_account_creation: true, max_accounts: default_max_accounts(), max_requests_per_minute: default_rate(), + allow_subdomains: true, forbidden_payloads: default_forbidden_payloads(), notes: Vec::new(), } @@ -469,6 +497,7 @@ impl ScopePolicy { (false, "allow_account_creation") => { p.soft.allow_account_creation = truthy(&value); sect = Sect::None; } (false, "max_accounts") => { if let Ok(n) = value.parse() { p.soft.max_accounts = n; } sect = Sect::None; } (false, "max_requests_per_minute") => { if let Ok(n) = value.parse() { p.soft.max_requests_per_minute = n; } sect = Sect::None; } + (false, "allow_subdomains") => { p.soft.allow_subdomains = truthy(&value); sect = Sect::None; } _ => { sect = Sect::None; } } } @@ -526,11 +555,22 @@ impl ScopePolicy { } } + /// The allowlist rule that authorizes `url`, if any β€” including the + /// optional sub-domain expansion of a `host` rule. + fn hard_match(&self, url: &str) -> Option<&Pattern> { + let host = crate::netguard::normalize_host(&host_of(url)); + self.hard.iter().find(|p| { + p.matches(url) + || (self.soft.allow_subdomains + && matches!(p, Pattern::Host(h) if host_is_subdomain(&host, &crate::netguard::normalize_host(h)))) + }) + } + pub fn in_hard_scope(&self, url: &str) -> bool { if self.exclude.iter().any(|p| p.matches(url)) { return false; } - self.hard.iter().any(|p| p.matches(url)) + self.hard_match(url).is_some() } /// The authorization decision for one interaction. @@ -545,7 +585,7 @@ impl ScopePolicy { if self.hard.is_empty() { return Decision::Deny("no hard scope configured β€” nothing is authorized".into()); } - if !self.hard.iter().any(|p| p.matches(url)) { + if self.hard_match(url).is_none() { return Decision::Deny(format!( "{host} is outside the authorized scope ({})", self.hard.iter().map(|p| p.as_text()).collect::>().join(", ") @@ -674,7 +714,7 @@ impl ScopePolicy { if self.soft.allow_account_creation && self.soft.max_accounts > 0 { format!(" (max {})", self.soft.max_accounts) } else { String::new() }, self.soft.max_requests_per_minute )); - s.push_str(" Discovering a host, link, subdomain or API does NOT authorize testing it. Report it as an observation instead.\n"); + s.push_str(" Discovering an unrelated host, link or API does NOT authorize testing it. Report it as an observation instead.\n"); for n in &self.soft.notes { s.push_str(&format!(" note: {n}\n")); } @@ -772,6 +812,30 @@ mod tests { p } + #[test] + fn a_host_rule_also_covers_its_subdomains_by_default() { + let p = policy(); + assert!(p.in_hard_scope("https://api.app.example.com/v1")); + assert!(p.in_hard_scope("https://app.example.com/x")); + assert!(!p.in_hard_scope("https://example.com/")); + assert!(!p.in_hard_scope("https://app.example.com.evil.test/")); + } + + #[test] + fn subdomain_expansion_can_be_turned_off() { + let mut p = policy(); + p.soft.allow_subdomains = false; + assert!(p.in_hard_scope("https://app.example.com/x")); + assert!(!p.in_hard_scope("https://api.app.example.com/v1")); + } + + #[test] + fn loopback_spellings_are_the_same_host() { + let p = ScopePolicy::for_target("http://localhost:3000"); + assert!(p.in_hard_scope("http://127.0.0.1:3000/")); + assert!(p.in_hard_scope("http://[::1]:3000/")); + } + #[test] fn host_of_strips_a_leading_http_method() { // "METHOD /path" endpoints (how agents usually report them) must not diff --git a/neurosploit-rs/crates/harness/src/toolbox/runner.rs b/neurosploit-rs/crates/harness/src/toolbox/runner.rs index 5c3055f..39c3a23 100644 --- a/neurosploit-rs/crates/harness/src/toolbox/runner.rs +++ b/neurosploit-rs/crates/harness/src/toolbox/runner.rs @@ -127,12 +127,10 @@ async fn run_shell(command: &str, timeout_secs: u64, sandbox: Option<&Sandbox>) } } -fn clip(mut s: String) -> String { - if s.len() > OUTPUT_CAP { - s.truncate(OUTPUT_CAP); - s.push_str("\n[truncated by NeuroSploit toolbox]"); - } - s +fn clip(s: String) -> String { + // Head+tail, UTF-8 safe. `OUTPUT_CAP` is overridable for operators who + // need the whole scanner dump; the default is deliberately generous. + crate::limits::clip(&s, crate::limits::env_cap("NEUROSPLOIT_CMD_CAP", OUTPUT_CAP)) } fn substitute(template: &str, target: &str) -> Result { diff --git a/neurosploit-rs/crates/harness/src/tunnel.rs b/neurosploit-rs/crates/harness/src/tunnel.rs new file mode 100644 index 0000000..ef19a7b --- /dev/null +++ b/neurosploit-rs/crates/harness/src/tunnel.rs @@ -0,0 +1,266 @@ +//! Public tunnels for callbacks and shells β€” ngrok, with a local HTTP sink. +//! +//! An out-of-band listener that only exists on `127.0.0.1` proves nothing: +//! the target cannot reach it. A tunnel gives that listener a public URL +//! without opening a port on the operator's router. ngrok is the smallest +//! option: the operator supplies an authtoken once (`NGROK_AUTHTOKEN`), and +//! this module starts `ngrok http `, discovers the assigned URL from +//! ngrok's local API, and serves a tiny request sink on that port so blind +//! callbacks are recorded instead of merely accepted. +//! +//! The sink is intentionally dumb. It writes one JSON line per request +//! (`peer`, method, path, headers, bounded body excerpt) and answers `ok`. +//! That is enough to prove SSRF/XXE/blind-RCE egress and to receive a +//! webshell's check-in without embedding any target-specific logic here. +//! +//! Secrets: the authtoken is passed to the child through the environment, not +//! argv, and is never logged. The tunnel is opt-in; without `NGROK_AUTHTOKEN` +//! (or `--authtoken`) nothing starts. + +use serde_json::json; +use std::path::{Path, PathBuf}; +use std::process::Stdio; +use std::time::Duration; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; + +#[derive(Clone, Debug)] +pub struct TunnelConfig { + /// Local port the sink listens on and ngrok forwards to. + pub port: u16, + /// Bind address for the sink (default 127.0.0.1). + pub bind: String, + pub authtoken: Option, + pub region: Option, + /// Reserved/custom domain, when the ngrok plan provides one. + pub domain: Option, + /// Run the local HTTP sink. Off only when the caller already serves it. + pub serve: bool, +} + +impl TunnelConfig { + pub fn from_env(port: Option) -> Self { + let port = port + .or_else(|| std::env::var("NEUROSPLOIT_TUNNEL_PORT").ok().and_then(|v| v.trim().parse().ok())) + .unwrap_or(8080); + Self { + port, + bind: std::env::var("NEUROSPLOIT_TUNNEL_BIND").ok().filter(|s| !s.trim().is_empty()).unwrap_or_else(|| "127.0.0.1".into()), + authtoken: env_first(&["NGROK_AUTHTOKEN", "NGROK_AUTH_TOKEN", "NEUROSPLOIT_NGROK_AUTHTOKEN"]), + region: std::env::var("NGROK_REGION").ok().filter(|s| !s.trim().is_empty()), + domain: std::env::var("NGROK_DOMAIN").ok().filter(|s| !s.trim().is_empty()), + serve: true, + } + } +} + +fn env_first(keys: &[&str]) -> Option { + keys.iter().find_map(|k| std::env::var(k).ok().map(|s| s.trim().to_string()).filter(|s| !s.is_empty())) +} + +/// The ngrok binary, if installed. A missing binary is a clear, actionable +/// error β€” never a silent "tunnel unavailable". +pub fn ngrok_bin() -> Option { + let path = std::env::var_os("PATH")?; + for dir in std::env::split_paths(&path) { + let p = dir.join("ngrok"); + if p.is_file() { + return Some(p); + } + } + None +} + +pub struct Tunnel { + pub public_url: String, + pub local_port: u16, + child: tokio::process::Child, +} + +impl Tunnel { + pub fn stop(mut self) { + let _ = self.child.start_kill(); + } +} + +/// Start ngrok and wait for the public URL (up to ~20s). +pub async fn start(config: &TunnelConfig) -> anyhow::Result { + let bin = ngrok_bin().ok_or_else(|| anyhow::anyhow!( + "ngrok is not installed or not on PATH β€” install it (https://ngrok.com/download) and set NGROK_AUTHTOKEN" + ))?; + let token = config.authtoken.clone().ok_or_else(|| anyhow::anyhow!( + "no ngrok authtoken β€” set NGROK_AUTHTOKEN (or pass --authtoken)" + ))?; + + let mut cmd = tokio::process::Command::new(bin); + cmd.arg("http") + .arg(config.port.to_string()) + .arg("--log=stdout") + .arg("--log-format=json") + .env("NGROK_AUTHTOKEN", token) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .kill_on_drop(true); + if let Some(r) = &config.region { + cmd.arg("--region").arg(r); + } + if let Some(d) = &config.domain { + cmd.arg("--domain").arg(d); + } + let child = cmd.spawn().map_err(|e| anyhow::anyhow!("could not start ngrok: {e}"))?; + + // ngrok exposes the assigned URL on its local API. Poll it rather than + // scraping stdout, which changes between versions. + let client = reqwest::Client::builder().timeout(Duration::from_secs(2)).build()?; + for _ in 0..40 { + tokio::time::sleep(Duration::from_millis(500)).await; + if let Ok(resp) = client.get("http://127.0.0.1:4040/api/tunnels").send().await { + if let Ok(v) = resp.json::().await { + if let Some(url) = pick_public_url(&v) { + return Ok(Tunnel { public_url: url, local_port: config.port, child }); + } + } + } + } + let mut t = Tunnel { public_url: String::new(), local_port: config.port, child }; + t.stop(); + anyhow::bail!("ngrok started but no public URL appeared on 127.0.0.1:4040 β€” check the authtoken and `ngrok diagnose`") +} + +fn pick_public_url(v: &serde_json::Value) -> Option { + let tunnels = v.get("tunnels")?.as_array()?; + tunnels + .iter() + .filter_map(|t| t.get("public_url").and_then(|u| u.as_str())) + .find(|u| u.starts_with("https://")) + .or_else(|| tunnels.iter().find_map(|t| t.get("public_url").and_then(|u| u.as_str()))) + .map(String::from) +} + +/// Bind the sink, walking forward from the preferred port when it is taken. +/// +/// A busy 8080 is normal (another OOB listener, a dev server, a previous +/// tunnel). Failing the whole command for it was needless: try the next 100 +/// ports and report the one that was actually used. `preferred == 0` asks the +/// OS to assign one. +pub async fn bind_sink(bind: &str, preferred: u16) -> anyhow::Result<(tokio::net::TcpListener, u16)> { + let mut last = None; + for offset in 0..100u16 { + let port = if preferred == 0 { 0 } else { preferred.saturating_add(offset) }; + match tokio::net::TcpListener::bind((bind, port)).await { + Ok(l) => { + let actual = l.local_addr().map(|a| a.port()).unwrap_or(port); + return Ok((l, actual)); + } + Err(e) => { + if e.kind() == std::io::ErrorKind::AddrInUse { + last = Some(e); + continue; + } + return Err(anyhow::anyhow!("cannot bind {bind}:{port} β€” {e}")); + } + } + } + Err(anyhow::anyhow!( + "no free port in {bind}:{preferred}..{} β€” {}", + preferred.saturating_add(99), + last.map(|e| e.to_string()).unwrap_or_default() + )) +} + +/// Serve the callback sink on an already-bound listener. One JSON line per +/// request, `ok` response; runs forever. +pub async fn serve_on(listener: tokio::net::TcpListener, log_dir: &Path) -> anyhow::Result<()> { + std::fs::create_dir_all(log_dir)?; + let log = log_dir.join("callbacks.jsonl"); + loop { + let Ok((mut sock, peer)) = listener.accept().await else { continue }; + let path = log.clone(); + tokio::spawn(async move { + let mut buf = vec![0u8; 16 * 1024]; + let n = match sock.read(&mut buf).await { + Ok(n) if n > 0 => n, + _ => 0, + }; + let req = String::from_utf8_lossy(&buf[..n]).to_string(); + let mut lines = req.lines(); + let first = lines.next().unwrap_or(""); + let mut parts = first.split_whitespace(); + let method = parts.next().unwrap_or(""); + let target = parts.next().unwrap_or(""); + let headers: Vec<&str> = lines.take_while(|l| !l.trim().is_empty()).collect(); + let excerpt = crate::limits::clip(&req, 8 * 1024); + let rec = json!({ + "at": now_ms(), + "peer": peer.to_string(), + "method": method, + "target": target, + "headers": headers, + "excerpt": excerpt, + }); + use std::io::Write; + if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&path) { + let _ = writeln!(f, "{}", rec); + } + let body = b"ok"; + let _ = sock.write_all(format!( + "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ).as_bytes()).await; + let _ = sock.write_all(body).await; + let _ = sock.shutdown().await; + }); + } +} + +fn now_ms() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0) +} + +/// Start the sink and the tunnel, print the public URL, and run until Ctrl-C. +pub async fn run(mut config: TunnelConfig) -> anyhow::Result<()> { + if config.serve { + let (listener, actual) = bind_sink(&config.bind, config.port).await?; + if actual != config.port { + println!(" \x1b[33mport {} was busy β€” using {}\x1b[0m", config.port, actual); + } + config.port = actual; + let dir = std::env::temp_dir().join("neurosploit-tunnel"); + tokio::spawn(async move { + if let Err(e) = serve_on(listener, &dir).await { + eprintln!(" \x1b[31mtunnel sink: {e}\x1b[0m"); + } + }); + tokio::time::sleep(Duration::from_millis(150)).await; + } + let tunnel = start(&config).await?; + println!(" \x1b[32mngrok tunnel\x1b[0m β†’ {}", tunnel.public_url); + println!(" local sink β†’ http://{}:{}", config.bind, config.port); + println!(" callbacks log β†’ {}", std::env::temp_dir().join("neurosploit-tunnel").join("callbacks.jsonl").display()); + println!(" use the public URL as --oob-domain. Ctrl-C stops the tunnel."); + tokio::signal::ctrl_c().await.ok(); + tunnel.stop(); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn picks_https_tunnel_first() { + let v = json!({ "tunnels": [ + { "public_url": "http://a.ngrok.io" }, + { "public_url": "https://b.ngrok.io" } + ]}); + assert_eq!(pick_public_url(&v).as_deref(), Some("https://b.ngrok.io")); + } + + #[test] + fn missing_tunnels_is_none() { + assert!(pick_public_url(&json!({})).is_none()); + } +} diff --git a/neurosploit-rs/crates/harness/src/types.rs b/neurosploit-rs/crates/harness/src/types.rs index 436f7f8..b6de014 100644 --- a/neurosploit-rs/crates/harness/src/types.rs +++ b/neurosploit-rs/crates/harness/src/types.rs @@ -338,7 +338,8 @@ pub struct RunConfig { /// the default and the most tested path. #[serde(default)] pub reactive: bool, - /// MCP tool profile: `web`, `mobile-android`, `mobile-ios`, `binary`, `burp`. + /// MCP tool profile: `web`, `mobile-android`, `mobile-ios`, `binary`, `burp`, + /// `cobaltstrike`, `infra`, `ad`, `cloud`, `kali`, `nmap`, `full`. /// When set, the matching MCP server and tool allowlist are auto-configured. #[serde(default)] pub mcp_profile: Option, diff --git a/web/public/app.js b/web/public/app.js index 97a478a..496552a 100644 --- a/web/public/app.js +++ b/web/public/app.js @@ -1,5 +1,5 @@ 'use strict'; -/* NeuroSploit v4.4.3 β€” web console frontend. Vanilla JS, no build step. */ +/* NeuroSploit β€” web console frontend. Vanilla JS, no build step. */ const $ = (sel, root = document) => root.querySelector(sel); const $$ = (sel, root = document) => Array.from(root.querySelectorAll(sel)); @@ -125,7 +125,7 @@ function clearFieldErrors() { $$('.field-error').forEach((el) => { el.textConten // view navigation // --------------------------------------------------------------------------- -const ALL_VIEWS = ['homeView','dashView','wizardView','liveView','detailView','pentestsView','prreviewsView','issuesView','reposView','domainsView','networksView','vaultView','guardrailsView','integrationsView','settingsView','c2View','toolboxView']; +const ALL_VIEWS = ['homeView','dashView','wizardView','liveView','detailView','pentestsView','prreviewsView','issuesView','reposView','projectsView','domainsView','networksView','vaultView','guardrailsView','integrationsView','settingsView','c2View','toolboxView']; function switchView(viewName) { state.activeView = viewName; @@ -137,9 +137,11 @@ function switchView(viewName) { }); const runHist = $('#sbRunHistory'); if (runHist) runHist.style.display = ['live','detail'].includes(viewName) ? '' : 'none'; + if (viewName === 'wizard') loadProjectOptions(); if (viewName === 'pentests') loadPentests(); if (viewName === 'issues') loadIssues(); if (viewName === 'repos') loadRepos(); + if (viewName === 'projects') loadProjects(); if (viewName === 'domains') loadDomains(); if (viewName === 'networks') loadNetworks(); if (viewName === 'integrations') loadIntegrations(); @@ -791,9 +793,11 @@ async function startExploitation() { const model = $('#fieldModelSelect').value; const focusParts = [$('#fieldFocus').value.trim(), ...state.customLeads].filter(Boolean); + await loadProjectOptions(); const body = { mode, name, + projectId: $('#fieldProject')?.value || undefined, target: mode === 'whitebox' ? undefined : target, repo: mode === 'whitebox' ? target : (repo || undefined), models: collectModels(), @@ -4121,7 +4125,7 @@ function makeExtras(viewSel, uid, getRunId) { body.insertAdjacentHTML('beforeend', extrasPanelsHtml(uid)); const x = { root, getRunId, graphData: null, extras: {}, chainFilter: 'all', - view: { k: 1, tx: 20, ty: 20, sel: null }, timers: {}, + view: { k: 1, tx: 20, ty: 20, sel: null, kindFilters: new Set() }, timers: {}, q: (k) => $(`[data-x="${k}"]`, root), count: (tab, n) => { const el = $(`[data-count="${tab}"]`, root); if (el) el.textContent = n; }, active: () => $('.run-tab.active', root)?.dataset.tab || 'findings', @@ -4170,7 +4174,7 @@ function extrasCounts(x) { async function extrasRefresh(x, extras, force) { if (!x) return; const id = x.getRunId(); - if (x.lastId !== id) { x.lastId = id; x.graphData = null; x.view = { k: 1, tx: 20, ty: 20, sel: null, filterFinding: null }; } + if (x.lastId !== id) { x.lastId = id; x.graphData = null; x.view = { k: 1, tx: 20, ty: 20, sel: null, filterFinding: null, kindFilters: new Set() }; } x.extras = extras || {}; try { await extrasGraph(x, force); } catch { /* no graph yet */ } extrasCounts(x); @@ -4322,6 +4326,20 @@ function gmName(n) { const p = n.props || {}; return p.title || p.name || p.category || p.path || p.type || p.address || n.key; } +function gmSub(n) { + const p = n.props || {}; + switch (n.label) { + case 'Host': case 'Target': case 'IPAddress': return p.address || p.ip || p.hostname || p.target || ''; + case 'Domain': return p.domain || p.name || ''; + case 'Service': case 'Technology': return p.port ? `:${p.port}` : p.url || p.protocol || ''; + case 'Endpoint': return p.path || p.url || p.method || ''; + case 'Finding': case 'Vulnerability': return p.cwe || p.owasp || ''; + case 'Credential': case 'Secret': case 'Identity': return p.username || p.account || p.type || ''; + case 'AttackStep': case 'ExploitAttempt': return p.technique || p.mitre || ''; + case 'BusinessImpact': return p.category || p.type || ''; + default: return ''; + } +} const GM_ICON = { Target: ``, @@ -4380,9 +4398,17 @@ function renderGraphMemory(x) { show(x.q('graph-empty'), !has); show(x.q('wrap'), has); renderGraphFindingList(x); - x.q('legend').innerHTML = [['internet', 'Internet'], ['asset', 'Host / Target'], ['surface', 'Service / Endpoint'], ['weak', 'Finding'], ['step', 'Attack Step'], ['cred', 'Credential / Role'], ['impact', 'Impact']] - .map(([k, l]) => `${esc(l)}`).join('') + + const kf = x.view.kindFilters || new Set(); + const legendItems = [['internet', 'Internet'], ['asset', 'Host / Target'], ['surface', 'Service / Endpoint'], ['weak', 'Finding'], ['step', 'Attack Step'], ['cred', 'Credential / Role'], ['impact', 'Impact']]; + x.q('legend').innerHTML = legendItems + .map(([k, l]) => ``).join('') + 'confirmedneeds validationhypothesis'; + $$('[data-kind]', x.q('legend')).forEach(btn => btn.addEventListener('click', () => { + const k = btn.dataset.kind; + if (kf.has(k)) kf.delete(k); else kf.add(k); + x.drawnSig = null; + renderGraphMemory(x); + })); if (!has) { stage.innerHTML = ''; return; } const filterFid = x.view.filterFinding || null; @@ -4390,6 +4416,7 @@ function renderGraphMemory(x) { const id = (n) => `${n.label}|${n.key}`; const eid = (e) => `${e.label}|${e.key}`; let nodes = data.nodes.filter((n) => full || !GM_HIDDEN.has(n.label)); + if (kf.size) nodes = nodes.filter((n) => !kf.has(GM_KIND[n.label] || 'meta')); let keep = new Set(nodes.map(id)); let edges = (data.edges || []).filter((e) => keep.has(eid(e.from)) && keep.has(eid(e.to))); if (!full) { @@ -4499,7 +4526,7 @@ function renderGraphMemory(x) { } // Circular node layout β€” left-to-right columns by entity kind - const NW = 140, NH = 90, GX = 60, GY = 30, PER = 8; + const NW = 180, NH = 110, GX = 90, GY = 42, PER = 7; const cols = new Map(); for (const n of nodes) { const c = GM_COL[n.label] ?? 3; @@ -4545,17 +4572,24 @@ function renderGraphMemory(x) { col += sub; } const width = col * (NW + GX); - const CX = NW / 2, CY = 28; + const CX = NW / 2, CY = 32; const path = (a, b) => { - const x1 = a.x + CX + 28, y1 = a.y + CY, x2 = b.x + CX - 28, y2 = b.y + CY; + const x1 = a.x + CX + 32, y1 = a.y + CY, x2 = b.x + CX - 32, y2 = b.y + CY; const mx = (x1 + x2) / 2; return `M${x1},${y1} C${mx},${y1} ${mx},${y2} ${x2},${y2}`; }; + const arrow = (st) => ({ confirmed: 'gm-ar-confirmed', needs_validation: 'gm-ar-needs', hypothesis: 'gm-ar-hyp', needs_review: 'gm-ar-review' }[st] || 'gm-ar-needs'); + const defs = ` + + + + + `; const svg = edges.map((e) => { const a = pos.get(eid(e.from)), b = pos.get(eid(e.to)); if (!a || !b) return ''; const st = e.status || 'needs_validation'; - return `${esc(e.type)} Β· ${esc(st)} Β· conf ${Number(e.confidence || 0).toFixed(2)}`; + return `${esc(e.type)} Β· ${esc(st)} Β· conf ${Number(e.confidence || 0).toFixed(2)}`; }).join(''); const cards = nodes.map((n) => { const p = pos.get(id(n)); @@ -4564,12 +4598,14 @@ function renderGraphMemory(x) { const sev = props.local_severity; const sevBadge = sev ? `${esc(sev.charAt(0).toUpperCase())}` : ''; const countBadge = props.endpoint_count ? `${props.endpoint_count}` : ''; + const sub = gmSub(n); return `
${gmIcon(n.label)}${sevBadge}${countBadge}
${esc(gmName(n))}
+ ${sub ? `
${esc(sub)}
` : ''}
${esc(n.label)}${props.stage ? ` Β· ${esc(props.stage)}` : ''}
`; }).join(''); - stage.innerHTML = `${svg}${cards}`; + stage.innerHTML = `${defs}${svg}${cards}`; stage.style.width = `${width + 80}px`; stage.style.height = `${maxH + 40}px`; gmApply(x); @@ -5004,6 +5040,123 @@ async function loadDomains() { } catch { body.innerHTML = '
No domains configured yet. Click + Add Domain to add one.
'; } } +// --------------------------------------------------------------------------- +// Projects / organisations β€” group every run of one target together. +// --------------------------------------------------------------------------- +async function loadProjectOptions() { + const sel = $('#fieldProject'); + if (!sel) return; + try { + const projects = await api('/api/projects'); + const cur = sel.value; + sel.innerHTML = '' + + projects.map(p => ``).join(''); + if ([...sel.options].some(o => o.value === cur)) sel.value = cur; + } catch { /* keep the previous options */ } +} + +async function loadProjects() { + const body = $('#projectsBody'); + if (!body) return; + try { + const [projects, runs] = await Promise.all([api('/api/projects'), api('/api/runs')]); + const orgs = [...new Set(projects.map(p => p.org || 'Default'))].sort((a, b) => a.localeCompare(b)); + const dl = $('#projectOrgList'); + if (dl) dl.innerHTML = orgs.map(o => ``).join(''); + if (!projects.length) { + body.innerHTML = '
No projects yet. Click + New Project to group a target\'s tests into one place.
'; + return; + } + const matches = (p, r) => (r.projectId && r.projectId === p.id) + || (p.runIds || []).includes(r.id) + || (p.targets || []).some(t => { + const needle = t.replace(/^https?:\/\//, '').replace(/\/.*$/, '').toLowerCase(); + const hay = String(r.target || '').toLowerCase(); + return needle && (hay === needle || hay.includes(needle)); + }); + const group = new Map(); + for (const p of projects) { + const org = p.org || 'Default'; + if (!group.has(org)) group.set(org, []); + group.get(org).push(p); + } + body.innerHTML = [...group.entries()].sort((a, b) => a[0].localeCompare(b[0])).map(([org, list]) => ` +
+

${esc(org)}

${list.length} project${list.length === 1 ? '' : 's'}
+
${list.map(p => { + const rs = runs.filter(r => matches(p, r)).sort((a, b) => b.ts - a.ts); + const findings = rs.reduce((n, r) => n + (r.findings || 0), 0); + return `
+
${esc(p.name)}
+
${esc(p.description || 'No description')}
+
${rs.length} test${rs.length === 1 ? '' : 's'} Β· ${findings} finding${findings === 1 ? '' : 's'}${p.targets?.length ? ' Β· ' + esc(p.targets.join(', ')) : ''}
+ ${rs.length ? `
${rs.slice(0, 6).map(r => ``).join('')}${rs.length > 6 ? `
+${rs.length - 6} more
` : ''}
` : '
No tests matched yet.
'} +
+ + +
+
`; + }).join('')}
+
`).join(''); + $$('[data-run]', body).forEach(el => el.addEventListener('click', () => { + const r = runs.find(x => x.id === el.dataset.run); + if (r) openRun({ id: r.id, state: r.state }); + })); + $$('[data-edit-project]', body).forEach(el => el.addEventListener('click', () => openProject(el.dataset.editProject, projects))); + $$('[data-del-project]', body).forEach(el => el.addEventListener('click', async () => { + if (!confirm('Delete this project? The runs themselves are not touched.')) return; + try { await api(`/api/projects/${encodeURIComponent(el.dataset.delProject)}`, { method: 'DELETE' }); toast('Project deleted', 'ok'); loadProjects(); } + catch (e) { toast(`Failed: ${e.message}`, 'error'); } + })); + } catch (e) { + body.innerHTML = `
Could not load projects: ${esc(e.message)}
`; + } +} + +function openProject(id, projects) { + const p = (projects || []).find(x => x.id === id) || {}; + $('#projectId').value = id || ''; + $('#projectOrg').value = p.org || ''; + $('#projectName').value = p.name || ''; + $('#projectTargets').value = (p.targets || []).join('\n'); + $('#projectDesc').value = p.description || ''; + $('#projectModalTitle').textContent = id ? 'Edit Project' : 'New Project'; + openModal('#projectModal'); + setTimeout(() => $('#projectName')?.focus(), 30); +} + +$('#btnAddProject')?.addEventListener('click', async () => { + let projects = []; + try { projects = await api('/api/projects'); } catch { /* still usable */ } + openProject(null, projects); +}); + +$('#btnProjectSubmit')?.addEventListener('click', async () => { + const id = $('#projectId')?.value || ''; + const name = $('#projectName')?.value?.trim(); + if (!name) { toast('Project name is required', 'error'); return; } + const data = { + org: $('#projectOrg')?.value?.trim() || 'Default', + name, + targets: ($('#projectTargets')?.value || '').split(/[\n,;]+/).map(s => s.trim()).filter(Boolean), + description: $('#projectDesc')?.value?.trim() || '', + }; + try { + await api(id ? `/api/projects/${encodeURIComponent(id)}` : '/api/projects', { + method: id ? 'PUT' : 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(data), + }); + closeModal('#projectModal'); + toast(id ? 'Project updated' : 'Project created', 'ok'); + loadProjects(); + } catch (e) { toast(`Failed: ${e.message}`, 'error'); } +}); + async function loadNetworks() { const body = $('#networksBody'); if (!body) return; @@ -5343,9 +5496,32 @@ function loadGuardrails() { $('#grOobHttp').value = cfg.oobHttp || ''; $('#grOobDns').value = cfg.oobDns || ''; $('#grSms').value = cfg.sms || ''; + renderGuardrailSummary(cfg); }).catch(() => {}); } +// The page is a compact summary; the editable form lives in a modal so the +// long list of controls does not push everything else off the screen. +function renderGuardrailSummary(cfg) { + const set = (sel, text) => { const el = $(sel); if (el) el.textContent = text; }; + const scope = [cfg.scopeHard, cfg.inScope].filter(Boolean).join(', ').replace(/\s*\n\s*/g, ', '); + set('#grSumScope', scope ? `Allow: ${scope}` : 'No extra scope β€” the target only.'); + const rate = cfg.rate ? `${cfg.rate} req/min` : 'unlimited rate'; + set('#grSumSafety', + `${cfg.destructive ? 'State-changing methods allowed' : 'State-changing methods blocked'} Β· ` + + `${cfg.accounts === false ? 'account creation off' : `max ${cfg.maxAccounts ?? 3} accounts`} Β· ${rate}`); + set('#grSumEnv', `${cfg.environment || 'production'} Β· ${cfg.policy || 'web'} policy`); + const egress = [cfg.transport, cfg.oobDomain && `OOB ${cfg.oobDomain}`].filter(Boolean).join(' Β· '); + set('#grSumEgress', egress || 'Direct egress Β· no out-of-band domain'); +} + +function openGuardrails(section) { + openModal('#guardrailsModal'); + if (!section) return; + const el = $(`#guardrailsModal [data-gr-section="${section}"]`); + if (el) setTimeout(() => el.scrollIntoView({ block: 'start', behavior: 'smooth' }), 30); +} + $('#btnGuardrailsSave')?.addEventListener('click', async () => { const data = { capToken: $('#grCapToken')?.value || '', @@ -5369,6 +5545,8 @@ $('#btnGuardrailsSave')?.addEventListener('click', async () => { }; try { await api('/api/config/guardrails', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }); + closeModal('#guardrailsModal'); + renderGuardrailSummary(data); toast('Guardrails saved', 'ok'); } catch (e) { toast(`Failed: ${e.message}`, 'error'); } }); @@ -5562,12 +5740,12 @@ $('#btnIntegSubmit')?.addEventListener('click', async () => { } finally { btn.disabled = false; btn.textContent = 'Save & Validate'; } }); -['#repoModal', '#domainModal', '#networkModal', '#integrationModal'].forEach(sel => { +['#repoModal', '#domainModal', '#networkModal', '#projectModal', '#guardrailsModal', '#integrationModal'].forEach(sel => { $(sel)?.addEventListener('click', (e) => { if (e.target === $(sel)) closeModal(sel); }); }); document.addEventListener('keydown', (e) => { if (e.key === 'Escape') { - ['#repoModal', '#domainModal', '#networkModal', '#integrationModal'].forEach(sel => { + ['#repoModal', '#domainModal', '#networkModal', '#projectModal', '#guardrailsModal', '#integrationModal'].forEach(sel => { if (!$(sel)?.hidden) closeModal(sel); }); } diff --git a/web/public/index.html b/web/public/index.html index d483223..4f194fc 100644 --- a/web/public/index.html +++ b/web/public/index.html @@ -3,7 +3,7 @@ -NeuroSploit v4.4.3 β€” Console +NeuroSploit β€” Console @@ -45,6 +45,7 @@
+
@@ -69,7 +70,7 @@
- v4.4.3 +
@@ -204,6 +205,19 @@
No domains configured yet.
+ + + + + +