feat: MCP profiles, graph filters, OpenSearch, cache, ingest, improve, repro, tunnel

New harness modules: cache (universal completion cache), improve (self-review),
ingest (IP/Swagger/OVPN/RoE parser), logship (OpenSearch integration), limits
(rate/budget guards), repro (PoC reproduction with REVEALSECRET vault), tunnel
(ngrok + HTTP callback sink). MCP profiles for 12 testing modes (Web, Mobile,
Binary, BurpSuite, CobaltStrike, Infra, AD, Cloud, Kali, Nmap, Full, Custom).

Frontend: clickable graph legend filters, node IP/domain/port info subtitles,
wider nodes for readability, projects/orgs views, vault/guardrails/integrations
views, scope subdomain expansion, version badge removal.

CLI: new subcommands (logs, tunnel, ingest, improve, repro), MCP profile flag.
README redesigned with architecture diagram, MCP profiles table, provider list.
This commit is contained in:
CyberSecurityUP committed 2026-11-22 02:20:18 -03:00
1 parent f6996d6f4e
commit 512f041910
26 files changed
+2936 -289

No files matched your search

+40
View File
@@ -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 <run-id> --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
+164 -187
View File
@@ -1,247 +1,224 @@
<h1 align="center">🧠 NeuroSploit v4.4.3</h1>
<div align="center">
<p align="center">
<a href="https://github.com/JoasASantos/NeuroSploit/stargazers"><img src="https://img.shields.io/github/stars/JoasASantos/NeuroSploit?style=for-the-badge&logo=github&color=8b5cf6" alt="Stars"></a>
<a href="https://github.com/JoasASantos/NeuroSploit/network/members"><img src="https://img.shields.io/github/forks/JoasASantos/NeuroSploit?style=for-the-badge&logo=github&color=a855f7" alt="Forks"></a>
<a href="https://github.com/JoasASantos/NeuroSploit/issues"><img src="https://img.shields.io/github/issues/JoasASantos/NeuroSploit?style=for-the-badge&color=22d3ee" alt="Issues"></a>
</p>
<img src="web/public/logo.svg" width="120" alt="NeuroSploit">
<p align="center">
<img src="https://img.shields.io/badge/Version-4.4.3-blue?style=flat-square">
<img src="https://img.shields.io/badge/Harness-Rust%20%7C%20tokio-e6b673?style=flat-square">
<img src="https://img.shields.io/badge/License-MIT-green?style=flat-square">
<img src="https://img.shields.io/badge/MD%20Agents-486-red?style=flat-square">
<img src="https://img.shields.io/badge/Modes-Black%20%7C%20White%20%7C%20Grey%20%7C%20Host%20%7C%20AI%20%7C%20Mobile%20%7C%20Container-9cf?style=flat-square">
</p>
# NeuroSploit
<p align="center">
<a href="https://neurosploitai.github.io/"><img src="https://img.shields.io/badge/Website-neurosploitai.github.io-8b5cf6?style=for-the-badge&logo=githubpages&logoColor=white" alt="Website"></a>
<a href="https://neurosploitai.github.io/docs.html"><img src="https://img.shields.io/badge/Docs-Tutorial%20%26%20Guide-22d3ee?style=for-the-badge&logo=readthedocs&logoColor=white" alt="Docs"></a>
</p>
**Autonomous penetration-testing harness — Rust, multi-model, CLI-first.**
<p align="center"><b>Autonomous, multi-model penetration-testing harness — Rust, CLI-first.</b><br>
<i>by Joas A Santos &amp; Red Team Leaders</i></p>
[![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)
<br>
[![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)
<br>
[**Website**](https://neurosploitai.github.io/) · [**Docs & Tutorial**](https://neurosploitai.github.io/docs.html) · [**TUTORIAL.md**](TUTORIAL.md) · [**BENCHMARK.md**](BENCHMARK.md)
</div>
---
## 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 <url>` | recon → select → exploit → vote → report |
| **White-box** | `neurosploit whitebox <repo>` | source / SAST review (file:line evidence) |
| **Grey-box** | `neurosploit greybox <repo> --url <app>` | code review **+** live exploitation together |
| **Host / Infra** | `neurosploit host <ip> --creds creds.yaml` | Linux / Windows / AD + cloud (AWS/GCP/Azure) |
| **AI / LLM** | `neurosploit aitest <ai-url>` | jailbreaks, prompt injection, OWASP LLM Top 10 / MCP |
| **Mobile / Binary** | `neurosploit mobile <app.apk\|.ipa\|bin>` | RE a local artifact (Ghidra / MobSF / Frida) |
| **Container** | `neurosploit container <image:tag>` | OCI image scan + SBOM (trivy/grype/syft) |
| **Mission Control** | `neurosploit tui <url>` | live TUI panels + a composer you type in mid-run |
| Mode | Command | Surface |
|:-----|:--------|:--------|
| **Black-box** | `neurosploit run <url>` | Web apps, APIs — recon → exploit → vote → report |
| **White-box** | `neurosploit whitebox <repo>` | Source / SAST review (`file:line` evidence) |
| **Grey-box** | `neurosploit greybox <repo> --url <app>` | Code review **+** live exploitation |
| **Host / Infra** | `neurosploit host <ip>` | Linux, Windows, AD, cloud (AWS/GCP/Azure) |
| **AI / LLM** | `neurosploit aitest <ai-url>` | Jailbreaks, prompt injection, OWASP LLM Top 10 |
| **Mobile** | `neurosploit mobile <app.apk\|.ipa>` | APK/IPA RE (Ghidra / MobSF / Frida) |
| **Container** | `neurosploit container <image:tag>` | OCI scan + SBOM (trivy/grype/syft) |
| **Mission Control** | `neurosploit tui <url>` | 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-<ts>-<target>/`:
- **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-<ts>-<target>/`:
| 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 <run> # ranked paths, on the run's own timeline
neurosploit paths <run> --mermaid # the graph
neurosploit paths <run> --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 <repo> <n> --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.
<div align="center">
> 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
</div>
+108
View File
@@ -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 <id>`) [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 <id>` (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=<id>` 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 <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).
+276 -1
View File
@@ -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<String>,
@@ -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<u16>,
/// ngrok authtoken (defaults to NGROK_AUTHTOKEN).
#[arg(long)]
authtoken: Option<String>,
/// ngrok region (us, eu, ap, au, sa, jp, in).
#[arg(long)]
region: Option<String>,
/// Reserved/custom ngrok domain, when the plan provides one.
#[arg(long)]
domain: Option<String>,
/// Bind address for the local sink (default 127.0.0.1).
#[arg(long)]
bind: Option<String>,
/// 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<String>,
/// OpenAPI/Swagger document (JSON or YAML) — base URLs and paths.
#[arg(long)]
swagger: Option<String>,
/// OpenVPN profile; becomes `openvpn:<path>` transport.
#[arg(long)]
ovpn: Option<String>,
/// Rules of Engagement text; `out-of-scope:` / `exclude:` lines become
/// hard exclusions, the rest becomes prompt notes.
#[arg(long)]
roe: Option<String>,
/// Topology image to record with the engagement.
#[arg(long)]
topology: Option<String>,
/// Where to write brief.json and scope.yaml (default `.neurosploit/ingest`).
#[arg(long)]
out: Option<String>,
},
/// 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<String>,
/// 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<String>,
},
/// 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<String>,
/// 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-<project>` unless OPENSEARCH_INDEX
/// overrides it.
#[arg(long)]
project: Option<String>,
},
/// Print the events that would be shipped, without sending them.
Preview {
run: String,
#[arg(long)]
project: Option<String>,
#[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::<serde_json::Value>(&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<String>, json: bool) -> anyhow::Result<()> {
let dir = resolve_run(base, run)?;
let mut findings = load_findings(&dir)?;
@@ -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}),
+2 -6
View File
@@ -107,12 +107,8 @@ pub(crate) fn unb64(s: &str) -> Option<Vec<u8>> {
.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.
+153
View File
@@ -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<HashMap<String, String>> {
static M: OnceLock<Mutex<HashMap<String, String>>> = 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<String> {
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"));
}
}
@@ -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<Signal> {
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::<serde_json::Value>(&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::<serde_json::Value>(&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\
# <short imperative title>\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<std::path::PathBuf> {
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"));
}
}
+259
View File
@@ -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<String>,
/// Base URLs from the API document.
pub base_urls: Vec<String>,
/// Endpoint paths from the API document.
pub endpoints: Vec<String>,
/// `openvpn:<path>` when a profile was supplied.
pub transport: Option<String>,
/// Hard exclusions found in the RoE.
pub out_of_scope: Vec<String>,
/// Free-text RoE notes, bounded.
pub notes: Vec<String>,
/// Path to the topology image, recorded for the report.
pub topology: Option<String>,
pub roe: Option<String>,
}
impl Brief {
pub fn targets(&self) -> Vec<String> {
let mut v: Vec<String> = 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<Brief> {
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::<serde_json::Value>(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<String>, 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"));
}
}
+10
View File
@@ -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};
+104
View File
@@ -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::<usize>().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);
}
}
@@ -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-<project>` 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<String>,
pub password: Option<String>,
/// 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<Self> {
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<String> {
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<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub agent: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
/// 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<serde_json::Value>,
}
impl LogEvent {
pub fn new(project: &str, kind: &str, level: &str, message: impl Into<String>) -> 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<LogEvent> {
let run_id = dir.file_name().and_then(|s| s.to_str()).map(|s| s.to_string());
let mut events: Vec<LogEvent> = 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::<serde_json::Value>(&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<String> {
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<serde_json::Value> {
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<PushReport> {
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::<serde_json::Value>(&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<String> {
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<PathBuf> {
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);
}
}
@@ -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<String> {
"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,
+15 -10
View File
@@ -23,7 +23,7 @@ pub struct Provider {
pub fn providers() -> Vec<Provider> {
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> {
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<Provider> {
// `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<Provider> {
// (`hermes chat -m <model> --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://<resource>.openai.azure.com), optionally AZURE_OPENAI_API_VERSION
// (default 2024-10-21), and use `azure:<your-deployment-name>` 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");
}
}
+11 -1
View File
@@ -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 {
@@ -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,
+4 -1
View File
@@ -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) { "<redacted — use your own>" } 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" {
+323
View File
@@ -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<String, String>,
}
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::<serde_json::Value>(&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::<serde_json::Value>(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<String>, value: impl Into<String>) {
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<String, String>, 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<String> {
let mut out: Vec<String> = Vec::new();
let push = |out: &mut Vec<String>, 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 <run> --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"));
}
}
+68 -4
View File
@@ -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::<Vec<_>>().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
@@ -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<String, String> {
+266
View File
@@ -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 <port>`, 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<String>,
pub region: Option<String>,
/// Reserved/custom domain, when the ngrok plan provides one.
pub domain: Option<String>,
/// Run the local HTTP sink. Off only when the caller already serves it.
pub serve: bool,
}
impl TunnelConfig {
pub fn from_env(port: Option<u16>) -> 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<String> {
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<PathBuf> {
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<Tunnel> {
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::<serde_json::Value>().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<String> {
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());
}
}
+2 -1
View File
@@ -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<String>,
+191 -13
View File
@@ -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: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="5"/><circle cx="12" cy="12" r="1.5" fill="currentColor"/></svg>`,
@@ -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]) => `<span class="gm-leg gk-${k}"><span class="gm-leg-dot"></span>${esc(l)}</span>`).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]) => `<button class="gm-leg gk-${k}${kf.has(k) ? '' : ' gm-leg-active'}" data-kind="${k}"><span class="gm-leg-dot"></span>${esc(l)}</button>`).join('') +
'<span class="gm-leg-sep"></span><span class="gm-edge-leg es-confirmed">confirmed</span><span class="gm-edge-leg es-needs_validation">needs validation</span><span class="gm-edge-leg es-hypothesis">hypothesis</span>';
$$('[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 = `<defs>
<marker id="gm-ar-confirmed" viewBox="0 0 8 8" refX="6.5" refY="4" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,0 L8,4 L0,8 z" fill="#22c55e"/></marker>
<marker id="gm-ar-needs" viewBox="0 0 8 8" refX="6.5" refY="4" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,0 L8,4 L0,8 z" fill="#f59e0b"/></marker>
<marker id="gm-ar-hyp" viewBox="0 0 8 8" refX="6.5" refY="4" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,0 L8,4 L0,8 z" fill="#94a3b8"/></marker>
<marker id="gm-ar-review" viewBox="0 0 8 8" refX="6.5" refY="4" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,0 L8,4 L0,8 z" fill="#38bdf8"/></marker>
</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 `<path class="gm-e es-${esc(st)}${GM_TRAVERSAL.has(e.type) ? ' gm-trav' : ''}" data-from="${esc(eid(e.from))}" data-to="${esc(eid(e.to))}" d="${path(a, b)}"><title>${esc(e.type)} · ${esc(st)} · conf ${Number(e.confidence || 0).toFixed(2)}</title></path>`;
return `<path class="gm-e es-${esc(st)}${GM_TRAVERSAL.has(e.type) ? ' gm-trav' : ''}" data-from="${esc(eid(e.from))}" data-to="${esc(eid(e.to))}" marker-end="url(#${arrow(st)})" d="${path(a, b)}"><title>${esc(e.type)} · ${esc(st)} · conf ${Number(e.confidence || 0).toFixed(2)}</title></path>`;
}).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 ? `<span class="gm-sev-badge sev ${sevClass(sev)}">${esc(sev.charAt(0).toUpperCase())}</span>` : '';
const countBadge = props.endpoint_count ? `<span class="gm-badge" style="background:var(--sev-high-fg);color:#fff">${props.endpoint_count}</span>` : '';
const sub = gmSub(n);
return `<div class="gm-node gk-${kind}" style="left:${p.x}px;top:${p.y}px;width:${NW}px" data-id="${esc(id(n))}">
<div class="gm-circle">${gmIcon(n.label)}${sevBadge}${countBadge}</div>
<div class="gm-node-label" title="${esc(gmName(n))}">${esc(gmName(n))}</div>
${sub ? `<div class="gm-node-info" title="${esc(sub)}">${esc(sub)}</div>` : ''}
<div class="gm-node-sub">${esc(n.label)}${props.stage ? ` · ${esc(props.stage)}` : ''}</div></div>`;
}).join('');
stage.innerHTML = `<svg class="gm-svg" width="${width + 80}" height="${maxH + 40}">${svg}</svg>${cards}`;
stage.innerHTML = `<svg class="gm-svg" width="${width + 80}" height="${maxH + 40}">${defs}${svg}</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 = '<div class="empty-state">No domains configured yet. Click <strong>+ Add Domain</strong> to add one.</div>'; }
}
// ---------------------------------------------------------------------------
// 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 = '<option value="">No project — save as an ungrouped test</option>' +
projects.map(p => `<option value="${esc(p.id)}">${esc(p.org ? p.org + ' / ' : '')}${esc(p.name)}</option>`).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 => `<option value="${esc(o)}"></option>`).join('');
if (!projects.length) {
body.innerHTML = '<div class="empty-state">No projects yet. Click <strong>+ New Project</strong> to group a target\'s tests into one place.</div>';
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]) => `
<div class="project-org">
<div class="project-org-head"><h2>${esc(org)}</h2><span class="pill">${list.length} project${list.length === 1 ? '' : 's'}</span></div>
<div class="config-grid">${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 `<div class="config-card project-card">
<div class="config-card-title">${esc(p.name)}</div>
<div class="config-card-desc">${esc(p.description || 'No description')}</div>
<div class="config-card-meta">${rs.length} test${rs.length === 1 ? '' : 's'} · ${findings} finding${findings === 1 ? '' : 's'}${p.targets?.length ? ' · ' + esc(p.targets.join(', ')) : ''}</div>
${rs.length ? `<div class="project-runs">${rs.slice(0, 6).map(r => `<button class="project-run" data-run="${esc(r.id)}" title="${esc(r.target || r.id)}">
<span class="state-dot state-${esc(r.state || 'unknown')}"></span>
<span class="project-run-name">${esc(r.name || r.target || r.id)}</span>
<span class="project-run-meta">${r.findings || 0}f · ${esc(r.state || '')}</span>
</button>`).join('')}${rs.length > 6 ? `<div class="project-run-more">+${rs.length - 6} more</div>` : ''}</div>` : '<div class="project-empty">No tests matched yet.</div>'}
<div class="config-card-actions">
<button class="btn btn-sm" data-edit-project="${esc(p.id)}">Edit</button>
<button class="btn btn-sm btn-danger" data-del-project="${esc(p.id)}">Delete</button>
</div>
</div>`;
}).join('')}</div>
</div>`).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 = `<div class="empty-state">Could not load projects: ${esc(e.message)}</div>`;
}
}
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);
});
}
+102 -10
View File
@@ -3,7 +3,7 @@
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>NeuroSploit v4.4.3 — Console</title>
<title>NeuroSploit — Console</title>
<link rel="icon" type="image/svg+xml" href="logo.svg">
<link rel="stylesheet" href="/vendor/xterm.css" />
<link rel="stylesheet" href="/style.css" />
@@ -45,6 +45,7 @@
<button class="sb-nav-item" data-view="issues"><span class="sb-nav-icon"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M5 21V4M5 4.5h12l-2.2 3.5L17 11.5H5"/></svg></span> Issues</button>
<div class="sb-nav-separator"></div>
<button class="sb-nav-item" data-view="repos"><span class="sb-nav-icon"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M3.5 7a2 2 0 0 1 2-2H10l2 2h6.5a2 2 0 0 1 2 2v8.5a2 2 0 0 1-2 2h-13a2 2 0 0 1-2-2z"/></svg></span> Repositories</button>
<button class="sb-nav-item" data-view="projects"><span class="sb-nav-icon"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M3.5 7.5A1.5 1.5 0 0 1 5 6h4l2 2h8a1.5 1.5 0 0 1 1.5 1.5v8A1.5 1.5 0 0 1 19 19H5a1.5 1.5 0 0 1-1.5-1.5z"/><path d="M8 12h8M8 15h5"/></svg></span> Projects</button>
<button class="sb-nav-item" data-view="domains"><span class="sb-nav-icon"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><circle cx="12" cy="12" r="8.5"/><path d="M3.5 12h17M12 3.5c3 2.6 3 14.4 0 17M12 3.5c-3 2.6-3 14.4 0 17"/></svg></span> Domains</button>
<button class="sb-nav-item" data-view="networks"><span class="sb-nav-icon"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><circle cx="12" cy="5.5" r="2"/><circle cx="5.5" cy="18.5" r="2"/><circle cx="18.5" cy="18.5" r="2"/><path d="M12 7.5v4M12 11.5l-5.2 5.4M12 11.5l5.2 5.4"/></svg></span> Networks</button>
<div class="sb-nav-separator"></div>
@@ -69,7 +70,7 @@
</div>
<div class="sb-bottom">
<span class="sb-version" id="sbVersion">v4.4.3</span>
<span class="sb-version" id="sbVersion"></span>
</div>
</aside>
@@ -204,6 +205,19 @@
<div class="page-body" id="domainsBody"><div class="empty-state">No domains configured yet.</div></div>
</section>
<!-- ============ PROJECTS / ORGS ============ -->
<section class="page-view" id="projectsView" hidden>
<header class="topbar">
<div>
<div class="topbar-title">Projects</div>
<div class="topbar-sub">Group every test of one customer, domain or target into its own project and organisation</div>
</div>
<div class="topbar-spacer"></div>
<button class="btn btn-accent" id="btnAddProject">+ New Project</button>
</header>
<div class="page-body" id="projectsBody"><div class="empty-state">Loading projects…</div></div>
</section>
<!-- ============ NETWORKS ============ -->
<section class="page-view" id="networksView" hidden>
<header class="topbar">
@@ -300,8 +314,41 @@
<div class="topbar-spacer"></div>
</header>
<div class="page-body" id="guardrailsBody">
<div class="config-grid" id="guardrailsSummary">
<div class="config-card">
<div class="config-card-title">Capability &amp; scope</div>
<div class="config-card-desc" id="grSumScope">No scope configured.</div>
<div class="config-card-actions"><button class="btn" onclick="openGuardrails('scope')">Edit</button></div>
</div>
<div class="config-card">
<div class="config-card-title">Safety guardrails</div>
<div class="config-card-desc" id="grSumSafety">—</div>
<div class="config-card-actions"><button class="btn" onclick="openGuardrails('safety')">Edit</button></div>
</div>
<div class="config-card">
<div class="config-card-title">Environment &amp; policy</div>
<div class="config-card-desc" id="grSumEnv">—</div>
<div class="config-card-actions"><button class="btn" onclick="openGuardrails('env')">Edit</button></div>
</div>
<div class="config-card">
<div class="config-card-title">Egress &amp; out-of-band</div>
<div class="config-card-desc" id="grSumEgress">—</div>
<div class="config-card-actions"><button class="btn" onclick="openGuardrails('egress')">Edit</button></div>
</div>
</div>
</div>
</section>
<!-- Guardrails editor — the long form lives in a modal, the page is a summary. -->
<div class="modal-overlay" id="guardrailsModal" hidden>
<div class="modal modal-lg">
<div class="modal-head">
<div class="title">Guardrails<span class="modal-sub">Authorization, scoping, safety controls, environment and egress</span></div>
<button class="icon-btn" onclick="closeModal('#guardrailsModal')" aria-label="Close"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M6 6l12 12M18 6 6 18"/></svg></button>
</div>
<div class="modal-body">
<div class="config-grid">
<div class="config-card" style="grid-column:1/-1;">
<div class="config-card" data-gr-section="scope" style="grid-column:1/-1;">
<div class="config-card-title">Capability Token</div>
<div class="form-group">
<label for="grCapToken">Capability token</label>
@@ -316,7 +363,7 @@
</div>
</div>
<div class="config-card" style="grid-column:1/-1;">
<div class="config-card" data-gr-section="safety" style="grid-column:1/-1;">
<div class="config-card-title">Scoping &amp; Guardrails <span class="pill" style="font-size:10px;">enforced in code</span></div>
<div class="config-card-desc">The hard scope is the boundary: a request whose host is not listed is refused before it is sent. Exclusions always win. A capability token still caps all of this.</div>
<div class="form-group">
@@ -369,7 +416,7 @@
</div>
</div>
<div class="config-card" style="grid-column:1/-1;">
<div class="config-card" data-gr-section="env" style="grid-column:1/-1;">
<div class="config-card-title">Environment &amp; Policy</div>
<div class="field-row">
<div class="form-group">
@@ -394,7 +441,7 @@
</div>
</div>
<div class="config-card" style="grid-column:1/-1;">
<div class="config-card" data-gr-section="egress" style="grid-column:1/-1;">
<div class="config-card-title">Egress &amp; Out-of-band</div>
<div class="form-group">
<label for="grTransport">Transport (how traffic reaches the target)</label>
@@ -425,12 +472,14 @@
</div>
</div>
<div class="config-card" style="grid-column:1/-1;">
<div class="config-card-actions"><button class="btn btn-accent" id="btnGuardrailsSave">Save</button></div>
</div>
</div>
</div>
<div class="modal-foot">
<button class="btn" onclick="closeModal('#guardrailsModal')">Cancel</button>
<button class="btn btn-accent" id="btnGuardrailsSave">Save guardrails</button>
</div>
</div>
</section>
</div>
<!-- ============ INTEGRATIONS ============ -->
<section class="page-view" id="integrationsView" hidden>
@@ -486,6 +535,13 @@
<div class="field-error" id="errName" hidden></div>
<div class="field-help">Identifies this engagement in the sidebar and run history — required.</div>
</div>
<div class="field-group">
<label class="field-label" for="fieldProject">Project <span class="req">— optional</span></label>
<select id="fieldProject">
<option value="">No project — save as an ungrouped test</option>
</select>
<div class="field-help">Every test saved to the same project — across black-box, white-box, host, cloud, PR review — is grouped together in <b>Projects</b>.</div>
</div>
<div>
<div class="section-title">What are you testing?</div>
<div class="section-desc">Pick the engagement type — this decides which CLI subcommand runs underneath.</div>
@@ -1360,6 +1416,42 @@
</div>
</div>
<!-- ============ PROJECT / ORG MODAL ============ -->
<div class="modal-overlay" id="projectModal" hidden>
<div class="modal modal-sm">
<div class="modal-head">
<div class="title" id="projectModalTitle">New Project</div>
<button class="icon-btn" onclick="closeModal('#projectModal')" aria-label="Close"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M6 6l12 12M18 6 6 18"/></svg></button>
</div>
<div class="modal-body">
<input type="hidden" id="projectId" />
<div class="field-group">
<label class="field-label" for="projectOrg">Organisation</label>
<input id="projectOrg" type="text" placeholder="Acme Corp" list="projectOrgList" />
<datalist id="projectOrgList"></datalist>
<div class="field-help">Groups projects by customer/company. Pick an existing one or type a new name.</div>
</div>
<div class="field-group">
<label class="field-label" for="projectName">Project name</label>
<input id="projectName" type="text" placeholder="Production web — acme.com" />
</div>
<div class="field-group">
<label class="field-label" for="projectTargets">Targets</label>
<textarea id="projectTargets" rows="3" placeholder="acme.com&#10;10.0.0.4&#10;https://app.acme.com"></textarea>
<div class="field-help">One target per line or comma-separated. Runs whose target matches are grouped here automatically.</div>
</div>
<div class="field-group">
<label class="field-label" for="projectDesc">Description (optional)</label>
<input id="projectDesc" type="text" placeholder="Q4 external assessment" />
</div>
</div>
<div class="modal-foot">
<button class="btn" onclick="closeModal('#projectModal')">Cancel</button>
<button class="btn btn-primary" id="btnProjectSubmit">Save Project</button>
</div>
</div>
</div>
<!-- ============ INTEGRATION CONFIG MODAL ============ -->
<div class="modal-overlay" id="integrationModal" hidden>
<div class="modal modal-sm">
+72 -42
View File
@@ -251,6 +251,26 @@ a { color: var(--accent); text-decoration: none; }
.config-card-meta { font-size: var(--fs-xs); color: var(--text-faint); font-family: var(--mono); }
.config-card-actions { display: flex; gap: var(--sp-2); margin-top: var(--sp-3); padding-top: var(--sp-3); border-top: 1px solid var(--border); }
/* projects / orgs — one card per project, runs grouped under it */
.project-org { margin-bottom: var(--sp-6); }
.project-org-head { display: flex; align-items: center; gap: var(--sp-3); margin: 0 0 var(--sp-3); }
.project-org-head h2 { margin: 0; font-size: var(--fs-lg); font-weight: 700; letter-spacing: -.01em; }
.project-card { display: flex; flex-direction: column; }
.project-runs { display: flex; flex-direction: column; gap: 2px; margin: var(--sp-3) 0; }
.project-run { display: flex; align-items: center; gap: var(--sp-2); width: 100%; text-align: left; padding: 6px 8px;
border: 1px solid transparent; border-radius: var(--radius-sm); background: var(--surface-2); color: var(--text);
font-size: var(--fs-xs); cursor: pointer; transition: border-color var(--t-fast), background var(--t-fast); }
.project-run:hover { border-color: var(--border-strong); background: var(--surface); }
.project-run-name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.project-run-meta { color: var(--text-faint); font-family: var(--mono); font-size: var(--fs-2xs); white-space: nowrap; }
.project-run-more { font-size: var(--fs-xs); color: var(--text-faint); padding: 2px 8px; }
.project-empty { font-size: var(--fs-xs); color: var(--text-faint); padding: var(--sp-2) 0; }
.state-dot { width: 7px; height: 7px; border-radius: 50%; flex: none; background: var(--text-faint); }
.state-dot.state-running { background: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 18%, transparent); }
.state-dot.state-complete, .state-dot.state-completed, .state-dot.state-done { background: var(--sev-low-fg); }
.state-dot.state-interrupted, .state-dot.state-failed, .state-dot.state-error { background: var(--sev-high-fg); }
@media (max-width: 760px) { .config-grid { grid-template-columns: 1fr; } .project-org-head { flex-wrap: wrap; } }
.btn-accent {
background: var(--accent); color: var(--accent-contrast); border: 1px solid var(--accent);
padding: var(--sp-2) var(--sp-4); border-radius: var(--radius-sm); font-size: var(--fs-sm); font-weight: 600;
@@ -1061,56 +1081,58 @@ body.resizing-ns { user-select: none; cursor: ns-resize; }
.ts-action { font-size: var(--fs-sm); color: var(--text-dim); margin-top: 2px; }
/* graph (web + internal network) — Wiz-style attack path visualization */
.gm-wrap { position: relative; height: 640px; border: 1px solid var(--border); border-radius: var(--radius-md); overflow: hidden; cursor: grab;
background-color: var(--surface); background-image: radial-gradient(var(--border) .5px, transparent .5px); background-size: 24px 24px; }
.gm-wrap { position: relative; height: 680px; border: 1px solid var(--border); border-radius: var(--radius-lg); overflow: hidden; cursor: grab;
background-color: var(--surface);
background-image:
radial-gradient(circle at 50% 0%, color-mix(in srgb, var(--accent) 7%, transparent), transparent 60%),
radial-gradient(var(--border-strong) .8px, transparent .8px);
background-size: 100% 100%, 22px 22px;
box-shadow: inset 0 1px 0 rgba(255,255,255,.35), inset 0 0 80px rgba(15,23,42,.04); }
.gm-wrap.dragging { cursor: grabbing; }
.gm-wrap[hidden] { display: none; }
.gm-stage { position: absolute; left: 0; top: 0; transform-origin: 0 0; }
.gm-svg { position: absolute; left: 0; top: 0; overflow: visible; pointer-events: none; }
.gm-e { fill: none; stroke-width: 2; opacity: .6; }
.gm-e.gm-trav { stroke-width: 2.5; opacity: .85; }
.gm-e.es-confirmed { stroke: var(--sev-low-fg); }
.gm-e.es-needs_validation { stroke: var(--sev-medium-fg); stroke-dasharray: 6 4; }
.gm-e.es-hypothesis { stroke: var(--text-faint); stroke-dasharray: 2 4; }
.gm-e.es-needs_review { stroke: var(--sev-info-fg); stroke-dasharray: 4 3; }
.gm-e { fill: none; stroke-width: 2.2; opacity: .7; stroke-linecap: round; transition: opacity .15s, stroke-width .15s;
filter: drop-shadow(0 1px 1px rgba(15,23,42,.10)); }
.gm-e.gm-trav { stroke-width: 3; opacity: .9; filter: drop-shadow(0 0 3px color-mix(in srgb, currentColor 35%, transparent)); }
.gm-e.es-confirmed { stroke: #22c55e; }
.gm-e.es-needs_validation { stroke: #f59e0b; stroke-dasharray: 8 5; }
.gm-e.es-hypothesis { stroke: #94a3b8; stroke-dasharray: 2 5; }
.gm-e.es-needs_review { stroke: #38bdf8; stroke-dasharray: 5 4; }
.gm-e:hover { opacity: 1; stroke-width: 4; }
.gm-stage.focusing .gm-e { opacity: .1; }
.gm-stage.focusing .gm-e.hl { opacity: 1; stroke-width: 3; }
/* Circular node — Wiz/Orca style */
.gm-node { position: absolute; display: flex; flex-direction: column; align-items: center; cursor: pointer; }
.gm-node:hover .gm-circle { transform: scale(1.08); box-shadow: 0 4px 16px rgba(0,0,0,.15); }
.gm-node.sel .gm-circle { outline: 3px solid var(--focus-ring); outline-offset: 2px; }
.gm-circle { width: 56px; height: 56px; border-radius: 50%; border: 2px solid var(--border-strong); background: var(--surface); display: flex; align-items: center; justify-content: center; transition: transform .15s, box-shadow .15s; position: relative; }
.gm-circle svg { width: 26px; height: 26px; }
.gm-node { position: absolute; display: flex; flex-direction: column; align-items: center; cursor: pointer; user-select: none; }
.gm-node:hover .gm-circle { transform: translateY(-2px) scale(1.06); }
.gm-node.sel .gm-circle { outline: 3px solid var(--focus-ring); outline-offset: 3px; }
.gm-circle { width: 64px; height: 64px; border-radius: 50%; border: 3px solid rgba(255,255,255,.9); color: #fff;
display: flex; align-items: center; justify-content: center; position: relative;
transition: transform .16s ease, box-shadow .16s ease, filter .16s ease;
box-shadow: 0 8px 22px -6px rgba(15,23,42,.35), 0 0 0 1px rgba(15,23,42,.06); }
.gm-circle::after { content: ""; position: absolute; inset: -7px; border-radius: 50%; opacity: 0; transition: opacity .16s; pointer-events: none;
background: radial-gradient(circle, color-mix(in srgb, currentColor 22%, transparent), transparent 68%); }
.gm-node:hover .gm-circle::after { opacity: 1; }
.gm-circle svg { width: 30px; height: 30px; stroke-width: 1.9; filter: drop-shadow(0 1px 1px rgba(0,0,0,.18)); }
.gm-badge { position: absolute; top: -4px; right: -4px; min-width: 18px; height: 18px; border-radius: 9px; font-size: 10px; font-weight: 700; display: flex; align-items: center; justify-content: center; padding: 0 4px; border: 2px solid var(--surface); }
.gm-node-label { font-size: var(--fs-xs); font-weight: 500; color: var(--text); text-align: center; max-width: 130px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; margin-top: 6px; }
.gm-node-sub { font-size: var(--fs-2xs); color: var(--text-faint); text-align: center; max-width: 130px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
/* Color rings by kind */
.gk-internet .gm-circle { border-color: #4da6ff; background: #e8f4fd; }
.gk-asset .gm-circle { border-color: #4da6ff; background: #e8f4fd; }
.gk-surface .gm-circle { border-color: #f59e0b; background: #fef3c7; }
.gk-weak .gm-circle { border-color: #ef4444; background: #fef2f2; }
.gk-step .gm-circle { border-color: #8b5cf6; background: #f3e8ff; }
.gk-cred .gm-circle { border-color: #10b981; background: #ecfdf5; }
.gk-impact .gm-circle { border-color: #ef4444; background: #fef2f2; }
.gk-meta .gm-circle { border-color: var(--border); background: var(--surface-2); }
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) .gk-internet .gm-circle { border-color: #60a5fa; background: rgba(96,165,250,.12); }
:root:not([data-theme="light"]) .gk-asset .gm-circle { border-color: #60a5fa; background: rgba(96,165,250,.12); }
:root:not([data-theme="light"]) .gk-surface .gm-circle { border-color: #fbbf24; background: rgba(251,191,36,.12); }
:root:not([data-theme="light"]) .gk-weak .gm-circle { border-color: #f87171; background: rgba(248,113,113,.12); }
:root:not([data-theme="light"]) .gk-step .gm-circle { border-color: #a78bfa; background: rgba(167,139,250,.12); }
:root:not([data-theme="light"]) .gk-cred .gm-circle { border-color: #34d399; background: rgba(52,211,153,.12); }
:root:not([data-theme="light"]) .gk-impact .gm-circle { border-color: #f87171; background: rgba(248,113,113,.12); }
}
:root[data-theme="dark"] .gk-internet .gm-circle { border-color: #60a5fa; background: rgba(96,165,250,.12); }
:root[data-theme="dark"] .gk-asset .gm-circle { border-color: #60a5fa; background: rgba(96,165,250,.12); }
:root[data-theme="dark"] .gk-surface .gm-circle { border-color: #fbbf24; background: rgba(251,191,36,.12); }
:root[data-theme="dark"] .gk-weak .gm-circle { border-color: #f87171; background: rgba(248,113,113,.12); }
:root[data-theme="dark"] .gk-step .gm-circle { border-color: #a78bfa; background: rgba(167,139,250,.12); }
:root[data-theme="dark"] .gk-cred .gm-circle { border-color: #34d399; background: rgba(52,211,153,.12); }
:root[data-theme="dark"] .gk-impact .gm-circle { border-color: #f87171; background: rgba(248,113,113,.12); }
.gm-node-label { font-size: var(--fs-sm); font-weight: 600; color: var(--text); text-align: center; max-width: 176px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; margin-top: 9px; letter-spacing: -.01em; }
.gm-node-info { font-size: 10px; font-family: var(--mono); color: var(--accent); text-align: center; max-width: 176px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; margin-top: 1px; opacity: .85; }
.gm-node-sub { font-size: var(--fs-xs); color: var(--text-faint); text-align: center; max-width: 176px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; margin-top: 1px; }
/* Solid Wiz-style fills by kind (white icon on saturated disc) */
.gk-internet .gm-circle { background: linear-gradient(145deg, #60a5fa, #2563eb); }
.gk-asset .gm-circle { background: linear-gradient(145deg, #38bdf8, #0284c7); }
.gk-surface .gm-circle { background: linear-gradient(145deg, #fbbf24, #ea580c); }
.gk-weak .gm-circle { background: linear-gradient(145deg, #fb7185, #dc2626); }
.gk-step .gm-circle { background: linear-gradient(145deg, #a78bfa, #7c3aed); }
.gk-cred .gm-circle { background: linear-gradient(145deg, #34d399, #059669); }
.gk-impact .gm-circle { background: linear-gradient(145deg, #fb7185, #dc2626); }
.gk-meta .gm-circle { background: linear-gradient(145deg, #94a3b8, #64748b); color: #fff; }
.gk-internet .gm-circle, .gk-asset .gm-circle { color: #fff; }
.gm-sev-badge { position: absolute; top: -2px; left: -2px; font-size: 9px; font-weight: 800; text-transform: uppercase; padding: 1px 5px; border-radius: 8px; }
.gm-leg { font-size: var(--fs-xs); padding: 3px 8px; border: 1px solid var(--border); border-radius: var(--radius-pill); background: var(--surface); color: var(--text-dim); display: inline-flex; align-items: center; gap: 6px; }
.gm-leg { font-size: var(--fs-xs); padding: 3px 8px; border: 1px solid var(--border); border-radius: var(--radius-pill); background: var(--surface); color: var(--text-dim); display: inline-flex; align-items: center; gap: 6px; cursor: pointer; transition: opacity .15s, box-shadow .15s; user-select: none; }
.gm-leg:hover { box-shadow: 0 0 0 2px color-mix(in srgb, var(--accent) 30%, transparent); }
.gm-leg:not(.gm-leg-active) { opacity: .35; }
.gm-leg-active { box-shadow: inset 0 0 0 1px var(--accent); }
.gm-leg .gm-leg-dot { width: 10px; height: 10px; border-radius: 50%; border: 2px solid; }
.gm-leg.gk-internet .gm-leg-dot { border-color: #4da6ff; }
.gm-leg.gk-asset .gm-leg-dot { border-color: #4da6ff; }
@@ -1125,7 +1147,15 @@ body.resizing-ns { user-select: none; cursor: ns-resize; }
.gm-edge-leg.es-confirmed::before { border-color: var(--sev-low-fg); }
.gm-edge-leg.es-needs_validation::before { border-color: var(--sev-medium-fg); border-top-style: dashed; }
.gm-edge-leg.es-hypothesis::before { border-color: var(--text-faint); border-top-style: dotted; }
.gm-zoom { position: absolute; left: 10px; bottom: 10px; display: flex; flex-direction: column; gap: 4px; }
.gm-zoom { position: absolute; left: 12px; bottom: 12px; display: flex; flex-direction: column; gap: 2px; padding: 4px;
background: color-mix(in srgb, var(--surface) 88%, transparent); border: 1px solid var(--border);
border-radius: var(--radius-pill); box-shadow: 0 8px 24px -10px rgba(15,23,42,.45); backdrop-filter: blur(8px); }
.gm-zoom .btn { width: 30px; height: 30px; padding: 0; border-radius: 50%; font-size: 15px; line-height: 1; display: grid; place-items: center; }
.gm-legend-bar { position: absolute; top: 12px; right: 12px; display: flex; flex-wrap: wrap; gap: 6px; max-width: 60%; justify-content: flex-end;
padding: 6px; border-radius: var(--radius-md); background: color-mix(in srgb, var(--surface) 82%, transparent);
border: 1px solid var(--border); box-shadow: 0 8px 24px -14px rgba(15,23,42,.4); backdrop-filter: blur(8px); }
.gm-node.gk-weak .gm-circle, .gm-node.gk-impact .gm-circle { box-shadow: 0 10px 26px -6px rgba(220,38,38,.45), 0 0 0 1px rgba(220,38,38,.15); }
.gm-node.gk-cred .gm-circle { box-shadow: 0 10px 26px -8px rgba(5,150,105,.4); }
.gm-detail { margin-top: var(--sp-3); border: 1px solid var(--border); border-radius: var(--radius-md); background: var(--surface); padding: var(--sp-3) var(--sp-4); }
.gm-detail header { display: flex; align-items: center; gap: var(--sp-2); justify-content: space-between; margin-bottom: var(--sp-2); }
.kv { border-collapse: collapse; font-size: var(--fs-xs); width: 100%; }
+103 -2
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env node
'use strict';
/**
* NeuroSploit v4.4.3 — web console backend.
* NeuroSploit — web console backend.
*
* Zero-dependency Node HTTP server that:
* - serves the static SPA in ./public
@@ -73,6 +73,35 @@ async function writeConfig(name, data) {
await fsp.writeFile(configFile(name), JSON.stringify(data, null, 2));
}
// run-id -> project-id. The launch chooses the project, but the run id is only
// known after recon prints it, so the binding is recorded here the moment it
// appears and survives a restart.
const RUN_PROJECTS_FILE = path.join(CONFIG_DIR, 'run-projects.json');
const runProjects = new Map();
try {
const raw = JSON.parse(fs.readFileSync(RUN_PROJECTS_FILE, 'utf8'));
for (const [k, v] of Object.entries(raw)) runProjects.set(k, v);
} catch { /* none yet */ }
function assignRunProject(runId, projectId) {
if (!runId) return;
if (projectId) runProjects.set(runId, projectId);
else runProjects.delete(runId);
fsp.mkdir(path.dirname(RUN_PROJECTS_FILE), { recursive: true })
.then(() => fsp.writeFile(RUN_PROJECTS_FILE, JSON.stringify(Object.fromEntries(runProjects), null, 2)))
.catch(() => {});
if (!projectId) return;
readConfig('projects').then((projects) => {
const i = projects.findIndex((p) => p.id === projectId);
if (i < 0) return;
if (!Array.isArray(projects[i].runIds)) projects[i].runIds = [];
if (projects[i].runIds.includes(runId)) return;
projects[i].runIds.push(runId);
projects[i].updatedAt = new Date().toISOString();
return writeConfig('projects', projects);
}).catch(() => {});
}
const JOBS_DIR = path.join(ROOT, '.neurosploit', 'web-jobs');
function jobFile(id) { return path.join(JOBS_DIR, `${id}.json`); }
function persistJob(job) {
@@ -91,6 +120,14 @@ function persistJob(job) {
}
function deleteJobFile(id) { try { fs.unlinkSync(jobFile(id)); } catch { /* gone already */ } }
// A project's targets may arrive as a comma/newline separated string or an
// array. Normalize to a trimmed, de-duplicated array so matching a run against
// the project is a simple substring test.
function normalizeTargets(v) {
const arr = Array.isArray(v) ? v : String(v || '').split(/[\s,;]+/);
return [...new Set(arr.map(s => String(s).trim()).filter(Boolean))];
}
const PUBLIC_DIR = path.join(WEB_DIR, 'public');
function findBinary() {
@@ -771,6 +808,7 @@ async function listRuns() {
ts,
name: engagementNames.get(id) || '',
target: status.target || meta.target || id.replace(/^ns-\d+-/, ''),
projectId: runProjects.get(id) || null,
state,
findings: findings.length,
severities: sevCount,
@@ -792,6 +830,7 @@ async function listRuns() {
ts: Math.floor((j.startedAt || Date.now()) / 1000),
name: j.name || '',
target: j.target || '',
projectId: j.projectId || null,
state: 'running',
findings: (j.findings || []).length,
severities: sevCount,
@@ -1152,6 +1191,7 @@ class Job extends EventEmitter {
this.args = args;
this.target = target || '';
this.name = name || '';
this.projectId = null;
this.pinnedAgents = [];
this.runId = null; // ns-<ts>-<target> workdir basename, once known
this.phase = 'starting';
@@ -1184,6 +1224,7 @@ class Job extends EventEmitter {
id: this.id,
target: this.target,
name: this.name,
projectId: this.projectId,
pinnedAgents: this.pinnedAgents,
interactive: !!this.repl,
runId: this.runId,
@@ -1298,7 +1339,11 @@ function ingestLine(job, rawLine) {
if (rep) job.reportUrl = rep[1];
const rid = line.match(/run id\s*:\s*(\S+)/);
if (rid) { job.runId = rid[1]; saveEngagementName(job.runId, job.name); }
if (rid) {
job.runId = rid[1];
saveEngagementName(job.runId, job.name);
assignRunProject(job.runId, job.projectId);
}
// --- live per-agent status, for the "what's being tested" panel ---
if (!job.agentStatus) job.agentStatus = {};
@@ -1419,6 +1464,7 @@ async function startJob(body) {
const args = buildArgs({ ...body, creds: credsPath, scopePath, collectionPath });
const job = new Job(id, BIN, args, body.repo || body.target || '', body.name || '');
job.pinnedAgents = body.agents || [];
job.projectId = body.projectId || null;
jobs.set(id, job);
const cloudEnv = body.cloudProvider ? await cloudEnvOverrides(body.cloudProvider) : {};
@@ -1499,6 +1545,7 @@ function sanitizeLaunch(body) {
mode: body.mode || 'run',
target: body.target || '',
repo: body.repo || '',
projectId: body.projectId || null,
models: body.models || [],
subscription: !!body.subscription,
mcp: !!body.mcp,
@@ -1577,6 +1624,7 @@ async function startJobViaRepl(body) {
const auth = authArgs({ ...body, scopePath });
const job = new Job(id, BIN, auth, body.repo || body.target || '', body.name || '');
job.pinnedAgents = body.agents || [];
job.projectId = body.projectId || null;
job.repl = true;
// Non-secret params needed to relaunch this job after a restart. No API keys,
// no creds-file contents — only what rebuilds the engagement shape so a
@@ -1682,6 +1730,7 @@ function loadPersistedJobs() {
if (!rec || !rec.id) continue;
const job = new Job(rec.id, BIN, [], rec.target || '', rec.name || '');
job.runId = rec.runId || null;
job.projectId = rec.projectId || (rec.launch && rec.launch.projectId) || null;
job.findings = rec.findings || [];
job.agents = rec.agents || 0;
job.agentsDone = rec.agentsDone || 0;
@@ -2686,6 +2735,58 @@ const server = http.createServer(async (req, res) => {
return sendJson(res, 200, body);
}
// ---- Config CRUD: projects / orgs ----
// A project groups every engagement (run) against one customer, domain or
// internal target so the console can show "all tests for target X" apart
// from everything else. Grouping only — it never touches the run data.
if (req.method === 'GET' && p === '/api/projects') return sendJson(res, 200, await readConfig('projects'));
if (req.method === 'POST' && p === '/api/projects') {
const body = await readBody(req);
const name = String(body.name || '').trim();
if (!name) return sendJson(res, 400, { error: 'project name is required' });
const projects = await readConfig('projects');
const item = {
id: crypto.randomUUID(),
org: String(body.org || 'Default').trim() || 'Default',
name,
targets: normalizeTargets(body.targets ?? body.target),
description: String(body.description || '').trim(),
runIds: Array.isArray(body.runIds) ? body.runIds.map(String) : [],
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
};
projects.push(item);
await writeConfig('projects', projects);
return sendJson(res, 200, item);
}
m = p.match(/^\/api\/projects\/([^/]+)$/);
if (req.method === 'PUT' && m) {
const body = await readBody(req);
const id = decodeURIComponent(m[1]);
let projects = await readConfig('projects');
const idx = projects.findIndex(x => x.id === id);
if (idx < 0) return sendJson(res, 404, { error: 'project not found' });
const prev = projects[idx];
projects[idx] = {
...prev,
org: body.org != null ? (String(body.org).trim() || 'Default') : prev.org,
name: body.name != null ? (String(body.name).trim() || prev.name) : prev.name,
targets: body.targets != null || body.target != null ? normalizeTargets(body.targets ?? body.target) : prev.targets,
description: body.description != null ? String(body.description).trim() : prev.description,
runIds: Array.isArray(body.runIds) ? body.runIds.map(String) : prev.runIds,
updatedAt: new Date().toISOString(),
};
await writeConfig('projects', projects);
return sendJson(res, 200, projects[idx]);
}
if (req.method === 'DELETE' && m) {
let projects = await readConfig('projects');
const before = projects.length;
projects = projects.filter(x => x.id !== decodeURIComponent(m[1]));
await writeConfig('projects', projects);
return sendJson(res, 200, { ok: true, removed: before - projects.length });
}
// ---- Config: guardrails ----
if (req.method === 'GET' && p === '/api/config/guardrails') return sendJson(res, 200, await readConfigObj('guardrails'));
if (req.method === 'PUT' && p === '/api/config/guardrails') {