diff --git a/neurosploit-rs/Cargo.lock b/neurosploit-rs/Cargo.lock index a2313fe..edbd90c 100644 --- a/neurosploit-rs/Cargo.lock +++ b/neurosploit-rs/Cargo.lock @@ -972,7 +972,7 @@ dependencies = [ [[package]] name = "neurosploit" -version = "4.6.0" +version = "4.6.1" dependencies = [ "anyhow", "clap", @@ -990,7 +990,7 @@ dependencies = [ [[package]] name = "neurosploit-harness" -version = "4.6.0" +version = "4.6.1" dependencies = [ "anyhow", "base64", diff --git a/neurosploit-rs/Cargo.toml b/neurosploit-rs/Cargo.toml index 83ce367..0c0fe0f 100644 --- a/neurosploit-rs/Cargo.toml +++ b/neurosploit-rs/Cargo.toml @@ -3,7 +3,7 @@ members = ["crates/harness", "app"] resolver = "2" [workspace.package] -version = "4.6.0" +version = "4.6.1" edition = "2021" license = "MIT" repository = "https://github.com/JoasASantos/NeuroSploit" diff --git a/neurosploit-rs/crates/harness/src/json_extract.rs b/neurosploit-rs/crates/harness/src/json_extract.rs index 0552aa2..1ddb570 100644 --- a/neurosploit-rs/crates/harness/src/json_extract.rs +++ b/neurosploit-rs/crates/harness/src/json_extract.rs @@ -34,9 +34,22 @@ use serde_json::Value; pub fn parse_reply(text: &str) -> Option { // Strip model-specific markup that wraps or replaces JSON output. let cleaned = strip_model_markup(text); - let text = &cleaned; - for cand in candidates(text) { + // Reasoning-first models draft inside / blocks before + // answering, and those drafts contain braces and half-written JSON. Scanning + // them alongside the real answer lets a draft win, so try the reply with the + // reasoning removed first. Fall back to the whole thing: a model that put + // its only JSON inside a reasoning block still gets parsed. + let without_reasoning = strip_reasoning_blocks(&cleaned); + if without_reasoning.trim() != cleaned.trim() { + for cand in candidates(&without_reasoning) { + if let Some(v) = parse_lenient(&cand) { + return Some(v); + } + } + } + + for cand in candidates(&cleaned) { if let Some(v) = parse_lenient(&cand) { return Some(v); } @@ -44,6 +57,33 @@ pub fn parse_reply(text: &str) -> Option { None } +/// Tags a model uses to think out loud before answering. +pub(crate) const REASONING_TAGS: &[&str] = + &["thinking", "think", "thought", "reasoning", "reflection", "scratchpad", "analysis"]; + +/// Remove reasoning blocks and everything inside them. +/// +/// Unlike the wrappers `strip_model_markup` handles, the *content* here is prose +/// the model never meant as output, so dropping the tags alone would leave the +/// draft behind. +pub(crate) fn strip_reasoning_blocks(text: &str) -> String { + let mut out = text.to_string(); + for tag in REASONING_TAGS { + // Opening tag with or without attributes, through its closing tag. + let Ok(re) = regex::Regex::new(&format!(r"(?is)<{tag}(\s[^>]*)?>.*?")) else { + continue; + }; + out = re.replace_all(&out, "\n").to_string(); + // An unterminated block (the model was cut off mid-thought) runs to the + // end of the reply. + let Ok(open) = regex::Regex::new(&format!(r"(?is)<{tag}(\s[^>]*)?>")) else { continue }; + if let Some(m) = open.find(&out) { + out.truncate(m.start()); + } + } + out +} + /// A tool call a model wrote as text instead of JSON. The harness resolves it /// against the toolbox catalog before executing anything. #[derive(Debug, Clone, PartialEq, Eq)] @@ -451,6 +491,38 @@ mod tests { assert!(v.is_array()); } + #[test] + fn a_draft_inside_thinking_does_not_beat_the_real_answer() { + let reply = r#" +Maybe [{"title":"draft guess","severity":"Critical"}] — no, I have not proven that. + + +[{"title":"Reflected XSS in search","severity":"High"}]"#; + let v = parse_reply(reply).unwrap(); + assert_eq!(v[0]["title"], "Reflected XSS in search"); + assert_eq!(v.as_array().unwrap().len(), 1); + } + + #[test] + fn json_that_only_exists_inside_a_reasoning_block_is_still_found() { + // Stripping must never cost us the one answer the model gave. + let reply = r#"[{"title":"Only here","severity":"Low"}]"#; + let v = parse_reply(reply).unwrap(); + assert_eq!(v[0]["title"], "Only here"); + } + + #[test] + fn an_unterminated_reasoning_block_is_dropped_to_the_end() { + let out = strip_reasoning_blocks("answer\n\ncut off mid-sentence and never"); + assert_eq!(out.trim(), "answer"); + } + + #[test] + fn reasoning_tags_with_attributes_are_stripped() { + let out = strip_reasoning_blocks(r#"noise[]"#); + assert_eq!(out.trim(), "[]"); + } + #[test] fn prose_brackets_before_the_answer_are_ignored() { // `[low] …` is a balanced `[...]` region but not valid JSON; the real diff --git a/neurosploit-rs/crates/harness/src/llm_pool.rs b/neurosploit-rs/crates/harness/src/llm_pool.rs index b9c3336..cc25320 100644 --- a/neurosploit-rs/crates/harness/src/llm_pool.rs +++ b/neurosploit-rs/crates/harness/src/llm_pool.rs @@ -226,7 +226,9 @@ impl FailoverChain { let noise = NoiseLevel::from_env(); let mut chain = Self::new(noise); - let defaults: &[(&str, f64, u32)] = &[ + // Per-provider pacing where we have a reason for it; everything else + // takes the conservative default. + let tuned: &[(&str, f64, u32)] = &[ ("anthropic", 60.0, 3), ("openai", 60.0, 3), ("gemini", 60.0, 3), @@ -240,13 +242,27 @@ impl FailoverChain { ("ollama", 10.0, 10), ]; - for &(name, rpm, thresh) in defaults { - let env_key = format!("{}_API_KEY", name.to_uppercase()); - let has_key = name == "ollama" - || std::env::var(&env_key).map(|v| !v.is_empty()).unwrap_or(false); - if has_key { - chain.add_provider(name, rpm, thresh); + // Walk the provider registry rather than a list kept here by hand. The + // hand-kept list named eleven providers and did not name `orcarouter`, + // so a run driven entirely by OrcaRouter reported pool health for three + // providers it never called and none for the one it did. A provider + // added through the console was invisible here for the same reason. + let installed = crate::models::installed_cli_backends(); + for pr in crate::models::providers() { + let usable = std::env::var(pr.env_key).map(|v| !v.trim().is_empty()).unwrap_or(false) + || (pr.kind == "cli" + && crate::models::cli_binary_for(pr.key) + .map(|b| installed.contains(&b)) + .unwrap_or(false)); + if !usable { + continue; } + let (rpm, thresh) = tuned + .iter() + .find(|(n, _, _)| *n == pr.key) + .map(|&(_, r, t)| (r, t)) + .unwrap_or((30.0, 5)); + chain.add_provider(pr.key, rpm, thresh); } chain @@ -269,18 +285,31 @@ impl FailoverChain { self.noise } + /// Health of the providers this run actually called. + /// + /// A provider that handled no request has no health to report, and listing + /// it reads as a failure: a run showed three providers `[Closed] reqs=0` + /// and looked like a pool-wide outage when nothing had gone wrong. pub fn status_report(&self) -> String { let mut s = String::new(); + let mut idle: Vec<&str> = Vec::new(); for p in &self.providers { - let state = p.breaker.state(); let reqs = p.total_requests.load(Ordering::Relaxed); + if reqs == 0 { + idle.push(&p.name); + continue; + } + let state = p.breaker.state(); let errs = p.total_errors.load(Ordering::Relaxed); let lat = p.latency_ms.load(Ordering::Relaxed); s.push_str(&format!( - " {} [{:?}] reqs={} errs={} lat={}ms err_rate={:.1}%\n", - p.name, state, reqs, errs, lat, p.error_rate() * 100.0 + " {} [{:?}] reqs={reqs} errs={errs} lat={lat}ms err_rate={:.1}%\n", + p.name, state, p.error_rate() * 100.0 )); } + if !idle.is_empty() { + s.push_str(&format!(" unused this run: {}\n", idle.join(", "))); + } s } @@ -364,8 +393,28 @@ mod tests { fn failover_chain_status() { let mut chain = FailoverChain::new(NoiseLevel::Balanced); chain.add_provider("test-provider", 60.0, 3); + chain.provider("test-provider").unwrap().record_request(120, 50, false); let report = chain.status_report(); - assert!(report.contains("test-provider")); - assert!(report.contains("Closed")); + assert!(report.contains("test-provider"), "{report}"); + assert!(report.contains("Closed"), "{report}"); + assert!(report.contains("reqs=1"), "{report}"); + } + + /// A provider that handled nothing has no health to report. Printing it as + /// `[Closed] reqs=0` made an untouched provider look like a failed one. + #[test] + fn a_provider_that_was_never_called_is_listed_as_unused() { + let mut chain = FailoverChain::new(NoiseLevel::Balanced); + chain.add_provider("called", 60.0, 3); + chain.add_provider("never-called", 60.0, 3); + chain.provider("called").unwrap().record_request(90, 10, false); + + let report = chain.status_report(); + assert!(report.contains("called [Closed] reqs=1"), "{report}"); + assert!(report.contains("unused this run: never-called"), "{report}"); + assert!( + !report.contains("never-called [Closed]"), + "an idle provider must not be reported as pool health: {report}" + ); } } diff --git a/neurosploit-rs/crates/harness/src/pipeline.rs b/neurosploit-rs/crates/harness/src/pipeline.rs index 2799fc2..92eb3f6 100644 --- a/neurosploit-rs/crates/harness/src/pipeline.rs +++ b/neurosploit-rs/crates/harness/src/pipeline.rs @@ -1915,6 +1915,25 @@ fn looks_like_tool_call(text: &str) -> bool { || crate::json_extract::parse_text_tool_call(text).is_some() } +/// Did the model only think out loud? +/// +/// A reasoning-first model can spend its whole turn inside `` and +/// ``, deciding to run curl, and stop — no findings, no tool-call +/// markup `looks_like_tool_call` recognises. That reply used to be dropped with +/// "model may have produced malformed JSON", which is the wrong diagnosis and +/// loses the agent's turn: the model has the evidence, it just never answered. +/// Treat it like a tool call and ask once for the answer. +fn looks_like_reasoning_only(text: &str) -> bool { + let has_block = crate::json_extract::REASONING_TAGS + .iter() + .any(|tag| text.to_ascii_lowercase().contains(&format!("<{tag}"))); + if !has_block { + return false; + } + // Nothing of substance survives once the thinking is removed. + crate::json_extract::strip_reasoning_blocks(text).trim().len() < 24 +} + /// Some API models answer with a tool call even when no tool executor is wired /// for that turn. Ask once for a JSON-only answer built from the evidence in the /// reply so the agent's work is not silently lost. @@ -1928,8 +1947,17 @@ async fn recover_findings( ) -> Vec { let system = "You extract confirmed security findings. Reply with ONLY a JSON array (may be []). No tool calls, no prose, no markdown."; let previous = original.chars().take(9000).collect::(); + // Name what the reply actually was. Telling a model that only thought out + // loud that it "contained tool-call markup" asks it to correct something it + // did not do. + let thinking_only = looks_like_reasoning_only(original); + let what = if thinking_only { + "stopped after thinking out loud and never gave an answer" + } else { + "contained tool-call markup instead of the findings JSON" + }; let mut user = format!( - "Your previous reply contained tool-call markup instead of the findings JSON. Using ONLY the evidence already in that reply, return the confirmed findings as a JSON array. If none are proven, return [].\n\nPREVIOUS REPLY:\n{previous}" + "Your previous reply {what}. Using ONLY the evidence already in that reply, return the confirmed findings as a JSON array. If none are proven, return [].\n\nPREVIOUS REPLY:\n{previous}" ); let mut ran = false; if let Some(call) = crate::json_extract::parse_text_tool_call(original) { @@ -1955,7 +1983,8 @@ async fn recover_findings( if !ran { let _ = tx .send(format!( - "🔧 {agent}: reply was a tool call, not findings — asking for a JSON-only answer" + "🔧 {agent}: {} — asking for a JSON-only answer", + if thinking_only { "reply was reasoning with no answer" } else { "reply was a tool call, not findings" } )) .await; } @@ -1965,10 +1994,24 @@ async fn recover_findings( } } +/// Whether the toolbox may install a tool it finds missing. +/// +/// `--provision` is the operator's explicit yes to installing software onto +/// *their own machine*, and it stays required there. A sandboxed run needs no +/// such ceremony: the install lands in a throwaway container, and the pipeline +/// already provisions the recon suite into that same container before the first +/// round. Without this, a sandboxed run announced "auto-installs tools", then +/// spent its rounds discovering that gau, subfinder and amass were missing and +/// telling the operator to "pass --provision" — for an install it was free to +/// perform. +fn provision_allowed(cfg: &RunConfig) -> bool { + std::env::var("NEUROSPLOIT_PROVISION").ok().as_deref() == Some("1") || cfg.sandbox.is_some() +} + fn tool_run_cfg(cfg: &RunConfig) -> crate::toolbox::ToolRunConfig { crate::toolbox::ToolRunConfig { sandbox: cfg.sandbox.clone(), - provision: std::env::var("NEUROSPLOIT_PROVISION").ok().as_deref() == Some("1"), + provision: provision_allowed(cfg), timeout_secs: Some(180), audit_dir: cfg.workdir.as_ref().map(|w| std::path::PathBuf::from(w).join("toolbox")), scope: Some(effective_scope(cfg)), @@ -2535,14 +2578,24 @@ pub async fn run(mut cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sender ranked.iter().filter(|a| chosen.iter().any(|c| c == &a.name)).take(cap).cloned().collect() } else { let total = sel.len(); - let mut sel = sel; - let dropped = cap_pinned(&mut sel, cfg.max_agents); - if dropped > 0 { + let sel = if cfg.max_agents > 0 && total > cfg.max_agents { + let (kept, unsupported) = rank_pinned(&sel, &recon, &focus, cfg.max_agents); let _ = tx.send(format!( - "--only: {total} pinned agent(s) — capped to {} by --max-agents (dropped {dropped})", - sel.len() + "--only: {total} pinned, --max-agents {} — ranked by recon fit, {} dropped", + cfg.max_agents, + total - kept.len() )).await; - } + if !unsupported.is_empty() { + let _ = tx.send(format!( + "⚠ --only: recon shows nothing to support {} — running it because you pinned it. \ + Raise --max-agents or narrow /only to spend the slots on the matched surface.", + unsupported.join(", ") + )).await; + } + kept + } else { + sel + }; let _ = tx.send(format!("--only: running {} pinned agent(s): {}", sel.len(), sel.iter().map(|a| a.name.clone()).collect::>().join(", "))).await; sel @@ -2618,9 +2671,16 @@ pub async fn run(mut cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sender )) .await; } + // Say which decision actually produced this list. A pinned run skips + // recon-based selection by design, and reporting it as "matching recon" + // told the operator the surface had been consulted when it had not. let _ = tx - .send(format!("intelligently selected {} agent(s) matching recon: {}", selected.len(), - selected.iter().map(|a| a.name.clone()).collect::>().join(", "))) + .send(format!( + "{} {} agent(s): {}", + if cfg.pinned.is_empty() { "intelligently selected" } else { "running operator-pinned" }, + selected.len(), + selected.iter().map(|a| a.name.clone()).collect::>().join(", ") + )) .await; // ---- 3. Exploit (parallel) ----------------------------------------- @@ -2791,7 +2851,7 @@ pub async fn run(mut cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sender match pool.complete_routed(Task::Exploit, &ag.name, &system_eff, &user).await { Ok((m, text)) => { let mut f = extract_findings(&text, &ag.name); - if f.is_empty() && looks_like_tool_call(&text) { + if f.is_empty() && (looks_like_tool_call(&text) || looks_like_reasoning_only(&text)) { f = recover_findings(pool, &ag.name, &text, &target, &tool_rc, &txc).await; } // Agents pick their own ids ("F1"), which collide across @@ -3814,7 +3874,7 @@ pub async fn run_greybox(cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Se ); match pool.complete_routed(Task::Exploit, &ag.name, &ag.system, &user).await { Ok((m, text)) => { let mut f = extract_findings(&text, &ag.name); - if f.is_empty() && looks_like_tool_call(&text) { + if f.is_empty() && (looks_like_tool_call(&text) || looks_like_reasoning_only(&text)) { f = recover_findings(pool, &ag.name, &text, &target, &tool_rc, &txc).await; } let _ = txc.send(format!("exploit {} via {} → {} candidate(s)", ag.name, m.label(), f.len())).await; @@ -4784,7 +4844,11 @@ pub(crate) fn parse_string_array(text: &str) -> Vec { /// Recon-driven agent selection with negative filtering. Scores each agent by /// how well its preconditions match the observed attack surface, penalizes /// agents for technologies NOT present, and caps output to `cap`. -fn heuristic_select(ranked: &[Agent], recon: &str, focus: &str, cap: usize) -> Vec { +/// Score every agent in `ranked` against what the recon actually found, best +/// first. Positive means the recon supports running it; zero or less means the +/// recon gives no reason to, or actively argues against it (a PHP agent on a +/// target with no PHP anywhere in it). +fn heuristic_scores<'a>(ranked: &'a [Agent], recon: &str, focus: &str) -> Vec<(i32, &'a Agent)> { let r = recon.to_lowercase(); let f = focus.to_lowercase(); @@ -4811,8 +4875,19 @@ fn heuristic_select(ranked: &[Agent], recon: &str, focus: &str, cap: usize) -> V || r.contains("single-page") || r.contains("spa"); let has_php = r.contains("php") || r.contains(".php") || r.contains("laravel") || r.contains("wordpress") || r.contains("drupal"); - let has_java = r.contains("java") || r.contains("spring") || r.contains("tomcat") - || r.contains("struts") || r.contains(".jsp"); + // "javascript" contains "java". Matching it raw made every page with a + // script tag look like a JVM service, so the "no Java here" exclusion never + // fired and JVM-only agents kept winning slots on targets with no Java. + let r_nojs = r.replace("javascript", ""); + let has_java = r_nojs.contains("java") + || r_nojs.contains("spring") + || r_nojs.contains("tomcat") + || r_nojs.contains("struts") + || r_nojs.contains("jboss") + || r_nojs.contains("jetty") + || r_nojs.contains("weblogic") + || r_nojs.contains("jsessionid") + || r_nojs.contains(".jsp"); let has_dotnet = r.contains(".net") || r.contains("aspnet") || r.contains("asp.net") || r.contains(".aspx") || r.contains("iis"); let has_python = r.contains("python") || r.contains("django") || r.contains("flask") @@ -4829,8 +4904,19 @@ fn heuristic_select(ranked: &[Agent], recon: &str, focus: &str, cap: usize) -> V let has_db_direct = r.contains(":5432") || r.contains(":3306") || r.contains(":1433") || r.contains(":27017") || r.contains(":6379") || r.contains("postgres") || r.contains("mysql") || r.contains("redis") || r.contains("mongo"); - let has_ai = r.contains("openai") || r.contains("llm") || r.contains("chatbot") - || r.contains("ai") || r.contains("prompt") || r.contains("vector"); + // Not a bare "ai": it is inside "domain" and "mail", which appear in every + // recon, so the LLM-agent exclusion below could never fire. + let has_ai = r.contains("openai") + || r.contains("anthropic") + || r.contains("llm") + || r.contains("chatbot") + || r.contains("copilot") + || r.contains("langchain") + || r.contains("huggingface") + || r.contains("bedrock") + || r.contains("embedding") + || r.contains("prompt") + || r.contains("vector"); let has_cors = r.contains("cors") || r.contains("access-control-allow"); let has_template = r.contains("template") || r.contains("jinja") || r.contains("twig") || r.contains("mustache") || r.contains("handlebars"); @@ -4914,7 +5000,10 @@ fn heuristic_select(ranked: &[Agent], recon: &str, focus: &str, cap: usize) -> V (&["websocket"], has_websocket), (&["file_upload", "zip_slip"], has_upload), (&["lfi", "rfi", "php"], has_php), - (&["deserial", "struts", "spring"], has_java), + // `java4shell`/`log4shell`/`jndi` name a JVM bug class. Without a Java + // fingerprint anywhere in the recon there is nothing for them to hit, + // and they were outscoring agents that matched the real surface. + (&["deserial", "struts", "spring", "java", "log4shell", "jndi", "jsp", "tomcat"], has_java), (&["aspnet", "deserial"], has_dotnet), (&["ssti", "flask", "django", "fastapi"], has_python), (&["express", "prototype_pollution"], has_node), @@ -5044,6 +5133,11 @@ fn heuristic_select(ranked: &[Agent], recon: &str, focus: &str, cap: usize) -> V }) .collect(); scored.sort_by_key(|x| std::cmp::Reverse(x.0)); + scored +} + +fn heuristic_select(ranked: &[Agent], recon: &str, focus: &str, cap: usize) -> Vec { + let scored = heuristic_scores(ranked, recon, focus); // Only keep agents with positive score — negative means recon actively excluded them let mut out: Vec = scored.iter().filter(|(s, _)| *s > 0).map(|(_, a)| (*a).clone()).collect(); if out.is_empty() { @@ -5052,6 +5146,25 @@ fn heuristic_select(ranked: &[Agent], recon: &str, focus: &str, cap: usize) -> V out.into_iter().take(cap).collect() } +/// Cut a pinned set down to `cap` by recon fit instead of by list order. +/// +/// When the operator pins more agents than `--max-agents` allows, *which* ones +/// survive is the whole decision: truncating the list picks by catalogue +/// position, so an agent for a stack the target does not run can take a slot +/// while every agent that matches the recon is dropped. Rank by the same signal +/// the auto-selector uses, and keep the top of it. +/// +/// Returns the agents to run, and the names among them the recon gives no +/// support for — those still run, because the operator asked for them by name, +/// but the operator is told. +fn rank_pinned(sel: &[Agent], recon: &str, focus: &str, cap: usize) -> (Vec, Vec) { + let scored = heuristic_scores(sel, recon, focus); + let head: Vec<(i32, &Agent)> = scored.into_iter().take(cap).collect(); + let unsupported: Vec = + head.iter().filter(|(s, _)| *s <= 0).map(|(_, a)| a.name.clone()).collect(); + (head.into_iter().map(|(_, a)| a.clone()).collect(), unsupported) +} + async fn validate(cfg: Option<&RunConfig>, candidates: Vec, pool: &ModelPool, sys: &str, vote_n: usize, tx: &Sender) -> Vec { validate_with_persist(cfg, candidates, pool, sys, vote_n, tx, None).await } @@ -5118,7 +5231,8 @@ async fn validate_with_persist(cfg: Option<&RunConfig>, candidates: Vec "Finding: {} | severity {} | {} | at {} | payload {} | evidence {} | impact {}", f.title, f.severity, f.cwe, f.endpoint, f.payload, f.evidence, f.impact ); - let (yes, total) = pool.vote(sys, &q, vote_n, finder.as_deref()).await; + let tally = pool.vote_detail(sys, &q, vote_n, finder.as_deref()).await; + let (yes, total) = (tally.confirmed, tally.total()); f.validated = crate::pool::quorum_confirmed(&f.severity, yes, total); f.votes = format!("{yes}/{total}"); if f.confidence == 0.0 && total > 0 { @@ -5132,6 +5246,17 @@ async fn validate_with_persist(cfg: Option<&RunConfig>, candidates: Vec if f.validation_level.is_empty() || f.validation_level == "source-detection" { f.validation_level = "ai-consensus".into(); } + } else if tally.no_verdict() { + // Models answered and none gave a verdict — prose, or + // reasoning that never reached a conclusion. That is a + // validator failure, not a judgement on the finding, and + // calling it a rejection buries the candidate under a + // verdict nobody reached. + f.review_status = "needs-review".into(); + f.review_reason = format!( + "validator gave no readable verdict ({}/{total} answered without one)", + tally.unclear + ); } else if yes >= 1 || total == 0 { f.review_status = "needs-review".into(); f.review_reason = if total == 0 { "validator unavailable".into() } @@ -5191,7 +5316,10 @@ async fn validate_with_persist(cfg: Option<&RunConfig>, candidates: Vec f.repro_steps = vec![format!("curl -i -s '{}' # inspect the response (status + headers + body) that proves this finding", f.endpoint)]; } let label = if f.validated { "CONFIRMED" } else if f.review_status == "needs-review" { "needs-review" } else { "rejected" }; - let _ = txc.send(format!("vote {} → {} ({})", f.title, label, f.votes)).await; + // `0/1` reads as "the validator said no". Say so when it did not + // say anything the harness could read. + let why = if tally.no_verdict() { " — validator gave no verdict" } else { "" }; + let _ = txc.send(format!("vote {} → {} ({}){why}", f.title, label, f.votes)).await; f } }) @@ -7128,18 +7256,6 @@ async fn merge_grey_zone_dupes(findings: Vec, tx: &Sender) -> V kept } -/// Apply `--max-agents` to an explicitly pinned set. Returns how many were -/// dropped, so a pinned re-test still respects the operator's cost cap. -fn cap_pinned(agents: &mut Vec, max: usize) -> usize { - if max > 0 && agents.len() > max { - let dropped = agents.len() - max; - agents.truncate(max); - dropped - } else { - 0 - } -} - /// An "unauthenticated admin access" claim — the family that produced ten /// near-identical findings for one `/admin` redirect/SPA response. fn admin_access_claim(f: &Finding) -> bool { @@ -8250,6 +8366,39 @@ async fn kali_provision_recon_tools(sb: &crate::sandbox::Sandbox, tx: &Sender/dev/null; true").await; } + + // Every install above ends in `2>/dev/null; true`, so none of them can fail + // loudly. That made "📦 provisioning Kali recon tools: …" a promise with no + // result attached: a run could print it, install nothing, and then spend its + // tool rounds rediscovering that the tools were missing. Check what actually + // landed and say so. + let after = sb + .exec(&format!( + "for t in {}; do command -v $t >/dev/null 2>&1 || echo $t; done", + missing.join(" ") + )) + .await; + let still_missing: Vec = match after { + Ok(o) => o.stdout.lines().map(|l| l.trim().to_string()).filter(|l| !l.is_empty()).collect(), + // The check itself failed — say that rather than imply success. + Err(e) => { + let _ = tx.send(format!("⚠ could not verify the Kali toolbox install: {e}")).await; + return; + } + }; + let installed = missing.len() - still_missing.len(); + if still_missing.is_empty() { + let _ = tx.send(format!("📦 provisioned {installed} Kali recon tool(s)")).await; + } else { + let _ = tx + .send(format!( + "⚠ provisioned {installed} of {} Kali recon tool(s) — still missing: {}. \ + Tool-recon will run with what is present.", + missing.len(), + still_missing.join(", ") + )) + .await; + } } /// One host's tool-recon result. Kept per host so every URL, endpoint and form @@ -8578,7 +8727,7 @@ async fn agent_tool_round( ); let run_cfg = crate::toolbox::ToolRunConfig { sandbox: cfg.sandbox.clone(), - provision: std::env::var("NEUROSPLOIT_PROVISION").ok().as_deref() == Some("1"), + provision: provision_allowed(cfg), timeout_secs: Some(180), audit_dir: cfg.workdir.as_ref().map(|w| std::path::PathBuf::from(w).join("toolbox")), scope: Some(effective_scope(cfg)), @@ -9480,21 +9629,115 @@ mod ops_wiring_tests { "CSRF-Disabled plugins/docker/views.py:95"); } + /// The `cleartext_transmission` reply from the evidelo run, verbatim in + /// shape: the model thought about running curl and stopped. It carried no + /// tool-call markup, so recovery never fired and the turn was dropped with + /// "model may have produced malformed JSON". #[test] - fn pinned_agents_are_capped_by_max_agents() { - let a = |n: &str| Agent { + fn a_reply_that_is_only_thinking_is_recognised_not_called_malformed() { + let reply = "\nwith HTTP downgrade and HSTS. Use curl; target is in scope. \ + Need verify with real responses. Let's inspect HTTP and HTTPS headers.\n\ + \n\n\nRun curl for HTTP and HTTPS headers.\n"; + assert!(looks_like_reasoning_only(reply)); + assert!(!looks_like_tool_call(reply), "it carries no tool-call markup — that was the gap"); + assert!(extract_findings(reply, "cleartext_transmission").is_empty()); + } + + #[test] + fn thinking_followed_by_an_answer_is_not_reasoning_only() { + let reply = "let me check the header\n\ + [{\"title\":\"Missing HSTS\",\"severity\":\"Low\"}]"; + assert!(!looks_like_reasoning_only(reply)); + let f = extract_findings(reply, "security_headers"); + assert_eq!(f.len(), 1); + assert_eq!(f[0].title, "Missing HSTS"); + } + + #[test] + fn a_plain_reply_with_no_reasoning_block_is_not_reasoning_only() { + assert!(!looks_like_reasoning_only("[]")); + assert!(!looks_like_reasoning_only("I could not reach the target.")); + } + + /// A one-model panel that answers with prose produced `0/1`, which the + /// pipeline read as a rejection. The two have to stay apart. + #[test] + fn a_panel_that_gave_no_verdict_is_not_a_rejection() { + use crate::pool::VoteTally; + let silent = VoteTally { confirmed: 0, rejected: 0, unclear: 1 }; + assert!(silent.no_verdict()); + assert_eq!(silent.total(), 1); + + let said_no = VoteTally { confirmed: 0, rejected: 1, unclear: 0 }; + assert!(!said_no.no_verdict(), "an explicit rejection is a verdict"); + + let nobody_answered = VoteTally::default(); + assert!(!nobody_answered.no_verdict(), "an empty panel is 'unavailable', handled separately"); + } + + fn test_agent(n: &str) -> Agent { + Agent { name: n.into(), title: String::new(), cwe: String::new(), kind: "vuln".into(), system: String::new(), user: String::new(), - }; - let mut v = vec![a("a"), a("b"), a("c"), a("d")]; - assert_eq!(cap_pinned(&mut v, 2), 2); - assert_eq!(v.len(), 2); - assert_eq!(cap_pinned(&mut v, 0), 0); - assert_eq!(v.len(), 2); + } + } + + /// The evidelo run: 232 agents pinned, `--max-agents 3`, and the three that + /// ran were a Java RCE detector, a PHP webshell exploit and a cleartext + /// check — on a Cloudflare-fronted JS site with no Java and no PHP on it. + /// Truncating the pinned list picked by catalogue position; ranking picks by + /// what the recon found. + #[test] + fn pinned_cap_keeps_the_agents_the_recon_supports() { + let recon = "GET https://www.evidelo.com.br/ -> HTTP 200 server: cloudflare; \ + content-security-policy: script-src 'self' 'unsafe-inline'; \ + 12 script(s), react bundle, /api/ endpoints, /robots.txt discloses /admin"; + let pinned = vec![ + test_agent("java4shell_detect"), + test_agent("php2shell_exploit"), + test_agent("cleartext_transmission"), + test_agent("xss_dom"), + test_agent("cors_misconfig"), + test_agent("idor"), + ]; + let (kept, unsupported) = rank_pinned(&pinned, recon, "", 3); + let names: Vec<&str> = kept.iter().map(|a| a.name.as_str()).collect(); + + assert_eq!(kept.len(), 3, "the cap is still honoured"); + assert!(!names.contains(&"java4shell_detect"), "no Java fingerprint: {names:?}"); + assert!(!names.contains(&"php2shell_exploit"), "no PHP fingerprint: {names:?}"); + assert!( + names.contains(&"xss_dom") || names.contains(&"cors_misconfig") || names.contains(&"idor"), + "the slots go to agents the recon supports: {names:?}" + ); + assert!(unsupported.is_empty(), "every kept agent has recon support: {unsupported:?}"); + } + + /// "javascript" contains "java". Before the fix this made every page with a + /// script tag read as a JVM service, which is what let the Java agent in. + #[test] + fn javascript_is_not_a_java_fingerprint() { + let pinned = vec![test_agent("java4shell_detect"), test_agent("security_headers")]; + let (kept, _) = rank_pinned(&pinned, "12 javascript bundle(s), application/javascript", "", 1); + assert_eq!(kept[0].name, "security_headers"); + + // A real Java fingerprint still selects it. + let (kept, _) = rank_pinned(&pinned, "Set-Cookie: JSESSIONID=..; x-powered-by: Servlet", "", 1); + assert_eq!(kept[0].name, "java4shell_detect"); + } + + /// A pinned agent with no recon support still runs — the operator named it — + /// but it comes back in `unsupported` so the operator is told. + #[test] + fn pinned_without_recon_support_still_runs_but_is_reported() { + let pinned = vec![test_agent("java4shell_detect"), test_agent("php2shell_exploit")]; + let (kept, unsupported) = rank_pinned(&pinned, "server: cloudflare, static html", "", 2); + assert_eq!(kept.len(), 2); + assert_eq!(unsupported.len(), 2, "both are reported as unsupported: {unsupported:?}"); } #[test] diff --git a/neurosploit-rs/crates/harness/src/pool.rs b/neurosploit-rs/crates/harness/src/pool.rs index 6307667..fc026f1 100644 --- a/neurosploit-rs/crates/harness/src/pool.rs +++ b/neurosploit-rs/crates/harness/src/pool.rs @@ -596,7 +596,14 @@ impl ModelPool { out } - pub async fn vote(&self, system: &str, user: &str, n: usize, skip: Option<&str>) -> (usize, usize) { + /// Run the panel and keep the three answers apart. + pub async fn vote_detail( + &self, + system: &str, + user: &str, + n: usize, + skip: Option<&str>, + ) -> VoteTally { let mut ordered: Vec = self.candidates.clone(); if let Some(finder) = skip { if ordered.len() > 1 { @@ -604,21 +611,51 @@ impl ModelPool { } } let panel = self.build_panel(ordered, n.max(1)); - let mut confirmed = 0usize; - let mut total = 0usize; + let mut tally = VoteTally::default(); for m in &panel { let _permit = match self.sem.acquire().await { Ok(p) => p, Err(_) => break, }; if let Ok(text) = self.one("validate", m, system, user).await { - total += 1; - if parse_verdict(&text) == Verdict::Confirmed { - confirmed += 1; + match parse_verdict(&text) { + Verdict::Confirmed => tally.confirmed += 1, + Verdict::Rejected => tally.rejected += 1, + Verdict::Unclear => tally.unclear += 1, } } } - (confirmed, total) + tally + } + + pub async fn vote(&self, system: &str, user: &str, n: usize, skip: Option<&str>) -> (usize, usize) { + let t = self.vote_detail(system, user, n, skip).await; + (t.confirmed, t.total()) + } +} + +/// What a validation panel actually said. +/// +/// A model that answers with prose, or with reasoning it never closed, produces +/// `Unclear` — which is not the same as a model that read the evidence and said +/// no. Collapsing them into `(confirmed, total)` made both arrive at the caller +/// as `0/1`, so a panel that simply failed to answer was reported to the +/// operator as a rejection. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct VoteTally { + pub confirmed: usize, + pub rejected: usize, + pub unclear: usize, +} + +impl VoteTally { + pub fn total(&self) -> usize { + self.confirmed + self.rejected + self.unclear + } + + /// Models answered, and not one of them gave a readable verdict. + pub fn no_verdict(&self) -> bool { + self.total() > 0 && self.confirmed == 0 && self.rejected == 0 } }