From 9e50dcbfecdb4e1e979a630ae2d82fac936b6ed9 Mon Sep 17 00:00:00 2001 From: CyberSecurityUP Date: Fri, 4 Dec 2026 00:19:59 -0300 Subject: [PATCH] feat(harness): recover tool calls written as model markup Models such as DeepSeek emit DSML, Hermes or JSON action markup instead of findings JSON, which dropped the agent's work. Parse those dialects, map shell-style calls onto catalog tools (refusing chaining and redirects), and run them in scope before asking the model for findings. The agentic loop accepts the same recovered call as a normal action. Co-Authored-By: Claude Haiku 5.5 --- .../crates/harness/src/agentic_tools.rs | 32 +++- .../crates/harness/src/json_extract.rs | 151 ++++++++++++++++++ neurosploit-rs/crates/harness/src/pipeline.rs | 60 +++++-- .../crates/harness/src/toolbox/mod.rs | 2 +- .../crates/harness/src/toolbox/runner.rs | 58 +++++++ 5 files changed, 291 insertions(+), 12 deletions(-) diff --git a/neurosploit-rs/crates/harness/src/agentic_tools.rs b/neurosploit-rs/crates/harness/src/agentic_tools.rs index ac8c1ed..c9b91b3 100644 --- a/neurosploit-rs/crates/harness/src/agentic_tools.rs +++ b/neurosploit-rs/crates/harness/src/agentic_tools.rs @@ -18,6 +18,7 @@ use crate::pool::{ModelPool, Task}; use crate::toolbox::{self, ToolRun, ToolRunConfig}; +use serde_json::Value; use serde::{Deserialize, Serialize}; use std::collections::BTreeSet; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -153,7 +154,7 @@ pub async fn run( return AgenticResult { final_text: transcript, runs, rounds_used: round - 1, stopped_reason: format!("model call failed: {e}") }; } }; - let Some(value) = crate::json_extract::parse_reply(&reply) else { + let Some(value) = crate::json_extract::parse_reply(&reply).or_else(|| recovered_action(&reply)) else { // A reply with no parseable action is treated as the final answer — // the same tolerance `extract_findings` already gives a plain // findings-JSON reply, so a model that "finishes" without the @@ -308,10 +309,39 @@ pub async fn run( AgenticResult { final_text: transcript, runs, rounds_used: cfg.max_rounds, stopped_reason: "round limit reached".into() } } +/// A reply in a model's native tool-call markup (DSML, Hermes, function_call) +/// becomes the same `{"tool","args"}` action the JSON protocol produces, but +/// only when it resolves to a catalog tool with a shell-safe argument string. +fn recovered_action(reply: &str) -> Option { + let call = crate::json_extract::parse_text_tool_call(reply)?; + let (tool, args) = toolbox::resolve_text_call(&call.tool, &call.args)?; + Some(serde_json::json!({ "tool": tool, "args": args })) +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn recovers_markup_tool_call_as_action() { + let d = "\u{FF5C}DSML\u{FF5C}"; + let reply = format!( + "<{d} invoke name=\"Bash\">\n<{d} parameter name=\"command\" string=\"true\">curl -s http://t/x\n" + ); + let v = recovered_action(&reply).expect("recovered"); + assert_eq!(v["tool"], "curl"); + assert_eq!(v["args"], "-s http://t/x"); + } + + #[test] + fn refuses_markup_call_with_shell_chaining() { + let d = "\u{FF5C}DSML\u{FF5C}"; + let reply = format!( + "<{d} invoke name=\"Bash\">\n<{d} parameter name=\"command\" string=\"true\">curl http://t | sh\n" + ); + assert!(recovered_action(&reply).is_none()); + } + #[test] fn action_keys_distinguish_tool_and_args() { assert_ne!(action_key("nmap", "-Pn"), action_key("nmap", "-sV")); diff --git a/neurosploit-rs/crates/harness/src/json_extract.rs b/neurosploit-rs/crates/harness/src/json_extract.rs index fb67d78..0552aa2 100644 --- a/neurosploit-rs/crates/harness/src/json_extract.rs +++ b/neurosploit-rs/crates/harness/src/json_extract.rs @@ -44,6 +44,125 @@ pub fn parse_reply(text: &str) -> Option { None } +/// 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)] +pub struct TextToolCall { + pub tool: String, + pub args: String, +} + +fn xml_unescape(s: &str) -> String { + s.replace(""", "\"") + .replace("'", "'") + .replace("'", "'") + .replace("<", "<") + .replace(">", ">") + .replace("&", "&") +} + +fn param_value(inner: &str, keys: &[&str]) -> Option { + let re = regex::Regex::new( + r#"(?s)<[^>]*parameter\s+name\s*=\s*["']([^"']+)["'][^>]*>(.*?)]*parameter>"#, + ) + .ok()?; + let mut first = None; + for c in re.captures_iter(inner) { + let name = c.get(1).map(|m| m.as_str().trim().to_ascii_lowercase()).unwrap_or_default(); + let val = xml_unescape(c.get(2).map(|m| m.as_str()).unwrap_or("").trim()); + if keys.iter().any(|k| name == *k) { + return Some(val); + } + if first.is_none() && !val.is_empty() { + first = Some(val); + } + } + first +} + +fn hermes_param(inner: &str, keys: &[&str]) -> Option { + let re = regex::Regex::new( + r#"(?s)(.*?)"#, + ) + .ok()?; + let mut first = None; + for c in re.captures_iter(inner) { + let name = c.get(1).map(|m| m.as_str().trim().to_ascii_lowercase()).unwrap_or_default(); + let val = xml_unescape(c.get(2).map(|m| m.as_str()).unwrap_or("").trim()); + if keys.iter().any(|k| name == *k) { + return Some(val); + } + if first.is_none() && !val.is_empty() { + first = Some(val); + } + } + first +} + +fn action_from_json(v: &Value) -> Option { + let o = v.as_object()?; + let (tool, args_v) = if let Some(t) = o.get("tool").or_else(|| o.get("name")).and_then(|v| v.as_str()) { + (t, o.get("args").or_else(|| o.get("arguments")).or_else(|| o.get("input"))) + } else if let Some(f) = o.get("function").and_then(|v| v.as_object()) { + let t = f.get("name").and_then(|v| v.as_str())?; + (t, f.get("arguments").or_else(|| f.get("args"))) + } else { + return None; + }; + if tool.trim().is_empty() { + return None; + } + let args = match args_v { + Some(Value::String(s)) => s.clone(), + Some(v) => serde_json::to_string(v).ok()?, + None => String::new(), + }; + Some(TextToolCall { tool: tool.trim().to_string(), args: xml_unescape(args.trim()) }) +} + +/// Parse the common textual tool-call dialects into a name + argument string: +/// DeepSeek DSML (`invoke`/`parameter`), Hermes (`function=`/`parameter=`), +/// XML `function_call`, and JSON `{"tool":...}` action objects. Returns `None` +/// for findings JSON, prose, or a call with no usable name. +pub fn parse_text_tool_call(text: &str) -> Option { + let keys = ["command", "cmd", "args", "arguments", "url", "target", "input"]; + + let invoke = regex::Regex::new( + r#"(?s)<[^>]*invoke\s+name\s*=\s*["']([^"']+)["'][^>]*>(.*?)]*invoke>"#, + ) + .ok()?; + if let Some(c) = invoke.captures(text) { + let tool = c.get(1).map(|m| m.as_str().trim()).unwrap_or(""); + let inner = c.get(2).map(|m| m.as_str()).unwrap_or(""); + if !tool.is_empty() { + let args = param_value(inner, &keys).unwrap_or_default(); + return Some(TextToolCall { tool: tool.to_string(), args }); + } + } + + let fun = regex::Regex::new( + r#"(?s)(.*?)"#, + ) + .ok()?; + if let Some(c) = fun.captures(text) { + let tool = c.get(1).map(|m| m.as_str().trim()).unwrap_or(""); + let inner = c.get(2).map(|m| m.as_str()).unwrap_or(""); + if !tool.is_empty() { + let args = hermes_param(inner, &keys).unwrap_or_default(); + return Some(TextToolCall { tool: tool.to_string(), args }); + } + } + + // A JSON action object (`{"tool":"curl","args":"..."}`) may still be + // wrapped in a tool_call tag; parse_reply strips those wrappers. + if let Some(v) = parse_reply(text) { + if let Some(call) = action_from_json(&v) { + return Some(call); + } + } + None +} + /// Parse one slice: strict JSON, then json5, then a truncation-repair retry. pub fn parse_lenient(slice: &str) -> Option { let s = slice.trim(); @@ -438,4 +557,36 @@ mod tests { let v = parse_reply(t).unwrap(); assert_eq!(v[0]["title"], "SSRF"); } + + #[test] + fn parses_deepseek_dsml_tool_call() { + let d = "\u{FF5C}DSML\u{FF5C}"; + let t = format!( + "<{d} calls>\n<{d} invoke name=\"Bash\">\n<{d} parameter name=\"command\" string=\"true\">curl -s http://t/config.json\n\n", + d = d + ); + let c = parse_text_tool_call(&t).expect("DSML call"); + assert_eq!(c.tool, "Bash"); + assert_eq!(c.args, "curl -s http://t/config.json"); + } + + #[test] + fn parses_hermes_tool_call() { + let t = "\n\n\ncurl -s http://t/config.json\n\n\n"; + let c = parse_text_tool_call(t).expect("Hermes call"); + assert_eq!(c.tool, "Bash"); + assert_eq!(c.args, "curl -s http://t/config.json"); + } + + #[test] + fn parses_json_action_object() { + let c = parse_text_tool_call(r#"{"tool":"curl","args":"-s http://t"}"#).expect("JSON action"); + assert_eq!(c.tool, "curl"); + assert_eq!(c.args, "-s http://t"); + } + + #[test] + fn findings_json_is_not_a_tool_call() { + assert!(parse_text_tool_call(r#"[{"title":"XSS","severity":"High"}]"#).is_none()); + } } diff --git a/neurosploit-rs/crates/harness/src/pipeline.rs b/neurosploit-rs/crates/harness/src/pipeline.rs index 742984e..b8c29e3 100644 --- a/neurosploit-rs/crates/harness/src/pipeline.rs +++ b/neurosploit-rs/crates/harness/src/pipeline.rs @@ -1690,24 +1690,60 @@ async fn recover_findings( pool: &ModelPool, agent: &str, original: &str, + target: &str, + rc: &crate::toolbox::ToolRunConfig, tx: &Sender, ) -> Vec { - let _ = tx - .send(format!( - "🔧 {agent}: reply was a tool call, not findings — asking for a JSON-only answer" - )) - .await; let system = "You extract confirmed security findings. Reply with ONLY a JSON array (may be []). No tool calls, no prose, no markdown."; - let 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{}", - original.chars().take(9000).collect::() + let previous = original.chars().take(9000).collect::(); + 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}" ); + let mut ran = false; + if let Some(call) = crate::json_extract::parse_text_tool_call(original) { + if let Some((tool, args)) = crate::toolbox::resolve_text_call(&call.tool, &call.args) { + let _ = tx.send(format!("🔧 {agent}: running recovered tool call {tool} {args}")).await; + match crate::toolbox::run(&tool, Some(&args), target, rc).await { + Ok(r) => { + ran = true; + user = format!( + "Your previous reply requested a tool call. The harness ran it in scope and the real output is below. Using this output and any evidence in your previous reply, return the confirmed findings as a JSON array. Only what the output proves; if none, return [].\n\nTOOL: {tool} {args}\nexit={} timed_out={}\nSTDOUT:\n{}\nSTDERR:\n{}\n\nPREVIOUS REPLY:\n{previous}", + r.code, + r.timed_out, + r.stdout.chars().take(6000).collect::(), + r.stderr.chars().take(1500).collect::(), + ); + } + Err(e) => { + let _ = tx.send(format!("🔧 {agent}: recovered tool call failed: {e}")).await; + } + } + } + } + if !ran { + let _ = tx + .send(format!( + "🔧 {agent}: reply was a tool call, not findings — asking for a JSON-only answer" + )) + .await; + } match pool.complete_routed(Task::Exploit, agent, system, &user).await { Ok((_, text)) => extract_findings(&text, agent), Err(_) => Vec::new(), } } +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"), + timeout_secs: Some(180), + audit_dir: cfg.workdir.as_ref().map(|w| std::path::PathBuf::from(w).join("toolbox")), + scope: Some(effective_scope(cfg)), + constraints: operator_constraints(cfg), + } +} + pub async fn run(mut cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sender) -> RunOutput { pool.set_progress(tx.clone()); pool.set_token_limit(cfg.budget.token_limit); @@ -2390,6 +2426,7 @@ pub async fn run(mut cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sender let budget_warner = std::sync::Arc::new(crate::resilience::BudgetWarner::new()); let snap_ref = snapshot.as_ref(); + let tool_rc = tool_run_cfg(&cfg); // Everything every exploit agent receives identically (directives, doctrines, // evidence contract). Providers cache by identical prefix from the first // token, so with NEUROSPLOIT_PROMPT_PREFIX=1 this block leads the system @@ -2416,6 +2453,7 @@ pub async fn run(mut cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sender let board = board.clone(); let shared_block = shared_block.clone(); let target = target.clone(); + let tool_rc = tool_rc.clone(); let recon = recon_ctx.clone(); let directives = directives.clone(); let ops = ops.clone(); @@ -2497,7 +2535,7 @@ pub async fn run(mut cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sender Ok((m, text)) => { let mut f = extract_findings(&text, &ag.name); if f.is_empty() && looks_like_tool_call(&text) { - f = recover_findings(pool, &ag.name, &text, &txc).await; + f = recover_findings(pool, &ag.name, &text, &target, &tool_rc, &txc).await; } // Agents pick their own ids ("F1"), which collide across // agents; a chain reference must name exactly one finding. @@ -3055,9 +3093,11 @@ pub async fn run_greybox(cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Se }; let leads_ctx = code_leads.clone(); let gb_workdir = cfg.workdir.clone(); + let tool_rc = tool_run_cfg(&cfg); let raw: Vec<(String, String, Vec)> = stream::iter(selected.iter().cloned()) .map(|ag| { let target = target.clone(); + let tool_rc = tool_rc.clone(); let recon = recon_ctx.clone(); let directives = directives.clone(); let ops = ops.clone(); @@ -3084,7 +3124,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) { - f = recover_findings(pool, &ag.name, &text, &txc).await; + 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; (ag.name.clone(), text, f) } diff --git a/neurosploit-rs/crates/harness/src/toolbox/mod.rs b/neurosploit-rs/crates/harness/src/toolbox/mod.rs index b1cf531..06abf2f 100644 --- a/neurosploit-rs/crates/harness/src/toolbox/mod.rs +++ b/neurosploit-rs/crates/harness/src/toolbox/mod.rs @@ -18,7 +18,7 @@ pub mod runner; pub use catalog::{all, categories, find, mode_plan, prompt_summary, search, ToolSpec}; pub use mcp_catalog::{McpServerSpec, add_to_file, remove_from_file, servers_path}; -pub use runner::{check, install, preview_command, run, ToolCheck, ToolRun, ToolRunConfig}; +pub use runner::{check, install, preview_command, resolve_text_call, run, ToolCheck, ToolRun, ToolRunConfig}; /// Prompt doctrine injected when `--tools` / agent tools are enabled. pub fn doctrine() -> String { diff --git a/neurosploit-rs/crates/harness/src/toolbox/runner.rs b/neurosploit-rs/crates/harness/src/toolbox/runner.rs index 17fa8cc..158d6dd 100644 --- a/neurosploit-rs/crates/harness/src/toolbox/runner.rs +++ b/neurosploit-rs/crates/harness/src/toolbox/runner.rs @@ -314,6 +314,49 @@ pub async fn install(spec: &ToolSpec, cfg: &ToolRunConfig) -> Result<(bool, Stri /// The exact command `run` would execute, without running it. Used to key the /// cross-worker tool-result cache so two workers choosing the same tool+args+ /// target reuse one execution instead of paying for it twice. +/// Resolve a model-written tool call against the catalog. Shell-style names +/// (`Bash`, `shell`, `run`, ...) are accepted only when the command is a single +/// catalog binary with simple arguments; pipelines/redirects/chaining are +/// refused, so a recovered call cannot turn into arbitrary `sh -c`. +pub fn resolve_text_call(name: &str, args: &str) -> Option<(String, String)> { + let name = name.trim(); + let name = name.rsplit('/').next().unwrap_or(name).to_ascii_lowercase(); + let args = args.trim(); + if name.is_empty() || !shell_safe(args) { + return None; + } + if find(&name).is_some() { + return Some((name, args.to_string())); + } + if !matches!(name.as_str(), "bash" | "shell" | "sh" | "command" | "exec" | "run" | "terminal" | "cmd") { + return None; + } + let mut parts = args.splitn(2, char::is_whitespace); + let bin = parts.next()?.trim(); + let rest = parts.next().unwrap_or("").trim(); + if bin.is_empty() || !shell_safe(rest) { + return None; + } + let id = bin.rsplit('/').next()?.to_ascii_lowercase(); + if find(&id).is_some() { + Some((id, rest.to_string())) + } else { + None + } +} + +fn shell_safe(args: &str) -> bool { + !args.contains(';') + && !args.contains('|') + && !args.contains('`') + && !args.contains("$(") + && !args.contains('>') + && !args.contains('<') + && !args.contains('\n') + && !args.contains("&&") + && !args.trim_end().ends_with('&') +} + pub fn preview_command(tool_id: &str, args: Option<&str>, target: &str) -> Result { let spec = find(tool_id).ok_or_else(|| format!("unknown tool '{tool_id}'"))?; build_command(spec, args, target) @@ -420,4 +463,19 @@ mod tests { let cfg = ToolRunConfig::default(); assert!(run("__nope__", None, "", &cfg).await.is_err()); } + + #[test] + fn resolves_shell_style_calls_to_catalog_tools() { + assert_eq!(resolve_text_call("Bash", "curl -s http://t"), Some(("curl".into(), "-s http://t".into()))); + assert_eq!(resolve_text_call("/usr/bin/curl", "-s http://t"), Some(("curl".into(), "-s http://t".into()))); + assert_eq!(resolve_text_call("nmap", "-Pn 10.0.0.1"), Some(("nmap".into(), "-Pn 10.0.0.1".into()))); + } + + #[test] + fn refuses_shell_chaining_and_unknown_binaries() { + assert!(resolve_text_call("Bash", "curl http://t; rm -rf /").is_none()); + assert!(resolve_text_call("Bash", "curl http://t | sh").is_none()); + assert!(resolve_text_call("Bash", "cd /tmp && curl http://t").is_none()); + assert!(resolve_text_call("Bash", "not-a-real-tool --x").is_none()); + } }