From bf4439652225d2bd05fe0490517c0421759619bd Mon Sep 17 00:00:00 2001 From: CyberSecurityUP Date: Tue, 1 Dec 2026 14:08:36 -0300 Subject: [PATCH] feat(c2): generic MCP C2 session reuse (any stdio MCP, not just ours) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - mcp_client: minimal stdio MCP client (initialize/tools.list/tools.call), newline JSON-RPC, ${VAR:-default} expansion - c2_reuse: import/normalize sessions from any C2 (Sliver/Havoc/Mythic/Adaptix/CS export shapes), pick the best existing session for a target, persist 0600, inject a reuse prompt block into chain/worker prompts - c2x sync --profile or --command : discovers the session-listing tool (sliver_sessions/havoc_demons/mythic_callbacks/ get_live_beacons, or pattern), calls it, imports the result — provider-agnostic - CLI: neurosploit c2x {sync,import,list,reuse,context} --- neurosploit-rs/app/src/c2xcli.rs | 187 +++++++ neurosploit-rs/app/src/main.rs | 7 + neurosploit-rs/crates/harness/src/c2_reuse.rs | 476 ++++++++++++++++++ neurosploit-rs/crates/harness/src/lib.rs | 2 + .../crates/harness/src/mcp_client.rs | 192 +++++++ neurosploit-rs/crates/harness/src/pipeline.rs | 5 +- .../crates/harness/src/reactive_bridge.rs | 4 +- 7 files changed, 871 insertions(+), 2 deletions(-) create mode 100644 neurosploit-rs/app/src/c2xcli.rs create mode 100644 neurosploit-rs/crates/harness/src/c2_reuse.rs create mode 100644 neurosploit-rs/crates/harness/src/mcp_client.rs diff --git a/neurosploit-rs/app/src/c2xcli.rs b/neurosploit-rs/app/src/c2xcli.rs new file mode 100644 index 0000000..7ff32d9 --- /dev/null +++ b/neurosploit-rs/app/src/c2xcli.rs @@ -0,0 +1,187 @@ +//! `neurosploit c2x …` — external C2 session reuse (Sliver/Havoc/Mythic/CS). +//! +//! Import an exported session list, list what is known, and pick the best +//! existing session for a target so chain steps reuse footholds. + +use clap::Subcommand; +use serde_json::{json, Value}; + +#[derive(Subcommand)] +pub enum C2xCmd { + /// Import an exported session list from an external C2 (Sliver/Havoc/Mythic/CS). + Import { + /// sliver | havoc | mythic | cobaltstrike + #[arg(long)] + kind: String, + /// Path to the exported JSON (array, or .sessions/.callbacks/.demons/.data). + #[arg(long)] + file: String, + #[arg(long)] + json: bool, + }, + /// List imported external sessions. + List { + #[arg(long)] + json: bool, + }, + /// Pick the best existing session for a target (IP / host / user). + Reuse { + #[arg(long)] + target: String, + #[arg(long)] + json: bool, + }, + /// Discover sessions from any stdio MCP C2 server (Sliver/Havoc/Mythic/ + /// Adaptix or a custom `--command`) and import them. + Sync { + /// Built-in C2 profile: sliver | havoc | mythic | adaptix. + #[arg(long)] + profile: Option, + /// Arbitrary stdio MCP command (overrides --profile). + #[arg(long)] + command: Option, + /// Arg for --command (repeatable). + #[arg(long = "arg")] + args: Vec, + /// Env KEY=VAL for --command (repeatable). + #[arg(long = "env")] + env: Vec, + /// Session kind label (defaults to the profile name). + #[arg(long)] + kind: Option, + /// Explicit session-listing tool (default: auto-detect). + #[arg(long)] + tool: Option, + #[arg(long, default_value_t = 60)] + timeout: u64, + #[arg(long)] + json: bool, + }, + /// Print the redacted reuse prompt block injected into agent prompts. + Context { + #[arg(long)] + json: bool, + }, +} + +fn env_pairs(pairs: &[String]) -> Vec<(String, String)> { + pairs + .iter() + .filter_map(|kv| kv.split_once('=')) + .map(|(k, v)| (k.trim().to_string(), harness::mcp_client::expand_vars(v.trim()))) + .filter(|(k, _)| !k.is_empty()) + .collect() +} + +/// Resolve a profile to its stdio MCP command/args/env from mcp_profiles. +fn profile_stdio(name: &str) -> Option<(String, Vec, Vec<(String, String)>)> { + use harness::mcp_profiles::{profile, Profile}; + let p = match name.to_ascii_lowercase().as_str() { + "sliver" | "sliverc2" => Profile::SliverC2, + "havoc" | "havocc2" => Profile::HavocC2, + "mythic" | "mythicc2" => Profile::MythicC2, + "adaptix" | "adaptixc2" => Profile::AdaptixC2, + _ => return None, + }; + let cfg = profile(&p).config; + let command = cfg.get("command").and_then(|x| x.as_str())?.to_string(); + let args = cfg + .get("args") + .and_then(|x| x.as_array()) + .map(|a| { + a.iter() + .filter_map(|v| v.as_str()) + .map(harness::mcp_client::expand_vars) + .collect() + }) + .unwrap_or_default(); + let env = cfg + .get("env") + .and_then(|x| x.as_object()) + .map(|o| { + o.iter() + .map(|(k, v)| { + ( + k.clone(), + harness::mcp_client::expand_vars(v.as_str().unwrap_or("")), + ) + }) + .collect() + }) + .unwrap_or_default(); + Some((command, args, env)) +} + +pub async fn handle_c2x(cmd: C2xCmd) -> anyhow::Result<()> { + let out: Value = match cmd { + C2xCmd::Import { kind, file, .. } => { + let body = std::fs::read_to_string(&file).map_err(|e| anyhow::anyhow!("{file}: {e}"))?; + let all = harness::c2_reuse::import(&kind, &body).map_err(|e| anyhow::anyhow!(e))?; + json!({ "ok": true, "imported_kind": kind, "total": all.len(), "sessions": all }) + } + C2xCmd::List { .. } => { + let all = harness::c2_reuse::load(); + json!({ "total": all.len(), "sessions": all }) + } + C2xCmd::Reuse { target, .. } => { + let all = harness::c2_reuse::load(); + match harness::c2_reuse::select(&all, &target) { + Some(s) => json!({ "ok": true, "target": target, "session": s }), + None => json!({ "ok": false, "target": target, "error": "no existing session matches this target" }), + } + } + C2xCmd::Sync { + profile, + command, + args, + env, + kind, + tool, + timeout, + .. + } => { + let (cmd, arglist, envlist, kind) = if let Some(c) = + command.as_deref().map(str::trim).filter(|c| !c.is_empty()) + { + ( + c.to_string(), + args.clone(), + env_pairs(&env), + kind.clone().unwrap_or_else(|| "custom".to_string()), + ) + } else if let Some(p) = profile.as_deref() { + match profile_stdio(p) { + Some((cmd, mut a, e)) => { + a.extend(args.iter().cloned()); + ( + cmd, + a, + e, + kind.clone().unwrap_or_else(|| p.to_string()), + ) + } + None => { + return Err(anyhow::anyhow!( + "unknown/incompatible profile '{p}' — use --command for a custom stdio MCP server (Cobalt Strike is HTTP: export its sessions and use `c2x import`)" + )) + } + } + } else { + return Err(anyhow::anyhow!( + "pass --profile or --command " + )); + }; + let report = + harness::c2_reuse::sync_stdio(&cmd, &arglist, &envlist, &kind, tool.as_deref(), timeout) + .await + .map_err(|e| anyhow::anyhow!(e))?; + json!({ "ok": true, "sync": report, "total": harness::c2_reuse::load().len() }) + } + C2xCmd::Context { .. } => json!({ "context": harness::c2_reuse::context() }), + }; + println!( + "{}", + serde_json::to_string_pretty(&out).unwrap_or_else(|_| "{}".into()) + ); + Ok(()) +} diff --git a/neurosploit-rs/app/src/main.rs b/neurosploit-rs/app/src/main.rs index 99d62b5..43db917 100644 --- a/neurosploit-rs/app/src/main.rs +++ b/neurosploit-rs/app/src/main.rs @@ -3,6 +3,7 @@ mod activitycli; mod adcli; mod c2cli; +mod c2xcli; mod checkpointcli; mod economycli; mod phishcli; @@ -457,6 +458,11 @@ enum Cmd { #[command(subcommand)] cmd: checkpointcli::CheckpointCmd, }, + /// External C2 session reuse (Sliver/Havoc/Mythic/CS): import, list, reuse. + C2x { + #[command(subcommand)] + cmd: c2xcli::C2xCmd, + }, /// 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, @@ -1427,6 +1433,7 @@ async fn main() -> anyhow::Result<()> { Cmd::Activity { cmd } => { activitycli::handle_activity(cmd).await?; } Cmd::Adchain { cmd } => { adcli::handle_ad(cmd).await?; } Cmd::Checkpoint { cmd } => { checkpointcli::handle_checkpoint(cmd).await?; } + Cmd::C2x { cmd } => { c2xcli::handle_c2x(cmd).await?; } Cmd::Mcp => { mcp::serve()?; } Cmd::Rebuild { run } => { // Accept either a path or a bare run id, resolved against the same diff --git a/neurosploit-rs/crates/harness/src/c2_reuse.rs b/neurosploit-rs/crates/harness/src/c2_reuse.rs new file mode 100644 index 0000000..fa0baca --- /dev/null +++ b/neurosploit-rs/crates/harness/src/c2_reuse.rs @@ -0,0 +1,476 @@ +//! External C2 session reuse (Sliver / Havoc / Mythic / Cobalt Strike). +//! +//! A complete red-team agent should reuse the footholds it already has — not +//! re-establish or re-spawn a session per intent. This module imports an +//! exported session list from an external C2, normalizes the common fields, +//! persists it under `.neurosploit/c2/external-sessions.json` (0600), and gives +//! the agent a way to pick the best existing session for a target so chain +//! steps can task it instead of starting from zero. +//! +//! It is deliberately tolerant of export shapes (`[...]`, `.sessions`, +//! `.callbacks`, `.demons`, `.data`) because each C2 names fields differently. + +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::io::Write; +use std::path::{Path, PathBuf}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ExternalSession { + pub id: String, + /// sliver | havoc | mythic | cobaltstrike + pub kind: String, + pub host: String, + pub user: String, + pub os: String, + pub arch: String, + pub internal_ip: String, + /// Milliseconds since epoch (0 = unknown). + pub last_seen: i64, + pub alive: bool, + pub note: String, +} + +pub fn 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") +} + +fn file() -> PathBuf { + dir().join("external-sessions.json") +} + +pub fn load() -> Vec { + std::fs::read_to_string(file()) + .ok() + .and_then(|s| serde_json::from_str::>(&s).ok()) + .unwrap_or_default() +} + +fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + 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.flush()?; + } + if path.exists() { + let _ = std::fs::remove_file(path); + } + std::fs::rename(&tmp, path) +} + +fn save(sessions: &[ExternalSession]) -> Result<(), String> { + let bytes = serde_json::to_vec_pretty(sessions).map_err(|e| e.to_string())?; + write_private(&file(), &bytes).map_err(|e| format!("could not write {}: {e}", file().display())) +} + +fn normalize_kind(kind: &str) -> String { + match kind.to_ascii_lowercase().as_str() { + "sliver" | "sliverc2" => "sliver", + "havoc" | "havocc2" => "havoc", + "mythic" | "mythicc2" => "mythic", + "cobaltstrike" | "cobalt" | "cs" | "cobalt_strike" => "cobaltstrike", + other => other, + } + .to_string() +} + +fn field<'a>(o: &'a Value, keys: &[&str]) -> Option<&'a Value> { + for k in keys { + if let Some(v) = o.get(*k) { + if !v.is_null() { + return Some(v); + } + } + } + None +} + +fn sfield(o: &Value, keys: &[&str]) -> String { + field(o, keys) + .map(|v| match v { + Value::String(s) => s.clone(), + other => other.to_string(), + }) + .unwrap_or_default() + .trim_matches('"') + .to_string() +} + +fn ts_to_ms(v: &Value) -> i64 { + let n = match v { + Value::Number(x) => x.as_i64().or_else(|| x.as_u64().map(|u| u as i64)).unwrap_or(0), + Value::String(s) => s.trim().parse::().unwrap_or(0), + _ => 0, + }; + if n > 1_000_000_000_000 { + n // already ms + } else if n > 1_000_000_000 { + n * 1000 // seconds → ms + } else { + 0 + } +} + +/// Parse an exported session list from any supported C2 into normalized +/// [`ExternalSession`]s. Tolerant of array vs object wrappers and field aliases. +pub fn parse_export(kind: &str, json: &str) -> Result, String> { + let v: Value = serde_json::from_str(json).map_err(|e| format!("invalid JSON: {e}"))?; + let arr: Vec = if let Some(a) = v.as_array() { + a.clone() + } else if let Some(a) = ["sessions", "data", "callbacks", "demons", "beacons", "items"] + .iter() + .find_map(|k| v.get(*k).and_then(|x| x.as_array())) + { + a.clone() + } else { + return Err( + "no session array found (expected a JSON array or one of .sessions/.data/.callbacks/.demons/.beacons/.items)" + .into(), + ); + }; + let kind = normalize_kind(kind); + let mut out = Vec::new(); + for o in arr { + if !o.is_object() { + continue; + } + let id = sfield(&o, &["id", "ID", "session_id", "SessionID", "sid", "uuid", "UUID", "callback_id"]); + let host = sfield(&o, &["host", "hostname", "Hostname", "Host", "computer", "Computer", "target", "Name"]); + let user = sfield(&o, &["user", "username", "Username", "User", "owner", "Owner", "user_name"]); + let os = sfield(&o, &["os", "OS", "platform", "Platform", "operating_system"]); + let arch = sfield(&o, &["arch", "Arch", "architecture", "Architecture"]); + let ip = sfield(&o, &["internal_ip", "InternalIP", "ip", "IP", "internal", "remote_address", "RemoteAddress", "host_ip", "ExternalIP"]); + let last_seen = field( + &o, + &["last_seen", "lastSeen", "last_checkin", "LastCheckin", "last_seen_at", "LastSeen", "updated_at", "UpdatedAt", "last_checkin_at"], + ) + .map(ts_to_ms) + .unwrap_or(0); + let alive = field(&o, &["alive", "Alive", "active", "Active", "is_alive", "IsAlive"]) + .and_then(|x| x.as_bool()) + .unwrap_or(true); + let note = sfield(&o, &["note", "description", "comment", "process", "Process", "listener"]); + let id = if id.is_empty() { + format!("{kind}-{}", out.len()) + } else { + id + }; + out.push(ExternalSession { + id, + kind: kind.clone(), + host, + user, + os, + arch, + internal_ip: ip, + last_seen, + alive, + note, + }); + } + Ok(out) +} + +fn merge(mut all: Vec, parsed: Vec) -> Vec { + for s in parsed { + if let Some(slot) = all.iter_mut().find(|x| x.kind == s.kind && x.id == s.id) { + *slot = s; + } else { + all.push(s); + } + } + all +} + +/// Merge parsed sessions into the persisted set, de-duplicated by (kind, id). +/// Returns the merged set. +pub fn import(kind: &str, json: &str) -> Result, String> { + let parsed = parse_export(kind, json)?; + let all = merge(load(), parsed); + save(&all)?; + Ok(all) +} + +/// Pick the best existing session for a target (IP / host / user): exact match +/// first, then substring; alive before dead, then most-recently-seen. +pub fn select<'a>(sessions: &'a [ExternalSession], target: &str) -> Option<&'a ExternalSession> { + let t = target.trim().to_ascii_lowercase(); + if t.is_empty() { + return None; + } + let mut cands: Vec<&ExternalSession> = sessions + .iter() + .filter(|s| { + let h = s.host.to_ascii_lowercase(); + let ip = s.internal_ip.to_ascii_lowercase(); + let u = s.user.to_ascii_lowercase(); + (!ip.is_empty() && (ip == t || ip.contains(&t))) + || (!h.is_empty() && (h == t || h.contains(&t))) + || (!u.is_empty() && u == t) + }) + .collect(); + cands.sort_by(|a, b| b.alive.cmp(&a.alive).then(b.last_seen.cmp(&a.last_seen))); + cands.into_iter().next() +} + +/// Preferred session-listing tools per C2 (from `mcp_profiles::tool_allowlist`). +pub fn session_tools_for(kind: &str) -> &'static [&'static str] { + match normalize_kind(kind).as_str() { + "sliver" => &["sliver_sessions", "sliver_beacons", "sliver_hosts"], + "havoc" => &["havoc_demons"], + "mythic" => &["mythic_callbacks"], + "adaptix" => &["get_live_beacons"], + "cobaltstrike" => &["cs_list_beacons"], + _ => &[], + } +} + +/// Pick a session-listing tool from any MCP server's `tools/list`: prefer the +/// known per-C2 name, else match a name that looks like it lists sessions. +pub fn find_session_tool(kind: &str, names: &[String]) -> Option { + for pref in session_tools_for(kind) { + if names.iter().any(|n| n.as_str() == *pref) { + return Some((*pref).to_string()); + } + } + let good = ["session", "beacon", "demon", "callback", "agent"]; + let bad = [ + "kill", "stop", "start", "create", "upload", "download", "delete", "rm", "remove", + "task", "file", "screenshot", "cred", "listener", "payload", "shell", "execute", + "inject", "sleep", "token", + ]; + names + .iter() + .find(|n| { + let l = n.to_ascii_lowercase(); + good.iter().any(|g| l.contains(g)) && !bad.iter().any(|b| l.contains(b)) + }) + .cloned() +} + +/// Pull text out of an MCP `tools/call` result (`content[].text`, +/// `structuredContent`, or a bare `text`). +pub fn extract_tool_text(result: &Value) -> String { + if let Some(arr) = result.get("content").and_then(|x| x.as_array()) { + let mut s = String::new(); + for p in arr { + if let Some(t) = p.get("text").and_then(|x| x.as_str()) { + if !s.is_empty() { + s.push('\n'); + } + s.push_str(t); + } + } + if !s.trim().is_empty() { + return s; + } + } + if let Some(st) = result.get("structuredContent") { + return st.to_string(); + } + if let Some(t) = result.get("text").and_then(|x| x.as_str()) { + return t.to_string(); + } + result.to_string() +} + +#[derive(Debug, Clone, Serialize)] +pub struct SyncReport { + pub kind: String, + pub tool: String, + pub fetched: usize, + pub total: usize, +} + +/// Discover C2 sessions from any stdio MCP server: initialize, list tools, +/// pick the session tool (or `tool` override), call it, normalize and persist. +pub async fn sync_stdio( + command: &str, + args: &[String], + env: &[(String, String)], + kind: &str, + tool: Option<&str>, + timeout_secs: u64, +) -> Result { + use std::time::Duration; + let to = Duration::from_secs(timeout_secs.max(1)); + let mut c = crate::mcp_client::McpStdio::spawn(command, args, env).await?; + if let Err(e) = c.initialize(to).await { + c.kill(); + return Err(e); + } + let tools = match c.tools_list(to).await { + Ok(t) => t, + Err(e) => { + c.kill(); + return Err(e); + } + }; + let names: Vec = tools + .iter() + .filter_map(|t| t.get("name").and_then(|x| x.as_str()).map(|s| s.to_string())) + .collect(); + let chosen = match tool.map(str::trim).filter(|t| !t.is_empty()) { + Some(t) => t.to_string(), + None => match find_session_tool(kind, &names) { + Some(t) => t, + None => { + let avail = names.join(", "); + c.kill(); + return Err(format!( + "no session-listing tool found on the MCP server (available: {avail}); pass --tool " + )); + } + }, + }; + let res = match c.call_tool(&chosen, serde_json::json!({}), to).await { + Ok(r) => r, + Err(e) => { + c.kill(); + return Err(e); + } + }; + c.kill(); + let text = extract_tool_text(&res); + let parsed = parse_export(kind, &text) + .map_err(|e| format!("could not parse `{chosen}` output: {e}"))?; + let fetched = parsed.len(); + let all = merge(load(), parsed); + save(&all)?; + Ok(SyncReport { + kind: normalize_kind(kind), + tool: chosen, + fetched, + total: all.len(), + }) +} + +/// Redacted prompt block: existing footholds a chain step can reuse. +pub fn context() -> String { + let sessions = load(); + if sessions.is_empty() { + return String::new(); + } + let rows: Vec = sessions + .iter() + .filter(|s| s.alive) + .take(12) + .map(|s| { + format!( + "- [{}] id={} host={} ip={} user={} os={} last_seen={}", + s.kind, + s.id, + if s.host.is_empty() { "?" } else { &s.host }, + if s.internal_ip.is_empty() { "?" } else { &s.internal_ip }, + if s.user.is_empty() { "?" } else { &s.user }, + if s.os.is_empty() { "?" } else { &s.os }, + s.last_seen, + ) + }) + .collect(); + if rows.is_empty() { + return String::new(); + } + format!( + "\n\nEXISTING C2 SESSIONS (reuse these footholds instead of re-establishing):\n{}\n\ +Pick a session for a host with `neurosploit c2x reuse --target ` and task it through its C2 client; \ +prefer an alive session whose last_seen is recent.\n", + rows.join("\n") + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_sliver_style_array() { + let json = r#"[ + {"ID":"abc123","Hostname":"WEB01","Username":"CORP\\svc","OS":"windows","Arch":"amd64","InternalIP":"10.0.1.20","LastCheckin":1700000000,"Alive":true}, + {"ID":"def456","Hostname":"DC01","Username":"CORP\\admin","OS":"windows","InternalIP":"10.0.2.5","Alive":true} + ]"#; + let s = parse_export("sliver", json).unwrap(); + assert_eq!(s.len(), 2); + assert_eq!(s[0].id, "abc123"); + assert_eq!(s[0].host, "WEB01"); + assert_eq!(s[0].internal_ip, "10.0.1.20"); + assert!(s[0].last_seen > 1_600_000_000_000); + } + + #[test] + fn parses_mythic_callbacks_wrapper() { + let json = r#"{"callbacks":[{"id":7,"host":"linux-db","user":"root","ip":"10.9.0.4","os":"linux","active":true}]}"#; + let s = parse_export("mythic", json).unwrap(); + assert_eq!(s.len(), 1); + assert_eq!(s[0].kind, "mythic"); + assert_eq!(s[0].internal_ip, "10.9.0.4"); + } + + #[test] + fn selection_prefers_exact_alive_recent() { + let sessions = vec![ + ExternalSession { id: "1".into(), kind: "sliver".into(), host: "WEB01".into(), user: "a".into(), os: "windows".into(), arch: "".into(), internal_ip: "10.0.1.20".into(), last_seen: 100, alive: false, note: "".into() }, + ExternalSession { id: "2".into(), kind: "sliver".into(), host: "WEB01".into(), user: "a".into(), os: "windows".into(), arch: "".into(), internal_ip: "10.0.1.20".into(), last_seen: 200, alive: true, note: "".into() }, + ExternalSession { id: "3".into(), kind: "sliver".into(), host: "WEB02".into(), user: "a".into(), os: "windows".into(), arch: "".into(), internal_ip: "10.0.1.21".into(), last_seen: 300, alive: true, note: "".into() }, + ]; + assert_eq!(select(&sessions, "10.0.1.20").unwrap().id, "2"); + assert_eq!(select(&sessions, "web02").unwrap().id, "3"); + assert!(select(&sessions, "10.9.9.9").is_none()); + } + + #[test] + fn picks_the_session_tool_for_a_c2() { + let names: Vec = ["sliver_version", "sliver_sessions", "sliver_kill_session"] + .iter() + .map(|s| s.to_string()) + .collect(); + assert_eq!(find_session_tool("sliver", &names).as_deref(), Some("sliver_sessions")); + // Unknown server: pattern-match a name that lists agents. + let generic: Vec = ["list_agents", "kill_agent", "upload_file"] + .iter() + .map(|s| s.to_string()) + .collect(); + assert_eq!(find_session_tool("custom", &generic).as_deref(), Some("list_agents")); + // Nothing that lists sessions. + let none: Vec = ["exec", "sleep"].iter().map(|s| s.to_string()).collect(); + assert!(find_session_tool("custom", &none).is_none()); + } + + #[test] + fn extracts_text_from_mcp_tool_result() { + let v = serde_json::json!({"content":[{"type":"text","text":"[{\"id\":\"1\"}]"}]}); + assert!(extract_tool_text(&v).contains("\"id\"")); + let s = serde_json::json!({"structuredContent":{"a":1}}); + assert!(extract_tool_text(&s).contains("\"a\"")); + } + + #[test] + fn merge_dedupes_by_kind_and_id() { + let a = parse_export("sliver", r#"[{"id":"x","host":"h1","ip":"10.0.0.1"}]"#).unwrap(); + let b = parse_export( + "sliver", + r#"[{"id":"x","host":"h1-updated","ip":"10.0.0.1"},{"id":"y","host":"h2","ip":"10.0.0.2"}]"#, + ) + .unwrap(); + let all = merge(a, b); + assert_eq!(all.len(), 2); + assert_eq!(all.iter().find(|s| s.id == "x").unwrap().host, "h1-updated"); + } +} diff --git a/neurosploit-rs/crates/harness/src/lib.rs b/neurosploit-rs/crates/harness/src/lib.rs index 9c8a619..7be42a2 100644 --- a/neurosploit-rs/crates/harness/src/lib.rs +++ b/neurosploit-rs/crates/harness/src/lib.rs @@ -22,6 +22,7 @@ pub mod budget; pub mod cache; pub mod capability; pub mod c2; +pub mod c2_reuse; pub mod chain; pub mod checkpoint; pub mod economy; @@ -54,6 +55,7 @@ pub mod knowledge; pub mod knowledge_graph; pub mod limits; pub mod logship; +pub mod mcp_client; pub mod mcp_hot_reload; pub mod mcp_profiles; pub mod memory; diff --git a/neurosploit-rs/crates/harness/src/mcp_client.rs b/neurosploit-rs/crates/harness/src/mcp_client.rs new file mode 100644 index 0000000..4b486b8 --- /dev/null +++ b/neurosploit-rs/crates/harness/src/mcp_client.rs @@ -0,0 +1,192 @@ +//! Minimal MCP stdio client (newline-delimited JSON-RPC 2.0). +//! +//! Just enough to drive *any* stdio MCP server generically: `initialize`, +//! `tools/list`, `tools/call`. Used by [`crate::c2_reuse`] to discover C2 +//! sessions from Sliver/Havoc/Mythic/Adaptix (or any custom server) instead of +//! hard-coding each C2's API. HTTP-transport MCP servers are handled by +//! exporting their session list and using `c2x import`. + +use serde_json::{json, Value}; +use std::process::Stdio; +use std::time::Duration; +use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; +use tokio::process::{Child, ChildStdin, ChildStdout, Command}; + +pub const DEFAULT_PROTOCOL: &str = "2024-11-05"; + +pub struct McpStdio { + child: Child, + stdin: ChildStdin, + out: BufReader, + next_id: u64, +} + +impl McpStdio { + pub async fn spawn( + command: &str, + args: &[String], + env: &[(String, String)], + ) -> Result { + if command.trim().is_empty() { + return Err("MCP command is empty".into()); + } + let mut cmd = Command::new(command); + cmd.args(args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()); + for (k, v) in env { + if !v.is_empty() { + cmd.env(k, v); + } + } + let mut child = cmd + .spawn() + .map_err(|e| format!("could not spawn MCP server `{command}`: {e}"))?; + let stdin = child.stdin.take().ok_or("MCP server has no stdin")?; + let stdout = child.stdout.take().ok_or("MCP server has no stdout")?; + Ok(Self { + child, + stdin, + out: BufReader::new(stdout), + next_id: 1, + }) + } + + async fn send(&mut self, msg: &Value) -> Result<(), String> { + let mut line = serde_json::to_string(msg).map_err(|e| e.to_string())?; + line.push('\n'); + self.stdin + .write_all(line.as_bytes()) + .await + .map_err(|e| format!("MCP write failed: {e}"))?; + self.stdin + .flush() + .await + .map_err(|e| format!("MCP flush failed: {e}")) + } + + async fn request(&mut self, method: &str, params: Value, timeout: Duration) -> Result { + let id = self.next_id; + self.next_id += 1; + self.send(&json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params })) + .await?; + let out = &mut self.out; + let fut = async move { + loop { + let mut buf = String::new(); + let n = match out.read_line(&mut buf).await { + Ok(n) => n, + Err(e) => return Err(format!("MCP read failed: {e}")), + }; + if n == 0 { + return Err::("MCP server closed its stdout".into()); + } + let line = buf.trim(); + if line.is_empty() { + continue; + } + let v: Value = match serde_json::from_str(line) { + Ok(v) => v, + Err(_) => continue, // log/noise line + }; + let rid = v + .get("id") + .and_then(|x| x.as_u64().or_else(|| x.as_i64().map(|n| n as u64))); + if rid != Some(id) { + continue; // a notification or another request's response + } + if let Some(err) = v.get("error") { + return Err(format!("MCP error: {err}")); + } + return Ok(v.get("result").cloned().unwrap_or(Value::Null)); + } + }; + match tokio::time::timeout(timeout, fut).await { + Ok(r) => r, + Err(_) => Err(format!("MCP `{method}` timed out")), + } + } + + pub async fn initialize(&mut self, timeout: Duration) -> Result<(), String> { + let _ = self + .request( + "initialize", + json!({ + "protocolVersion": DEFAULT_PROTOCOL, + "capabilities": {}, + "clientInfo": { "name": "neurosploit", "version": env!("CARGO_PKG_VERSION") } + }), + timeout, + ) + .await?; + self.send(&json!({ "jsonrpc": "2.0", "method": "notifications/initialized" })) + .await?; + Ok(()) + } + + pub async fn tools_list(&mut self, timeout: Duration) -> Result, String> { + let r = self.request("tools/list", json!({}), timeout).await?; + Ok(r.get("tools").and_then(|x| x.as_array()).cloned().unwrap_or_default()) + } + + pub async fn call_tool(&mut self, name: &str, args: Value, timeout: Duration) -> Result { + self.request("tools/call", json!({ "name": name, "arguments": args }), timeout) + .await + } + + pub fn kill(&mut self) { + let _ = self.child.start_kill(); + } +} + +impl Drop for McpStdio { + fn drop(&mut self) { + let _ = self.child.start_kill(); + } +} + +/// Expand `${NAME}` / `${NAME:-default}` in an MCP profile arg (the profiles use +/// this shell-style form for install paths). Empty env values fall back to the +/// default. +pub fn expand_vars(s: &str) -> String { + let bytes = s.as_bytes(); + let mut out = String::with_capacity(s.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'$' && i + 1 < bytes.len() && bytes[i + 1] == b'{' { + if let Some(rel_end) = s[i + 2..].find('}') { + let inner = &s[i + 2..i + 2 + rel_end]; + let (name, default) = match inner.split_once(":-") { + Some((n, d)) => (n, Some(d)), + None => (inner, None), + }; + let val = std::env::var(name) + .ok() + .filter(|v| !v.is_empty()) + .or_else(|| default.map(|d| d.to_string())) + .unwrap_or_default(); + out.push_str(&val); + i = i + 2 + rel_end + 1; + continue; + } + } + out.push(bytes[i] as char); + i += 1; + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn expands_default_and_env() { + std::env::set_var("NS_MCP_TEST_VAL", "/opt/x"); + assert_eq!(expand_vars("${NS_MCP_TEST_VAL}/bin"), "/opt/x/bin"); + assert_eq!(expand_vars("${NS_MCP_UNSET_VAR:-/opt/default}/db"), "/opt/default/db"); + assert_eq!(expand_vars("no-vars"), "no-vars"); + std::env::remove_var("NS_MCP_TEST_VAL"); + } +} diff --git a/neurosploit-rs/crates/harness/src/pipeline.rs b/neurosploit-rs/crates/harness/src/pipeline.rs index 1bdeaca..c806114 100644 --- a/neurosploit-rs/crates/harness/src/pipeline.rs +++ b/neurosploit-rs/crates/harness/src/pipeline.rs @@ -351,6 +351,8 @@ fn operator_directives(cfg: &RunConfig) -> String { s.push_str(&crate::traces::prompt_block(cfg.workdir.as_deref(), None)); // Step-level worker activity: what other workers actually executed. s.push_str(&crate::activity::prompt_block(cfg.workdir.as_deref(), None)); + // Existing external C2 footholds to reuse instead of re-establishing. + s.push_str(&crate::c2_reuse::context()); // Adaptive payload intelligence: WAF bypass history, target stack, parameter profiles. if let Some(ref workdir) = cfg.workdir { let adapt_path = std::path::Path::new(workdir).join("adaptive-engine.json"); @@ -3628,9 +3630,10 @@ async fn chain_from_seed(pool: &ModelPool, target: &str, directives: &str, recon let short: String = seed.title.chars().take(28).collect(); let c2 = crate::c2::agent_context().await; let econ = crate::economy::context().await; + let c2x = crate::c2_reuse::context(); let pivot_block = if pivot_ctx.is_empty() { String::new() } else { format!("\n{pivot_ctx}\n") }; let user = format!( - "AUTHORIZED engagement on {target}.\n\n{directives}{react}{depth}{decision}{chain}{safety}{doctrine}{c2}{econ}{pivot_block}\ + "AUTHORIZED engagement on {target}.\n\n{directives}{react}{depth}{decision}{chain}{safety}{doctrine}{c2}{econ}{c2x}{pivot_block}\ 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. When targeting hosts on a different subnet, USE the pivot proxy instructions above — your tools run on the operator box, not on the compromised host, so without the proxy you cannot reach internal subnets. Every claim needs a real tool receipt.\n\n\ diff --git a/neurosploit-rs/crates/harness/src/reactive_bridge.rs b/neurosploit-rs/crates/harness/src/reactive_bridge.rs index 2fedbf3..696e3d0 100644 --- a/neurosploit-rs/crates/harness/src/reactive_bridge.rs +++ b/neurosploit-rs/crates/harness/src/reactive_bridge.rs @@ -348,10 +348,11 @@ pub async fn run_reactive( } else { String::new() }; + let c2x_block = crate::c2_reuse::context(); let user = format!( "Target: {}\nTask: {:?}\nSpecific target: {}\nRationale: {}\ - {}{}{}{}{}\n\ + {}{}{}{}{}{}\n\ Execute this task. Report results using the prefixes: Finding:, Fact:, Negative:\n\ {}", cfg.target, @@ -363,6 +364,7 @@ pub async fn run_reactive( probe_block, activity_block, catalog_block, + c2x_block, if ctx.wrapping() { "\nWRAP-UP: Time is running out. Persist your results NOW and stop." } else { "" }, );