From 9e7e1b3ebbe91e13e3f2a158978e0aba0978c83d Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Wed, 23 Sep 2026 14:38:12 +0200 Subject: [PATCH] feat(findings): add pentest and DAST findings by hand or from a report (#337) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A DAST run or penetration test is done by a person. Its results had no way into Prüfwerk, so they could not sit next to the scan's findings or go into the evidence. - POST /api/v1/targets/{id}/findings adds one finding; the same finding (tool, title, location) twice is a 409. - POST /api/v1/targets/{id}/findings/import?format=sarif|zap&kind=... reads a SARIF 2.1.0 or OWASP ZAP JSON report (up to 20 MB); findings already on the target are counted, not added again. A document that is not the named format is a 422. - Both need the organisation's IT_ADMIN role (the dev tenant's user now has it). The finding records who added it and how to reproduce it. - New ScanType::Pentest. A finding's CWE maps it to CRA controls through the control map (controls_for_cwe: any tool's binding for that CWE). - Dashboard: a panel on each target's details with the form and the import; the finding detail shows the reproduction steps and who reported it. German and English. - Guide: docs/guide/manual-findings.md. Tests: SARIF and ZAP parsing, CWE and score handling, fingerprints, the admin check, and an integration test (MongoDB) that adds, re-adds, imports twice, and refuses a non-SARIF document and an unknown target. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p --- .../src/api/handlers/manual_findings.rs | 259 ++++++++++++++++ compliance-agent/src/api/handlers/mod.rs | 1 + compliance-agent/src/api/routes.rs | 11 + compliance-agent/src/api/server.rs | 5 +- compliance-agent/src/import/mod.rs | 198 ++++++++++++ compliance-agent/src/import/sarif.rs | 289 ++++++++++++++++++ compliance-agent/src/import/zap.rs | 201 ++++++++++++ compliance-agent/src/lib.rs | 1 + compliance-agent/src/pipeline/plan.rs | 4 +- compliance-agent/tests/manual_findings.rs | 178 +++++++++++ compliance-core/src/models/finding.rs | 9 + compliance-core/src/models/scan.rs | 4 + .../src/components/manual_findings.rs | 208 +++++++++++++ compliance-dashboard/src/components/mod.rs | 1 + compliance-dashboard/src/i18n/texts.rs | 124 +++++++- .../src/infrastructure/manual_findings.rs | 107 +++++++ .../src/infrastructure/mod.rs | 1 + .../src/pages/finding_detail.rs | 11 + compliance-dashboard/src/pages/targets.rs | 6 + control-map/src/lib.rs | 23 ++ docs/.vitepress/config.mts | 1 + docs/guide/manual-findings.md | 62 ++++ 22 files changed, 1700 insertions(+), 4 deletions(-) create mode 100644 compliance-agent/src/api/handlers/manual_findings.rs create mode 100644 compliance-agent/src/import/mod.rs create mode 100644 compliance-agent/src/import/sarif.rs create mode 100644 compliance-agent/src/import/zap.rs create mode 100644 compliance-agent/tests/manual_findings.rs create mode 100644 compliance-dashboard/src/components/manual_findings.rs create mode 100644 compliance-dashboard/src/infrastructure/manual_findings.rs create mode 100644 docs/guide/manual-findings.md diff --git a/compliance-agent/src/api/handlers/manual_findings.rs b/compliance-agent/src/api/handlers/manual_findings.rs new file mode 100644 index 0000000..8da3830 --- /dev/null +++ b/compliance-agent/src/api/handlers/manual_findings.rs @@ -0,0 +1,259 @@ +//! Findings from a manual DAST run or a penetration test: entered in a form, +//! or imported from the tool's report. They sit next to the scan's findings +//! on the target (see [`crate::import`]). +//! +//! Writing findings into a tenant's record is an administrator's action: the +//! tester is given an account in the customer's organisation with the +//! `IT_ADMIN` role. + +use std::sync::Arc; + +use axum::body::Bytes; +use axum::extract::{Extension, Path, Query}; +use axum::http::StatusCode; +use axum::Json; +use mongodb::bson::{doc, oid::ObjectId}; +use serde::{Deserialize, Serialize}; + +use compliance_core::models::{Finding, ScanType}; +use compliance_core::tenant::OrgRole; +use compliance_core::tenant_ctx::TenantCtx; + +use super::dto::tenant_db; +use super::ApiResponse; +use crate::agent::ComplianceAgent; +use crate::database::Database; +use crate::import::{sarif, zap, ManualFinding, Provenance}; + +type AgentExt = Extension>; + +/// Largest report an import accepts. +pub const MAX_IMPORT_BYTES: usize = 20 * 1024 * 1024; + +/// What kind of manual test a finding comes from. +#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum ManualKind { + Dast, + Pentest, +} + +impl From for ScanType { + fn from(kind: ManualKind) -> Self { + match kind { + ManualKind::Dast => ScanType::Dast, + ManualKind::Pentest => ScanType::Pentest, + } + } +} + +/// `POST /api/v1/targets/{id}/findings`. +#[derive(Debug, Deserialize)] +pub struct CreateFindingRequest { + pub kind: ManualKind, + /// The tool used, if any; `manual` otherwise. + #[serde(default)] + pub tool: Option, + #[serde(flatten)] + pub finding: ManualFinding, +} + +/// The report formats an import reads. +#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum ImportFormat { + Sarif, + Zap, +} + +/// `?format=&kind=` of an import. +#[derive(Debug, Deserialize)] +pub struct ImportParams { + pub format: ImportFormat, + pub kind: ManualKind, +} + +/// What an import did. +#[derive(Debug, Serialize, PartialEq, Eq)] +pub struct ImportSummary { + /// Findings in the report. + pub total: usize, + /// Findings added. + pub imported: usize, + /// Findings already on the target (the same report imported again). + pub duplicates: usize, +} + +/// Only an organisation's IT administrator writes findings by hand. +fn require_admin(tenant: &TenantCtx) -> Result<(), StatusCode> { + if tenant.0.org_roles.contains(&OrgRole::ItAdmin) { + Ok(()) + } else { + Err(StatusCode::FORBIDDEN) + } +} + +/// The target must exist in this tenant. +async fn require_target(db: &Database, id: &str) -> Result<(), StatusCode> { + let oid = ObjectId::parse_str(id).map_err(|_| StatusCode::BAD_REQUEST)?; + db.onboarded_targets() + .find_one(doc! { "_id": oid }) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .map(|_| ()) + .ok_or(StatusCode::NOT_FOUND) +} + +/// Store `finding` unless one with its fingerprint exists. Returns whether it +/// was added. +async fn insert_new(db: &Database, finding: &mut Finding) -> Result { + let existing = db + .findings() + .find_one(doc! { "fingerprint": &finding.fingerprint }) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + if existing.is_some() { + return Ok(false); + } + let res = db + .findings() + .insert_one(&*finding) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + finding.id = res.inserted_id.as_object_id(); + Ok(true) +} + +/// POST /api/v1/targets/{id}/findings — add one finding by hand. 409 when the +/// same finding (tool, title, location) is already on the target. +#[tracing::instrument(skip_all, fields(target_id = %id))] +pub async fn create_finding( + Extension(agent): AgentExt, + tenant: TenantCtx, + Path(id): Path, + Json(req): Json, +) -> Result<(StatusCode, Json>), StatusCode> { + require_admin(&tenant)?; + if req.finding.title.trim().is_empty() { + return Err(StatusCode::UNPROCESSABLE_ENTITY); + } + let db = tenant_db(&agent, &tenant).await?; + require_target(&db, &id).await?; + let tool = req + .tool + .filter(|t| !t.trim().is_empty()) + .unwrap_or_else(|| "manual".to_string()); + let mut finding = req.finding.into_finding(Provenance { + target_id: &id, + scan_type: req.kind.into(), + scanner: &tool, + reported_by: &tenant.0.user_id, + }); + if !insert_new(&db, &mut finding).await? { + return Err(StatusCode::CONFLICT); + } + Ok(( + StatusCode::CREATED, + Json(ApiResponse { + data: finding, + total: None, + page: None, + }), + )) +} + +/// POST /api/v1/targets/{id}/findings/import?format=sarif|zap&kind=dast|pentest +/// — the body is the report itself. Findings already on the target are +/// skipped, so importing a report again adds nothing. +#[tracing::instrument(skip_all, fields(target_id = %id))] +pub async fn import_findings( + Extension(agent): AgentExt, + tenant: TenantCtx, + Path(id): Path, + Query(params): Query, + body: Bytes, +) -> Result>, StatusCode> { + require_admin(&tenant)?; + let parsed: Vec<(String, ManualFinding)> = match params.format { + ImportFormat::Sarif => sarif::parse(&body), + ImportFormat::Zap => zap::parse(&body).map(|f| { + f.into_iter() + .map(|x| ("OWASP ZAP".to_string(), x)) + .collect() + }), + } + .map_err(|e| { + tracing::info!("import refused: {e}"); + StatusCode::UNPROCESSABLE_ENTITY + })?; + let db = tenant_db(&agent, &tenant).await?; + require_target(&db, &id).await?; + + let mut summary = ImportSummary { + total: parsed.len(), + imported: 0, + duplicates: 0, + }; + for (tool, manual) in parsed { + let mut finding = manual.into_finding(Provenance { + target_id: &id, + scan_type: params.kind.into(), + scanner: &tool, + reported_by: &tenant.0.user_id, + }); + if insert_new(&db, &mut finding).await? { + summary.imported += 1; + } else { + summary.duplicates += 1; + } + } + Ok(Json(ApiResponse { + data: summary, + total: None, + page: None, + })) +} + +#[cfg(test)] +mod tests { + use super::*; + use compliance_core::tenant::{TenantContext, TenantStatus}; + + fn tenant(roles: Vec) -> TenantCtx { + TenantCtx(TenantContext { + tenant_id: "t".into(), + tenant_slug: "t".into(), + org_roles: roles, + products: vec![], + plan: "dev".into(), + status: TenantStatus::Active, + user_id: "u".into(), + user_name: None, + }) + } + + #[test] + fn only_an_it_admin_writes_findings() { + assert_eq!(require_admin(&tenant(vec![OrgRole::ItAdmin])), Ok(())); + assert_eq!( + require_admin(&tenant(vec![OrgRole::User, OrgRole::Cxo])), + Err(StatusCode::FORBIDDEN) + ); + } + + #[test] + fn a_form_finding_reads_kind_tool_and_fields() { + let req: CreateFindingRequest = serde_json::from_value(serde_json::json!({ + "kind": "pentest", + "title": "Telnet open with default password", + "severity": "critical", + "cwe": "1392", + "location": "tcp://192.0.2.10:23", + "reproduction": "telnet 192.0.2.10, log in as root/root", + })) + .unwrap_or_else(|e| panic!("request parses: {e}")); + assert_eq!(ScanType::from(req.kind), ScanType::Pentest); + assert_eq!(req.tool, None); + assert_eq!(req.finding.cwe.as_deref(), Some("1392")); + } +} diff --git a/compliance-agent/src/api/handlers/mod.rs b/compliance-agent/src/api/handlers/mod.rs index 69d7d09..fd55beb 100644 --- a/compliance-agent/src/api/handlers/mod.rs +++ b/compliance-agent/src/api/handlers/mod.rs @@ -8,6 +8,7 @@ pub mod graph; pub mod health; pub mod help_chat; pub mod issues; +pub mod manual_findings; pub mod mcp_tokens; pub mod notifications; pub mod onboarding; diff --git a/compliance-agent/src/api/routes.rs b/compliance-agent/src/api/routes.rs index 7d42bad..a498748 100644 --- a/compliance-agent/src/api/routes.rs +++ b/compliance-agent/src/api/routes.rs @@ -70,6 +70,17 @@ pub fn build_router() -> Router { "/api/v1/findings/{id}/feedback", patch(handlers::update_finding_feedback), ) + // Findings from a manual DAST run or penetration test. + .route( + "/api/v1/targets/{id}/findings", + post(handlers::manual_findings::create_finding), + ) + .route( + "/api/v1/targets/{id}/findings/import", + post(handlers::manual_findings::import_findings).layer(DefaultBodyLimit::max( + handlers::manual_findings::MAX_IMPORT_BYTES, + )), + ) .route("/api/v1/sbom", get(handlers::list_sbom)) .route("/api/v1/sbom/filters", get(handlers::sbom_filters)) .route("/api/v1/sbom/export", get(handlers::export_sbom)) diff --git a/compliance-agent/src/api/server.rs b/compliance-agent/src/api/server.rs index 00590d4..56ab651 100644 --- a/compliance-agent/src/api/server.rs +++ b/compliance-agent/src/api/server.rs @@ -13,7 +13,7 @@ use tower_http::trace::TraceLayer; use compliance_core::auth::{require_jwt_auth, require_tenant_status, JwksState}; use compliance_core::config::AppEnv; use compliance_core::shutdown::{self, Shutdown}; -use compliance_core::{TenantContext, TenantStatus}; +use compliance_core::{OrgRole, TenantContext, TenantStatus}; use crate::agent::ComplianceAgent; use crate::api::handlers; @@ -45,7 +45,8 @@ pub async fn inject_dev_tenant(mut request: Request, next: Next) -> Response { let ctx = TenantContext { tenant_slug: tenant_id.clone(), tenant_id, - org_roles: vec![], + // The single local user administers the dev organisation. + org_roles: vec![OrgRole::ItAdmin], products: vec![], plan: "dev".to_string(), status: TenantStatus::Active, diff --git a/compliance-agent/src/import/mod.rs b/compliance-agent/src/import/mod.rs new file mode 100644 index 0000000..3a18ac4 --- /dev/null +++ b/compliance-agent/src/import/mod.rs @@ -0,0 +1,198 @@ +//! Findings from outside the scan pipeline: entered by hand, or imported from +//! a tool's report (SARIF 2.1.0, OWASP ZAP JSON). +//! +//! A DAST run or a penetration test is done by a person, not by the agent. Its +//! results still belong next to the scan's findings, with the same fields, so +//! the customer sees one list and the evidence pack one set. + +pub mod sarif; +pub mod zap; + +use compliance_core::models::{Finding, ScanType, Severity}; +use serde::Deserialize; + +use crate::pipeline::dedup; + +/// Longest excerpt of evidence (a request or response) kept on a finding. +const MAX_EVIDENCE_CHARS: usize = 4_000; + +/// What a finding from a manual test says, whether typed into the form or +/// read from a report. +#[derive(Debug, Clone, Deserialize, PartialEq)] +pub struct ManualFinding { + pub title: String, + #[serde(default)] + pub description: String, + pub severity: Severity, + /// `CWE-79`, or just `79`. + #[serde(default)] + pub cwe: Option, + #[serde(default)] + pub cvss_score: Option, + /// Where it was found: a URL, an endpoint, a file. + #[serde(default)] + pub location: Option, + /// A request or response excerpt that shows it. + #[serde(default)] + pub evidence: Option, + #[serde(default)] + pub reproduction: Option, + #[serde(default)] + pub remediation: Option, + /// The tool's rule or plugin id, for an imported finding. + #[serde(default)] + pub rule_id: Option, +} + +/// Where a finding came from, for the stored record. +#[derive(Debug, Clone, Copy)] +pub struct Provenance<'a> { + /// The target the finding belongs to. + pub target_id: &'a str, + /// `Dast` or `Pentest`. + pub scan_type: ScanType, + /// The tool that found it, or `manual`. + pub scanner: &'a str, + /// The user who entered or imported it. + pub reported_by: &'a str, +} + +impl ManualFinding { + /// The finding as stored. Its fingerprint covers the target, tool, rule, + /// title and location, so importing the same report twice adds nothing. + pub fn into_finding(self, from: Provenance<'_>) -> Finding { + let cwe = self.cwe.as_deref().and_then(normalise_cwe); + let fingerprint = dedup::compute_fingerprint(&[ + from.target_id, + from.scanner, + &from.scan_type.to_string(), + self.rule_id.as_deref().unwrap_or_default(), + &self.title, + self.location.as_deref().unwrap_or_default(), + ]); + let mut finding = Finding::new( + from.target_id.to_string(), + fingerprint, + from.scanner.to_string(), + from.scan_type, + self.title, + self.description, + self.severity, + ); + finding.control_refs = cwe.as_deref().map(control_refs).unwrap_or_default(); + finding.cwe = cwe; + finding.cvss_score = self.cvss_score.filter(|s| (0.0..=10.0).contains(s)); + finding.file_path = self.location.filter(|l| !l.trim().is_empty()); + finding.code_snippet = self.evidence.map(|e| truncate(&e, MAX_EVIDENCE_CHARS)); + finding.reproduction = self.reproduction.filter(|r| !r.trim().is_empty()); + finding.remediation = self.remediation.filter(|r| !r.trim().is_empty()); + finding.rule_id = self.rule_id; + finding.reported_by = Some(from.reported_by.to_string()); + finding + } +} + +/// `CWE-79` from `79`, `cwe-79` or `CWE-79`; `None` for anything else. +pub fn normalise_cwe(raw: &str) -> Option { + let digits = raw.trim().to_ascii_uppercase(); + let digits = digits.strip_prefix("CWE-").unwrap_or(&digits); + (!digits.is_empty() && digits.chars().all(|c| c.is_ascii_digit()) && digits != "0") + .then(|| format!("CWE-{digits}")) +} + +/// The CRA controls a verified weakness is evidence for (see +/// [`control_map::ControlMap::controls_for_cwe`]). +fn control_refs(cwe: &str) -> Vec { + control_map::ControlMap::cra() + .map(|map| { + map.controls_for_cwe(cwe) + .into_iter() + .map(|c| c.control.clone()) + .collect() + }) + .unwrap_or_default() +} + +/// `text` cut to at most `max` characters, on a character boundary. +fn truncate(text: &str, max: usize) -> String { + match text.char_indices().nth(max) { + Some((cut, _)) => format!("{}…", &text[..cut]), + None => text.to_string(), + } +} + +/// A severity from a CVSS-style score (0–10). +pub fn severity_from_score(score: f64) -> Severity { + match score { + s if s >= 9.0 => Severity::Critical, + s if s >= 7.0 => Severity::High, + s if s >= 4.0 => Severity::Medium, + s if s > 0.0 => Severity::Low, + _ => Severity::Info, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn provenance() -> Provenance<'static> { + Provenance { + target_id: "t1", + scan_type: ScanType::Pentest, + scanner: "manual", + reported_by: "u-1", + } + } + + fn finding(title: &str, location: Option<&str>) -> ManualFinding { + ManualFinding { + title: title.to_string(), + description: "d".to_string(), + severity: Severity::High, + cwe: Some("79".to_string()), + cvss_score: Some(7.5), + location: location.map(String::from), + evidence: Some("x".repeat(MAX_EVIDENCE_CHARS + 10)), + reproduction: Some(" ".to_string()), + remediation: None, + rule_id: None, + } + } + + #[test] + fn a_manual_finding_is_stored_like_a_scanned_one() { + let f = + finding("Reflected XSS", Some("https://device.local/login")).into_finding(provenance()); + assert_eq!(f.scan_type, ScanType::Pentest); + assert_eq!(f.cwe.as_deref(), Some("CWE-79")); + assert_eq!(f.file_path.as_deref(), Some("https://device.local/login")); + assert_eq!(f.reported_by.as_deref(), Some("u-1")); + assert_eq!(f.reproduction, None, "blank text is not stored"); + assert!(f + .code_snippet + .is_some_and(|e| e.chars().count() == MAX_EVIDENCE_CHARS + 1)); + assert!(!f.control_refs.is_empty(), "CWE-79 maps to a CRA control"); + } + + #[test] + fn the_same_finding_twice_has_one_fingerprint() { + let a = finding("XSS", Some("/a")).into_finding(provenance()); + let b = finding("XSS", Some("/a")).into_finding(provenance()); + let c = finding("XSS", Some("/b")).into_finding(provenance()); + assert_eq!(a.fingerprint, b.fingerprint); + assert_ne!(a.fingerprint, c.fingerprint); + } + + #[test] + fn cwes_and_scores_are_read_leniently() { + assert_eq!(normalise_cwe("cwe-89").as_deref(), Some("CWE-89")); + assert_eq!(normalise_cwe(" 22 ").as_deref(), Some("CWE-22")); + assert_eq!(normalise_cwe("0"), None); + assert_eq!(normalise_cwe("CWE-"), None); + assert_eq!(normalise_cwe("injection"), None); + assert_eq!(severity_from_score(9.8), Severity::Critical); + assert_eq!(severity_from_score(5.0), Severity::Medium); + assert_eq!(severity_from_score(0.0), Severity::Info); + } +} diff --git a/compliance-agent/src/import/sarif.rs b/compliance-agent/src/import/sarif.rs new file mode 100644 index 0000000..f35cd23 --- /dev/null +++ b/compliance-agent/src/import/sarif.rs @@ -0,0 +1,289 @@ +//! SARIF 2.1.0: what most security tools can write (Burp and ZAP through +//! extensions, Nuclei, CodeQL, semgrep, commercial DAST tools). +//! +//! Only what a finding needs is read; everything else in the document is +//! ignored, so a tool's extensions do not break the import. + +use std::collections::HashMap; + +use serde::Deserialize; + +use super::{normalise_cwe, severity_from_score, ManualFinding}; +use compliance_core::models::Severity; + +#[derive(Deserialize)] +struct Log { + /// Required, as in the schema: a JSON document without it is not SARIF, + /// and must not import as an empty report. + runs: Vec, +} + +#[derive(Deserialize)] +struct Run { + tool: Tool, + #[serde(default)] + results: Vec, +} + +#[derive(Deserialize)] +struct Tool { + driver: Driver, +} + +#[derive(Deserialize)] +struct Driver { + name: String, + #[serde(default)] + rules: Vec, +} + +#[derive(Deserialize)] +struct Rule { + id: String, + #[serde(default, rename = "shortDescription")] + short_description: Option, + #[serde(default, rename = "fullDescription")] + full_description: Option, + #[serde(default)] + help: Option, + #[serde(default)] + properties: Option, +} + +#[derive(Deserialize, Default)] +struct Properties { + #[serde(default)] + tags: Vec, + /// GitHub's convention: a CVSS-like score as a string or number. + #[serde(default, rename = "security-severity")] + security_severity: Option, +} + +#[derive(Deserialize)] +struct Message { + #[serde(default)] + text: String, +} + +#[derive(Deserialize)] +struct SarifResult { + #[serde(default, rename = "ruleId")] + rule_id: Option, + #[serde(default)] + level: Option, + message: Message, + #[serde(default)] + locations: Vec, + #[serde(default)] + properties: Option, +} + +#[derive(Deserialize)] +struct Location { + #[serde(default, rename = "physicalLocation")] + physical: Option, +} + +#[derive(Deserialize)] +struct PhysicalLocation { + #[serde(default, rename = "artifactLocation")] + artifact: Option, + #[serde(default)] + region: Option, +} + +#[derive(Deserialize)] +struct ArtifactLocation { + #[serde(default)] + uri: Option, +} + +#[derive(Deserialize)] +struct Region { + #[serde(default, rename = "startLine")] + start_line: Option, + #[serde(default)] + snippet: Option, +} + +/// The findings of a SARIF document, each with the name of the tool that +/// reported it. +/// +/// # Errors +/// +/// When the document is not SARIF (no `runs`, or a run without a tool). +pub fn parse(json: &[u8]) -> Result, serde_json::Error> { + let log: Log = serde_json::from_slice(json)?; + Ok(log + .runs + .into_iter() + .flat_map(|run| { + let tool = run.tool.driver.name; + let rules: HashMap = run + .tool + .driver + .rules + .into_iter() + .map(|r| (r.id.clone(), r)) + .collect(); + run.results + .into_iter() + .map(|result| (tool.clone(), to_finding(result, &rules))) + .collect::>() + }) + .collect()) +} + +fn to_finding(result: SarifResult, rules: &HashMap) -> ManualFinding { + let rule = result.rule_id.as_deref().and_then(|id| rules.get(id)); + let score = result + .properties + .as_ref() + .and_then(score_of) + .or_else(|| rule.and_then(|r| r.properties.as_ref()).and_then(score_of)); + let severity = score.map_or_else( + || level_severity(result.level.as_deref()), + severity_from_score, + ); + let tags = rule + .and_then(|r| r.properties.as_ref()) + .map(|p| p.tags.as_slice()) + .unwrap_or_default(); + let physical = result.locations.first().and_then(|l| l.physical.as_ref()); + let location = physical + .and_then(|p| p.artifact.as_ref()) + .and_then(|a| a.uri.clone()) + .map(|uri| { + match physical + .and_then(|p| p.region.as_ref()) + .and_then(|r| r.start_line) + { + Some(line) => format!("{uri}:{line}"), + None => uri, + } + }); + let title = rule + .and_then(|r| r.short_description.as_ref()) + .map(|m| m.text.clone()) + .filter(|t| !t.is_empty()) + .or_else(|| result.rule_id.clone()) + .unwrap_or_else(|| first_line(&result.message.text)); + let description = match rule.and_then(|r| r.full_description.as_ref()) { + Some(full) if !full.text.is_empty() && full.text != result.message.text => { + format!("{}\n\n{}", result.message.text, full.text) + } + _ => result.message.text.clone(), + }; + ManualFinding { + title, + description, + severity, + cwe: tags.iter().find_map(|t| cwe_from_tag(t)), + cvss_score: score, + location, + evidence: physical + .and_then(|p| p.region.as_ref()) + .and_then(|r| r.snippet.as_ref()) + .map(|s| s.text.clone()), + reproduction: None, + remediation: rule.and_then(|r| r.help.as_ref()).map(|h| h.text.clone()), + rule_id: result.rule_id, + } +} + +/// `external/cwe/cwe-79` (CodeQL, semgrep) or `CWE-79`. +fn cwe_from_tag(tag: &str) -> Option { + let lower = tag.to_ascii_lowercase(); + let id = lower.rsplit('/').next().unwrap_or(&lower); + id.starts_with("cwe-").then(|| normalise_cwe(id)).flatten() +} + +fn score_of(p: &Properties) -> Option { + match p.security_severity.as_ref()? { + serde_json::Value::Number(n) => n.as_f64(), + serde_json::Value::String(s) => s.trim().parse().ok(), + _ => None, + } +} + +fn level_severity(level: Option<&str>) -> Severity { + match level { + Some("error") => Severity::High, + Some("note") => Severity::Low, + Some("none") => Severity::Info, + // SARIF's default level is `warning`. + _ => Severity::Medium, + } +} + +fn first_line(text: &str) -> String { + text.lines() + .next() + .unwrap_or("Finding") + .chars() + .take(160) + .collect() +} + +#[cfg(test)] +#[allow(clippy::expect_used)] +mod tests { + use super::*; + + const REPORT: &str = r#"{ + "version": "2.1.0", + "runs": [{ + "tool": { "driver": { "name": "Nuclei", "rules": [{ + "id": "default-login", + "shortDescription": { "text": "Default credentials accepted" }, + "fullDescription": { "text": "The web UI accepts admin/admin." }, + "help": { "text": "Force a password change on first login." }, + "properties": { "tags": ["security", "external/cwe/cwe-1392"], "security-severity": "9.1" } + }]}}, + "results": [ + { "ruleId": "default-login", "level": "error", + "message": { "text": "admin/admin works on /login" }, + "locations": [{ "physicalLocation": { "artifactLocation": { "uri": "https://192.0.2.10/login" } } }] }, + { "level": "note", "message": { "text": "Server banner discloses version\nnginx/1.18" } } + ] + }] + }"#; + + #[test] + fn results_become_findings_with_rule_details() { + let findings = parse(REPORT.as_bytes()).expect("sarif"); + assert_eq!(findings.len(), 2); + let (tool, login) = &findings[0]; + assert_eq!(tool, "Nuclei"); + assert_eq!(login.title, "Default credentials accepted"); + assert_eq!( + login.severity, + Severity::Critical, + "security-severity 9.1 wins over the level" + ); + assert_eq!(login.cwe.as_deref(), Some("CWE-1392")); + assert_eq!(login.location.as_deref(), Some("https://192.0.2.10/login")); + assert!(login.description.contains("admin/admin works")); + assert!(login.description.contains("accepts admin/admin")); + assert_eq!( + login.remediation.as_deref(), + Some("Force a password change on first login.") + ); + + let (_, banner) = &findings[1]; + assert_eq!(banner.title, "Server banner discloses version"); + assert_eq!(banner.severity, Severity::Low); + assert_eq!(banner.location, None); + } + + #[test] + fn a_document_that_is_not_sarif_is_refused() { + assert!( + parse(br#"{"runs": [{"results": []}]}"#).is_err(), + "a run needs a tool" + ); + assert!(parse(br#"{"not": "sarif"}"#).is_err(), "runs is required"); + assert!(parse(b"not json").is_err()); + assert!(parse(br#"{"runs": []}"#).is_ok_and(|f| f.is_empty())); + } +} diff --git a/compliance-agent/src/import/zap.rs b/compliance-agent/src/import/zap.rs new file mode 100644 index 0000000..6ab71e5 --- /dev/null +++ b/compliance-agent/src/import/zap.rs @@ -0,0 +1,201 @@ +//! OWASP ZAP's JSON report ("Traditional JSON Report"). +//! +//! ZAP reports one alert per rule and site, with every URL it fired on as an +//! instance. One finding per alert keeps a crawl of a hundred pages with the +//! same missing header from becoming a hundred findings; the first instance is +//! its location, and the count is said in the description. + +use serde::Deserialize; + +use super::ManualFinding; +use compliance_core::models::Severity; + +#[derive(Deserialize)] +struct Report { + site: Vec, +} + +#[derive(Deserialize)] +struct Site { + #[serde(default)] + alerts: Vec, +} + +#[derive(Deserialize)] +struct Alert { + #[serde(default)] + pluginid: String, + #[serde(default)] + alert: String, + #[serde(default)] + name: String, + #[serde(default)] + riskcode: String, + #[serde(default)] + desc: String, + #[serde(default)] + solution: String, + #[serde(default)] + cweid: String, + #[serde(default)] + instances: Vec, +} + +#[derive(Deserialize)] +struct Instance { + #[serde(default)] + uri: String, + #[serde(default)] + method: String, + #[serde(default)] + param: String, + #[serde(default)] + evidence: String, +} + +/// The findings of a ZAP JSON report. +/// +/// # Errors +/// +/// When the document is not a ZAP report (no `site` list). +pub fn parse(json: &[u8]) -> Result, serde_json::Error> { + let report: Report = serde_json::from_slice(json)?; + Ok(report + .site + .into_iter() + .flat_map(|site| site.alerts) + .map(to_finding) + .collect()) +} + +fn to_finding(alert: Alert) -> ManualFinding { + let title = if alert.alert.is_empty() { + alert.name + } else { + alert.alert + }; + let first = alert.instances.first(); + let mut description = strip_html(&alert.desc); + if alert.instances.len() > 1 { + description.push_str(&format!( + "\n\nFound on {} URLs; the first is shown.", + alert.instances.len() + )); + } + ManualFinding { + title, + description, + severity: risk_severity(&alert.riskcode), + cwe: Some(alert.cweid).filter(|c| !c.is_empty() && c != "-1"), + cvss_score: None, + location: first.map(|i| i.uri.clone()).filter(|u| !u.is_empty()), + evidence: first.and_then(|i| { + let parts: Vec = [ + (!i.method.is_empty()).then(|| format!("{} {}", i.method, i.uri)), + (!i.param.is_empty()).then(|| format!("param: {}", i.param)), + (!i.evidence.is_empty()).then(|| format!("evidence: {}", i.evidence)), + ] + .into_iter() + .flatten() + .collect(); + (!parts.is_empty()).then(|| parts.join("\n")) + }), + reproduction: None, + remediation: Some(strip_html(&alert.solution)).filter(|s| !s.is_empty()), + rule_id: Some(alert.pluginid).filter(|p| !p.is_empty()), + } +} + +/// ZAP's risk code: 3 high, 2 medium, 1 low, 0 informational. +fn risk_severity(code: &str) -> Severity { + match code.trim() { + "3" => Severity::High, + "2" => Severity::Medium, + "1" => Severity::Low, + _ => Severity::Info, + } +} + +/// ZAP writes its texts as HTML paragraphs; keep the words, one paragraph per +/// line. +fn strip_html(html: &str) -> String { + let mut text = String::with_capacity(html.len()); + let mut in_tag = false; + let mut tag = String::new(); + for c in html.chars() { + match (in_tag, c) { + (false, '<') => { + in_tag = true; + tag.clear(); + } + (true, '>') => { + in_tag = false; + if tag.eq_ignore_ascii_case("/p") || tag.eq_ignore_ascii_case("br") { + text.push('\n'); + } + } + (true, c) => tag.push(c), + (false, c) => text.push(c), + } + } + text.lines() + .map(str::trim) + .filter(|l| !l.is_empty()) + .collect::>() + .join("\n") +} + +#[cfg(test)] +#[allow(clippy::expect_used)] +mod tests { + use super::*; + + const REPORT: &str = r#"{ + "@version": "2.15.0", + "site": [{ + "@name": "https://192.0.2.10", + "alerts": [ + { "pluginid": "10038", "alert": "Content Security Policy (CSP) Header Not Set", + "riskcode": "2", "confidence": "3", "cweid": "693", + "desc": "

CSP is an added layer of security.

It helps against XSS.

", + "solution": "

Set the Content-Security-Policy header.

", + "instances": [ + { "uri": "https://192.0.2.10/", "method": "GET", "param": "", "evidence": "" }, + { "uri": "https://192.0.2.10/login", "method": "GET", "param": "", "evidence": "" } + ] }, + { "pluginid": "10096", "alert": "Timestamp Disclosure", "riskcode": "0", + "cweid": "-1", "desc": "", "solution": "", "instances": [] } + ] + }] + }"#; + + #[test] + fn one_finding_per_alert_with_its_first_url() { + let findings = parse(REPORT.as_bytes()).expect("zap"); + assert_eq!(findings.len(), 2); + let csp = &findings[0]; + assert_eq!(csp.severity, Severity::Medium); + assert_eq!(csp.cwe.as_deref(), Some("693")); + assert_eq!(csp.location.as_deref(), Some("https://192.0.2.10/")); + assert_eq!(csp.rule_id.as_deref(), Some("10038")); + assert!(csp + .description + .starts_with("CSP is an added layer of security.\nIt helps")); + assert!(csp.description.contains("Found on 2 URLs")); + assert_eq!( + csp.remediation.as_deref(), + Some("Set the Content-Security-Policy header.") + ); + assert_eq!(csp.evidence.as_deref(), Some("GET https://192.0.2.10/")); + + let ts = &findings[1]; + assert_eq!(ts.severity, Severity::Info); + assert_eq!(ts.cwe, None, "ZAP's -1 means no CWE"); + assert_eq!(ts.location, None); + } + + #[test] + fn a_document_that_is_not_a_zap_report_is_refused() { + assert!(parse(br#"{"runs": []}"#).is_err()); + } +} diff --git a/compliance-agent/src/lib.rs b/compliance-agent/src/lib.rs index d702d3d..c27245d 100644 --- a/compliance-agent/src/lib.rs +++ b/compliance-agent/src/lib.rs @@ -9,6 +9,7 @@ pub mod database; pub mod demo_seed; pub mod error; pub mod fixtures; +pub mod import; pub mod ingest; pub mod lifecycle; pub mod llm; diff --git a/compliance-agent/src/pipeline/plan.rs b/compliance-agent/src/pipeline/plan.rs index 877f330..ead2c57 100644 --- a/compliance-agent/src/pipeline/plan.rs +++ b/compliance-agent/src/pipeline/plan.rs @@ -132,7 +132,9 @@ fn phase_for(scan: ScanType) -> ScanPhase { ScanType::Lint => ScanPhase::LintScanning, ScanType::CodeReview => ScanPhase::CodeReview, ScanType::Graph => ScanPhase::GraphBuilding, - ScanType::Dast => ScanPhase::DastScanning, + // A penetration test is done by a person and never planned here; its + // findings are entered or imported, so it borrows the dynamic phase. + ScanType::Dast | ScanType::Pentest => ScanPhase::DastScanning, ScanType::FirmwareStatic => ScanPhase::FirmwareStatic, ScanType::PlcControlLogic => ScanPhase::PlcAnalysis, ScanType::MobileStatic => ScanPhase::MobileStatic, diff --git a/compliance-agent/tests/manual_findings.rs b/compliance-agent/tests/manual_findings.rs new file mode 100644 index 0000000..38b24a2 --- /dev/null +++ b/compliance-agent/tests/manual_findings.rs @@ -0,0 +1,178 @@ +//! Findings from a manual DAST run or penetration test: entered by hand and +//! imported from a report, next to the scan's findings on the target. +//! +//! Drives the real API against a live Mongo. Skips cleanly when no Mongo is +//! reachable. + +#![allow(clippy::expect_used, clippy::unwrap_used)] + +mod common; + +use std::sync::Arc; + +use axum::{middleware, Extension}; + +use compliance_agent::agent::ComplianceAgent; +use compliance_agent::api; +use compliance_agent::database::DatabasePool; + +use common::dev_config; + +/// The tenant `inject_dev_tenant` puts every request in. +const TENANT: &str = "dev"; + +const SARIF: &str = r#"{ + "version": "2.1.0", + "runs": [{ + "tool": { "driver": { "name": "Nuclei", "rules": [ + { "id": "default-login", "shortDescription": { "text": "Default credentials accepted" }, + "properties": { "tags": ["external/cwe/cwe-798"], "security-severity": "9.1" } } + ]}}, + "results": [ + { "ruleId": "default-login", "message": { "text": "admin/admin works" }, + "locations": [{ "physicalLocation": { "artifactLocation": { "uri": "https://192.0.2.10/login" } } }] }, + { "level": "note", "message": { "text": "Server banner discloses version" } } + ] + }] +}"#; + +struct Harness { + base_url: String, + client: reqwest::Client, + pool: DatabasePool, +} + +async fn start() -> Option { + let uri = std::env::var("TEST_MONGODB_URI") + .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); + let db_name = format!( + "manual_{}", + &uuid::Uuid::new_v4().simple().to_string()[..12] + ); + let Ok(pool) = DatabasePool::connect(&uri, &db_name).await else { + eprintln!("SKIP manual_findings: no MongoDB reachable at {uri}"); + return None; + }; + let agent = Arc::new(ComplianceAgent::new(dev_config(uri, db_name), pool.clone())); + let app = api::routes::build_router() + .layer(Extension(agent)) + .layer(middleware::from_fn(api::server::inject_dev_tenant)); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(async move { + axum::serve(listener, app).await.ok(); + }); + Some(Harness { + base_url: format!("http://127.0.0.1:{port}"), + client: reqwest::Client::new(), + pool, + }) +} + +impl Harness { + async fn post_json(&self, path: &str, body: serde_json::Value) -> (u16, serde_json::Value) { + let resp = self + .client + .post(format!("{}{path}", self.base_url)) + .json(&body) + .send() + .await + .unwrap(); + let status = resp.status().as_u16(); + (status, resp.json().await.unwrap_or_default()) + } + + async fn import(&self, path: &str, report: &str) -> (u16, serde_json::Value) { + let resp = self + .client + .post(format!("{}{path}", self.base_url)) + .body(report.to_string()) + .send() + .await + .unwrap(); + let status = resp.status().as_u16(); + (status, resp.json().await.unwrap_or_default()) + } + + async fn findings(&self, target: &str) -> Vec { + let body: serde_json::Value = self + .client + .get(format!( + "{}/api/v1/findings?repo_id={target}&limit=50", + self.base_url + )) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + body["data"].as_array().cloned().unwrap_or_default() + } +} + +#[tokio::test] +async fn pentest_findings_are_added_and_imported_once() { + let Some(h) = start().await else { return }; + + // Arrange: a target. + let (_, created) = h + .post_json( + "/api/v1/targets", + serde_json::json!({ "name": "sensor", "target_type": "firmware_rtos" }), + ) + .await; + let id = created["data"]["_id"]["$oid"].as_str().unwrap().to_string(); + + // Act: one finding by hand, the same one again, then a report twice. + let finding = serde_json::json!({ + "kind": "pentest", + "title": "Telnet open with a default password", + "severity": "critical", + "cwe": "798", + "location": "tcp://192.0.2.10:23", + "reproduction": "telnet 192.0.2.10; root/root", + }); + let (added, body) = h + .post_json(&format!("/api/v1/targets/{id}/findings"), finding.clone()) + .await; + let (again, _) = h + .post_json(&format!("/api/v1/targets/{id}/findings"), finding) + .await; + let import_path = format!("/api/v1/targets/{id}/findings/import?format=sarif&kind=pentest"); + let (_, first) = h.import(&import_path, SARIF).await; + let (_, second) = h.import(&import_path, SARIF).await; + let (refused, _) = h.import(&import_path, "{\"not\": \"sarif\"}").await; + let (missing, _) = h + .post_json( + "/api/v1/targets/000000000000000000000000/findings", + serde_json::json!({ "kind": "dast", "title": "x", "severity": "low" }), + ) + .await; + + // Assert + assert_eq!(added, 201); + assert_eq!(body["data"]["scan_type"], "pentest"); + assert_eq!(body["data"]["reported_by"], "dev-user"); + assert!(body["data"]["control_refs"] + .as_array() + .unwrap() + .iter() + .any(|c| c == "cra-ai-8")); + assert_eq!(again, 409, "the same finding is not added twice"); + assert_eq!(first["data"]["imported"], 2); + assert_eq!(second["data"]["imported"], 0); + assert_eq!(second["data"]["duplicates"], 2); + assert_eq!(refused, 422); + assert_eq!(missing, 404); + + let stored = h.findings(&id).await; + assert_eq!(stored.len(), 3, "{stored:#?}"); + let nuclei = stored + .iter() + .find(|f| f["scanner"] == "Nuclei" && f["severity"] == "critical") + .expect("imported finding"); + assert_eq!(nuclei["file_path"], "https://192.0.2.10/login"); + + h.pool.drop_tenant(TENANT).await.ok(); +} diff --git a/compliance-core/src/models/finding.rs b/compliance-core/src/models/finding.rs index 5085b9c..ce3aea6 100644 --- a/compliance-core/src/models/finding.rs +++ b/compliance-core/src/models/finding.rs @@ -80,6 +80,13 @@ pub struct Finding { /// triage against the `control-map` LUT). Empty when unmapped. #[serde(default)] pub control_refs: Vec, + /// Who entered or imported this finding by hand (a user id); `None` for + /// findings a scanner produced. + #[serde(default)] + pub reported_by: Option, + /// How to reproduce the finding, for findings from a manual test. + #[serde(default)] + pub reproduction: Option, #[serde(with = "super::serde_helpers::bson_datetime")] pub created_at: DateTime, #[serde(with = "super::serde_helpers::bson_datetime")] @@ -123,6 +130,8 @@ impl Finding { triage_rationale: None, developer_feedback: None, control_refs: Vec::new(), + reported_by: None, + reproduction: None, created_at: now, updated_at: now, } diff --git a/compliance-core/src/models/scan.rs b/compliance-core/src/models/scan.rs index 9328b51..d9a20e5 100644 --- a/compliance-core/src/models/scan.rs +++ b/compliance-core/src/models/scan.rs @@ -27,6 +27,9 @@ pub enum ScanType { /// Dynamic probing of a running PLC/SPS device over industrial protocols /// (Modbus/TCP, OPC UA, …) for exposed/unauthenticated control access. IcsProbe, + /// A penetration test done by a person; its findings are entered or + /// imported by hand. + Pentest, } impl std::fmt::Display for ScanType { @@ -47,6 +50,7 @@ impl std::fmt::Display for ScanType { Self::MobileStatic => write!(f, "mobile_static"), Self::ContainerScan => write!(f, "container_scan"), Self::IcsProbe => write!(f, "ics_probe"), + Self::Pentest => write!(f, "pentest"), } } } diff --git a/compliance-dashboard/src/components/manual_findings.rs b/compliance-dashboard/src/components/manual_findings.rs new file mode 100644 index 0000000..1a4ca25 --- /dev/null +++ b/compliance-dashboard/src/components/manual_findings.rs @@ -0,0 +1,208 @@ +//! On a target: add a finding from a manual DAST run or penetration test, or +//! import the tool's report (SARIF, ZAP JSON). The agent refuses both for +//! anyone but the organisation's administrators, and the refusal is shown. + +use dioxus::prelude::*; + +use crate::i18n::texts::{common, findings as ftx, manual as tx}; +use crate::i18n::use_lang; +use crate::infrastructure::manual_findings::{ + create_manual_finding, import_findings_report, ManualFindingDto, +}; + +/// `Some(text)` for a field with something in it. +fn filled(value: String) -> Option { + (!value.trim().is_empty()).then_some(value) +} + +/// The outcome of the last save or import, shown under the panel. +#[derive(Debug, Clone, PartialEq)] +enum Outcome { + None, + Working, + Done(String), + Failed(String), +} + +#[component] +pub fn ManualFindingsPanel(target_id: String, on_change: EventHandler<()>) -> Element { + let lang = use_lang()(); + let mut kind = use_signal(|| "pentest".to_string()); + let mut title = use_signal(String::new); + let mut severity = use_signal(|| "high".to_string()); + let mut cwe = use_signal(String::new); + let mut cvss = use_signal(String::new); + let mut location = use_signal(String::new); + let mut tool = use_signal(String::new); + let description = use_signal(String::new); + let evidence = use_signal(String::new); + let reproduction = use_signal(String::new); + let remediation = use_signal(String::new); + let mut format = use_signal(|| "sarif".to_string()); + let mut report = use_signal(|| Option::::None); + let mut outcome = use_signal(|| Outcome::None); + + let id_for_save = target_id.clone(); + let id_for_import = target_id; + let busy = outcome() == Outcome::Working; + let field = "display: flex; flex-direction: column; gap: 4px; flex: 1; min-width: 200px;"; + let area = "width: 100%; min-height: 60px;"; + + rsx! { + div { style: "margin-top: 8px;", + div { style: "opacity: 0.75; font-size: 0.85em; margin-bottom: 8px;", {tx::HINT.get(lang)} } + div { style: "display: flex; gap: 8px; flex-wrap: wrap; align-items: flex-end;", + label { style: field, + {tx::KIND.get(lang)} + select { + value: "{kind}", + onchange: move |e| kind.set(e.value()), + option { value: "pentest", selected: kind() == "pentest", {tx::KIND_PENTEST.get(lang)} } + option { value: "dast", selected: kind() == "dast", {tx::KIND_DAST.get(lang)} } + } + } + } + + h5 { style: "margin: 12px 0 6px;", {tx::ADD_ONE.get(lang)} } + div { style: "display: flex; gap: 8px; flex-wrap: wrap;", + label { style: "{field} flex: 2;", + {tx::FINDING_TITLE.get(lang)} + input { r#type: "text", value: "{title}", oninput: move |e| title.set(e.value()) } + } + label { style: field, + {tx::SEVERITY.get(lang)} + select { + value: "{severity}", + onchange: move |e| severity.set(e.value()), + option { value: "critical", selected: severity() == "critical", {common::CRITICAL.get(lang)} } + option { value: "high", selected: severity() == "high", {common::HIGH.get(lang)} } + option { value: "medium", selected: severity() == "medium", {common::MEDIUM.get(lang)} } + option { value: "low", selected: severity() == "low", {common::LOW.get(lang)} } + option { value: "info", selected: severity() == "info", {ftx::INFO.get(lang)} } + } + } + } + div { style: "display: flex; gap: 8px; flex-wrap: wrap; margin-top: 6px;", + label { style: "{field} flex: 2;", + {tx::LOCATION.get(lang)} + input { r#type: "text", value: "{location}", oninput: move |e| location.set(e.value()) } + } + label { style: field, + {tx::CWE.get(lang)} + input { r#type: "text", value: "{cwe}", oninput: move |e| cwe.set(e.value()) } + } + label { style: field, + {tx::CVSS.get(lang)} + input { r#type: "number", min: "0", max: "10", step: "0.1", value: "{cvss}", oninput: move |e| cvss.set(e.value()) } + } + label { style: field, + {tx::TOOL.get(lang)} + input { r#type: "text", value: "{tool}", oninput: move |e| tool.set(e.value()) } + } + } + for (label, mut signal) in [ + (tx::DESCRIPTION, description), + (tx::EVIDENCE, evidence), + (tx::REPRODUCTION, reproduction), + (tx::REMEDIATION, remediation), + ] { + label { style: "display: block; margin-top: 6px;", + {label.get(lang)} + textarea { style: area, value: "{signal}", oninput: move |e| signal.set(e.value()) } + } + } + button { + class: "btn btn-primary", + style: "margin-top: 8px;", + disabled: busy || title().trim().is_empty(), + onclick: move |_| { + let dto = ManualFindingDto { + kind: kind(), + title: title(), + severity: severity(), + description: description(), + cwe: filled(cwe()), + cvss_score: cvss().trim().replace(',', ".").parse().ok(), + location: filled(location()), + evidence: filled(evidence()), + reproduction: filled(reproduction()), + remediation: filled(remediation()), + tool: filled(tool()), + }; + let id = id_for_save.clone(); + outcome.set(Outcome::Working); + spawn(async move { + match create_manual_finding(id, dto).await { + Ok(()) => { + outcome.set(Outcome::Done(tx::SAVED.get(lang).to_string())); + for mut s in [title, cwe, cvss, location, description, evidence, reproduction, remediation] { + s.set(String::new()); + } + on_change.call(()); + } + Err(e) => outcome.set(Outcome::Failed(e.to_string())), + } + }); + }, + {tx::SAVE.get(lang)} + } + + h5 { style: "margin: 16px 0 6px;", {tx::IMPORT.get(lang)} } + div { style: "display: flex; gap: 8px; flex-wrap: wrap; align-items: flex-end;", + label { style: field, + {tx::FORMAT.get(lang)} + select { + value: "{format}", + onchange: move |e| format.set(e.value()), + option { value: "sarif", selected: format() == "sarif", "SARIF 2.1.0" } + option { value: "zap", selected: format() == "zap", "OWASP ZAP (JSON)" } + } + } + label { style: "{field} flex: 2;", + {tx::FILE.get(lang)} + input { + r#type: "file", + accept: ".json,.sarif", + onchange: move |evt| report.set(evt.files().into_iter().next()), + } + } + button { + class: "btn btn-secondary", + disabled: busy || report().is_none(), + onclick: move |_| { + let Some(file) = report() else { return; }; + let id = id_for_import.clone(); + let (fmt, k) = (format(), kind()); + outcome.set(Outcome::Working); + spawn(async move { + match import_findings_report(id, fmt, k, file.into()).await { + Ok(summary) => { + outcome.set(Outcome::Done(format!( + "{} {}, {} {}", + summary.imported, + tx::IMPORTED.get(lang), + summary.duplicates, + tx::DUPLICATES.get(lang) + ))); + report.set(None); + on_change.call(()); + } + Err(e) => outcome.set(Outcome::Failed(e.to_string())), + } + }); + }, + {tx::RUN_IMPORT.get(lang)} + } + } + + match outcome() { + Outcome::None => rsx! {}, + Outcome::Working => rsx! { div { style: "margin-top: 8px; opacity: 0.7;", {tx::WORKING.get(lang)} } }, + Outcome::Done(msg) => rsx! { div { style: "margin-top: 8px; color: var(--success);", "{msg}" } }, + Outcome::Failed(e) => rsx! { + div { style: "margin-top: 8px; color: var(--danger);", "{tx::FAILED.get(lang)}: {e}" } + }, + } + } + } +} diff --git a/compliance-dashboard/src/components/mod.rs b/compliance-dashboard/src/components/mod.rs index d3fa3a0..6896bc7 100644 --- a/compliance-dashboard/src/components/mod.rs +++ b/compliance-dashboard/src/components/mod.rs @@ -7,6 +7,7 @@ pub mod demo_targets; pub mod file_tree; pub mod help_chat; pub mod lang_toggle; +pub mod manual_findings; pub mod notification_bell; pub mod page_header; pub mod pagination; diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index 546bffb..447cd6f 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -1141,6 +1141,14 @@ pub mod findings { de: "Speichern fehlgeschlagen", en: "Saving failed", }; + pub const REPRODUCTION: Text = Text { + de: "Reproduktion", + en: "Steps to reproduce", + }; + pub const REPORTED_BY: Text = Text { + de: "Erfasst von", + en: "Reported by", + }; /// A finding status in words. Exhaustive: a new status needs both. pub fn status(status: &FindingStatus) -> Text { @@ -1186,12 +1194,13 @@ pub mod findings { ScanType::MobileStatic => ("Mobile App", "Mobile app"), ScanType::ContainerScan => ("Container", "Container"), ScanType::IcsProbe => ("Industrieprotokolle (ICS)", "Industrial protocols (ICS)"), + ScanType::Pentest => ("Penetrationstest", "Penetration test"), }; Text { de, en } } /// Every scan type a finding can carry, in the filter's order. - pub const SCAN_TYPES: [ScanType; 15] = [ + pub const SCAN_TYPES: [ScanType; 16] = [ ScanType::Sast, ScanType::SecretDetection, ScanType::Cve, @@ -1200,6 +1209,7 @@ pub mod findings { ScanType::PlcControlLogic, ScanType::IcsProbe, ScanType::Dast, + ScanType::Pentest, ScanType::Lint, ScanType::CodeReview, ScanType::Gdpr, @@ -1432,3 +1442,115 @@ pub mod sbom { en: "Computing diff...", }; } + +/// Adding findings from a manual DAST run or penetration test. +pub mod manual { + use super::Text; + + pub const TITLE: Text = Text { + de: "Befunde aus manuellen Tests", + en: "Findings from manual tests", + }; + pub const HINT: Text = Text { + de: "Ergebnisse eines DAST-Laufs oder Penetrationstests erscheinen neben den \ + Befunden der Prüfung. Nur Administratoren der Organisation können sie anlegen.", + en: "Results of a DAST run or penetration test appear next to the scan's \ + findings. Only the organisation's administrators can add them.", + }; + pub const ADD_ONE: Text = Text { + de: "Befund erfassen", + en: "Add a finding", + }; + pub const IMPORT: Text = Text { + de: "Bericht importieren", + en: "Import a report", + }; + pub const KIND: Text = Text { + de: "Test", + en: "Test", + }; + pub const KIND_PENTEST: Text = Text { + de: "Penetrationstest", + en: "Penetration test", + }; + pub const KIND_DAST: Text = Text { + de: "DAST", + en: "DAST", + }; + pub const FINDING_TITLE: Text = Text { + de: "Titel", + en: "Title", + }; + pub const SEVERITY: Text = Text { + de: "Schweregrad", + en: "Severity", + }; + pub const CWE: Text = Text { + de: "CWE (z. B. 798)", + en: "CWE (e.g. 798)", + }; + pub const CVSS: Text = Text { + de: "CVSS-Wert (0–10)", + en: "CVSS score (0–10)", + }; + pub const LOCATION: Text = Text { + de: "Fundstelle (URL, Endpunkt, Port)", + en: "Location (URL, endpoint, port)", + }; + pub const TOOL: Text = Text { + de: "Werkzeug (optional)", + en: "Tool (optional)", + }; + pub const DESCRIPTION: Text = Text { + de: "Beschreibung", + en: "Description", + }; + pub const EVIDENCE: Text = Text { + de: "Nachweis (Anfrage/Antwort, Ausgabe)", + en: "Evidence (request/response, output)", + }; + pub const REPRODUCTION: Text = Text { + de: "Schritte zur Reproduktion", + en: "Steps to reproduce", + }; + pub const REMEDIATION: Text = Text { + de: "Empfohlene Behebung", + en: "Recommended fix", + }; + pub const SAVE: Text = Text { + de: "Befund speichern", + en: "Save finding", + }; + pub const SAVED: Text = Text { + de: "Befund gespeichert.", + en: "Finding saved.", + }; + pub const FORMAT: Text = Text { + de: "Format", + en: "Format", + }; + pub const FILE: Text = Text { + de: "Berichtsdatei", + en: "Report file", + }; + pub const RUN_IMPORT: Text = Text { + de: "Importieren", + en: "Import", + }; + pub const IMPORTED: Text = Text { + de: "importiert", + en: "imported", + }; + pub const DUPLICATES: Text = Text { + de: "bereits vorhanden", + en: "already present", + }; + pub const FAILED: Text = Text { + de: "Fehlgeschlagen", + en: "Failed", + }; + pub const WORKING: Text = Text { + de: "Wird verarbeitet …", + en: "Working...", + }; +} diff --git a/compliance-dashboard/src/infrastructure/manual_findings.rs b/compliance-dashboard/src/infrastructure/manual_findings.rs new file mode 100644 index 0000000..db33ebc --- /dev/null +++ b/compliance-dashboard/src/infrastructure/manual_findings.rs @@ -0,0 +1,107 @@ +//! Findings from a manual DAST run or penetration test: one entered in a +//! form, or a tool's report imported (see the agent's `import` module). + +use dioxus::prelude::*; +use serde::{Deserialize, Serialize}; + +/// A finding typed into the form. +#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)] +pub struct ManualFindingDto { + /// `pentest` or `dast`. + pub kind: String, + pub title: String, + /// `critical`, `high`, `medium`, `low` or `info`. + pub severity: String, + #[serde(skip_serializing_if = "String::is_empty")] + pub description: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub cwe: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub cvss_score: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub location: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub evidence: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub reproduction: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub remediation: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub tool: Option, +} + +/// What an import did. +#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)] +pub struct ImportSummary { + pub total: usize, + pub imported: usize, + pub duplicates: usize, +} + +/// The agent's reply to an import (read on the server only). +#[cfg(feature = "server")] +#[derive(Debug, Deserialize)] +struct ImportResponse { + data: ImportSummary, +} + +/// Add one finding to a target. +#[server] +pub async fn create_manual_finding( + target_id: String, + finding: ManualFindingDto, +) -> Result<(), ServerFnError> { + let resp = super::agent_client::agent_request( + reqwest::Method::POST, + &format!("/api/v1/targets/{target_id}/findings"), + ) + .await? + .json(&finding) + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + super::agent_client::ok_or_error(resp).await +} + +/// Import a SARIF or ZAP JSON report into a target, streamed to the agent as +/// the request body. `format` is `sarif` or `zap`, `kind` is `pentest` or +/// `dast`. +#[post("/api/findings-import/{id}?format&kind")] +pub async fn import_findings_report( + id: String, + format: String, + kind: String, + file: dioxus::fullstack::FileStream, +) -> Result { + let resp = super::agent_client::agent_request( + reqwest::Method::POST, + &format!("/api/v1/targets/{id}/findings/import?format={format}&kind={kind}"), + ) + .await? + .header(reqwest::header::CONTENT_TYPE, "application/json") + .body(reqwest::Body::wrap_stream(file)) + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + let body: ImportResponse = super::agent_client::json_or_error(resp).await?; + Ok(body.data) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn empty_optional_fields_are_not_sent() { + let dto = ManualFindingDto { + kind: "pentest".into(), + title: "Telnet open".into(), + severity: "high".into(), + ..Default::default() + }; + let json = serde_json::to_value(&dto).unwrap_or_default(); + assert_eq!(json["kind"], "pentest"); + assert!(json.get("description").is_none()); + assert!(json.get("cwe").is_none()); + } +} diff --git a/compliance-dashboard/src/infrastructure/mod.rs b/compliance-dashboard/src/infrastructure/mod.rs index f2de95a..66cda84 100644 --- a/compliance-dashboard/src/infrastructure/mod.rs +++ b/compliance-dashboard/src/infrastructure/mod.rs @@ -7,6 +7,7 @@ pub mod findings; pub mod graph; pub mod help_chat; pub mod issues; +pub mod manual_findings; pub mod mcp; pub mod mcp_tokens; pub mod notifications; diff --git a/compliance-dashboard/src/pages/finding_detail.rs b/compliance-dashboard/src/pages/finding_detail.rs index 8c02887..879abac 100644 --- a/compliance-dashboard/src/pages/finding_detail.rs +++ b/compliance-dashboard/src/pages/finding_detail.rs @@ -94,6 +94,10 @@ pub fn FindingDetailPage(id: String) -> Element { } span { style: "opacity: 0.7;", {tx::COL_SCANNER.get(lang)} } span { "{f.scanner}" } + if let Some(who) = &f.reported_by { + span { style: "opacity: 0.7;", {tx::REPORTED_BY.get(lang)} } + span { "{who}" } + } if let Some(rule) = &f.rule_id { span { style: "opacity: 0.7;", {tx::RULE.get(lang)} } span { style: "font-family: monospace; word-break: break-all;", "{rule}" } @@ -133,6 +137,13 @@ pub fn FindingDetailPage(id: String) -> Element { } } + if let Some(steps) = &f.reproduction { + div { class: "card", + div { class: "card-header", {tx::REPRODUCTION.get(lang)} } + p { style: "white-space: pre-wrap;", "{steps}" } + } + } + if let Some(remediation) = &f.remediation { div { class: "card", div { class: "card-header", {tx::REMEDIATION.get(lang)} } diff --git a/compliance-dashboard/src/pages/targets.rs b/compliance-dashboard/src/pages/targets.rs index ef03593..5454c51 100644 --- a/compliance-dashboard/src/pages/targets.rs +++ b/compliance-dashboard/src/pages/targets.rs @@ -10,6 +10,7 @@ use dioxus_free_icons::icons::bs_icons::*; use dioxus_free_icons::Icon; use crate::components::demo_targets::DemoTargetsButton; +use crate::components::manual_findings::ManualFindingsPanel; use crate::components::page_header::PageHeader; use crate::components::scan_runs::{status_badge, ScanRunList}; use crate::components::toast::{ToastType, Toasts}; @@ -580,6 +581,11 @@ pub fn TargetsPage() -> Element { } h4 { style: "margin: 12px 0 6px;", {tx::APPLICABLE_SCANS.get(lang)} } TargetScans { id: id.clone() } + h4 { style: "margin: 12px 0 6px;", {crate::i18n::texts::manual::TITLE.get(lang)} } + ManualFindingsPanel { + target_id: id.clone(), + on_change: move |_| targets.restart(), + } } } } diff --git a/control-map/src/lib.rs b/control-map/src/lib.rs index 897815a..65320a9 100644 --- a/control-map/src/lib.rs +++ b/control-map/src/lib.rs @@ -114,6 +114,17 @@ impl ControlMap { .collect() } + /// Controls any tool binds to `cwe`. For findings a person verified (a + /// penetration test), where the tool that would have found it does not + /// matter: the weakness is the same one a scanner's rule for it covers. + /// Controls bound only by rule id are never matched this way. + pub fn controls_for_cwe(&self, cwe: &str) -> Vec<&ControlEntry> { + self.controls + .iter() + .filter(|c| c.scans.iter().any(|s| s.cwe.iter().any(|x| x == cwe))) + .collect() + } + /// Count of controls in each coverage bucket. pub fn summary(&self) -> CoverageSummary { let mut s = CoverageSummary::default(); @@ -153,6 +164,18 @@ pub enum MapError { mod tests { use super::*; + #[test] + fn a_cwe_maps_whatever_tool_found_it() { + let map = ControlMap::cra().expect("map"); + let ids: Vec<&str> = map + .controls_for_cwe("CWE-798") + .iter() + .map(|c| c.control.as_str()) + .collect(); + assert!(ids.contains(&"cra-ai-8"), "{ids:?}"); + assert!(map.controls_for_cwe("CWE-0").is_empty()); + } + #[test] fn cra_map_loads_all_40_controls() { let map = ControlMap::cra().expect("CRA map should parse"); diff --git a/docs/.vitepress/config.mts b/docs/.vitepress/config.mts index f70c59d..ff1c315 100644 --- a/docs/.vitepress/config.mts +++ b/docs/.vitepress/config.mts @@ -26,6 +26,7 @@ export default withMermaid(defineConfig({ { text: 'PLC / SPS (CODESYS)', link: '/guide/plc' }, { text: 'Demo Targets', link: '/guide/demo-targets' }, { text: 'Understanding Findings', link: '/guide/findings' }, + { text: 'Findings from Manual Tests', link: '/guide/manual-findings' }, { text: 'SBOM & Licenses', link: '/guide/sbom' }, { text: 'Issues & Tracking', link: '/guide/issues' }, { text: 'Webhooks & PR Reviews', link: '/guide/webhooks' }, diff --git a/docs/guide/manual-findings.md b/docs/guide/manual-findings.md new file mode 100644 index 0000000..cf69cf4 --- /dev/null +++ b/docs/guide/manual-findings.md @@ -0,0 +1,62 @@ +# Findings from Manual Tests + +A DAST run or a penetration test is done by a person, not by the scanner. Its +results still belong on the target, next to the scan's findings: in the same +list, with the same statuses, and in the same evidence. + +Two ways to add them, both on a target's details under **Targets**: + +- **Add a finding**: one at a time, in a form. +- **Import a report**: a tool's report as a whole, in SARIF 2.1.0 or OWASP + ZAP's JSON report. + +Only the organisation's administrators (`IT_ADMIN`) can add or import findings. +A tester working for a customer is invited into that customer's organisation +with that role. + +## Add a finding + +| Field | Notes | +|---|---| +| Test | Penetration test or DAST | +| Title, severity | Required | +| Location | A URL, an endpoint, a port (`tcp://192.0.2.10:23`) | +| CWE | `798` or `CWE-798`. It links the finding to the CRA requirements that weakness falls under | +| CVSS score | 0–10 | +| Tool | Optional; `manual` when empty | +| Description, evidence, steps to reproduce, recommended fix | Free text. Evidence is kept up to 4,000 characters | + +The same finding (same tool, title and location) can be added only once. + +## Import a report + +| Format | Written by | One finding per | +|---|---|---| +| SARIF 2.1.0 | Nuclei, Burp and ZAP (via extensions), most commercial DAST tools | result | +| OWASP ZAP JSON ("Traditional JSON Report") | ZAP | alert: its first URL is the location, and the description says how many URLs it was found on | + +Severity comes from the report: SARIF's `security-severity` score when present, +else the result's level; ZAP's risk code. CWEs are read from SARIF rule tags +(`external/cwe/cwe-79`) and ZAP's `cweid`. + +Importing the same report again adds nothing: each finding already on the +target is counted as already present. + +## API + +```bash +# One finding +curl -X POST "$AGENT/api/v1/targets/$TARGET/findings" \ + -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \ + -d '{"kind": "pentest", "title": "Telnet open with a default password", + "severity": "critical", "cwe": "798", "location": "tcp://192.0.2.10:23", + "reproduction": "telnet 192.0.2.10, log in as root/root"}' + +# A report (the body is the report itself, up to 20 MB) +curl -X POST "$AGENT/api/v1/targets/$TARGET/findings/import?format=sarif&kind=pentest" \ + -H "Authorization: Bearer $TOKEN" --data-binary @nuclei.sarif +``` + +`format` is `sarif` or `zap`; `kind` is `pentest` or `dast`. The import answers +with `{"total": …, "imported": …, "duplicates": …}`. A document that is not +the named format is refused with 422, and a user without `IT_ADMIN` with 403. -- 2.54.1