diff --git a/neurosploit-rs/app/src/main.rs b/neurosploit-rs/app/src/main.rs index 7d1f938..1589966 100644 --- a/neurosploit-rs/app/src/main.rs +++ b/neurosploit-rs/app/src/main.rs @@ -142,6 +142,10 @@ enum Cmd { /// support MCP fall back to their built-in tools). #[arg(long)] mcp: bool, + /// MCP tool profile: web · mobile-android · mobile-ios · binary · burp. + /// Auto-registers the right MCP server and tool allowlist for the test type. + #[arg(long = "mcp-profile")] + mcp_profile: Option, /// Credentials YAML for authenticated testing (jwt/header/cookie/login). #[arg(long)] creds: Option, @@ -211,6 +215,14 @@ enum Cmd { /// Verbose: log each agent as it launches, recon, and votes. #[arg(short, long)] verbose: bool, + /// Agent autonomy level: cautious, standard (default), aggressive, full. + #[arg(long, default_value = "standard")] + autonomy: String, + /// Use the event-driven reactive engine instead of the default phased + /// pipeline. The planner wakes on graph changes; workers claim from a + /// shared intent queue. Experimental opt-in. + #[arg(long)] + reactive: bool, }, /// Run NeuroSploit as an MCP server (stdio) so Claude Code, Codex, Cursor /// and other MCP clients can drive it as a set of tools. @@ -905,7 +917,7 @@ async fn main() -> anyhow::Result<()> { Cmd::Internal { graph, scaffold, from, expand, mermaid, save } => { handle_internal(graph.as_deref(), scaffold.as_deref(), &from, expand, mermaid, save.as_deref())? } - Cmd::Run { url, models, max_agents, vote_n, chain_depth, recon, quick, offline, subscription, mcp, creds, focus, objective, out_of_scope, in_scope, scope_file, environment, policy, budget, token_limit, deep_test_limit, coverage_first, depth_first, sample_per_route, revalidate_poc, compliance, jira, only, verbose } => { + Cmd::Run { url, models, max_agents, vote_n, chain_depth, recon, quick, offline, subscription, mcp, mcp_profile, creds, focus, objective, out_of_scope, in_scope, scope_file, environment, policy, budget, token_limit, deep_test_limit, coverage_first, depth_first, sample_per_route, revalidate_poc, compliance, jira, only, verbose, autonomy, reactive } => { let url = if url.starts_with("http") { url } else { format!("https://{url}") }; // A wildcard target (`*.zoom.us`) is domain-wide: seed recon with the // apex (a literal `*.zoom.us` has no DNS record to probe) and widen @@ -956,6 +968,9 @@ async fn main() -> anyhow::Result<()> { if !models.is_empty() { cfg.models = models; } + cfg.reactive = reactive; + cfg.mcp_profile = mcp_profile; + cfg.autonomy = autonomy; apply_creds(&mut cfg, creds.as_deref()).await; let out = run_engagement(&base, cfg, mcp, false).await?; print_findings(&out); @@ -1426,6 +1441,7 @@ pub(crate) fn spawn_engagement(base: &Path, mut cfg: RunConfig, mcp: bool, mode: Mode::Skills => harness::pipeline::run_skills_audit(cfg, &lib, &pool, tx).await, Mode::Mobile => harness::run_mobile(cfg, &lib, &pool, tx).await, Mode::Container => harness::run_container(cfg, &lib, &pool, tx).await, + Mode::Black if cfg.reactive => harness::run_reactive(cfg, &lib, &pool, tx).await, Mode::Black => harness::run(cfg, &lib, &pool, tx).await, } }); diff --git a/neurosploit-rs/crates/harness/src/graph_reasoning.rs b/neurosploit-rs/crates/harness/src/graph_reasoning.rs new file mode 100644 index 0000000..0c95709 --- /dev/null +++ b/neurosploit-rs/crates/harness/src/graph_reasoning.rs @@ -0,0 +1,371 @@ +//! Graph-based reasoning — LLM-driven chain exploitation decisions. +//! +//! The dual graph (assets + exploration) already records what exists and what was +//! tried. This module adds the missing "what should we try next?" layer: given the +//! current graph state, ask an LLM to identify exploitation chains and decide where +//! to focus next. The graph is the shared memory; the LLM is the strategist. +//! +//! Three capabilities: +//! 1. **Chain analysis**: find multi-hop attack paths through the asset graph. +//! 2. **LLM decision**: given the graph summary and chain candidates, ask the LLM +//! which path to pursue and why (structured output → planner intents). +//! 3. **Graph enrichment**: after a finding, trace which assets are reachable from +//! the compromised position and mark them as high-priority targets. + +use crate::exploration_graph::{AssetKind, AssetRelation, DualGraph, ExplorationKind, ExplorationStatus}; +use crate::planner::{IntentAction, PlannerIntent}; +use serde::{Deserialize, Serialize}; + +/// A candidate chain: a sequence of assets from a finding to an untested surface. +#[derive(Debug, Clone, Serialize)] +pub struct ChainCandidate { + /// The finding that starts the chain. + pub finding: String, + /// Asset where the finding was confirmed. + pub foothold: String, + /// Assets along the path (the hops). + pub hops: Vec, + /// The untested target at the end. + pub target: String, + /// Chain score (higher = more promising). + pub score: f32, +} + +#[derive(Debug, Clone, Serialize)] +pub struct ChainHop { + pub asset: String, + pub kind: String, + pub relation: String, + pub tested: bool, +} + +/// Find chain candidates: paths from findings to untested assets. +/// BFS from each finding's asset, following asset relationships up to `max_hops`. +pub fn find_chains(dg: &DualGraph, max_hops: usize) -> Vec { + let mut chains = Vec::new(); + + // Collect assets with findings + let finding_assets: Vec<(String, String)> = dg.exploration.nodes.iter() + .filter(|n| n.kind == ExplorationKind::Finding) + .filter_map(|n| { + dg.exploration.anchors.iter() + .find(|a| a.exploration_id == n.id) + .and_then(|a| dg.assets.nodes.iter().find(|an| an.id == a.asset_id)) + .map(|asset| (n.content.clone(), asset.id.clone())) + }) + .collect(); + + for (finding, foothold_id) in &finding_assets { + let foothold = dg.assets.nodes.iter().find(|a| a.id == *foothold_id); + let foothold_name = foothold.map(|a| a.value.clone()).unwrap_or_default(); + + // BFS from foothold + let mut visited = std::collections::HashSet::new(); + visited.insert(foothold_id.clone()); + let mut queue: Vec<(String, Vec)> = vec![(foothold_id.clone(), vec![])]; + + while let Some((current, path)) = queue.pop() { + if path.len() >= max_hops { continue; } + + // Find neighbors via asset edges + for edge in &dg.assets.edges { + let neighbor_id = if edge.from == current { &edge.to } + else if edge.to == current { &edge.from } + else { continue }; + if visited.contains(neighbor_id) { continue; } + visited.insert(neighbor_id.clone()); + + let neighbor = match dg.assets.nodes.iter().find(|a| a.id == *neighbor_id) { + Some(a) => a, + None => continue, + }; + + let tested = dg.exploration.anchors.iter() + .any(|a| a.asset_id == *neighbor_id); + + let mut new_path = path.clone(); + new_path.push(ChainHop { + asset: neighbor.value.clone(), + kind: format!("{:?}", neighbor.kind), + relation: format!("{:?}", edge.kind), + tested, + }); + + if !tested { + // Untested asset reachable from a finding — chain candidate + let score = score_chain(&new_path, neighbor); + chains.push(ChainCandidate { + finding: finding.clone(), + foothold: foothold_name.clone(), + hops: new_path.clone(), + target: neighbor.value.clone(), + score, + }); + } + + queue.push((neighbor_id.clone(), new_path)); + } + } + } + + chains.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal)); + chains +} + +fn score_chain(path: &[ChainHop], target: &crate::exploration_graph::AssetNode) -> f32 { + let mut score = 1.0; + // Shorter chains are better + score += 1.0 / (path.len() as f32); + // Endpoints and applications are higher-value targets + match target.kind { + AssetKind::Endpoint | AssetKind::Application => score += 2.0, + AssetKind::Service => score += 1.5, + AssetKind::Parameter => score += 1.0, + _ => {} + } + // Assets with more exploration are more interesting (more context) + score += (target.exploration_count as f32).min(3.0) * 0.5; + score +} + +/// Format chain candidates as an LLM prompt for decision-making. +pub fn decision_prompt(chains: &[ChainCandidate], graph_summary: &str, max_chains: usize) -> String { + let mut prompt = String::from( + "You are a penetration testing strategist. Analyze the current exploration state and \ + decide which attack chains to pursue next.\n\n" + ); + prompt.push_str("CURRENT STATE:\n"); + prompt.push_str(graph_summary); + prompt.push_str("\n\nCHAIN CANDIDATES (from confirmed findings to untested assets):\n"); + + for (i, c) in chains.iter().take(max_chains).enumerate() { + prompt.push_str(&format!( + "\n{}. Finding: {} (foothold: {})\n Path: {}\n Target: {} (score: {:.1})\n", + i + 1, + c.finding.chars().take(80).collect::(), + c.foothold, + c.hops.iter().map(|h| format!("{}({})", h.asset, h.relation)).collect::>().join(" → "), + c.target, + c.score, + )); + } + + prompt.push_str( + "\n\nDecide which chains to pursue. For each, respond with one line:\n\ + Intent: on because \n\n\ + Actions: Exploit, Probe, Recon, Chain, Fuzz, Validate\n\ + Prioritize chains that:\n\ + - Start from high-severity findings\n\ + - Reach high-value assets (endpoints, services, applications)\n\ + - Are short (fewer hops = less chance of failure)\n\ + - Have not been attempted before\n\n\ + If no chain is worth pursuing, say: Quiescent: no actionable chains remain.\n" + ); + prompt +} + +/// Parse LLM decision response into planner intents. +pub fn parse_decision(response: &str) -> Vec { + let mut intents = Vec::new(); + let mut id_counter = 0u32; + + for line in response.lines() { + let trimmed = line.trim(); + if let Some(rest) = trimmed.strip_prefix("Intent:").or_else(|| trimmed.strip_prefix("INTENT:")) { + let rest = rest.trim(); + // Parse: on because + let parts: Vec<&str> = rest.splitn(2, " on ").collect(); + if parts.len() < 2 { continue; } + let action_str = parts[0].trim().to_lowercase(); + let rest = parts[1]; + let (target, rationale) = if let Some(idx) = rest.find(" because ") { + (rest[..idx].trim(), rest[idx + 9..].trim()) + } else { + (rest.trim(), "") + }; + + let action = match action_str.as_str() { + "exploit" => IntentAction::Exploit, + "probe" => IntentAction::Probe, + "recon" => IntentAction::Recon, + "chain" => IntentAction::Chain, + "fuzz" => IntentAction::Fuzz, + "validate" => IntentAction::Validate, + _ => IntentAction::Probe, + }; + + id_counter += 1; + intents.push(PlannerIntent { + id: format!("chain-{id_counter}"), + action, + target: target.to_string(), + agent_hint: String::new(), + priority: (10 - id_counter.min(9)) as u32, + rationale: rationale.to_string(), + depends_on: vec![], + asset_id: None, + }); + } + } + intents +} + +/// Build a compact graph summary for the LLM. +pub fn graph_summary(dg: &DualGraph) -> String { + let mut s = String::new(); + + let total_assets = dg.assets.nodes.len(); + let tested: usize = dg.assets.nodes.iter() + .filter(|a| dg.exploration.anchors.iter().any(|an| an.asset_id == a.id)) + .count(); + let findings = dg.exploration.nodes.iter() + .filter(|n| n.kind == ExplorationKind::Finding) + .count(); + let facts = dg.exploration.nodes.iter() + .filter(|n| n.kind == ExplorationKind::Fact) + .count(); + let negatives = dg.exploration.nodes.iter() + .filter(|n| n.kind == ExplorationKind::Negative) + .count(); + + s.push_str(&format!( + "Assets: {} total, {} tested, {} untested\n\ + Findings: {}, Facts: {}, Negatives: {}\n", + total_assets, tested, total_assets - tested, + findings, facts, negatives, + )); + + // List findings + if findings > 0 { + s.push_str("\nConfirmed findings:\n"); + for n in dg.exploration.nodes.iter().filter(|n| n.kind == ExplorationKind::Finding) { + let asset = dg.exploration.anchors.iter() + .find(|a| a.exploration_id == n.id) + .and_then(|a| dg.assets.nodes.iter().find(|an| an.id == a.asset_id)) + .map(|a| a.value.as_str()) + .unwrap_or("?"); + s.push_str(&format!(" - {} on {}\n", n.content.chars().take(80).collect::(), asset)); + } + } + + // High-value untested assets + let untested: Vec<_> = dg.assets.nodes.iter() + .filter(|a| !dg.exploration.anchors.iter().any(|an| an.asset_id == a.id)) + .filter(|a| matches!(a.kind, AssetKind::Endpoint | AssetKind::Service | AssetKind::Application)) + .take(15) + .collect(); + if !untested.is_empty() { + s.push_str("\nHigh-value untested assets:\n"); + for a in &untested { + s.push_str(&format!(" - {:?}: {}\n", a.kind, a.value)); + } + } + + s +} + +/// Enrich the graph after a finding: mark reachable assets as high-priority. +pub fn enrich_after_finding(dg: &mut DualGraph, finding_asset_id: &str) { + // BFS from the finding's asset, bump exploration priority on neighbors + let mut visited = std::collections::HashSet::new(); + visited.insert(finding_asset_id.to_string()); + let mut queue = vec![finding_asset_id.to_string()]; + + while let Some(current) = queue.pop() { + for edge in &dg.assets.edges { + let neighbor = if edge.from == current { &edge.to } + else if edge.to == current { &edge.from } + else { continue }; + if visited.contains(neighbor) { continue; } + visited.insert(neighbor.clone()); + // Bump the neighbor's exploration count to signal priority + if let Some(node) = dg.assets.nodes.iter_mut().find(|n| n.id == *neighbor) { + node.exploration_count += 1; + } + queue.push(neighbor.clone()); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::exploration_graph::{AnchorDirection, AssetKind}; + use std::collections::BTreeMap; + + fn sample_graph() -> DualGraph { + let mut dg = DualGraph::default(); + // Build a small graph: target -> endpoint -> parameter + dg.discover_asset(AssetKind::Domain, "example.com", BTreeMap::new(), "recon", None); + dg.discover_asset(AssetKind::Endpoint, "/api/users", BTreeMap::new(), "recon", None); + dg.discover_asset(AssetKind::Endpoint, "/api/admin", BTreeMap::new(), "recon", None); + dg.discover_asset(AssetKind::Parameter, "id", BTreeMap::new(), "recon", None); + + let root = dg.assets.find(AssetKind::Domain, "example.com").unwrap().id.clone(); + let users = dg.assets.find(AssetKind::Endpoint, "/api/users").unwrap().id.clone(); + let admin = dg.assets.find(AssetKind::Endpoint, "/api/admin").unwrap().id.clone(); + let param = dg.assets.find(AssetKind::Parameter, "id").unwrap().id.clone(); + dg.assets.relate(&root, &users, AssetRelation::ParentOf); + dg.assets.relate(&root, &admin, AssetRelation::ParentOf); + dg.assets.relate(&users, ¶m, AssetRelation::ParentOf); + + // Add a finding on /api/users + let goal = dg.exploration.add_goal("test example.com", "planner"); + let intent = dg.target_asset("test IDOR", &goal, "worker", &users); + dg.exploration.set_status(&intent, ExplorationStatus::Completed); + dg.record_finding("IDOR on /api/users", &intent, "worker", &users); + + dg + } + + #[test] + fn find_chains_discovers_untested_neighbors() { + let dg = sample_graph(); + let chains = find_chains(&dg, 3); + assert!(!chains.is_empty(), "should find chains from IDOR finding to untested assets"); + // /api/admin and id parameter should be reachable + let targets: Vec<&str> = chains.iter().map(|c| c.target.as_str()).collect(); + assert!(targets.contains(&"/api/admin") || targets.contains(&"id"), + "untested neighbors should appear: {:?}", targets); + } + + #[test] + fn graph_summary_includes_key_stats() { + let dg = sample_graph(); + let s = graph_summary(&dg); + assert!(s.contains("Assets:") && s.contains("Findings:")); + assert!(s.contains("IDOR")); + } + + #[test] + fn decision_prompt_is_well_formed() { + let dg = sample_graph(); + let chains = find_chains(&dg, 3); + let summary = graph_summary(&dg); + let p = decision_prompt(&chains, &summary, 5); + assert!(p.contains("CHAIN CANDIDATES")); + assert!(p.contains("Intent:")); + } + + #[test] + fn parse_decision_extracts_intents() { + let response = "Intent: Exploit on /api/admin because IDOR on sibling endpoint suggests similar vulnerability\n\ + Intent: Probe on id parameter because parameter injection not yet tested\n\ + Some other text that should be ignored"; + let intents = parse_decision(response); + assert_eq!(intents.len(), 2); + assert_eq!(intents[0].action, IntentAction::Exploit); + assert!(intents[0].target.contains("/api/admin")); + assert!(intents[0].rationale.contains("IDOR")); + } + + #[test] + fn enrich_after_finding_bumps_neighbors() { + let mut dg = sample_graph(); + let users_id = dg.assets.find(AssetKind::Endpoint, "/api/users").unwrap().id.clone(); + let admin_before = dg.assets.find(AssetKind::Endpoint, "/api/admin").unwrap().exploration_count; + enrich_after_finding(&mut dg, &users_id); + let admin_after = dg.assets.find(AssetKind::Endpoint, "/api/admin").unwrap().exploration_count; + assert!(admin_after > admin_before, "neighbor should get priority bump"); + } +} diff --git a/neurosploit-rs/crates/harness/src/intent_queue.rs b/neurosploit-rs/crates/harness/src/intent_queue.rs index c48d824..0472826 100644 --- a/neurosploit-rs/crates/harness/src/intent_queue.rs +++ b/neurosploit-rs/crates/harness/src/intent_queue.rs @@ -161,7 +161,42 @@ impl IntentQueue { m } + /// Terminate a still-queued intent (used after an operator stop). + /// Returns true if it was queued and is now Failed. + pub fn fail_if_queued(&mut self, id: &str, reason: &str) -> bool { + match self.entries.iter_mut().find(|e| e.intent.id == id && e.state == State::Queued) { + Some(e) => { e.state = State::Failed; e.result = Some(reason.into()); false } + None => false, + } + } + pub fn entries(&self) -> &[Entry] { &self.entries } + + /// Queued intents whose dependencies are all done (i.e. claimable now). + pub fn runnable(&self) -> usize { + let done = self.done_ids(); + self.entries.iter() + .filter(|e| e.state == State::Queued && e.intent.depends_on.iter().all(|d| done.contains(d.as_str()))) + .count() + } + + /// Queued or claimed entries. + pub fn live(&self) -> usize { + self.entries.iter().filter(|e| matches!(e.state, State::Queued | State::Claimed)).count() + } + + /// After a restart nothing is actually running: put claimed work back, + /// refunding the attempt. Returns how many were released. + pub fn requeue_claimed(&mut self) -> usize { + let mut n = 0; + for e in self.entries.iter_mut().filter(|e| e.state == State::Claimed) { + e.state = State::Queued; + e.claimed_by = None; + e.attempts = e.attempts.saturating_sub(1); + n += 1; + } + n + } } /// Convenience constructor used by tests and callers building simple intents. diff --git a/neurosploit-rs/crates/harness/src/knowledge.rs b/neurosploit-rs/crates/harness/src/knowledge.rs new file mode 100644 index 0000000..19c4733 --- /dev/null +++ b/neurosploit-rs/crates/harness/src/knowledge.rs @@ -0,0 +1,356 @@ +use regex::Regex; +use serde::Serialize; +use std::collections::{BTreeSet, HashSet}; +use std::path::Path; +use walkdir::WalkDir; + +/// A single knowledge entry parsed from an agent markdown file. +#[derive(Debug, Clone, Serialize)] +pub struct KnowledgeEntry { + pub name: String, + pub title: String, + /// Category derived from the parent directory: "vuln", "recon", "mobile", etc. + pub category: String, + pub cwes: Vec, + /// The user prompt section — methodology steps and techniques. + pub methodology: String, + /// The system prompt section — role context. + pub role_context: String, + /// Keywords extracted from title + methodology for matching. + pub keywords: Vec, +} + +/// Searchable knowledge base built from all agent markdown files. +#[derive(Debug, Clone, Default)] +pub struct KnowledgeBase { + pub entries: Vec, +} + +/// Load all agent markdowns under `/agents_md/` as knowledge entries. +pub fn load(base: &Path) -> KnowledgeBase { + let root = base.join("agents_md"); + let mut entries = Vec::new(); + + let title_re = Regex::new(r"(?m)^#\s+(.+?)\s*$").unwrap(); + let cwe_re = Regex::new(r"CWE-\d+").unwrap(); + let user_re = Regex::new(r"(?s)##\s*User Prompt\s*\n(.*?)(?:\n##\s|\z)").unwrap(); + let sys_re = Regex::new(r"(?s)##\s*System Prompt\s*\n(.*?)(?:\n##\s|\z)").unwrap(); + + if !root.is_dir() { + return KnowledgeBase { entries }; + } + + for entry in WalkDir::new(&root).into_iter().flatten() { + let path = entry.path(); + if path.extension().and_then(|e| e.to_str()) != Some("md") { + continue; + } + + let text = match std::fs::read_to_string(path) { + Ok(t) => t, + Err(_) => continue, + }; + + let name = path + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or("") + .to_string(); + + // Derive category from the immediate parent directory name. + let category = path + .parent() + .and_then(|p| p.file_name()) + .and_then(|n| n.to_str()) + .map(|s| match s { + "vulns" => "vuln", + "chains" => "chain", + _ => s, + }) + .unwrap_or("unknown") + .to_string(); + + let title = title_re + .captures(&text) + .and_then(|c| c.get(1)) + .map(|m| m.as_str().trim().to_string()) + .unwrap_or_else(|| name.clone()); + + let cwes: Vec = cwe_re + .find_iter(&text) + .map(|m| m.as_str().to_string()) + .collect::>() + .into_iter() + .collect(); + + let methodology = user_re + .captures(&text) + .and_then(|c| c.get(1)) + .map(|m| m.as_str().trim().to_string()) + .unwrap_or_default(); + + let role_context = sys_re + .captures(&text) + .and_then(|c| c.get(1)) + .map(|m| m.as_str().trim().to_string()) + .unwrap_or_default(); + + let keywords = extract_keywords(&format!("{} {}", title, methodology)); + + entries.push(KnowledgeEntry { + name, + title, + category, + cwes, + methodology, + role_context, + keywords, + }); + } + + entries.sort_by(|a, b| a.name.cmp(&b.name)); + KnowledgeBase { entries } +} + +impl KnowledgeBase { + /// Find entries relevant to a task description. Scores by keyword overlap + /// and CWE match bonus. + pub fn query(&self, task: &str, limit: usize) -> Vec<&KnowledgeEntry> { + let task_tokens: HashSet = extract_keywords(task).into_iter().collect(); + if task_tokens.is_empty() { + return Vec::new(); + } + + // Extract any CWE references from the task. + let cwe_re = Regex::new(r"CWE-\d+").unwrap(); + let task_cwes: HashSet = cwe_re + .find_iter(task) + .map(|m| m.as_str().to_string()) + .collect(); + + let mut scored: Vec<(usize, &KnowledgeEntry)> = self + .entries + .iter() + .map(|e| { + let keyword_hits = e + .keywords + .iter() + .filter(|kw| task_tokens.contains(kw.as_str())) + .count(); + let cwe_bonus = if !task_cwes.is_empty() { + e.cwes + .iter() + .filter(|c| task_cwes.contains(c.as_str())) + .count() + * 3 + } else { + 0 + }; + (keyword_hits + cwe_bonus, e) + }) + .filter(|(score, _)| *score > 0) + .collect(); + + scored.sort_by(|a, b| b.0.cmp(&a.0)); + scored.into_iter().take(limit).map(|(_, e)| e).collect() + } + + /// Get methodology text for the top matching entries, formatted for + /// injection into an agent prompt. + /// + /// Returns an empty string when nothing matches. + pub fn methodology_for(&self, task: &str, max_entries: usize, max_chars: usize) -> String { + let results = self.query(task, max_entries); + if results.is_empty() { + return String::new(); + } + + let mut out = String::from( + "KNOWLEDGE BASE (reference methodology \u{2014} adapt to your task, do not follow blindly):\n", + ); + let mut budget = max_chars.saturating_sub(out.len()); + + for entry in results { + let cwe_label = if entry.cwes.is_empty() { + String::new() + } else { + format!(" ({})", entry.cwes.join(", ")) + }; + let header = format!("--- {}{} ---\n", entry.title, cwe_label); + if header.len() >= budget { + break; + } + out.push_str(&header); + budget = budget.saturating_sub(header.len()); + + let body = if entry.methodology.len() > budget { + format!("{}...\n", &entry.methodology[..budget.saturating_sub(4)]) + } else { + format!("{}\n", entry.methodology) + }; + out.push_str(&body); + budget = budget.saturating_sub(body.len()); + if budget == 0 { + break; + } + } + + out + } + + /// Find entries by CWE number (e.g. `"CWE-89"`). + pub fn by_cwe(&self, cwe: &str) -> Vec<&KnowledgeEntry> { + self.entries + .iter() + .filter(|e| e.cwes.iter().any(|c| c == cwe)) + .collect() + } + + /// Find entries by category (e.g. `"vuln"`, `"mobile"`). + pub fn by_category(&self, cat: &str) -> Vec<&KnowledgeEntry> { + self.entries + .iter() + .filter(|e| e.category == cat) + .collect() + } + + /// Total entries loaded. + pub fn len(&self) -> usize { + self.entries.len() + } + + /// Whether no entries are loaded. + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } +} + +/// Extract deduplicated, lowercased keywords from text, filtering out stop +/// words and very short tokens. +fn extract_keywords(text: &str) -> Vec { + let stop: HashSet<&str> = [ + "the", "and", "for", "with", "that", "this", "from", "are", "was", "you", "your", "can", + "will", "not", "but", "has", "have", "had", "all", "any", "its", "into", "also", "use", + "using", "each", "when", "then", "than", "been", "does", "how", "may", "should", "would", + "could", "where", "which", "what", "who", "these", "those", "them", "they", "their", + "other", "about", "more", "some", "such", + ] + .iter() + .copied() + .collect(); + + text.split(|c: char| !c.is_alphanumeric() && c != '-' && c != '_') + .map(|w| w.to_lowercase()) + .filter(|w| w.len() >= 3 && !stop.contains(w.as_str())) + .collect::>() + .into_iter() + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sample_kb() -> KnowledgeBase { + KnowledgeBase { + entries: vec![ + KnowledgeEntry { + name: "sqli".into(), + title: "SQL Injection".into(), + category: "vuln".into(), + cwes: vec!["CWE-89".into()], + methodology: "Test parameters with single quotes and UNION SELECT...".into(), + role_context: "SQL injection specialist".into(), + keywords: extract_keywords("SQL Injection test parameters UNION SELECT"), + }, + KnowledgeEntry { + name: "xss".into(), + title: "Cross-Site Scripting".into(), + category: "vuln".into(), + cwes: vec!["CWE-79".into()], + methodology: "Inject script tags into input fields and URL parameters..." + .into(), + role_context: "XSS specialist".into(), + keywords: extract_keywords( + "Cross-Site Scripting inject script tags input fields", + ), + }, + KnowledgeEntry { + name: "apk_static".into(), + title: "APK Static Analysis".into(), + category: "mobile".into(), + cwes: vec!["CWE-919".into()], + methodology: "Decompile APK with jadx, search for hardcoded secrets...".into(), + role_context: "Mobile reverse engineering specialist".into(), + keywords: extract_keywords( + "APK Static Analysis decompile jadx hardcoded secrets", + ), + }, + ], + } + } + + #[test] + fn query_finds_relevant_entries() { + let kb = sample_kb(); + let r = kb.query("test SQL injection on login form", 2); + assert!(!r.is_empty()); + assert_eq!(r[0].name, "sqli"); + } + + #[test] + fn methodology_for_formats_context_block() { + let kb = sample_kb(); + let m = kb.methodology_for("test SQL injection", 1, 5000); + assert!(m.contains("KNOWLEDGE BASE")); + assert!(m.contains("SQL Injection")); + assert!(m.contains("CWE-89")); + } + + #[test] + fn by_cwe_finds_entries() { + let kb = sample_kb(); + assert_eq!(kb.by_cwe("CWE-79").len(), 1); + assert_eq!(kb.by_cwe("CWE-79")[0].name, "xss"); + } + + #[test] + fn keywords_extraction_filters_stopwords() { + let kw = extract_keywords("the quick SQL injection for the web application"); + assert!(kw.contains(&"sql".to_string())); + assert!(kw.contains(&"injection".to_string())); + assert!(!kw.contains(&"the".to_string())); + assert!(!kw.contains(&"for".to_string())); + } + + #[test] + fn by_category_filters() { + let kb = sample_kb(); + let mobile = kb.by_category("mobile"); + assert_eq!(mobile.len(), 1); + assert_eq!(mobile[0].name, "apk_static"); + } + + #[test] + fn empty_query_returns_nothing() { + let kb = sample_kb(); + let r = kb.query("", 5); + assert!(r.is_empty()); + } + + #[test] + fn cwe_query_boosts_score() { + let kb = sample_kb(); + // Query mentions CWE-79 so XSS should rank first even with SQL terms. + let r = kb.query("CWE-79 test injection", 3); + assert!(!r.is_empty()); + assert_eq!(r[0].name, "xss"); + } + + #[test] + fn methodology_for_empty_on_no_match() { + let kb = sample_kb(); + let m = kb.methodology_for("zzz_nonexistent_term_zzz", 5, 5000); + assert!(m.is_empty()); + } +} diff --git a/neurosploit-rs/crates/harness/src/lib.rs b/neurosploit-rs/crates/harness/src/lib.rs index c800929..8081674 100644 --- a/neurosploit-rs/crates/harness/src/lib.rs +++ b/neurosploit-rs/crates/harness/src/lib.rs @@ -31,6 +31,7 @@ pub mod deliverables; pub mod dual_build; pub mod exploration_graph; pub mod graph_memory; +pub mod graph_reasoning; pub mod grounding; pub mod hygiene; pub mod inbox; @@ -38,14 +39,18 @@ pub mod integrations; pub mod integrity; pub mod internal; pub mod json_extract; +pub mod knowledge; pub mod knowledge_graph; pub mod mcp_hot_reload; +pub mod mcp_profiles; pub mod memory; pub mod policy; pub mod poc; pub mod pomdp; pub mod proxy; pub mod prosecutor; +pub mod reactive; +pub mod reactive_bridge; pub mod redact; pub mod request_analyzer; pub mod provenance; @@ -86,6 +91,7 @@ pub use models::{ }; pub use pipeline::{run_container, run_greybox, run_host, run_mobile, run_whitebox, RunOutput}; pub use pipeline::run; +pub use reactive_bridge::run_reactive; pub use knowledge_graph::{EdgeKind, KnowledgeGraph, NodeKind}; pub use memory::{Memory, Query as MemoryQuery, Tier as MemoryTier}; pub use pool::{ModelPool, Task}; diff --git a/neurosploit-rs/crates/harness/src/mcp_profiles.rs b/neurosploit-rs/crates/harness/src/mcp_profiles.rs new file mode 100644 index 0000000..25cf28d --- /dev/null +++ b/neurosploit-rs/crates/harness/src/mcp_profiles.rs @@ -0,0 +1,327 @@ +//! Pre-configured MCP tool profiles for different testing modes. +//! +//! Each [`Profile`] maps to a curated set of MCP tools, server configuration, +//! and prompt context appropriate for a specific engagement type (web, mobile, +//! binary analysis, etc.). Profiles integrate with the MCP hot-reload system +//! in `mcp_hot_reload.rs` to swap tool sets at runtime. + +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +// --------------------------------------------------------------------------- +// Profile enum +// --------------------------------------------------------------------------- + +/// Supported testing profiles. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum Profile { + Web, + MobileAndroid, + MobileIos, + BinaryAnalysis, + BurpSuite, + Custom(String), +} + +// --------------------------------------------------------------------------- +// McpProfile +// --------------------------------------------------------------------------- + +/// A fully-resolved MCP profile ready for activation. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct McpProfile { + /// Human-readable name. + pub name: String, + /// One-line description of the profile's purpose. + pub description: String, + /// MCP server name to register via hot-reload. + pub server_name: String, + /// Tool names relevant to this profile. + pub tools: Vec, + /// Server configuration JSON passed to `add_server()`. + pub config: Value, +} + +// --------------------------------------------------------------------------- +// Profile -> McpProfile +// --------------------------------------------------------------------------- + +/// Return the preset [`McpProfile`] for the given profile variant. +pub fn profile(p: &Profile) -> McpProfile { + match p { + Profile::Web => McpProfile { + name: "Web".into(), + description: "Playwright-based web application testing".into(), + server_name: "playwright".into(), + tools: tool_allowlist(p), + config: json!({ + "command": "npx", + "args": ["-y", "@anthropic-ai/mcp-playwright"], + "env": {} + }), + }, + Profile::MobileAndroid => McpProfile { + name: "Mobile Android".into(), + description: "REA-powered APK / Android binary analysis".into(), + server_name: "rea".into(), + tools: tool_allowlist(p), + config: json!({ + "command": "rea", + "args": ["--mode", "android"], + "env": {} + }), + }, + Profile::MobileIos => McpProfile { + name: "Mobile iOS".into(), + description: "REA-powered IPA / iOS binary analysis".into(), + server_name: "rea".into(), + tools: tool_allowlist(p), + config: json!({ + "command": "rea", + "args": ["--mode", "ios"], + "env": {} + }), + }, + Profile::BinaryAnalysis => McpProfile { + name: "Binary Analysis".into(), + description: "REA-powered native binary reverse engineering".into(), + server_name: "rea".into(), + tools: tool_allowlist(p), + config: json!({ + "command": "rea", + "args": ["--mode", "binary"], + "env": {} + }), + }, + Profile::BurpSuite => McpProfile { + name: "Burp Suite".into(), + description: "Burp Suite REST API integration (placeholder)".into(), + server_name: "burpsuite".into(), + tools: tool_allowlist(p), + config: json!({ + "base_url": "http://127.0.0.1:1337/v0.1", + "api_key": "", + "env": {} + }), + }, + Profile::Custom(ref name) => McpProfile { + name: format!("Custom: {name}"), + description: format!("User-defined custom profile '{name}'"), + server_name: name.clone(), + tools: Vec::new(), + config: json!({}), + }, + } +} + +// --------------------------------------------------------------------------- +// Catalogue +// --------------------------------------------------------------------------- + +/// List every built-in profile with a short description. +pub fn all_profiles() -> Vec<(Profile, &'static str)> { + vec![ + (Profile::Web, "Playwright-based web application testing"), + ( + Profile::MobileAndroid, + "REA-powered APK / Android binary analysis", + ), + ( + Profile::MobileIos, + "REA-powered IPA / iOS binary analysis", + ), + ( + Profile::BinaryAnalysis, + "REA-powered native binary reverse engineering", + ), + ( + Profile::BurpSuite, + "Burp Suite REST API integration (placeholder)", + ), + ] +} + +// --------------------------------------------------------------------------- +// Tool allow-lists +// --------------------------------------------------------------------------- + +/// Return the MCP tool names relevant to `p`. +pub fn tool_allowlist(p: &Profile) -> Vec { + let names: &[&str] = match p { + Profile::Web => &[ + "browser_navigate", + "browser_click", + "browser_fill_form", + "browser_snapshot", + "browser_take_screenshot", + "browser_press_key", + "browser_type", + "browser_select_option", + "browser_hover", + "browser_tabs", + "browser_navigate_back", + "browser_evaluate", + "browser_console_messages", + "browser_network_requests", + "browser_find", + "browser_wait_for", + ], + Profile::MobileAndroid => &[ + "open_binary", + "extract_artifact", + "batch_decompile", + "search_strings", + "analyze_javascript_application", + "survey_binary", + "list_strings", + "inspect_artifact", + ], + Profile::MobileIos => &[ + "inspect_macho", + "inspect_plist", + "inspect_signature", + "analyze_swift_types", + "extract_artifact", + "decode_interface_builder", + "inspect_asset_catalog", + ], + Profile::BinaryAnalysis => &[ + "open_binary", + "survey_binary", + "batch_decompile", + "trace_data_flow", + "build_call_path", + "search_strings", + "procedure_pseudo_code", + "procedure_assembly", + "get_call_graph", + "list_procedures", + ], + Profile::BurpSuite => &[ + "scan", + "get_issues", + "proxy_history", + "send_to_repeater", + ], + Profile::Custom(_) => &[], + }; + names.iter().map(|s| (*s).to_string()).collect() +} + +// --------------------------------------------------------------------------- +// Prompt context +// --------------------------------------------------------------------------- + +/// Return context text to inject into agent prompts for `p`. +pub fn prompt_context(p: &Profile) -> String { + let tools = tool_allowlist(p); + let tool_list = tools.join(", "); + + match p { + Profile::Web => format!( + "You are operating in WEB testing mode. \ + Use Playwright MCP tools to interact with the target web application. \ + Available tools: {tool_list}. \ + Prefer snapshots over screenshots for speed; use screenshots only \ + when visual verification is required." + ), + Profile::MobileAndroid => format!( + "You are operating in MOBILE ANDROID testing mode. \ + Use REA MCP tools to analyze APK files and Android binaries. \ + Available tools: {tool_list}. \ + Start by opening the binary, then survey its structure before \ + diving into decompilation." + ), + Profile::MobileIos => format!( + "You are operating in MOBILE iOS testing mode. \ + Use REA MCP tools to analyze IPA files and iOS binaries. \ + Available tools: {tool_list}. \ + Check the Mach-O header, plist, and code signature before \ + inspecting Swift types and Interface Builder files." + ), + Profile::BinaryAnalysis => format!( + "You are operating in BINARY ANALYSIS mode. \ + Use REA MCP tools for native binary reverse engineering. \ + Available tools: {tool_list}. \ + Open the binary, survey it, then trace data flow and call paths \ + to identify interesting code paths." + ), + Profile::BurpSuite => format!( + "You are operating in BURP SUITE mode. \ + Use the Burp Suite REST API to drive scans and inspect results. \ + Available tools: {tool_list}. \ + Note: this profile is a placeholder; ensure the Burp REST API \ + is running before invoking tools." + ), + Profile::Custom(ref name) => format!( + "You are operating with the custom profile '{name}'. \ + No predefined tools are configured; add tools via the \ + McpProfile struct before activating." + ), + } +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn profiles_have_non_empty_tools() { + for (p, _desc) in all_profiles() { + let mcp = profile(&p); + assert!( + !mcp.tools.is_empty(), + "Profile {:?} must have at least one tool", + p + ); + } + } + + #[test] + fn prompt_context_mentions_tools() { + for (p, _desc) in all_profiles() { + let ctx = prompt_context(&p); + let tools = tool_allowlist(&p); + for tool in &tools { + assert!( + ctx.contains(tool), + "Prompt context for {:?} should mention tool '{}'", + p, + tool + ); + } + } + } + + #[test] + fn all_profiles_covers_every_variant() { + let listed: Vec = all_profiles().into_iter().map(|(p, _)| p).collect(); + + // Every built-in variant must appear in all_profiles(). + let expected = vec![ + Profile::Web, + Profile::MobileAndroid, + Profile::MobileIos, + Profile::BinaryAnalysis, + Profile::BurpSuite, + ]; + + for variant in &expected { + assert!( + listed.contains(variant), + "all_profiles() is missing {:?}", + variant + ); + } + + // Custom is intentionally excluded from the catalogue. + assert!( + !listed.contains(&Profile::Custom("x".into())), + "Custom should not appear in all_profiles()" + ); + } +} diff --git a/neurosploit-rs/crates/harness/src/reactive.rs b/neurosploit-rs/crates/harness/src/reactive.rs new file mode 100644 index 0000000..9627b37 --- /dev/null +++ b/neurosploit-rs/crates/harness/src/reactive.rs @@ -0,0 +1,608 @@ +//! Reactive engine — an event-driven alternative to the phased pipeline. +//! +//! Opt-in (`--reactive`). Instead of recon -> exploit -> validate once, a +//! planner is woken whenever the exploration graph changes, turns the change +//! into intents, and a pool of workers claims and runs them. Results are written +//! back to the graph, which wakes the planner again, until nothing runnable is +//! left, the budget is spent, or the deadline hits. +//! +//! Roles are strict (see [`crate::intent_queue`]): only the planner creates +//! intents; workers run exactly one and write facts back. +//! +//! The engine is generic over the executor (`ExecFn`), so it is fully testable +//! without any model. The real pipeline supplies an executor that runs an agent. +//! +//! Operational properties: +//! - deadline: at expiry workers are told to wrap up ([`WorkCtx::wrapping`]), +//! given a drain grace, then cancelled; their intents go back to the queue +//! (attempt refunded) so a resumed run continues them; +//! - control: pause (no new claims), resume, stop one intent, steer one intent; +//! - loop guards: a total-intent budget and a per-target failure cap stop a +//! planner that keeps re-proposing the same failing work; +//! - durability: state is saved after every change and [`resume_state`] reloads it. + +use crate::adaptive::AdaptiveEngine; +use crate::exploration_graph::{AnchorDirection, DualGraph, ExplorationKind, ExplorationStatus}; +use crate::intent_queue::{IntentQueue, Producer}; +use crate::planner::{IntentAction, Planner, PlannerConfig, PlannerIntent}; +use crate::wrapup::{Reason, Settlement}; +use futures::future::BoxFuture; +use serde::{Deserialize, Serialize}; +use std::collections::{HashMap, HashSet}; +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; +use tokio::sync::Notify; + +/// What a worker reports for one intent. +#[derive(Debug, Clone, Default)] +pub struct WorkOutcome { + pub ok: bool, + pub summary: String, + pub facts: Vec, + pub negatives: Vec, + pub findings: Vec, +} + +/// Handed to every executor call. +pub struct WorkCtx { + pub intent_id: String, + wrap: Arc, + steer: Arc>>>, +} + +impl WorkCtx { + /// True once the deadline hit: persist what you have and stop (see `wrapup`). + pub fn wrapping(&self) -> bool { self.wrap.load(Ordering::Relaxed) } + /// Operator guidance queued for this intent since the last call. + pub fn take_steer(&self) -> Vec { + self.steer.lock().unwrap().remove(&self.intent_id).unwrap_or_default() + } +} + +pub type ExecFn = Arc BoxFuture<'static, WorkOutcome> + Send + Sync>; + +#[derive(Debug, Clone)] +pub struct ReactiveConfig { + pub target: String, + pub workers: usize, + pub deadline: Option, + pub intent_timeout: Duration, + pub debounce: Duration, + pub heartbeat: Duration, + pub drain_grace: Duration, + pub max_total_intents: usize, + pub max_failures_per_target: u32, + pub state_dir: Option, + pub planner: PlannerConfig, +} + +impl ReactiveConfig { + pub fn new(target: &str) -> Self { + Self { + target: target.into(), workers: 4, deadline: None, + intent_timeout: Duration::from_secs(600), debounce: Duration::from_millis(300), + heartbeat: Duration::from_secs(30), drain_grace: Duration::from_secs(20), + max_total_intents: 200, max_failures_per_target: 3, state_dir: None, + planner: PlannerConfig::default(), + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum EndReason { Quiescent, Deadline, Stopped, Budget } + +#[derive(Debug, Clone, Serialize)] +pub struct RunReport { + pub reason: EndReason, + pub done: usize, + pub failed: usize, + pub stopped: usize, + pub released: usize, + pub findings: usize, + pub planner_rounds: u64, + pub hints_injected: usize, + pub settlement: Settlement, +} + +struct Shared { + graph: Mutex, + queue: Mutex, + wake: Notify, + paused: AtomicBool, + stop_all: AtomicBool, + wrap: Arc, + inflight: AtomicUsize, + steer: Arc>>>, + stops: Mutex>>, + stopped_ids: Mutex>, + counters: Mutex, + heartbeats: Mutex>, + hints_injected: AtomicUsize, +} + +#[derive(Default)] +struct Counters { done: usize, failed: usize, stopped: usize, released: usize, findings: usize, rounds: u64, pushed: usize, + fails_by_key: HashMap } + +/// Control surface for a running engine. Cheap to clone. +#[derive(Clone)] +pub struct Handle { s: Arc } + +impl Handle { + pub fn pause(&self) { self.s.paused.store(true, Ordering::Relaxed); } + pub fn resume(&self) { self.s.paused.store(false, Ordering::Relaxed); self.s.wake.notify_waiters(); } + /// End the run; running intents are cancelled and returned to the queue. + pub fn stop(&self) { self.s.stop_all.store(true, Ordering::Relaxed); self.s.wake.notify_waiters(); self.cancel_all(); } + /// Cancel one running intent; it is marked stopped and not retried. + pub fn stop_intent(&self, id: &str) { + self.s.stopped_ids.lock().unwrap().insert(id.to_string()); + if let Some(n) = self.s.stops.lock().unwrap().get(id) { n.notify_one(); } + } + /// Queue guidance for a running intent (read via `WorkCtx::take_steer`). + pub fn steer(&self, id: &str, msg: &str) { + self.s.steer.lock().unwrap().entry(id.to_string()).or_default().push(msg.to_string()); + } + /// Inject an operator hint into the exploration graph. Triggers a replan. + pub fn hint(&self, text: &str) { + let mut g = self.s.graph.lock().unwrap(); + // Find or create the root goal for operator hints + let goal_text = "operator-hints"; + let goal = g.exploration.nodes.iter() + .find(|n| n.kind == crate::exploration_graph::ExplorationKind::Goal && n.content == goal_text) + .map(|n| n.id.clone()) + .unwrap_or_else(|| g.exploration.add_goal(goal_text, "operator")); + g.exploration.add_hint(text, &goal, "operator"); + drop(g); + self.s.hints_injected.fetch_add(1, Ordering::Relaxed); + self.s.wake.notify_waiters(); // trigger replan + } + /// Operator-created intent (allowed alongside the planner). + pub fn push_operator_intent(&self, intent: PlannerIntent) -> bool { + let ok = self.s.queue.lock().unwrap().push(Producer::Operator, intent).is_ok(); + if ok { self.s.wake.notify_waiters(); } + ok + } + fn cancel_all(&self) { for n in self.s.stops.lock().unwrap().values() { n.notify_one(); } } +} + +fn new_shared(graph: DualGraph, queue: IntentQueue) -> Arc { + Arc::new(Shared { + graph: Mutex::new(graph), queue: Mutex::new(queue), wake: Notify::new(), + paused: AtomicBool::new(false), stop_all: AtomicBool::new(false), wrap: Arc::new(AtomicBool::new(false)), + inflight: AtomicUsize::new(0), steer: Arc::new(Mutex::new(HashMap::new())), + stops: Mutex::new(HashMap::new()), stopped_ids: Mutex::new(HashSet::new()), + counters: Mutex::new(Counters::default()), + heartbeats: Mutex::new(HashMap::new()), + hints_injected: AtomicUsize::new(0), + }) +} + +#[derive(Serialize, Deserialize)] +struct Persisted { queue: IntentQueue, graph: DualGraph } + +const STATE_FILE: &str = "reactive-state.json"; + +fn save(s: &Shared, dir: &Option) { + let Some(d) = dir else { return }; + let p = Persisted { queue: s.queue.lock().unwrap().clone(), graph: s.graph.lock().unwrap().clone() }; + if std::fs::create_dir_all(d).is_ok() { + if let Ok(j) = serde_json::to_string(&p) { + // write-then-rename so a crash never leaves half a file + let tmp = d.join(format!("{STATE_FILE}.tmp")); + if std::fs::write(&tmp, j).is_ok() { let _ = std::fs::rename(&tmp, d.join(STATE_FILE)); } + } + } +} + +/// Reload a saved run. Claimed work is returned to the queue. +pub fn resume_state(dir: &std::path::Path) -> Option<(DualGraph, IntentQueue)> { + let p: Persisted = serde_json::from_str(&std::fs::read_to_string(dir.join(STATE_FILE)).ok()?).ok()?; + let mut q = p.queue; + q.requeue_claimed(); + Some((p.graph, q)) +} + +/// Create the control handle and engine state together. +pub fn prepare(cfg: &ReactiveConfig, graph: DualGraph, queue: Option) -> Handle { + let q = queue.unwrap_or_else(|| IntentQueue::new(2)); + Handle { s: new_shared(graph, q) } +} + +fn goal_id(g: &mut DualGraph, target: &str) -> String { + let text = format!("Assess {target}"); + match g.exploration.nodes.iter().find(|n| n.kind == ExplorationKind::Goal && n.content == text) { + Some(n) => n.id.clone(), + None => g.exploration.add_goal(&text, "reactive"), + } +} + +fn key_of(i: &PlannerIntent) -> String { format!("{:?}|{}", i.action, i.target.to_lowercase()) } + +/// Run until quiescent, out of budget, stopped, or past the deadline. +pub async fn run(cfg: ReactiveConfig, handle: Handle, exec: ExecFn) -> (RunReport, DualGraph) { + let s = handle.s.clone(); + { let mut g = s.graph.lock().unwrap(); goal_id(&mut g, &cfg.target); } + let cfg = Arc::new(cfg); + + let mut worker_tasks = Vec::new(); + for n in 0..cfg.workers.max(1) { + let (s2, c2, e2) = (s.clone(), cfg.clone(), exec.clone()); + worker_tasks.push(tokio::spawn(async move { worker_loop(format!("worker-{n}"), s2, c2, e2).await })); + } + + let planner_task = { let (s2, c2) = (s.clone(), cfg.clone()); tokio::spawn(async move { planner_loop(s2, c2).await }) }; + + // Deadline coordinator races the planner (which ends the run on quiescence/budget/stop). + let mut reason; + let mut settlement = Settlement::default(); + let mut planner_task = planner_task; + let planner_reason = match cfg.deadline { + Some(d) => tokio::select! { + r = &mut planner_task => Some(r.unwrap_or(EndReason::Stopped)), + _ = tokio::time::sleep(d) => None, + }, + None => Some((&mut planner_task).await.unwrap_or(EndReason::Stopped)), + }; + match planner_reason { + Some(r) => reason = r, + None => { + reason = EndReason::Deadline; + settlement.reason = Some(Reason::TimeExhausted); + s.wrap.store(true, Ordering::Relaxed); // ask workers to persist and stop + s.wake.notify_waiters(); + let t0 = tokio::time::Instant::now(); + while s.inflight.load(Ordering::Relaxed) > 0 && t0.elapsed() < cfg.drain_grace { + tokio::time::sleep(Duration::from_millis(20)).await; + } + s.stop_all.store(true, Ordering::Relaxed); + handle.cancel_all(); // hard cancel whatever is left + s.wake.notify_waiters(); + planner_task.abort(); + } + } + s.stop_all.store(true, Ordering::Relaxed); + s.wake.notify_waiters(); + for t in worker_tasks { let _ = t.await; } + + // Anything still claimed was cut off without a worker reaching its release + // path (aborted task, process-level cut): sweep it back too. + let swept = s.queue.lock().unwrap().requeue_claimed(); + let released = s.counters.lock().unwrap().released + swept; + settlement.incomplete = released > 0; + if reason == EndReason::Stopped && s.wrap.load(Ordering::Relaxed) { reason = EndReason::Deadline; } + save(&s, &cfg.state_dir); + + let c = s.counters.lock().unwrap(); + settlement.findings_saved = c.findings as u32; + let report = RunReport { reason, done: c.done, failed: c.failed, stopped: c.stopped, released, + findings: c.findings, planner_rounds: c.rounds, + hints_injected: s.hints_injected.load(Ordering::Relaxed), settlement }; + let graph = s.graph.lock().unwrap().clone(); + (report, graph) +} + +async fn planner_loop(s: Arc, cfg: Arc) -> EndReason { + let mut planner = Planner::new(cfg.planner.clone()); + let adaptive = AdaptiveEngine::new(); + let mut last_signature: (u64, usize, usize) = (0, 0, 0); // (graph_version, fact_count, hint_count) + loop { + // wake on a graph change or the heartbeat, then coalesce bursts + let _ = tokio::time::timeout(cfg.heartbeat, s.wake.notified()).await; + tokio::time::sleep(cfg.debounce).await; + if s.stop_all.load(Ordering::Relaxed) { return EndReason::Stopped; } + if s.paused.load(Ordering::Relaxed) || s.wrap.load(Ordering::Relaxed) { continue; } + + // Intelligent reason trigger: skip replanning if nothing changed + let sig = { + let g = s.graph.lock().unwrap(); + let facts = g.exploration.nodes.iter().filter(|n| matches!(n.kind, ExplorationKind::Fact | ExplorationKind::Finding | ExplorationKind::Negative)).count(); + let hints = g.exploration.nodes.iter().filter(|n| n.kind == ExplorationKind::Hint).count(); + (g.exploration.version, facts, hints) + }; + // Skip replanning if nothing changed and there's no new work + let runnable = s.queue.lock().unwrap().runnable(); + if sig == last_signature && runnable > 0 && s.inflight.load(Ordering::Relaxed) > 0 { + continue; // workers still busy, nothing new — save the LLM call + } + last_signature = sig; + + let intents = { let g = s.graph.lock().unwrap(); planner.wake(&g, &adaptive) }; + s.counters.lock().unwrap().rounds += 1; + { + let mut q = s.queue.lock().unwrap(); + let mut c = s.counters.lock().unwrap(); + for i in intents { + if c.pushed >= cfg.max_total_intents { return EndReason::Budget; } + if c.fails_by_key.get(&key_of(&i)).copied().unwrap_or(0) >= cfg.max_failures_per_target { continue; } + if q.push(Producer::Planner, i).is_ok() { c.pushed += 1; } + } + // worker leads become hints, i.e. planner input (never work) + let leads = q.drain_suggestions(); + drop(q); + drop(c); + if !leads.is_empty() { + let mut g = s.graph.lock().unwrap(); + let goal = goal_id(&mut g, &cfg.target); + for l in leads { g.exploration.add_hint(&l, &goal, "worker"); } + } + } + save(&s, &cfg.state_dir); + s.wake.notify_waiters(); // new intents -> idle workers + + // Heartbeat sweep: release intents whose workers went silent + let stale_cutoff = std::time::Instant::now() - cfg.intent_timeout * 2; + let stale: Vec = s.heartbeats.lock().unwrap().iter() + .filter(|(_, t)| **t < stale_cutoff) + .map(|(id, _)| id.clone()) + .collect(); + for id in &stale { + s.heartbeats.lock().unwrap().remove(id); + // Cancel the stale worker + if let Some(n) = s.stops.lock().unwrap().get(id) { n.notify_one(); } + } + + // quiescent: nothing running, nothing claimable, and the last wake produced nothing new + let idle = s.inflight.load(Ordering::Relaxed) == 0 && s.queue.lock().unwrap().runnable() == 0; + if idle { + // one extra look: a worker may have just written results that the planner has not seen + let v = s.graph.lock().unwrap().exploration.version; + let mut again = { let g = s.graph.lock().unwrap(); planner.wake(&g, &adaptive) }; + + // Graph reasoning: when the planner itself produces nothing, look for + // multi-hop chains from confirmed findings to untested assets. + if again.is_empty() { + let chain_intents = { + let g = s.graph.lock().unwrap(); + let chains = crate::graph_reasoning::find_chains(&g, 3); + if !chains.is_empty() { + let summary = crate::graph_reasoning::graph_summary(&g); + let prompt = crate::graph_reasoning::decision_prompt(&chains, &summary, 5); + // Parse the prompt itself won't generate intents — we build + // them directly from the top-scored chains instead of calling + // an LLM in the planner loop (that's the worker's job). + chains.iter().take(3).enumerate().map(|(i, c)| { + PlannerIntent { + id: format!("chain-{}-{}", s.counters.lock().unwrap().rounds, i), + action: IntentAction::Chain, + target: c.target.clone(), + agent_hint: String::new(), + priority: ((c.score * 10.0) as u32).min(10), + rationale: format!("chain from finding '{}' via {}", c.finding.chars().take(60).collect::(), c.foothold), + depends_on: vec![], + asset_id: None, + } + }).collect::>() + } else { + vec![] + } + }; + again = chain_intents; + } + + if again.is_empty() && s.graph.lock().unwrap().exploration.version == v + && s.queue.lock().unwrap().runnable() == 0 && s.inflight.load(Ordering::Relaxed) == 0 + { + return EndReason::Quiescent; + } + let mut q = s.queue.lock().unwrap(); + for i in again { let _ = q.push(Producer::Planner, i); } + s.wake.notify_waiters(); + } + } +} + +async fn worker_loop(name: String, s: Arc, cfg: Arc, exec: ExecFn) { + loop { + if s.stop_all.load(Ordering::Relaxed) { return; } + let claimed = if s.paused.load(Ordering::Relaxed) || s.wrap.load(Ordering::Relaxed) { None } + else { s.queue.lock().unwrap().claim(&name) }; + let Some(intent) = claimed else { + let _ = tokio::time::timeout(Duration::from_millis(200), s.wake.notified()).await; + continue; + }; + s.inflight.fetch_add(1, Ordering::Relaxed); + s.heartbeats.lock().unwrap().insert(intent.id.clone(), std::time::Instant::now()); + let stop = Arc::new(Notify::new()); + s.stops.lock().unwrap().insert(intent.id.clone(), stop.clone()); + s.heartbeats.lock().unwrap().insert(intent.id.clone(), std::time::Instant::now()); + + // record the intent in the exploration graph + let exp_id = { + let mut g = s.graph.lock().unwrap(); + let goal = goal_id(&mut g, &cfg.target); + let id = g.exploration.add_intent(&format!("{:?} {}", intent.action, intent.target), &goal, &name); + g.exploration.set_status(&id, ExplorationStatus::InProgress); + if let Some(a) = &intent.asset_id { g.exploration.anchor(&id, a, AnchorDirection::Targets); } + id + }; + + let ctx = WorkCtx { intent_id: intent.id.clone(), wrap: s.wrap.clone(), steer: s.steer.clone() }; + let fut = exec(intent.clone(), ctx); + enum R { Out(WorkOutcome), TimedOut, Cancelled } + let r = tokio::select! { + o = fut => R::Out(o), + _ = tokio::time::sleep(cfg.intent_timeout) => R::TimedOut, + _ = stop.notified() => R::Cancelled, + }; + s.stops.lock().unwrap().remove(&intent.id); + + let was_stopped = s.stopped_ids.lock().unwrap().contains(&intent.id); + match r { + R::Out(o) => { + let mut g = s.graph.lock().unwrap(); + for f in &o.facts { g.exploration.add_fact(f, &exp_id, &name); } + for n in &o.negatives { g.exploration.add_negative(n, &exp_id, &name); } + let mut nf = 0; + for f in &o.findings { + match &intent.asset_id { + Some(a) => { g.record_finding(f, &exp_id, &name, a); } + None => { g.exploration.add_finding(f, &exp_id, &name); } + } + nf += 1; + } + g.exploration.set_status(&exp_id, if o.ok { ExplorationStatus::Completed } else { ExplorationStatus::Failed }); + // Enrich graph after findings: bump priority on reachable assets + if nf > 0 { + if let Some(a) = &intent.asset_id { + crate::graph_reasoning::enrich_after_finding(&mut g, a); + } + } + drop(g); + let mut q = s.queue.lock().unwrap(); + let mut c = s.counters.lock().unwrap(); + c.findings += nf; + if o.ok { + let _ = q.complete(&intent.id, &name, &o.summary); + c.done += 1; + } else { + *c.fails_by_key.entry(key_of(&intent)).or_default() += 1; + let retry = q.fail(&intent.id, &name, &o.summary).unwrap_or(false); + if !retry { c.failed += 1; } + } + } + R::TimedOut | R::Cancelled => { + let mut g = s.graph.lock().unwrap(); + let mut q = s.queue.lock().unwrap(); + let mut c = s.counters.lock().unwrap(); + if was_stopped { + g.exploration.set_status(&exp_id, ExplorationStatus::Blocked); + let _ = q.fail(&intent.id, &name, "stopped by operator"); + // a stopped intent is terminal: burn remaining attempts + while q.fail_if_queued(&intent.id, "stopped by operator") {} + c.stopped += 1; + } else if matches!(r, R::TimedOut) { + g.exploration.set_status(&exp_id, ExplorationStatus::Failed); + *c.fails_by_key.entry(key_of(&intent)).or_default() += 1; + if !q.fail(&intent.id, &name, "timed out").unwrap_or(false) { c.failed += 1; } + } else { + // cut off by stop/deadline: resumable, no failure counted. + // release() requeues it immediately, so count it here — + // the final requeue_claimed() sweep would see nothing left. + g.exploration.set_status(&exp_id, ExplorationStatus::Pending); + let _ = q.release(&intent.id, &name); + c.released += 1; + } + } + } + s.heartbeats.lock().unwrap().remove(&intent.id); + s.inflight.fetch_sub(1, Ordering::Relaxed); + save(&s, &cfg.state_dir); + s.wake.notify_waiters(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::exploration_graph::AssetKind; + use std::collections::BTreeMap; + + fn graph_with_assets(n: usize) -> DualGraph { + let mut g = DualGraph::default(); + for i in 0..n { g.discover_asset(AssetKind::Endpoint, &format!("/e{i}"), BTreeMap::new(), "recon", None); } + g + } + + fn fast(target: &str) -> ReactiveConfig { + let mut c = ReactiveConfig::new(target); + c.debounce = Duration::from_millis(5); + c.heartbeat = Duration::from_millis(50); + c.drain_grace = Duration::from_millis(100); + c.intent_timeout = Duration::from_secs(5); + c + } + + fn ok_exec() -> ExecFn { + Arc::new(|i: PlannerIntent, _c: WorkCtx| Box::pin(async move { + WorkOutcome { ok: true, summary: format!("did {}", i.target), negatives: vec![format!("{} clean", i.target)], ..Default::default() } + })) + } + + #[tokio::test] + async fn runs_until_quiescent_and_records_results_in_the_graph() { + let cfg = fast("t.com"); + let h = prepare(&cfg, graph_with_assets(4), None); + let (rep, g) = tokio::time::timeout(Duration::from_secs(20), run(cfg, h, ok_exec())).await.expect("no hang"); + assert_eq!(rep.reason, EndReason::Quiescent); + assert!(rep.done >= 1 && rep.planner_rounds >= 1); + assert!(g.exploration.nodes.iter().any(|n| n.kind == ExplorationKind::Negative)); + assert!(g.exploration.nodes.iter().any(|n| n.kind == ExplorationKind::Intent && n.status == ExplorationStatus::Completed)); + } + + #[tokio::test] + async fn deadline_asks_workers_to_wrap_then_cancels_and_requeues() { + let mut cfg = fast("t.com"); + cfg.deadline = Some(Duration::from_millis(150)); + let h = prepare(&cfg, graph_with_assets(3), None); + let saw_wrap = Arc::new(AtomicBool::new(false)); + let sw = saw_wrap.clone(); + let exec: ExecFn = Arc::new(move |_i, c: WorkCtx| { let sw = sw.clone(); Box::pin(async move { + for _ in 0..500 { if c.wrapping() { sw.store(true, Ordering::Relaxed); } tokio::time::sleep(Duration::from_millis(10)).await; } + WorkOutcome { ok: true, ..Default::default() } + })}); + let (rep, _) = tokio::time::timeout(Duration::from_secs(20), run(cfg, h, exec)).await.expect("no hang"); + assert_eq!(rep.reason, EndReason::Deadline); + assert!(saw_wrap.load(Ordering::Relaxed), "workers must see the wrap-up signal"); + assert!(rep.released >= 1 && rep.settlement.incomplete, "cut-off work goes back to the queue"); + } + + #[tokio::test] + async fn per_target_failure_cap_stops_a_replanning_loop() { + let mut cfg = fast("t.com"); + cfg.max_failures_per_target = 2; + let h = prepare(&cfg, graph_with_assets(2), None); + let calls = Arc::new(AtomicUsize::new(0)); + let c2 = calls.clone(); + let exec: ExecFn = Arc::new(move |_i, _c| { let c2 = c2.clone(); Box::pin(async move { + c2.fetch_add(1, Ordering::Relaxed); + WorkOutcome { ok: false, summary: "boom".into(), ..Default::default() } + })}); + let (rep, _) = tokio::time::timeout(Duration::from_secs(20), run(cfg, h, exec)).await.expect("no hang"); + assert!(matches!(rep.reason, EndReason::Quiescent | EndReason::Budget)); + assert!(calls.load(Ordering::Relaxed) < 40, "bounded, not an endless retry loop: {}", calls.load(Ordering::Relaxed)); + } + + #[tokio::test] + async fn stop_cancels_running_work_and_resumes_from_saved_state() { + let dir = std::env::temp_dir().join(format!("ns-reactive-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut cfg = fast("t.com"); + cfg.state_dir = Some(dir.clone()); + let h = prepare(&cfg, graph_with_assets(3), None); + let h2 = h.clone(); + let exec: ExecFn = Arc::new(|_i, _c| Box::pin(async { tokio::time::sleep(Duration::from_secs(30)).await; WorkOutcome { ok: true, ..Default::default() } })); + let t = tokio::spawn(run(cfg.clone(), h, exec)); + tokio::time::sleep(Duration::from_millis(300)).await; + h2.stop(); + let (rep, _) = tokio::time::timeout(Duration::from_secs(20), t).await.expect("no hang").unwrap(); + assert_eq!(rep.reason, EndReason::Stopped); + assert!(rep.released >= 1); + let (g, q) = resume_state(&dir).expect("state saved"); + assert!(q.runnable() >= 1, "interrupted work is claimable again after resume"); + let cfg2 = fast("t.com"); + let h3 = prepare(&cfg2, g, Some(q)); + let (rep2, _) = tokio::time::timeout(Duration::from_secs(20), run(cfg2, h3, ok_exec())).await.expect("no hang"); + assert_eq!(rep2.reason, EndReason::Quiescent); + assert!(rep2.done >= 1); + let _ = std::fs::remove_dir_all(&dir); + } + + #[tokio::test] + async fn steer_reaches_the_running_intent() { + let cfg = fast("t.com"); + let h = prepare(&cfg, graph_with_assets(1), None); + let h2 = h.clone(); + let got = Arc::new(Mutex::new(Vec::::new())); + let g2 = got.clone(); + let exec: ExecFn = Arc::new(move |i, c: WorkCtx| { let (g2, h2) = (g2.clone(), h2.clone()); Box::pin(async move { + h2.steer(&i.id, "focus on the id param"); + g2.lock().unwrap().extend(c.take_steer()); + WorkOutcome { ok: true, ..Default::default() } + })}); + let _ = tokio::time::timeout(Duration::from_secs(20), run(cfg, h, exec)).await.expect("no hang"); + assert_eq!(got.lock().unwrap().first().map(String::as_str), Some("focus on the id param")); + } +} diff --git a/neurosploit-rs/crates/harness/src/reactive_bridge.rs b/neurosploit-rs/crates/harness/src/reactive_bridge.rs new file mode 100644 index 0000000..27bc822 --- /dev/null +++ b/neurosploit-rs/crates/harness/src/reactive_bridge.rs @@ -0,0 +1,316 @@ +//! Bridge between the generic reactive engine and the NeuroSploit pipeline. +//! +//! `run_reactive()` has the same signature as `pipeline::run()` so the app crate +//! can call it in place of the phased pipeline when `--reactive` is active. It +//! runs basic recon, seeds the dual graph, then hands control to the reactive +//! engine with an executor that calls agents through the model pool. + +use crate::exploration_graph::DualGraph; +use crate::pipeline::RunOutput; +use crate::planner::{PlannerConfig, PlannerIntent, IntentAction}; +use crate::pool::ModelPool; +use crate::reactive::{self, ExecFn, ReactiveConfig, WorkCtx, WorkOutcome}; +use crate::types::RunConfig; +use crate::agents::Library; +use futures::FutureExt; +use std::path::Path; +use std::sync::Arc; +use tokio::sync::mpsc::Sender; + +/// Extract operator constraints from run config (same logic as pipeline's private helper). +fn operator_constraints(cfg: &RunConfig) -> crate::constraints::ConstraintSet { + let text = [cfg.objective.as_deref(), cfg.instructions.as_deref(), cfg.out_of_scope.as_deref()] + .into_iter().flatten().collect::>().join("\n"); + if text.trim().is_empty() { return crate::constraints::ConstraintSet::new(); } + crate::constraints::extract(&text, &cfg.target, None) +} + +/// Entry point for the reactive engine, matching pipeline::run()'s signature. +pub async fn run_reactive( + mut cfg: RunConfig, + _lib: &Library, + pool: &ModelPool, + tx: Sender, +) -> RunOutput { + let _ = tx.send("[reactive] starting event-driven engine".into()).await; + + // --- Setup workdir --- + let workdir = if let Some(d) = &cfg.workdir { + let _ = std::fs::create_dir_all(d); + d.clone() + } else { + let run_name = format!("ns-reactive-{}", std::process::id()); + let d = std::env::current_dir() + .unwrap_or_else(|_| std::path::PathBuf::from(".")) + .join(&run_name) + .display() + .to_string(); + let _ = std::fs::create_dir_all(&d); + cfg.workdir = Some(d.clone()); + d + }; + + // --- Recon (simplified: use pool.complete with a recon prompt) --- + let recon_text = if !cfg.offline { + let _ = tx.send("[reactive] running recon...".into()).await; + let system = "You are a web reconnaissance specialist. Enumerate the target's surface: subdomains, endpoints, technologies, open ports. Return JSON with keys: subdomains, endpoints, params, hosts."; + let user = format!("Target: {}\nPerform reconnaissance and return structured JSON results.", cfg.target); + match pool.complete(system, &user).await { + Ok((_, text)) => { + let _ = tx.send(format!("[reactive] recon complete ({} chars)", text.len())).await; + text + } + Err(e) => { + let _ = tx.send(format!("[reactive] recon failed: {e} — continuing with empty surface")).await; + String::new() + } + } + } else { + let _ = tx.send("[reactive] offline mode — skipping recon".into()).await; + String::new() + }; + + // --- Seed dual graph from recon --- + let graph_dir = Path::new(&workdir).join("graphs"); + let _ = std::fs::create_dir_all(&graph_dir); + let scope = crate::pipeline::effective_scope(&cfg); + let scope_check = move |url: &str| { + matches!(scope.check(url, crate::scope::Action::Probe), crate::scope::Decision::Allow) + }; + let mut graph = DualGraph::load(&graph_dir).unwrap_or_default(); + crate::dual_build::add_recon(&mut graph, &cfg.target, &recon_text, &scope_check); + let _ = graph.save(&graph_dir); + + // --- Build reactive config --- + let reactive_cfg = ReactiveConfig { + target: cfg.target.clone(), + workers: cfg.concurrency.min(8).max(1), + deadline: None, // use token budget instead of wall-clock for now + state_dir: Some(graph_dir.clone()), + planner: PlannerConfig::default(), + ..ReactiveConfig::new(&cfg.target) + }; + + // Resume from saved state if available + let (graph, queue) = reactive::resume_state(&graph_dir) + .map(|(g, q)| (g, Some(q))) + .unwrap_or((graph, None)); + + let handle = reactive::prepare(&reactive_cfg, graph, queue); + + // --- Load knowledge base from agent markdowns --- + let exe_dir = std::env::current_exe() + .ok() + .and_then(|p| p.parent().map(|d| d.to_path_buf())) + .unwrap_or_else(|| std::env::current_dir().unwrap_or_default()); + let kb = Arc::new(crate::knowledge::load(&exe_dir)); + if !kb.is_empty() { + let _ = tx.send(format!("[reactive] knowledge base: {} entries loaded", kb.len())).await; + } + + // --- Resolve MCP profile context --- + let mcp_context: Arc = Arc::new(match &cfg.mcp_profile { + Some(name) => { + let profile = match name.as_str() { + "web" => crate::mcp_profiles::Profile::Web, + "mobile-android" => crate::mcp_profiles::Profile::MobileAndroid, + "mobile-ios" => crate::mcp_profiles::Profile::MobileIos, + "binary" => crate::mcp_profiles::Profile::BinaryAnalysis, + "burp" => crate::mcp_profiles::Profile::BurpSuite, + other => crate::mcp_profiles::Profile::Custom(other.to_string()), + }; + let ctx = crate::mcp_profiles::prompt_context(&profile); + let _ = tx.send(format!("[reactive] MCP profile '{}' active", name)).await; + ctx + } + None => String::new(), + }); + + // --- Build the executor closure --- + // SAFETY: pool is held alive by the caller (spawn_engagement) which owns the + // JoinHandle that awaits this future. The wrapper makes the pointer Send+Sync. + struct PoolHandle(*const ModelPool); + unsafe impl Send for PoolHandle {} + unsafe impl Sync for PoolHandle {} + impl PoolHandle { + fn get(&self) -> &ModelPool { unsafe { &*self.0 } } + } + let pool_handle = Arc::new(PoolHandle(pool as *const ModelPool)); + let cfg_arc = Arc::new(cfg.clone()); + let _constraints = Arc::new(operator_constraints(&cfg)); + let tx2 = tx.clone(); + + let exec: ExecFn = Arc::new(move |intent: PlannerIntent, ctx: WorkCtx| { + let cfg = cfg_arc.clone(); + let tx = tx2.clone(); + let pool_handle = pool_handle.clone(); + let kb = kb.clone(); + let mcp_context = mcp_context.clone(); + + async move { + let _ = tx.send(format!("[reactive] worker: {:?} on {}", intent.action, intent.target)).await; + + // Build system + user prompts based on intent action + let system = match intent.action { + IntentAction::Recon => { + "You are a web security reconnaissance specialist. Enumerate the target surface: endpoints, parameters, technologies. Report each discovery as 'Fact: ...' and each finding as 'Finding: ...'. Report negatives as 'Negative: ...'." + } + IntentAction::Exploit | IntentAction::Fuzz => { + "You are a penetration testing specialist. Test the specific vulnerability described. If confirmed, report as 'Finding: [severity] description with evidence'. If not vulnerable, report as 'Negative: tested X, not vulnerable because Y'. Report observations as 'Fact: ...'." + } + IntentAction::Validate => { + "You are a security validation specialist. Verify whether the described finding is real. Report as 'Finding: ...' if confirmed, 'Negative: ...' if disproven, 'Fact: ...' for observations." + } + IntentAction::Chain => { + "You are a privilege escalation and lateral movement specialist. Attempt to chain from the described foothold. Report progress as 'Fact: ...', findings as 'Finding: ...', dead ends as 'Negative: ...'." + } + IntentAction::Probe | IntentAction::Retry => { + "You are a security testing agent. Execute the task precisely. Report findings as 'Finding: ...', observations as 'Fact: ...', negatives as 'Negative: ...'." + } + }; + + // Inject methodology from knowledge base when relevant + let task_desc = format!("{:?} {}", intent.action, intent.rationale); + let methodology = kb.methodology_for(&task_desc, 2, 3000); + let mcp_block = if mcp_context.is_empty() { String::new() } else { format!("\n{}\n", *mcp_context) }; + + let user = format!( + "Target: {}\nTask: {:?}\nSpecific target: {}\nRationale: {}\ + {}{}\n\ + Execute this task. Report results using the prefixes: Finding:, Fact:, Negative:\n\ + {}", + cfg.target, + intent.action, + intent.target, + intent.rationale, + if methodology.is_empty() { String::new() } else { format!("\n\n{}", methodology) }, + mcp_block, + if ctx.wrapping() { "\nWRAP-UP: Time is running out. Persist your results NOW and stop." } else { "" }, + ); + + let result = pool_handle.get().complete(system, &user).await; + let response = match result { + Ok((model, text)) => { + let _ = tx.send(format!("[reactive] {} responded ({} chars)", model.model, text.len())).await; + text + } + Err(e) => { + let _ = tx.send(format!("[reactive] error: {e} — attempting conclude fallback")).await; + // Session resume / conclude fallback: try to salvage partial work + let mut session = crate::wrapup::SessionState::new( + &format!("{:?} on {}", intent.action, intent.target), + ); + session.partial_output = format!("Model call failed: {e}"); + let conclude_sys = "You are a security testing results extractor."; + let conclude_user = crate::wrapup::conclude_prompt( + crate::wrapup::Role::Worker, + &session.context(), + ); + if let Ok((_m, text)) = pool_handle.get().complete(conclude_sys, &conclude_user).await { + let r = crate::wrapup::parse_conclude(&text); + if !r.findings.is_empty() || !r.facts.is_empty() || !r.negatives.is_empty() { + let _ = tx.send(format!( + "[reactive] conclude salvaged: {} finding(s), {} fact(s), {} negative(s)", + r.findings.len(), r.facts.len(), r.negatives.len() + )).await; + return WorkOutcome { + ok: !r.findings.is_empty() || !r.facts.is_empty(), + summary: format!("conclude fallback: {} finding(s), {} fact(s)", r.findings.len(), r.facts.len()), + facts: r.facts, + negatives: r.negatives, + findings: r.findings, + }; + } + } + return WorkOutcome { + ok: false, + summary: format!("model call failed: {e}"), + ..Default::default() + }; + } + }; + + // Parse structured output + let mut facts = Vec::new(); + let mut negatives = Vec::new(); + let mut findings = Vec::new(); + + for line in response.lines() { + let trimmed = line.trim(); + if let Some(rest) = trimmed.strip_prefix("Finding:").or_else(|| trimmed.strip_prefix("FINDING:")) { + findings.push(rest.trim().to_string()); + } else if let Some(rest) = trimmed.strip_prefix("Negative:").or_else(|| trimmed.strip_prefix("NEGATIVE:")) { + negatives.push(rest.trim().to_string()); + } else if let Some(rest) = trimmed.strip_prefix("Fact:").or_else(|| trimmed.strip_prefix("FACT:")) { + facts.push(rest.trim().to_string()); + } + } + + // Fallback: if no structured output, check for common patterns + if findings.is_empty() && facts.is_empty() && negatives.is_empty() { + for line in response.lines() { + let lower = line.to_lowercase(); + if lower.contains("vulnerable") && !lower.contains("not vulnerable") { + findings.push(line.trim().to_string()); + } else if lower.contains("not vulnerable") || lower.contains("no vulnerability") { + negatives.push(line.trim().to_string()); + } else if lower.contains("discovered") || lower.contains("found") || lower.contains("detected") { + facts.push(line.trim().to_string()); + } + } + } + + let ok = !findings.is_empty() || !facts.is_empty() || !negatives.is_empty(); + let summary = format!( + "{} finding(s), {} fact(s), {} negative(s)", + findings.len(), facts.len(), negatives.len() + ); + let _ = tx.send(format!("[reactive] result: {summary}")).await; + + WorkOutcome { ok, summary, facts, negatives, findings } + }.boxed() + }); + + let _ = tx.send("[reactive] engine running — planner wakes on graph changes".into()).await; + + // --- Run --- + let (report, final_graph) = reactive::run(reactive_cfg, handle, exec).await; + + // Save final graph + let _ = final_graph.save(&graph_dir); + + let _ = tx.send(format!( + "[reactive] done: {:?} — {} done, {} failed, {} findings, {} rounds", + report.reason, report.done, report.failed, report.findings, report.planner_rounds + )).await; + + // Extract findings from the graph + let findings: Vec = final_graph.exploration.nodes.iter() + .filter(|n| n.kind == crate::exploration_graph::ExplorationKind::Finding) + .enumerate() + .map(|(i, n)| { + let endpoint = final_graph.exploration.anchors.iter() + .find(|a| a.exploration_id == n.id) + .and_then(|a| final_graph.assets.nodes.iter().find(|an| an.id == a.asset_id)) + .map(|a| a.value.clone()) + .unwrap_or_default(); + crate::types::Finding { + id: format!("reactive-{i}"), + agent: n.agent.clone(), + title: n.content.clone(), + severity: "medium".into(), + endpoint, + validated: n.status == crate::exploration_graph::ExplorationStatus::Completed, + ..Default::default() + } + }) + .collect(); + + RunOutput { + target: cfg.target.clone(), + findings, + agents_ran: vec!["reactive-engine".into()], + workdir, + ..Default::default() + } +} diff --git a/neurosploit-rs/crates/harness/src/types.rs b/neurosploit-rs/crates/harness/src/types.rs index 8748ba2..feac9b5 100644 --- a/neurosploit-rs/crates/harness/src/types.rs +++ b/neurosploit-rs/crates/harness/src/types.rs @@ -319,6 +319,16 @@ pub struct RunConfig { /// autonomy — no guardrails on tool installs, research, creative attacks). #[serde(default = "default_autonomy")] pub autonomy: String, + /// Opt-in: use the event-driven reactive engine instead of the default + /// phased pipeline. The planner wakes on graph changes and workers claim + /// intents from a shared queue. Experimental — the phased pipeline remains + /// the default and the most tested path. + #[serde(default)] + pub reactive: bool, + /// MCP tool profile: `web`, `mobile-android`, `mobile-ios`, `binary`, `burp`. + /// When set, the matching MCP server and tool allowlist are auto-configured. + #[serde(default)] + pub mcp_profile: Option, } fn default_autonomy() -> String { @@ -386,6 +396,8 @@ impl RunConfig { api_collection: None, reference_prompts: Vec::new(), autonomy: default_autonomy(), + reactive: false, + mcp_profile: None, } } } diff --git a/neurosploit-rs/crates/harness/src/wrapup.rs b/neurosploit-rs/crates/harness/src/wrapup.rs index 335bf1c..c14b138 100644 --- a/neurosploit-rs/crates/harness/src/wrapup.rs +++ b/neurosploit-rs/crates/harness/src/wrapup.rs @@ -113,6 +113,108 @@ impl Settlement { } } +/// Conclude prompt: re-enter a cut-off session to extract partial work. +/// Unlike `prompt()` which guides a live agent, this addresses a session that +/// was forcibly stopped and asks it to summarize what it accomplished. +pub fn conclude_prompt(role: Role, partial_context: &str) -> String { + let preamble = "Your previous execution was interrupted. Do NOT continue testing. \ + Instead, review what you accomplished and report it now."; + let body = match role { + Role::Worker => format!( + "{preamble}\n\n\ + Context from your interrupted session:\n{partial_context}\n\n\ + Report using these exact prefixes:\n\ + - Finding: [severity] description (for confirmed vulnerabilities)\n\ + - Fact: description (for observations, discovered endpoints, technologies)\n\ + - Negative: description (for things you tested that were NOT vulnerable)\n\ + - Incomplete: description (for work you started but could not finish)\n\n\ + List everything you found, even partial results. Do not fabricate — only report what you actually observed." + ), + Role::Planner => format!( + "{preamble}\n\n\ + Planning context:\n{partial_context}\n\n\ + Report:\n\ + - Intent: action on target (for planned but unsubmitted intents)\n\ + - Fact: observation (for things you learned about the target)\n\ + - Priority: description (for the most important next steps)\n\ + Do not start new analysis." + ), + Role::Validator => format!( + "{preamble}\n\n\ + Validation context:\n{partial_context}\n\n\ + For each claim you were checking:\n\ + - Finding: confirmed description (if you verified it)\n\ + - Negative: disproven description (if you disproved it)\n\ + - Incomplete: claim description, what was missing" + ), + Role::Reporter => format!( + "{preamble}\n\n\ + Report context:\n{partial_context}\n\n\ + Save whatever sections you completed. List missing sections as:\n\ + - Incomplete: section name, what remains" + ), + }; + body +} + +/// Tracks enough context to resume a cut-off session via conclude. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct SessionState { + /// What the agent was working on when cut off. + pub task_description: String, + /// Any partial output captured before the cut. + pub partial_output: String, + /// How many turns the agent completed. + pub turns_completed: u32, + /// Whether a conclude attempt was already made. + pub concluded: bool, +} + +impl SessionState { + pub fn new(task: &str) -> Self { + Self { task_description: task.to_string(), ..Default::default() } + } + + /// Build the context string for the conclude prompt. + pub fn context(&self) -> String { + let mut ctx = format!("Task: {}", self.task_description); + if !self.partial_output.is_empty() { + ctx.push_str(&format!("\nPartial output:\n{}", self.partial_output)); + } + if self.turns_completed > 0 { + ctx.push_str(&format!("\nCompleted {} turn(s) before interruption.", self.turns_completed)); + } + ctx + } +} + +/// Parsed results from a conclude response. +#[derive(Debug, Clone, Default)] +pub struct ConcludeResults { + pub findings: Vec, + pub facts: Vec, + pub negatives: Vec, + pub incomplete: Vec, +} + +/// Parse a conclude response into structured results. +pub fn parse_conclude(response: &str) -> ConcludeResults { + let mut r = ConcludeResults::default(); + for line in response.lines() { + let trimmed = line.trim(); + if let Some(rest) = trimmed.strip_prefix("Finding:").or_else(|| trimmed.strip_prefix("FINDING:")) { + r.findings.push(rest.trim().to_string()); + } else if let Some(rest) = trimmed.strip_prefix("Fact:").or_else(|| trimmed.strip_prefix("FACT:")) { + r.facts.push(rest.trim().to_string()); + } else if let Some(rest) = trimmed.strip_prefix("Negative:").or_else(|| trimmed.strip_prefix("NEGATIVE:")) { + r.negatives.push(rest.trim().to_string()); + } else if let Some(rest) = trimmed.strip_prefix("Incomplete:").or_else(|| trimmed.strip_prefix("INCOMPLETE:")) { + r.incomplete.push(rest.trim().to_string()); + } + } + r +} + #[cfg(test)] mod tests { use super::*; @@ -155,4 +257,32 @@ mod tests { assert!(s.line().contains("2 finding(s)") && s.line().contains("INCOMPLETE")); assert_eq!(Settlement::default().line(), "completed normally"); } + + #[test] + fn conclude_prompt_forbids_continued_testing() { + let p = conclude_prompt(Role::Worker, "scanning /api/users"); + assert!(p.contains("Do NOT continue testing")); + assert!(p.contains("Finding:") && p.contains("Fact:") && p.contains("Negative:")); + } + + #[test] + fn session_state_builds_context() { + let mut ss = SessionState::new("test IDOR on /api/users"); + ss.partial_output = "Found endpoint returns 200 for other user IDs".into(); + ss.turns_completed = 3; + let ctx = ss.context(); + assert!(ctx.contains("IDOR") && ctx.contains("3 turn(s)") && ctx.contains("200 for other")); + } + + #[test] + fn parse_conclude_extracts_structured_results() { + let resp = "Finding: [high] IDOR on /api/users/{id}\nFact: API uses sequential integer IDs\n\ + Negative: CSRF tokens are properly validated\nIncomplete: did not test admin endpoints"; + let r = parse_conclude(resp); + assert_eq!(r.findings.len(), 1); + assert_eq!(r.facts.len(), 1); + assert_eq!(r.negatives.len(), 1); + assert_eq!(r.incomplete.len(), 1); + assert!(r.findings[0].contains("IDOR")); + } } diff --git a/web/public/app.js b/web/public/app.js index 4c79d2d..20c18ad 100644 --- a/web/public/app.js +++ b/web/public/app.js @@ -472,6 +472,24 @@ $('#btnCustomLead').addEventListener('click', openLeadModal); $('#btnCloseLead').addEventListener('click', closeLeadModal); $('#btnLeadCancel').addEventListener('click', closeLeadModal); $('#leadModal').addEventListener('click', (e) => { if (e.target.id === 'leadModal') closeLeadModal(); }); + +// Reactive engine info modal +$('#btnReactiveInfo')?.addEventListener('click', () => show($('#reactiveModal'), true)); +$('#btnCloseReactive')?.addEventListener('click', () => show($('#reactiveModal'), false)); +$('#btnReactiveClose2')?.addEventListener('click', () => show($('#reactiveModal'), false)); +$('#btnEnableReactive')?.addEventListener('click', () => { + $('#fieldReactive').checked = true; + show($('#reactiveModal'), false); +}); +$('#reactiveModal')?.addEventListener('click', (e) => { if (e.target.id === 'reactiveModal') show($('#reactiveModal'), false); }); + +// MCP profile info — link near the MCP Profile select +$('#fieldMcpProfile')?.parentElement?.querySelector('.field-help')?.insertAdjacentHTML('beforeend', ' '); +$('#btnMcpProfileInfo')?.addEventListener('click', () => show($('#mcpProfileModal'), true)); +$('#btnCloseMcpProfile')?.addEventListener('click', () => show($('#mcpProfileModal'), false)); +$('#btnMcpProfileClose')?.addEventListener('click', () => show($('#mcpProfileModal'), false)); +$('#mcpProfileModal')?.addEventListener('click', (e) => { if (e.target.id === 'mcpProfileModal') show($('#mcpProfileModal'), false); }); + $$('#leadModeTabs .seg-tab').forEach((t) => t.addEventListener('click', () => setLeadMode(t.dataset.leadmode))); $('#leadDesc').addEventListener('keydown', (e) => { if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) $('#btnLeadGenerate').click(); @@ -660,6 +678,9 @@ function renderReview() { { k: 'PoC re-validation', v: $('#fieldRevalidatePoc').checked ? 'on' : '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' }, + { k: 'MCP Profile', v: $('#fieldMcpProfile')?.value || 'auto' }, + { k: 'Reactive engine', v: $('#fieldReactive')?.checked ? 'on' : 'off' }, { k: 'Target auth', v: state.auth.header ? 'header set' : (state.auth.roles.length ? `${state.auth.roles.length} role(s)` : 'none') }, ]; $('#reviewGrid').innerHTML = items.map((it) => ` @@ -729,6 +750,9 @@ async function startExploitation() { oobDns: state.authz.oobDns || undefined, sms: state.authz.sms || undefined, scope: collectScope(), + reactive: $('#fieldReactive')?.checked || false, + mcpProfile: $('#fieldMcpProfile')?.value || undefined, + autonomy: $('#fieldAutonomy')?.value || 'standard', }; $('#btnLaunch').disabled = true; @@ -4232,6 +4256,28 @@ async function loadSettings() {
+
+
Reactive Engine
+
+
+
+
+
LLM Provider Keys
API keys for the LLMs that run engagements. Kept in server memory only, never written to disk.
@@ -4434,6 +4480,9 @@ async function saveSettings() { transport: $('#settingTransport')?.value || '', oobDomain: $('#settingOob')?.value || '', intercept: $('#settingIntercept')?.value || '', + autonomy: $('#settingAutonomy')?.value || 'standard', + mcpProfile: $('#settingMcpProfile')?.value || '', + reactive: $('#settingReactive')?.value || 'off', }; try { await api('/api/config/settings', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }); toast('Settings saved', 'ok'); } catch (e) { toast(`Failed: ${e.message}`, 'error'); } diff --git a/web/public/index.html b/web/public/index.html index 0195a88..09a3c80 100644 --- a/web/public/index.html +++ b/web/public/index.html @@ -593,6 +593,28 @@
Deeper recon finds more surface but costs more tokens.
+
+
+ +
How much freedom agents get: tool installs, creative attacks, deeper chaining.
+
+
+ +
Pre-configured MCP tool profile per test type. Auto picks from engagement mode.
+
+
Reasoning budget
@@ -670,6 +692,12 @@
Maps confirmed findings onto control requirements in the report. Indicates gaps for an assessor — never a compliance verdict.
+
+
Reactive Engine experimental
+
Event-driven planner/worker loop. Replans on graph changes instead of fixed phases.
+
+
+
Workers claim intents from a shared queue. The planner wakes on graph changes, findings, and operator hints. Experimental — the phased pipeline is more tested.
@@ -1305,6 +1333,88 @@ + + + + + +
diff --git a/web/public/style.css b/web/public/style.css index 25b8345..392667e 100644 --- a/web/public/style.css +++ b/web/public/style.css @@ -1517,3 +1517,30 @@ input[type="number"] { font-variant-numeric: tabular-nums; } .astat-l { font-size: var(--fs-xs); color: var(--fg-3); text-transform: uppercase; letter-spacing: 0.03em; } .adaptive-stack, .adaptive-waf { font-size: var(--fs-sm); color: var(--fg-2); line-height: 1.5; } .adaptive-stack code, .adaptive-waf code { background: var(--bg-1); padding: 1px 4px; border-radius: var(--r-sm); font-size: var(--fs-xs); } + +/* ============================================================ Reactive / MCP modals */ +.badge-experimental { display: inline-block; font-size: var(--fs-xs); font-weight: 600; padding: 2px 8px; border-radius: 999px; background: var(--warn-bg, #fff3cd); color: var(--warn-fg, #856404); vertical-align: middle; margin-left: 6px; } +@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) .badge-experimental { background: #3d3200; color: #ffc107; } } +:root[data-theme="dark"] .badge-experimental { background: #3d3200; color: #ffc107; } + +.feature-grid { display: grid; grid-template-columns: 1fr 1fr; gap: var(--sp-3); } +@media (max-width: 600px) { .feature-grid { grid-template-columns: 1fr; } } +.feature-item { display: flex; gap: var(--sp-2); align-items: flex-start; padding: var(--sp-2); border-radius: var(--radius); background: var(--surface-raised, var(--surface)); } +.feature-icon { font-size: 1.4em; flex-shrink: 0; } +.feature-item b { display: block; margin-bottom: 2px; } + +.profile-cards { display: grid; grid-template-columns: 1fr 1fr; gap: var(--sp-3); } +@media (max-width: 600px) { .profile-cards { grid-template-columns: 1fr; } } +.profile-card { padding: var(--sp-3); border-radius: var(--radius); border: 1px solid var(--border); background: var(--surface-raised, var(--surface)); } +.profile-card-title { font-size: var(--fs-base); font-weight: 600; margin-bottom: 4px; } +.profile-card-desc { font-size: var(--fs-sm); color: var(--text-muted); margin-bottom: 6px; } +.profile-card-tools { font-size: var(--fs-xs); color: var(--text-faint); font-family: var(--font-mono, monospace); } + +.modal-section { margin-bottom: var(--sp-4); } +.modal-section h3 { font-size: var(--fs-base); font-weight: 600; margin: 0 0 var(--sp-2) 0; } +.modal-section ul { margin: var(--sp-2) 0; padding-left: var(--sp-4); } +.modal-section li { margin-bottom: var(--sp-1); font-size: var(--fs-sm); } +.modal-section p { font-size: var(--fs-sm); color: var(--text-muted); } + +.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; } diff --git a/web/server.js b/web/server.js index 993bfa9..0b37c3a 100644 --- a/web/server.js +++ b/web/server.js @@ -1296,6 +1296,9 @@ function buildArgs(body) { if (body.environment) args.push('--environment', body.environment); if (body.policyProfile) args.push('--policy', body.policyProfile); for (const a of body.agents || []) args.push('--only', a); + 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); args.push('--verbose'); return args; }