From fde91c0b7445ec77bbe73c4dd7ee685f057c1058 Mon Sep 17 00:00:00 2001 From: CyberSecurityUP Date: Thu, 3 Dec 2026 16:17:47 -0300 Subject: [PATCH] feat: wire-first deterministic gates for sourcemap/admin/rate/IDOR - replay a safe GET and store the real request/response as evidence - sourcemap must be served and parse; admin rejects redirect/WAF/SPA/shell; rate/IDOR without a receipt become leads; generic findings go through judge - only validated findings are reported; the rest are leads --- neurosploit-rs/crates/harness/src/gates.rs | 445 ++++++++++++++++++ neurosploit-rs/crates/harness/src/lib.rs | 1 + neurosploit-rs/crates/harness/src/pipeline.rs | 36 +- 3 files changed, 466 insertions(+), 16 deletions(-) create mode 100644 neurosploit-rs/crates/harness/src/gates.rs diff --git a/neurosploit-rs/crates/harness/src/gates.rs b/neurosploit-rs/crates/harness/src/gates.rs new file mode 100644 index 0000000..9a48886 --- /dev/null +++ b/neurosploit-rs/crates/harness/src/gates.rs @@ -0,0 +1,445 @@ +//! Deterministic, wire-first gates. +//! +//! The LLM vote is a second opinion, not the gate. Before a finding is reported +//! the harness re-issues a safe GET itself, keeps the real request/response as +//! evidence, and applies class-specific rules: +//! +//! - sourcemap: the `.map` must be served and parse as a source map; +//! - admin/exposed panel: a redirect, WAF page, SPA fallback or an admin shell +//! without privileged data is not an unauthenticated admin; +//! - rate-limit/IDOR: without a burst / identity-pair receipt it is a lead; +//! - everything else: the CWE validator judges the measured exchange. +//! +//! Only POST/PUT/PATCH/DELETE findings are left alone (a replay could mutate +//! state); they stay leads unless the agent already supplied evidence. + +use crate::pipeline::{default_scan_headers, default_user_agent, effective_scope}; +use crate::types::Finding; +use crate::validation::{Evidence, Exchange, Verdict}; +use std::collections::BTreeMap; +use std::time::{Duration, Instant}; +use tokio::sync::mpsc::Sender; + +const MAX_PROBES: usize = 40; +const MAX_BODY: usize = 256 * 1024; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Class { + Sourcemap, + Admin, + RateLimit, + Idor, + Generic, +} + +fn class_of(f: &Finding) -> Class { + let t = f.title.to_ascii_lowercase(); + let a = f.agent.to_ascii_lowercase(); + let cwe = f.cwe.to_ascii_lowercase(); + if a.contains("sourcemap") || t.contains("sourcemap") || t.contains("source map") { + return Class::Sourcemap; + } + if t.contains("rate limit") + || t.contains("rate-limit") + || t.contains("ratelimit") + || a.contains("rate_limit") + { + return Class::RateLimit; + } + if t.contains("idor") + || t.contains("bola") + || t.contains("sequential") + || t.contains("broken object") + || a == "idor" + || a == "bola" + { + return Class::Idor; + } + if f.endpoint.to_ascii_lowercase().contains("/admin") + || f.endpoint.to_ascii_lowercase().contains("/administrator") + || t.contains("admin panel") + || t.contains("admin access") + || t.contains("exposed admin") + || ((cwe.contains("306") || cwe.contains("862") || cwe.contains("425")) && t.contains("admin")) + { + return Class::Admin; + } + Class::Generic +} + +fn unsafe_method(f: &Finding) -> bool { + let blob = format!("{} {} {}", f.title, f.payload, f.evidence).to_ascii_lowercase(); + ["post ", "put ", "patch ", "delete "].iter().any(|m| blob.contains(m)) +} + +fn absolute(cfg: &crate::types::RunConfig, endpoint: &str) -> Option { + let e = endpoint.trim(); + if e.starts_with("http://") || e.starts_with("https://") { + return reqwest::Url::parse(e).ok(); + } + // "GET /admin" or a bare path. + let path = if e.starts_with('/') { + e.split_whitespace().next()? + } else { + e.split_whitespace().nth(1)? + }; + let base = reqwest::Url::parse(&cfg.target) + .or_else(|_| reqwest::Url::parse(&format!("https://{}", crate::scope::host_of(&cfg.target)))) + .ok()?; + base.join(path).ok() +} + +fn same_origin_root(url: &reqwest::Url) -> Option { + let mut u = url.clone(); + u.set_path("/"); + u.set_query(None); + u.set_fragment(None); + Some(u) +} + +fn sourcemap_url(f: &Finding, endpoint: &reqwest::Url) -> Option { + if endpoint.path().ends_with(".map") { + return Some(endpoint.clone()); + } + if endpoint.path().ends_with(".js") { + let mut u = endpoint.clone(); + u.set_query(None); + u.set_fragment(None); + let path = format!("{}.map", u.path()); + u.set_path(&path); + return Some(u); + } + // The agent may have quoted the map URL in its evidence/PoC. + for src in [&f.payload, &f.evidence] { + for tok in src.split_whitespace() { + if tok.starts_with("http") && tok.contains(".map") { + if let Ok(u) = reqwest::Url::parse(tok.trim_end_matches(['.', ')', '"', '\''])) { + return Some(u); + } + } + } + } + None +} + +fn client(cfg: &crate::types::RunConfig) -> reqwest::Client { + reqwest::Client::builder() + .danger_accept_invalid_certs(true) + .timeout(Duration::from_secs(12)) + .redirect(reqwest::redirect::Policy::none()) + .default_headers(default_scan_headers()) + .user_agent(cfg.user_agent.clone().unwrap_or_else(default_user_agent)) + .build() + .unwrap_or_default() +} + +async fn get(client: &reqwest::Client, cfg: &crate::types::RunConfig, url: &reqwest::Url) -> Option { + let start = Instant::now(); + let mut req = client.get(url.clone()); + let mut request_headers = BTreeMap::new(); + if let Some(auth) = cfg.auth.as_deref().filter(|s| !s.trim().is_empty()) { + if let Some((k, v)) = auth.split_once(':') { + let (k, v) = (k.trim(), v.trim()); + if !k.is_empty() { + req = req.header(k, v); + request_headers.insert(k.to_ascii_lowercase(), v.to_string()); + } + } + } + let resp = req.send().await.ok()?; + let status = resp.status().as_u16(); + let headers: BTreeMap = resp + .headers() + .iter() + .map(|(k, v)| (k.as_str().to_ascii_lowercase(), v.to_str().unwrap_or("").to_string())) + .collect(); + let content_type = headers.get("content-type").cloned().unwrap_or_default(); + let body = resp.text().await.ok()?.chars().take(MAX_BODY).collect::(); + Some(Exchange { + method: "GET".into(), + url: url.to_string(), + status, + body, + content_type, + elapsed_ms: start.elapsed().as_millis() as u64, + headers, + request_headers, + provenance: "wire:harness".into(), + ..Default::default() + }) +} + +fn summary(ex: &Exchange) -> String { + format!( + "GET {} -> HTTP {} ({} bytes, {})", + ex.url, + ex.status, + ex.body.len(), + if ex.content_type.is_empty() { "unknown" } else { &ex.content_type } + ) +} + +fn apply(f: &mut Finding, v: Verdict, evidence: Evidence) { + f.evidence_data = Some(evidence); + f.validation_level = "deterministic".into(); + match v { + Verdict::Confirmed(reason) => { + f.validated = true; + f.review_status = "confirmed".into(); + f.review_reason = reason; + } + Verdict::Rejected(reason) => { + f.validated = false; + f.review_status = "rejected".into(); + f.review_reason = reason; + } + Verdict::NeedsReview(reason) => { + f.validated = false; + f.review_status = "needs-review".into(); + f.review_reason = reason; + } + } +} + +fn waf_blocked(ex: &Exchange) -> Option { + let v = crate::waf::classify_exchange(ex); + if v.origin.supports_a_finding() { + None + } else { + Some(format!("the response came from the {} ({}) — the application was not reached", v.origin.as_str(), v.reason)) + } +} + +fn admin_has_data(ex: &Exchange) -> bool { + let b = ex.body.to_ascii_lowercase(); + let ct = ex.content_type.to_ascii_lowercase(); + (ct.contains("json") + && (b.contains("\"users\"") || b.contains("\"roles\"") || b.contains("\"admin\"") || b.contains("\"accounts\""))) + || (b.contains(" V out.into_iter().take(cap).collect() } -async fn validate(candidates: Vec, pool: &ModelPool, sys: &str, vote_n: usize, tx: &Sender) -> Vec { - validate_with_persist(candidates, pool, sys, vote_n, tx, None).await +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 } -async fn validate_with_persist(candidates: Vec, pool: &ModelPool, sys: &str, vote_n: usize, tx: &Sender, workdir: Option<&str>) -> Vec { +async fn validate_with_persist(cfg: Option<&RunConfig>, candidates: Vec, pool: &ModelPool, sys: &str, vote_n: usize, tx: &Sender, workdir: Option<&str>) -> Vec { // --no-validate: operator opted out of the adversarial vote. Keep every // finding with the severity its agent assigned, marked `unvalidated` — the // panel discards nothing. (Set by the launcher when cfg.no_validate.) @@ -4435,9 +4435,13 @@ async fn validate_with_persist(candidates: Vec, pool: &ModelPool, sys: persist_rejected(workdir, &vote_rejected); } flagged.extend(all); - // Only deterministic/LLM-confirmed findings are reported. Candidates that - // failed to provide a replayable request/response, or that the validators - // could not confirm, are kept as LEADS (leads.json) — never as findings. + // Wire-first deterministic gates: replay the request, keep the actual + // request/response as evidence, and decide sourcemap/admin/rate/IDOR (or the + // CWE validator) before anything is reported. Without a receipt it is a lead. + if let Some(cfg) = cfg { + flagged = crate::gates::enforce(cfg, flagged, tx).await; + } + // Only validated findings are reported. Candidates/leads stay in leads.json. let (validated_only, leads): (Vec<_>, Vec<_>) = flagged.into_iter().partition(|f| f.validated); persist_leads(workdir, &leads); validated_only @@ -6638,7 +6642,7 @@ pub async fn run_container(cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: let transcript = transcript_of(&raw); let candidates = dedup_findings(raw.iter().flat_map(|(_, _, f)| f.clone()).collect()); let _ = tx.send(format!("{} finding(s) (deduped) - validating", candidates.len())).await; - let findings = validate(candidates, pool, VOTE_SYS, effective_vote_n(&cfg), &tx).await; + let findings = validate(Some(&cfg), candidates, pool, VOTE_SYS, effective_vote_n(&cfg), &tx).await; finish(cfg, lib, pool, recon, transcript, findings, selected, &mut rl, crate::grounding::GroundMode::Empirical, String::new(), tx).await } @@ -6843,7 +6847,7 @@ pub async fn run_mobile(cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sen let transcript = transcript_of(&raw); let candidates = dedup_findings(raw.iter().flat_map(|(_, _, f)| f.clone()).collect()); let _ = tx.send(format!("{} candidate finding(s) (deduped) - validating", candidates.len())).await; - let findings = validate(candidates, pool, VOTE_SYS, effective_vote_n(&cfg), &tx).await; + let findings = validate(Some(&cfg), candidates, pool, VOTE_SYS, effective_vote_n(&cfg), &tx).await; let findings = refute_pass(findings, pool, effective_vote_n(&cfg), &tx).await; finish(cfg, lib, pool, recon, transcript, findings, selected, &mut rl, crate::grounding::GroundMode::Empirical, String::new(), tx).await } @@ -7051,7 +7055,7 @@ pub async fn run_host(cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sende } } let _ = tx.send(format!("{} candidate finding(s) (deduped) — validating", candidates.len())).await; - let mut findings = validate(candidates, pool, VOTE_SYS, effective_vote_n(&cfg), &tx).await; + let mut findings = validate(Some(&cfg), candidates, pool, VOTE_SYS, effective_vote_n(&cfg), &tx).await; let chained = attack_chain(pool, &cfg, &recon, &findings, &lib.chains, &tx).await; findings.extend(chained); findings = dedup_findings(findings); @@ -8008,7 +8012,7 @@ pub async fn run_ai(cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sender< } } let _ = tx.send(format!("{} AI candidate(s) — validating", candidates.len())).await; - let mut findings = validate(candidates, pool, VOTE_SYS, effective_vote_n(&cfg), &tx).await; + let mut findings = validate(Some(&cfg), candidates, pool, VOTE_SYS, effective_vote_n(&cfg), &tx).await; let chained = attack_chain(pool, &cfg, &recon, &findings, &lib.chains, &tx).await; findings.extend(chained); findings = dedup_findings(findings); @@ -8072,7 +8076,7 @@ pub async fn run_skills_audit(cfg: RunConfig, lib: &Library, pool: &ModelPool, t crate::traces::record_all(cfg.workdir.as_deref(), &raw); let transcript = transcript_of(&raw); let candidates = dedup_findings(raw.iter().flat_map(|(_, _, f)| f.clone()).collect()); - let findings = validate(candidates, pool, CODE_VOTE_SYS, effective_vote_n(&cfg), &tx).await; + let findings = validate(Some(&cfg), candidates, pool, CODE_VOTE_SYS, effective_vote_n(&cfg), &tx).await; finish(cfg, lib, pool, "{}".into(), transcript, findings, agents, &mut rl, crate::grounding::GroundMode::Symbolic, context, tx).await }