From ec656c1ada04577568908b3784a8b2cc4a1689af Mon Sep 17 00:00:00 2001 From: Joas A Santos <34966120+CyberSecurityUP@users.noreply.github.com> Date: Fri, 4 Dec 2026 12:30:31 -0300 Subject: [PATCH] feat(skills): have a model read what findings yielded, alongside the keywords MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit capabilities_from matches keywords over a finding's title, impact and evidence. It misses a credential phrased in words the list does not carry, and it mints rce from a finding that merely warns command injection is possible. Add a second reader. capabilities_via_model shows a model the findings and the nine-name vocabulary and asks what the tester can now do that they could not before, with the distinction stated: a parameter reported vulnerable to command injection is not rce, a command whose output is in the evidence is. The two are unioned, never substituted. Only names from CAPABILITIES survive — anything the model invents is dropped — and a failed or refused call leaves the keyword result standing, so the read can only widen what was already derived. Off with NEUROSPLOIT_CAPABILITY_READ=off, and skipped once the USD budget is in wrap-up, since it is one call per round. Fixes a latent bug the new tests surfaced: SkillMeta derived Default, giving max_rounds 0, while the field's serde default is 2. The key-value frontmatter parser starts from Default::default() and fills in only the keys a file names, and route drops any skill that has reached its max_rounds — so a skill whose frontmatter omitted the key loaded with 0 and was silently unroutable. No shipped skill omits it, so nothing was broken in practice, but the next one written would have been. Default is now written by hand to agree with serde. Five tests: that only vocabulary names survive the filter, that an unusable reply cannot narrow the keyword result, that route uses supplied capabilities rather than re-deriving them, that frontmatter without max_rounds is still routable, and that the two defaults cannot drift apart again. Co-Authored-By: Claude Opus 5 --- neurosploit-rs/crates/harness/src/pipeline.rs | 49 +++- neurosploit-rs/crates/harness/src/skill.rs | 272 +++++++++++++++++- 2 files changed, 309 insertions(+), 12 deletions(-) diff --git a/neurosploit-rs/crates/harness/src/pipeline.rs b/neurosploit-rs/crates/harness/src/pipeline.rs index da7856b..f26a046 100644 --- a/neurosploit-rs/crates/harness/src/pipeline.rs +++ b/neurosploit-rs/crates/harness/src/pipeline.rs @@ -2912,9 +2912,10 @@ pub async fn run(mut cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sender let _ = tx.send(format!("🛑 USD budget wrap-up — ${remaining:.4} left, stopping exploration")).await; break; } + let capabilities = read_capabilities(pool, &all_findings, &tx).await; let next_skills = crate::skill::next_round( - &skill_catalog, &all_findings, &skills_ran, explored, "web", &recon, - round, &exploration_budget, + &skill_catalog, &all_findings, &skills_ran, explored, &capabilities, "web", + &recon, round, &exploration_budget, ); if next_skills.is_empty() { break; } let names: Vec = next_skills.iter().map(|s| format!("{}({})", s.skill.name, s.reason)).collect(); @@ -3232,6 +3233,45 @@ struct ExploreCtx<'a> { /// Run the skill-based exploration loop on a set of initial findings. /// Returns extra findings discovered through chained skill execution. +/// What the findings so far have yielded, read twice: once by keyword, and — +/// unless NEUROSPLOIT_CAPABILITY_READ=off — once by a model. +/// +/// The two are unioned. The keyword pass is free and catches the obvious +/// cases; the model pass catches a credential phrased in words the keyword +/// list does not carry. A failed or refused model call leaves the keyword +/// result standing, so this can only widen what was already derived. +async fn read_capabilities( + pool: &ModelPool, + findings: &[Finding], + tx: &Sender, +) -> std::collections::HashSet { + let mut caps = crate::skill::capabilities_from(findings); + + let off = std::env::var("NEUROSPLOIT_CAPABILITY_READ") + .map(|v| v.eq_ignore_ascii_case("off") || v == "0") + .unwrap_or(false); + if off || findings.is_empty() || pool.stop_exploiting() + || crate::budget::cost_ledger().wrap_up_mode() + { + return caps; + } + + match crate::skill::capabilities_via_model(pool, findings).await { + Ok(model_caps) => { + let added: Vec<&String> = model_caps.difference(&caps).collect(); + if !added.is_empty() { + let names = added.iter().map(|s| s.as_str()).collect::>().join(", "); + let _ = tx.send(format!("🧬 capability read added: {names}")).await; + } + caps.extend(model_caps); + } + Err(e) => { + let _ = tx.send(format!("🧬 capability read unavailable ({e}) — keyword only")).await; + } + } + caps +} + async fn exploration_loop( ctx: &mut ExploreCtx<'_>, initial_findings: &[Finding], @@ -3281,8 +3321,9 @@ async fn exploration_loop( let _ = ctx.tx.send(format!("🛑 USD budget wrap-up mode — ${remaining:.4} remaining, stopping exploration")).await; break; } + let capabilities = read_capabilities(ctx.pool, &all_findings, &ctx.tx).await; let next_skills = crate::skill::next_round( - &skill_catalog, &all_findings, &skills_ran, explored, ctx.mode, + &skill_catalog, &all_findings, &skills_ran, explored, &capabilities, ctx.mode, &ctx.recon_ctx, round, &budget, ); if next_skills.is_empty() { break; } @@ -4713,7 +4754,7 @@ const STRING_ELEMENT_KEYS: &[&str] = &["name", "agent", "id", "value"]; /// when they stray from "reply with a JSON array of strings": a wrapper object /// around the array, and array elements that are objects carrying the string in a /// `name`/`agent`/`id` field. -fn parse_string_array(text: &str) -> Vec { +pub(crate) fn parse_string_array(text: &str) -> Vec { let arr = match crate::json_extract::parse_reply(text) { Some(serde_json::Value::Array(a)) => a, Some(serde_json::Value::Object(o)) => { diff --git a/neurosploit-rs/crates/harness/src/skill.rs b/neurosploit-rs/crates/harness/src/skill.rs index 58d13d4..014c5c4 100644 --- a/neurosploit-rs/crates/harness/src/skill.rs +++ b/neurosploit-rs/crates/harness/src/skill.rs @@ -30,7 +30,7 @@ use std::collections::{HashMap, HashSet}; use std::path::Path; /// A skill's frontmatter metadata, parsed from the YAML block. -#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct SkillMeta { /// Recon signals that make this skill relevant (e.g., "php", "graphql", /// "jwt", "upload", "api"). Matched case-insensitively against recon text. @@ -89,6 +89,29 @@ pub struct SkillMeta { fn default_max_rounds() -> u32 { 2 } +/// Hand-written so it agrees with the serde defaults above. +/// +/// A derived Default would give `max_rounds: 0`, and the key-value frontmatter +/// parser starts from `Default::default()` and fills in only the keys the file +/// names. A skill whose frontmatter omitted `max_rounds` would therefore load +/// with 0, and `route` drops any skill whose runs so far have reached its +/// max_rounds — so it would be silently unroutable, with nothing to show why. +impl Default for SkillMeta { + fn default() -> Self { + Self { + triggers: Vec::new(), + cwe: Vec::new(), + chains: Vec::new(), + requires: Vec::new(), + priority: 0, + max_rounds: default_max_rounds(), + category: String::new(), + consumes: Vec::new(), + modes: Vec::new(), + } + } +} + /// A loaded skill — the markdown methodology + its metadata. #[derive(Debug, Clone, Serialize)] pub struct Skill { @@ -328,6 +351,11 @@ fn extract_section(text: &str, header: &str) -> String { /// Context the router uses to score skills. pub struct ExplorationContext { + /// What the findings so far have yielded. The caller supplies this so a + /// model's reading of the findings can be unioned in alongside the + /// keyword deriver; leave it empty and `route` derives it itself. + pub capabilities: HashSet, + /// Engagement mode, matched against each skill's `modes`. Empty matches /// every skill, which keeps older callers working. pub mode: String, @@ -350,8 +378,15 @@ pub struct ScoredSkill { pub fn route(catalog: &SkillCatalog, ctx: &ExplorationContext, limit: usize) -> Vec { let recon_lower = ctx.recon.to_ascii_lowercase(); // What the findings so far have yielded, independent of which skill found - // it or whether an edge was declared to anything. - let available = capabilities_from(&ctx.findings); + // it or whether an edge was declared to anything. The caller may have + // already widened this with a model's reading; fall back to deriving it. + let derived; + let available: &HashSet = if ctx.capabilities.is_empty() { + derived = capabilities_from(&ctx.findings); + &derived + } else { + &ctx.capabilities + }; let mut scored: Vec = catalog.skills.iter() .filter_map(|skill| { @@ -513,6 +548,7 @@ pub fn next_round( all_findings: &[crate::types::Finding], skills_ran: &HashSet, explored: usize, + capabilities: &HashSet, mode: &str, recon: &str, round: u32, @@ -527,6 +563,7 @@ pub fn next_round( } let ctx = ExplorationContext { + capabilities: capabilities.clone(), mode: mode.to_string(), recon: recon.to_string(), findings: all_findings.to_vec(), @@ -702,6 +739,7 @@ mod tests { test_skill("ssrf", vec!["api", "curl", "fetch"], vec![]), ]); let ctx = ExplorationContext { + capabilities: HashSet::new(), mode: String::new(), recon: "MySQL database detected on port 3306, PHP application".into(), findings: vec![], @@ -732,6 +770,7 @@ mod tests { }; let ctx = ExplorationContext { + capabilities: HashSet::new(), mode: String::new(), recon: String::new(), findings: vec![finding], @@ -754,7 +793,7 @@ mod tests { // `round` is 1-based: max_rounds = 1 permits round 1 and refuses round 2. let budget = ExplorationBudget { max_rounds: 1, ..Default::default() }; - let next = next_round(&catalog, &[], &ran, 0, "", "html page", 2, &budget); + let next = next_round(&catalog, &[], &ran, 0, &HashSet::new(), "", "html page", 2, &budget); assert!(next.is_empty(), "should stop after max_rounds"); } @@ -793,6 +832,7 @@ mod tests { test_skill("xss", vec![], vec![]), ]); let ctx = ExplorationContext { + capabilities: HashSet::new(), mode: String::new(), recon: "some target".into(), findings: vec![], @@ -839,6 +879,7 @@ mod loop_reality_tests { let catalog = catalog_of(skills); let ctx = ExplorationContext { + capabilities: HashSet::new(), mode: String::new(), recon: "nginx php mysql /login /api/users".into(), findings: Vec::new(), @@ -873,6 +914,7 @@ mod loop_reality_tests { }]); let ctx = ExplorationContext { + capabilities: HashSet::new(), mode: String::new(), recon: "nginx php mysql /login".into(), findings: Vec::new(), @@ -906,6 +948,7 @@ mod shipped_catalog_tests { assert!(catalog.total() > 100, "catalogue did not load: {}", catalog.total()); let ctx = ExplorationContext { + capabilities: HashSet::new(), mode: String::new(), recon: "nginx 1.18 php 7.4 mysql wordpress /wp-admin /api/users?id=1 \ swagger jwt bearer eyJ upload multipart url=https://x" @@ -935,6 +978,7 @@ mod shipped_catalog_tests { f.severity = "High".into(); let ctx = ExplorationContext { + capabilities: HashSet::new(), mode: String::new(), recon: "api gateway".into(), findings: vec![f], @@ -1011,7 +1055,7 @@ mod budget_tests { // 40 agents already ran in the selection phase. let skills_ran: HashSet = (0..40).map(|i| format!("opening_agent_{i}")).collect(); - let picked = next_round(&catalog, &[], &skills_ran, 0, "", "php mysql", 1, &budget); + let picked = next_round(&catalog, &[], &skills_ran, 0, &HashSet::new(), "", "php mysql", 1, &budget); assert!(!picked.is_empty(), "exploration refused after a 40-agent opening selection"); } @@ -1022,7 +1066,7 @@ mod budget_tests { let budget = ExplorationBudget { max_rounds: 3, max_skills_per_round: 5, max_total_skills: 20, }; - let picked = next_round(&catalog, &[], &HashSet::new(), 20, "", "php", 1, &budget); + let picked = next_round(&catalog, &[], &HashSet::new(), 20, &HashSet::new(), "", "php", 1, &budget); assert!(picked.is_empty(), "budget of 20 did not stop the loop at 20 explored"); } @@ -1035,12 +1079,12 @@ mod budget_tests { }; for round in 1..=3 { assert!( - !next_round(&catalog, &[], &HashSet::new(), 0, "", "php", round, &budget).is_empty(), + !next_round(&catalog, &[], &HashSet::new(), 0, &HashSet::new(), "", "php", round, &budget).is_empty(), "round {round} refused with max_rounds = 3", ); } assert!( - next_round(&catalog, &[], &HashSet::new(), 0, "", "php", 4, &budget).is_empty(), + next_round(&catalog, &[], &HashSet::new(), 0, &HashSet::new(), "", "php", 4, &budget).is_empty(), "round 4 ran with max_rounds = 3", ); } @@ -1058,6 +1102,7 @@ mod mode_scoping_tests { fn pick(mode: &str, recon: &str, limit: usize) -> Vec<(String, f64)> { let catalog = load_catalog(&repo_root()); let ctx = ExplorationContext { + capabilities: HashSet::new(), mode: mode.into(), recon: recon.into(), findings: Vec::new(), skills_ran: HashSet::new(), round: 1, }; @@ -1116,6 +1161,7 @@ mod mode_scoping_tests { let catalog = load_catalog(&repo_root()); for mode in ["web", "whitebox", "host", "container", "mobile"] { let ctx = ExplorationContext { + capabilities: HashSet::new(), mode: mode.into(), recon: "the quick brown fox".into(), findings: Vec::new(), skills_ran: HashSet::new(), round: 1, @@ -1347,6 +1393,7 @@ mod capability_tests { let catalog = load_catalog(&repo_root()); let skills_ran = findings.iter().map(|f| f.agent.clone()).collect(); let ctx = ExplorationContext { + capabilities: HashSet::new(), mode: mode.into(), recon: recon.into(), findings, skills_ran, round: 2, }; route(&catalog, &ctx, 15).into_iter() @@ -1433,3 +1480,212 @@ mod capability_tests { } } + +/// The capability vocabulary, as the model is shown it. +fn capability_menu() -> String { + [ + ("credential", "a username and password, hash or ticket that can now be used"), + ("secret", "an API key, token or private key recovered"), + ("cloud_token", "credentials for AWS, GCP or Azure specifically"), + ("internal_host", "an internal address or hostname that was not previously reachable"), + ("endpoint", "an application endpoint or route not previously known"), + ("source_read", "the ability to read files or source off the target"), + ("rce", "command or code execution on the target"), + ("session", "a session, cookie or account the tester can now act as"), + ("admin_access", "administrative or privileged access"), + ] + .iter() + .map(|(k, d)| format!(" {k} — {d}")) + .collect::>() + .join("\n") +} + +const CAPABILITY_SYS: &str = "\ +You read penetration-test findings and report only what the tester can now DO \ +that they could not before. + +Reply with a JSON array of capability names, drawn only from the list given. \ +Reply [] if the findings establish none of them. + +Judge what was actually achieved, not what a finding warns is possible. A report \ +that a parameter is vulnerable to command injection is not `rce`; a command whose \ +output is in the evidence is. A note that passwords are stored weakly is not \ +`credential`; a password the tester now holds is."; + +/// Ask a model what the findings yielded, as a second reader alongside +/// `capabilities_from`. +/// +/// The keyword deriver only knows the words it was written with: it misses a +/// credential described in unfamiliar phrasing, and it will mint `rce` from a +/// finding that merely discusses command execution. A model reads the prose. +/// +/// Returns only names from [`CAPABILITIES`] — anything else the model says is +/// dropped — and an error leaves the caller with the keyword result, so this +/// can only widen what was already found, never narrow or break it. +pub async fn capabilities_via_model( + pool: &crate::pool::ModelPool, + findings: &[crate::types::Finding], +) -> Result, String> { + if findings.is_empty() { + return Ok(HashSet::new()); + } + + let digest: String = findings.iter() + .take(25) + .map(|f| { + let evidence: String = f.evidence.chars().take(600).collect(); + format!( + "- [{}] {}\n impact: {}\n evidence: {}", + f.severity, f.title, + f.impact.chars().take(200).collect::(), + evidence.replace('\n', " "), + ) + }) + .collect::>() + .join("\n"); + + let user = format!( + "CAPABILITIES:\n{}\n\nFINDINGS:\n{digest}\n\nJSON array only.", + capability_menu(), + ); + + let (_m, text) = pool + .complete_routed(crate::pool::Task::Validate, "capability-read", CAPABILITY_SYS, &user) + .await + .map_err(|e| e.to_string())?; + + let known: HashSet<&str> = CAPABILITIES.iter().copied().collect(); + Ok(crate::pipeline::parse_string_array(&text) + .into_iter() + .map(|s| s.trim().to_ascii_lowercase()) + .filter(|s| known.contains(s.as_str())) + .collect()) +} + +#[cfg(test)] +mod capability_read_tests { + use super::*; + + /// Whatever a model replies, only names from the closed vocabulary may + /// reach the router. The parse is shared with `capabilities_via_model`; + /// this pins the filter that guards it. + #[test] + fn only_known_capabilities_survive_the_filter() { + let known: HashSet<&str> = CAPABILITIES.iter().copied().collect(); + let reply = r#"["credential", "RCE", "shell_access", "domain_admin", "secret", ""]"#; + let got: HashSet = crate::pipeline::parse_string_array(reply) + .into_iter() + .map(|s| s.trim().to_ascii_lowercase()) + .filter(|s| known.contains(s.as_str())) + .collect(); + + assert!(got.contains("credential")); + assert!(got.contains("rce"), "lowercasing should admit RCE"); + assert!(got.contains("secret")); + assert!(!got.contains("shell_access"), "invented capability admitted"); + assert!(!got.contains("domain_admin"), "invented capability admitted"); + assert_eq!(got.len(), 3); + } + + /// A model reply that parses to nothing must leave the keyword result + /// untouched rather than clearing it. + #[test] + fn an_unusable_reply_cannot_narrow_the_keyword_result() { + let mut f = crate::types::Finding::default(); + f.agent = "sqli_union".into(); + f.title = "Dumped the users table".into(); + f.impact = "Recovered credentials for the admin account".into(); + let keyword = capabilities_from(std::slice::from_ref(&f)); + assert!(keyword.contains("credential"), "fixture should derive a credential"); + + let known: HashSet<&str> = CAPABILITIES.iter().copied().collect(); + let from_model: HashSet = crate::pipeline::parse_string_array("I cannot help with that") + .into_iter() + .map(|s| s.trim().to_ascii_lowercase()) + .filter(|s| known.contains(s.as_str())) + .collect(); + + let mut merged = keyword.clone(); + merged.extend(from_model); + assert!(merged.contains("credential")); + assert!(merged.len() >= keyword.len(), "the union narrowed the keyword result"); + } + + /// The router must use what the caller supplies rather than re-deriving, + /// or anything the model added is discarded on the way in. + #[test] + fn route_uses_the_capabilities_it_is_given() { + let mut meta = SkillMeta::default(); + meta.consumes = vec!["rce".into()]; + let catalog = { + let skills = vec![Skill { + name: "linux_priv_esc".into(), title: "x".into(), cwe: String::new(), + category: "infra".into(), meta, system: String::new(), user: String::new(), + }]; + let by_name = skills.iter().enumerate().map(|(i, s)| (s.name.clone(), i)).collect(); + SkillCatalog { skills, by_name, chain_map: HashMap::new() } + }; + + // A finding whose words establish nothing the keyword deriver knows. + let mut f = crate::types::Finding::default(); + f.agent = "obscure".into(); + f.title = "Operator-supplied payload returned the expected marker".into(); + + assert!( + !capabilities_from(std::slice::from_ref(&f)).contains("rce"), + "fixture must not be derivable by keyword, or the test proves nothing", + ); + + let ctx = ExplorationContext { + capabilities: ["rce".to_string()].into_iter().collect(), + mode: String::new(), + recon: String::new(), + findings: vec![f], + skills_ran: HashSet::new(), + round: 2, + }; + + let picked = route(&catalog, &ctx, 5); + assert_eq!(picked.len(), 1, "supplied capability did not reach the router"); + assert!(picked[0].reason.contains("yields:rce")); + assert!(picked[0].score >= 15.0, "score {} below the round gate", picked[0].score); + } +} + +#[cfg(test)] +mod default_tests { + use super::*; + + /// The key-value frontmatter parser starts from `SkillMeta::default()` and + /// fills in only the keys a file names. A derived Default gives + /// `max_rounds: 0`, and `route` drops any skill that has reached its + /// max_rounds — so a skill whose frontmatter omitted the key would be + /// silently unroutable. + #[test] + fn frontmatter_without_max_rounds_is_still_routable() { + let text = "---\ntriggers: php\npriority: 20\n---\n# X\n"; + let (meta, _body) = parse_frontmatter(text); + assert_eq!(meta.max_rounds, 2, "omitted max_rounds did not take the documented default"); + + let catalog = { + let skills = vec![Skill { + name: "x".into(), title: "X".into(), cwe: String::new(), + category: "vuln".into(), meta, system: String::new(), user: String::new(), + }]; + let by_name = skills.iter().enumerate().map(|(i, s)| (s.name.clone(), i)).collect(); + SkillCatalog { skills, by_name, chain_map: HashMap::new() } + }; + let ctx = ExplorationContext { + capabilities: HashSet::new(), mode: String::new(), + recon: "php nginx".into(), findings: Vec::new(), + skills_ran: HashSet::new(), round: 1, + }; + assert_eq!(route(&catalog, &ctx, 5).len(), 1, "skill was dropped before scoring"); + } + + /// The two defaults must not drift apart again. + #[test] + fn the_struct_default_matches_the_serde_default() { + assert_eq!(SkillMeta::default().max_rounds, default_max_rounds()); + } +}