fix: kill leaked recon pipelines, recover tool-call replies, Neo4j circuit-break

- host recon runs in its own process group and SIGKILLs the group on timeout (gau/katana no longer outlive the run)
- when an agent replies with tool-call markup instead of JSON, ask once for a JSON-only answer over the same evidence
- remember an unreachable Neo4j for the process so later graph phases skip it silently
- warn when many agents are pinned with --max-agents 0 and when vote-n exceeds distinct models
This commit is contained in:
CyberSecurityUP committed 2026-12-02 21:40:07 -03:00
1 parent 06c6497f54
commit de41c9769b
4 files changed
+190 -16

No files matched your search

+1
View File
@@ -965,6 +965,7 @@ dependencies = [
"futures",
"hmac",
"json5",
"libc",
"regex",
"reqwest",
"serde",
+3
View File
@@ -21,3 +21,6 @@ sha2 = "0.10"
hmac = "0.12"
base64 = "0.22"
regex = "1"
[target.'cfg(unix)'.dependencies]
libc = "0.2"
@@ -38,6 +38,19 @@ use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::fmt::Write as _;
use std::sync::atomic::{AtomicBool, Ordering};
/// Once Neo4j fails to answer, stop trying for the rest of the process: a lab
/// run without Neo4j should not print a connection error in every graph phase.
static NEO4J_DOWN: AtomicBool = AtomicBool::new(false);
pub fn neo4j_disabled() -> bool {
NEO4J_DOWN.load(Ordering::Relaxed)
}
pub fn mark_neo4j_down() {
NEO4J_DOWN.store(true, Ordering::Relaxed);
}
// ---------------------------------------------------------------------------
// Schema
@@ -2167,6 +2180,9 @@ impl Neo4j {
to_name: &str,
engagement: Option<&str>,
) -> Vec<Value> {
if neo4j_disabled() {
return Vec::new();
}
let eng_filter = if engagement.is_some() {
" WHERE ALL(n IN nodes(p) WHERE n.engagement = $engagement)"
} else {
@@ -2182,7 +2198,10 @@ impl Neo4j {
match self.query_rows(&cypher, params).await {
Ok(rows) => rows.into_iter().filter_map(|r| r.into_iter().next()).collect(),
Err(e) => {
eprintln!("[graph_memory] query_shortest_path error: {e}");
if !neo4j_disabled() {
eprintln!("[graph_memory] query_shortest_path error: {e}");
mark_neo4j_down();
}
vec![]
}
}
@@ -2190,6 +2209,9 @@ impl Neo4j {
/// Query Neo4j for all owned nodes (confirmed footholds).
pub async fn query_owned_nodes(&self, engagement: Option<&str>) -> Vec<Value> {
if neo4j_disabled() {
return Vec::new();
}
let cypher = if engagement.is_some() {
"MATCH (n) WHERE n.status = 'owned' AND n.engagement = $engagement \
RETURN n.name AS name, labels(n)[0] AS label, n.address AS address LIMIT 50"
@@ -2207,7 +2229,10 @@ impl Neo4j {
Value::Object(obj)
}).collect(),
Err(e) => {
eprintln!("[graph_memory] query_owned_nodes error: {e}");
if !neo4j_disabled() {
eprintln!("[graph_memory] query_owned_nodes error: {e}");
mark_neo4j_down();
}
vec![]
}
}
@@ -2274,6 +2299,9 @@ impl Neo4j {
/// Query Neo4j for suggested next moves: edges from owned nodes to unowned targets.
pub async fn query_next_moves(&self, engagement: Option<&str>) -> Vec<Value> {
if neo4j_disabled() {
return Vec::new();
}
let cypher = if engagement.is_some() {
"MATCH (a)-[r]->(b) WHERE a.status = 'owned' AND (b.status IS NULL OR b.status <> 'owned') \
AND a.engagement = $engagement \
@@ -2294,7 +2322,10 @@ impl Neo4j {
Value::Object(obj)
}).collect(),
Err(e) => {
eprintln!("[graph_memory] query_next_moves error: {e}");
if !neo4j_disabled() {
eprintln!("[graph_memory] query_next_moves error: {e}");
mark_neo4j_down();
}
vec![]
}
}
+152 -13
View File
@@ -1645,6 +1645,42 @@ fn record_ad_receipts(workdir: Option<&str>, raw: &[(String, String, Vec<Finding
crate::ad_recipe::record(workdir, &receipts)
}
/// Does this reply consist of tool-call markup rather than findings JSON?
fn looks_like_tool_call(text: &str) -> bool {
let t = text.to_ascii_lowercase();
[
"<tool_call", "<tool_calls", "<invoke", "<parameter", "<function_call",
"<action", "<command", "<tool_code", "<tool_req", "dsml",
]
.iter()
.any(|m| t.contains(m))
}
/// 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.
async fn recover_findings(
pool: &ModelPool,
agent: &str,
original: &str,
tx: &Sender<String>,
) -> Vec<Finding> {
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::<String>()
);
match pool.complete_routed(Task::Exploit, agent, system, &user).await {
Ok((_, text)) => extract_findings(&text, agent),
Err(_) => Vec::new(),
}
}
pub async fn run(mut cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sender<String>) -> RunOutput {
pool.set_progress(tx.clone());
pool.set_token_limit(cfg.budget.token_limit);
@@ -1659,6 +1695,17 @@ pub async fn run(mut cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sender
cfg.objective = Some(DEFAULT_WEB_OBJECTIVE.to_string());
}
let distinct_models = cfg.models.iter().cloned().collect::<std::collections::BTreeSet<_>>().len();
if distinct_models > 0 && effective_vote_n(&cfg) > distinct_models {
let _ = tx
.send(format!(
"⚠ vote-n={} but only {} distinct model(s) configured — validation votes are not independent",
effective_vote_n(&cfg),
distinct_models
))
.await;
}
// Authorization first. A supplied token that does not verify ends the run
// here: proceeding would mean acting on a grant nobody can prove was
// issued, which is the one failure this whole layer exists to prevent.
@@ -2235,6 +2282,14 @@ pub async fn run(mut cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sender
if cfg.pinned.is_empty() && crate::teamboard::enabled() {
crate::teamboard::discovery_first(&mut selected);
}
if !cfg.pinned.is_empty() && cfg.max_agents == 0 && selected.len() > 30 {
let _ = tx
.send(format!(
"⚠ {} agent(s) pinned and --max-agents is 0 (all run) — set --max-agents to cap cost/time",
selected.len()
))
.await;
}
let _ = tx
.send(format!("intelligently selected {} agent(s) matching recon: {}", selected.len(),
selected.iter().map(|a| a.name.clone()).collect::<Vec<_>>().join(", ")))
@@ -2389,6 +2444,9 @@ 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) {
f = recover_findings(pool, &ag.name, &text, &txc).await;
}
// Agents pick their own ids ("F1"), which collide across
// agents; a chain reference must name exactly one finding.
for c in f.iter_mut() {
@@ -2972,7 +3030,10 @@ pub async fn run_greybox(cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Se
body = ag.user.replace("{target}", &target).replace("{recon_json}", &recon),
);
match pool.complete_routed(Task::Exploit, &ag.name, &ag.system, &user).await {
Ok((m, text)) => { let f = extract_findings(&text, &ag.name);
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;
}
let _ = txc.send(format!("exploit {} via {} → {} candidate(s)", ag.name, m.label(), f.len())).await;
(ag.name.clone(), text, f) }
Err(e) => {
@@ -3144,15 +3205,23 @@ async fn graph_checkpoint(
if let Some(d) = cfg.workdir.as_deref() {
let _ = crate::dual_build::update_and_save(&Path::new(d).join("graphs"), &cfg.target, recon, findings, &in_scope);
}
let neo = gm::Neo4j::resolve(cfg.neo4j.as_deref());
let mut neo = if gm::neo4j_disabled() {
None
} else {
gm::Neo4j::resolve(cfg.neo4j.as_deref())
};
if let Some(n) = &neo {
match n.fetch_paths(&gb.target_id, 300).await {
Ok(remote) => gb.absorb(remote),
Err(e) => {
gm::mark_neo4j_down();
let _ = tx.send(format!("🕸 graph [{phase}]: neo4j read skipped ({e})")).await;
}
}
}
if gm::neo4j_disabled() {
neo = None;
}
let cs = gm::chains(&gb, 8, 30);
let moves = gm::next_moves(&gb, &cs, 10);
let todo = gm::todo(&gb, &cs);
@@ -3182,20 +3251,25 @@ async fn graph_checkpoint(
gm::record_paths(&mut pb, &cs, &rid);
match n.push_with_engagement(&pb, &rid, cfg.engagement.as_deref()).await {
Ok(_) => synced = " · neo4j synced".into(),
Err(e) => synced = format!(" · neo4j push skipped ({e})"),
Err(e) => {
gm::mark_neo4j_down();
synced = format!(" · neo4j push skipped ({e})");
}
}
// Exploration graph (assets + what was tried): push it and turn
// "untested assets next to a finding" into prompt leads for the agents.
if let Some(d) = cfg.workdir.as_deref() {
if let Ok(dg) = crate::exploration_graph::DualGraph::load(&Path::new(d).join("graphs")) {
match crate::neo4j_exploration::sync(n, &dg, &cfg.target, &rid).await {
Ok(leads) if !leads.is_empty() => {
let cur = gm::live_context(&rid);
gm::set_live_context(&rid, format!("{cur}{}", crate::neo4j_exploration::suggestion_block(&leads)));
synced.push_str(&format!(" · {} chain lead(s)", leads.len()));
if !gm::neo4j_disabled() {
if let Ok(dg) = crate::exploration_graph::DualGraph::load(&Path::new(d).join("graphs")) {
match crate::neo4j_exploration::sync(n, &dg, &cfg.target, &rid).await {
Ok(leads) if !leads.is_empty() => {
let cur = gm::live_context(&rid);
gm::set_live_context(&rid, format!("{cur}{}", crate::neo4j_exploration::suggestion_block(&leads)));
synced.push_str(&format!(" · {} chain lead(s)", leads.len()));
}
Ok(_) => {}
Err(e) => synced.push_str(&format!(" · exploration sync skipped ({e})")),
}
Ok(_) => {}
Err(e) => synced.push_str(&format!(" · exploration sync skipped ({e})")),
}
}
}
@@ -7038,6 +7112,51 @@ async fn recon_tool(cfg: &RunConfig, tool: &str, command: &str) -> Option<String
recon_tool_timed(cfg, tool, command, 90).await
}
/// Run a shell pipeline in its own process group so a timeout kills every
/// descendant (gau / waybackurls / katana / curl), not just the `sh` wrapper.
#[cfg(unix)]
async fn run_shell_group(command: &str, secs: u64) -> Option<std::process::Output> {
struct KillGroup(Option<i32>);
impl Drop for KillGroup {
fn drop(&mut self) {
if let Some(pgid) = self.0 {
unsafe {
libc::kill(-pgid, libc::SIGKILL);
}
}
}
}
let mut cmd = tokio::process::Command::new("sh");
cmd.arg("-c").arg(command).kill_on_drop(true);
// New session → new process group; killing -pgid reaches the grandchildren.
unsafe {
cmd.pre_exec(|| {
libc::setsid();
Ok(())
});
}
let child = cmd.spawn().ok()?;
let mut guard = KillGroup(child.id().map(|p| p as i32));
match tokio::time::timeout(std::time::Duration::from_secs(secs), child.wait_with_output()).await {
Ok(Ok(out)) => {
guard.0 = None; // finished cleanly — never signal a (maybe reused) pgid
Some(out)
}
_ => None, // guard drops → SIGKILL the whole pipeline
}
}
#[cfg(not(unix))]
async fn run_shell_group(command: &str, secs: u64) -> Option<std::process::Output> {
tokio::time::timeout(
std::time::Duration::from_secs(secs),
tokio::process::Command::new("sh").arg("-c").arg(command).kill_on_drop(true).output(),
)
.await
.ok()?
.ok()
}
/// `recon_tool` with an explicit time budget, for slow headless analysers.
pub(crate) async fn recon_tool_timed(cfg: &RunConfig, tool: &str, command: &str, secs: u64) -> Option<String> {
// Operator constraint (e.g. "no port scan") enforced in code, not by prompt.
@@ -7058,8 +7177,7 @@ pub(crate) async fn recon_tool_timed(cfg: &RunConfig, tool: &str, command: &str,
let exists = tokio::process::Command::new("which").arg(tool).output().await
.map(|o| o.status.success()).unwrap_or(false);
if !exists { return None; }
let out = tokio::time::timeout(std::time::Duration::from_secs(secs),
tokio::process::Command::new("sh").arg("-c").arg(command).output()).await.ok()?.ok()?;
let out = run_shell_group(command, secs).await?;
let s = String::from_utf8_lossy(&out.stdout).to_string();
if s.trim().is_empty() { None } else { Some(s) }
}
@@ -8332,4 +8450,25 @@ mod ops_wiring_tests {
assert_eq!(clean_finding_title("Source CSRF-Disabled Reviewer at plugins/docker/views.py:95", "code_csrf_disabled"),
"CSRF-Disabled plugins/docker/views.py:95");
}
#[test]
fn tool_call_markup_is_recognized() {
assert!(looks_like_tool_call(
"<tool_calls><invoke name=\"run\"><parameter name=\"cmd\">x</parameter></invoke></tool_calls>"
));
assert!(looks_like_tool_call("</||DSML||parameter>"));
assert!(!looks_like_tool_call("[{\"title\":\"Reflected XSS\",\"severity\":\"High\"}]"));
}
#[cfg(unix)]
#[tokio::test]
async fn recon_timeout_kills_the_whole_pipeline() {
let marker = std::env::temp_dir().join(format!("ns-kill-{}", std::process::id()));
let _ = std::fs::remove_file(&marker);
let cmd = format!("sleep 2; echo leaked > {}", marker.display());
assert!(run_shell_group(&cmd, 1).await.is_none(), "must time out");
tokio::time::sleep(std::time::Duration::from_millis(2500)).await;
assert!(!marker.exists(), "a grandchild survived the timeout kill");
let _ = std::fs::remove_file(&marker);
}
}