diff --git a/.gitignore b/.gitignore index ac3f01d..17acc30 100644 --- a/.gitignore +++ b/.gitignore @@ -4,4 +4,5 @@ __pycache__/ *.egg-info/ *.pyc artifacts/ +generated/ target/ diff --git a/README.md b/README.md index 8d286c6..3f7124a 100644 --- a/README.md +++ b/README.md @@ -119,6 +119,8 @@ openvas-enrich-results \ By default the CLI and e2e flow prefer the Rust enrichment binary when it is present. The current Python implementation stays available as an explicit `--engine python` reference/debug path. +For the standalone offline enrichment CLI, the Python wrapper now passes large file-based jobs +straight through to the Rust binary instead of loading the enriched payload back into Python memory. If you want to invoke the Rust binary directly, build it first and call `scan-enrich-results`: @@ -159,7 +161,7 @@ This command: 4. Polls according to the configured completion mode: quick checks stop after first findings; full checks wait for the scan status to reach `succeeded` 5. Fetches results in JSON format 6. Enriches each result with matching NASL VT metadata from `vt-metadata.json` and/or matching Notus advisory metadata from `.notus` files when available (Rust by default when bundled, Python optionally for reference/debugging) - - current implementation selectively loads feed metadata by OID/CVE, but it does not yet stream the full raw result set end-to-end + - the Rust CLI now performs a two-pass, streaming file-based enrichment path so large offline result sets do not need to be materialized in memory all at once 7. Stops the scan after first findings in quick mode, or lets it finish naturally in full mode 8. Deletes the scan @@ -357,6 +359,24 @@ cargo build --release -p scan-enrichment ./target/release/scan-enrich-results --help ``` +Generate synthetic large-result fixtures and compare Python vs Rust enrichment performance: + +```bash +python3 scripts/generate_synthetic_results.py \ + --output generated/synthetic-scan-results-500k.json \ + --vt-metadata-output generated/synthetic-vt-metadata.json + +python3 scripts/benchmark_enrichment.py \ + --results generated/synthetic-scan-results-500k.json \ + --vt-metadata generated/synthetic-vt-metadata.json \ + --runs 3 +``` + +The benchmark script builds the release Rust binary if needed, runs both engines against the same +fixture, verifies semantic output parity by normalized JSON SHA-256 (and also reports byte-for-byte +output parity separately), and writes a JSON report to +`generated/enrichment-benchmark-report.json`. + This keeps the project virtualenv in `.venv/` and avoids ad-hoc `pip install` drift. ## VS Code devcontainer diff --git a/rust/scan-enrichment/src/lib.rs b/rust/scan-enrichment/src/lib.rs index 4685e3b..88829e0 100644 --- a/rust/scan-enrichment/src/lib.rs +++ b/rust/scan-enrichment/src/lib.rs @@ -1,11 +1,12 @@ use std::collections::{BTreeSet, HashMap, HashSet}; use std::fs; -use std::io::Read; +use std::io::{BufRead, BufReader, Read, Write}; use std::path::{Path, PathBuf}; use anyhow::{anyhow, Context, Result}; use flate2::read::GzDecoder; -use serde_json::{Map, Value}; +use serde::de::{DeserializeSeed, IgnoredAny, MapAccess, SeqAccess, Visitor}; +use serde_json::{Deserializer, Map, Value}; use walkdir::WalkDir; const VT_METADATA_FILENAME: &str = "vt-metadata.json"; @@ -18,13 +19,27 @@ pub fn run_cli( scap_path: Option<&Path>, output_path: Option<&Path>, ) -> Result<()> { - let enriched = - enrich_results_from_files(results_path, vt_metadata_path, notus_path, scap_path)?; - let rendered = serde_json::to_string_pretty(&enriched)?; if let Some(path) = output_path { - fs::write(path, format!("{rendered}\n"))?; + let file = fs::File::create(path) + .with_context(|| format!("Failed to create {}", path.display()))?; + let writer = std::io::BufWriter::new(file); + enrich_results_from_files_to_writer( + results_path, + vt_metadata_path, + notus_path, + scap_path, + writer, + )?; } else { - println!("{rendered}"); + let stdout = std::io::stdout(); + let writer = std::io::BufWriter::new(stdout.lock()); + enrich_results_from_files_to_writer( + results_path, + vt_metadata_path, + notus_path, + scap_path, + writer, + )?; } Ok(()) } @@ -46,69 +61,271 @@ pub fn enrich_results_from_files( Some(path) => Some(load_notus_advisory_index(path, &oids)?), None => None, }; + let cve_ids = collect_needed_cve_ids(vt_index.as_ref(), notus_index.as_ref()); + let scap_index = match scap_path { + Some(path) if !cve_ids.is_empty() => Some(load_scap_cve_index(path, &cve_ids)?), + Some(_) => Some(HashMap::new()), + None => None, + }; + + Ok(enrich_results( + results, + vt_index.as_ref(), + notus_index.as_ref(), + scap_index.as_ref(), + )) +} + +pub fn enrich_results_from_files_to_writer( + results_path: &Path, + vt_metadata_path: Option<&Path>, + notus_path: Option<&Path>, + scap_path: Option<&Path>, + mut writer: W, +) -> Result<()> { + let oids = collect_oids_from_results_path(results_path)?; + let vt_index = match vt_metadata_path { + Some(path) => Some(load_vt_metadata_index(path, &oids)?), + None => None, + }; + let notus_index = match notus_path { + Some(path) => Some(load_notus_advisory_index(path, &oids)?), + None => None, + }; + let cve_ids = collect_needed_cve_ids(vt_index.as_ref(), notus_index.as_ref()); + let scap_index = match scap_path { + Some(path) if !cve_ids.is_empty() => Some(load_scap_cve_index(path, &cve_ids)?), + Some(_) => Some(HashMap::new()), + None => None, + }; + + writer.write_all(b"[")?; + let mut first = true; + stream_results(results_path, |result| { + let enriched = enrich_one_result( + result, + vt_index.as_ref(), + notus_index.as_ref(), + scap_index.as_ref(), + ); + if !first { + writer.write_all(b",\n")?; + } else { + first = false; + } + serde_json::to_writer(&mut writer, &enriched)?; + Ok(()) + })?; + if !first { + writer.write_all(b"\n")?; + } + writer.write_all(b"]\n")?; + writer.flush()?; + Ok(()) +} + +fn load_results(path: &Path) -> Result>> { + let mut results = Vec::new(); + stream_results(path, |result| { + results.push(result); + Ok(()) + })?; + Ok(results) +} + +fn collect_oids(results: &[Map]) -> HashSet { + results.iter().filter_map(extract_result_oid).collect() +} +fn collect_oids_from_results_path(path: &Path) -> Result> { + let mut oids = HashSet::new(); + stream_results(path, |result| { + if let Some(oid) = extract_result_oid(&result) { + oids.insert(oid); + } + Ok(()) + })?; + Ok(oids) +} + +fn collect_needed_cve_ids( + vt_index: Option<&HashMap>, + notus_index: Option<&HashMap>>, +) -> BTreeSet { let mut cve_ids = BTreeSet::new(); - if let Some(index) = &vt_index { + if let Some(index) = vt_index { for entry in index.values() { for cve in extract_cve_ids_from_vt_metadata(entry) { cve_ids.insert(cve); } } } - if let Some(index) = ¬us_index { + if let Some(index) = notus_index { for entries in index.values() { for cve in extract_cve_ids_from_notus_metadata(entries) { cve_ids.insert(cve); } } } + cve_ids +} - let scap_index = match scap_path { - Some(path) if !cve_ids.is_empty() => Some(load_scap_cve_index(path, &cve_ids)?), - Some(_) => Some(HashMap::new()), - None => None, - }; +fn stream_results(path: &Path, mut callback: F) -> Result<()> +where + F: FnMut(Map) -> Result<()>, +{ + let file = + fs::File::open(path).with_context(|| format!("Failed to read {}", path.display()))?; + let mut reader: Box = + if path.extension().and_then(|value| value.to_str()) == Some("gz") { + Box::new(BufReader::new(GzDecoder::new(file))) + } else { + Box::new(BufReader::new(file)) + }; + let first = first_non_whitespace_byte(&mut reader)? + .ok_or_else(|| anyhow!("Scanner results JSON must not be empty"))?; + let mut deserializer = Deserializer::from_reader(reader); + match first { + b'[' => { + let seed = ResultArraySeed { + callback: &mut callback, + }; + seed.deserialize(&mut deserializer)?; + } + b'{' => { + let seed = ResultsObjectSeed { + callback: &mut callback, + }; + seed.deserialize(&mut deserializer)?; + } + _ => { + return Err(anyhow!( + "Scanner results JSON must be a list or an object with a results list" + )); + } + } + Ok(()) +} - Ok(enrich_results( - results, - vt_index.as_ref(), - notus_index.as_ref(), - scap_index.as_ref(), - )) +fn first_non_whitespace_byte(reader: &mut R) -> Result> { + loop { + let buffer = reader.fill_buf()?; + if buffer.is_empty() { + return Ok(None); + } + let consumed = buffer + .iter() + .take_while(|byte| byte.is_ascii_whitespace()) + .count(); + if consumed < buffer.len() { + return Ok(Some(buffer[consumed])); + } + reader.consume(consumed); + } } -fn load_results(path: &Path) -> Result>> { - let payload = read_json(path)?; - match payload { - Value::Array(items) => items.into_iter().map(as_object).collect::>>(), - Value::Object(mut obj) => { - let results = obj.remove("results").ok_or_else(|| { - anyhow!("Scanner results JSON must be a list or an object with a results list") - })?; - match results { - Value::Array(items) => items.into_iter().map(as_object).collect::>>(), - _ => Err(anyhow!( - "Scanner results JSON must be a list or an object with a results list" - )), - } +struct ResultArraySeed<'a, F> { + callback: &'a mut F, +} + +impl<'de, 'a, F> DeserializeSeed<'de> for ResultArraySeed<'a, F> +where + F: FnMut(Map) -> Result<()>, +{ + type Value = (); + + fn deserialize(self, deserializer: D) -> std::result::Result + where + D: serde::Deserializer<'de>, + { + deserializer.deserialize_seq(ResultArrayVisitor { + callback: self.callback, + }) + } +} + +struct ResultArrayVisitor<'a, F> { + callback: &'a mut F, +} + +impl<'de, 'a, F> Visitor<'de> for ResultArrayVisitor<'a, F> +where + F: FnMut(Map) -> Result<()>, +{ + type Value = (); + + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("a JSON array of scan result objects") + } + + fn visit_seq(self, mut seq: A) -> std::result::Result + where + A: SeqAccess<'de>, + { + while let Some(item) = seq.next_element::>()? { + (self.callback)(item).map_err(serde::de::Error::custom)?; } - _ => Err(anyhow!( - "Scanner results JSON must be a list or an object with a results list" - )), + Ok(()) } } -fn as_object(value: Value) -> Result> { - match value { - Value::Object(obj) => Ok(obj), - _ => Err(anyhow!( - "Scanner results JSON must contain only result objects" - )), +struct ResultsObjectSeed<'a, F> { + callback: &'a mut F, +} + +impl<'de, 'a, F> DeserializeSeed<'de> for ResultsObjectSeed<'a, F> +where + F: FnMut(Map) -> Result<()>, +{ + type Value = (); + + fn deserialize(self, deserializer: D) -> std::result::Result + where + D: serde::Deserializer<'de>, + { + deserializer.deserialize_map(ResultsObjectVisitor { + callback: self.callback, + }) } } -fn collect_oids(results: &[Map]) -> HashSet { - results.iter().filter_map(extract_result_oid).collect() +struct ResultsObjectVisitor<'a, F> { + callback: &'a mut F, +} + +impl<'de, 'a, F> Visitor<'de> for ResultsObjectVisitor<'a, F> +where + F: FnMut(Map) -> Result<()>, +{ + type Value = (); + + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("an object containing a results array") + } + + fn visit_map(self, mut map: A) -> std::result::Result + where + A: MapAccess<'de>, + { + let mut found_results = false; + while let Some(key) = map.next_key::()? { + if key == "results" { + found_results = true; + let seed = ResultArraySeed { + callback: self.callback, + }; + map.next_value_seed(seed)?; + } else { + let _: IgnoredAny = map.next_value()?; + } + } + if !found_results { + return Err(serde::de::Error::custom( + "Scanner results JSON must be a list or an object with a results list", + )); + } + Ok(()) + } } fn extract_result_oid(result: &Map) -> Option { diff --git a/scripts/benchmark_enrichment.py b/scripts/benchmark_enrichment.py new file mode 100644 index 0000000..c4b0790 --- /dev/null +++ b/scripts/benchmark_enrichment.py @@ -0,0 +1,179 @@ +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import statistics +import subprocess +import sys +import tempfile +import time +from pathlib import Path +from typing import Any + +REPO_ROOT = Path(__file__).resolve().parents[1] +DEFAULT_RESULTS = REPO_ROOT / "generated" / "synthetic-scan-results-500k.json" +DEFAULT_VT_METADATA = REPO_ROOT / "generated" / "synthetic-vt-metadata.json" +DEFAULT_REPORT = REPO_ROOT / "generated" / "enrichment-benchmark-report.json" + + +def ensure_rust_binary() -> Path: + candidate = REPO_ROOT / "target" / "release" / "scan-enrich-results" + if candidate.is_file(): + return candidate + subprocess.run( + ["cargo", "build", "--release", "-p", "scan-enrichment"], + cwd=REPO_ROOT, + check=True, + ) + if not candidate.is_file(): + raise FileNotFoundError("Rust enrichment binary was not built at target/release/scan-enrich-results") + return candidate + + +def sha256_file(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def semantic_sha256_file(path: Path) -> str: + payload = json.loads(path.read_text(encoding="utf-8")) + normalized = json.dumps(payload, sort_keys=True, separators=(",", ":")) + return hashlib.sha256(normalized.encode("utf-8")).hexdigest() + + +def run_command(command: list[str], *, env: dict[str, str]) -> dict[str, Any]: + with tempfile.NamedTemporaryFile(prefix="enrichment-bench-", suffix=".json", delete=False) as tmp: + output_path = Path(tmp.name) + started = time.perf_counter() + try: + subprocess.run(command + ["--output", str(output_path)], cwd=REPO_ROOT, env=env, check=True) + elapsed = time.perf_counter() - started + return { + "command": command, + "elapsed_seconds": elapsed, + "output_path": str(output_path), + "output_bytes": output_path.stat().st_size, + "byte_output_sha256": sha256_file(output_path), + "semantic_output_sha256": semantic_sha256_file(output_path), + } + except Exception: + output_path.unlink(missing_ok=True) + raise + + +def summarize_runs(label: str, runs: list[dict[str, Any]]) -> dict[str, Any]: + timings = [run["elapsed_seconds"] for run in runs] + byte_hashes = {run["byte_output_sha256"] for run in runs} + semantic_hashes = {run["semantic_output_sha256"] for run in runs} + output_sizes = {run["output_bytes"] for run in runs} + if len(byte_hashes) != 1 or len(semantic_hashes) != 1 or len(output_sizes) != 1: + raise ValueError(f"{label} runs did not produce stable output") + return { + "label": label, + "runs": runs, + "min_seconds": min(timings), + "max_seconds": max(timings), + "mean_seconds": statistics.mean(timings), + "median_seconds": statistics.median(timings), + "byte_output_sha256": next(iter(byte_hashes)), + "semantic_output_sha256": next(iter(semantic_hashes)), + "output_bytes": next(iter(output_sizes)), + } + + +def cleanup_runs(runs: list[dict[str, Any]]) -> None: + for run in runs: + Path(run["output_path"]).unlink(missing_ok=True) + + +def main() -> int: + parser = argparse.ArgumentParser( + description="Benchmark Python vs Rust OpenVAS enrichment on a generated scan-results payload" + ) + parser.add_argument("--results", type=Path, default=DEFAULT_RESULTS) + parser.add_argument("--vt-metadata", type=Path, default=DEFAULT_VT_METADATA) + parser.add_argument("--runs", type=int, default=3) + parser.add_argument("--warmups", type=int, default=1) + parser.add_argument("--report", type=Path, default=DEFAULT_REPORT) + args = parser.parse_args() + + if not args.results.is_file(): + raise FileNotFoundError(f"Results file not found: {args.results}") + if not args.vt_metadata.is_file(): + raise FileNotFoundError(f"VT metadata file not found: {args.vt_metadata}") + + rust_bin = ensure_rust_binary() + python_env = os.environ.copy() + python_env["PYTHONPATH"] = str(REPO_ROOT / "src") + os.pathsep + python_env.get("PYTHONPATH", "") + + python_command = [ + sys.executable, + "-m", + "scan_examples.enrichment", + "--engine", + "python", + "--results", + str(args.results), + "--vt-metadata", + str(args.vt_metadata), + ] + rust_command = [ + str(rust_bin), + "--results", + str(args.results), + "--vt-metadata", + str(args.vt_metadata), + ] + + for _ in range(args.warmups): + warm_python = run_command(python_command, env=python_env) + warm_rust = run_command(rust_command, env=os.environ.copy()) + cleanup_runs([warm_python, warm_rust]) + + python_runs = [run_command(python_command, env=python_env) for _ in range(args.runs)] + rust_runs = [run_command(rust_command, env=os.environ.copy()) for _ in range(args.runs)] + + try: + python_summary = summarize_runs("python", python_runs) + rust_summary = summarize_runs("rust", rust_runs) + byte_for_byte_output_parity = ( + python_summary["byte_output_sha256"] + == rust_summary["byte_output_sha256"] + ) + semantic_parity = ( + python_summary["semantic_output_sha256"] + == rust_summary["semantic_output_sha256"] + ) + report = { + "results_path": str(args.results), + "vt_metadata_path": str(args.vt_metadata), + "runs": args.runs, + "warmups": args.warmups, + "python": python_summary, + "rust": rust_summary, + "byte_for_byte_output_parity": byte_for_byte_output_parity, + "semantic_output_parity": semantic_parity, + "speedup_vs_python": ( + python_summary["mean_seconds"] / rust_summary["mean_seconds"] + if rust_summary["mean_seconds"] + else None + ), + } + args.report.parent.mkdir(parents=True, exist_ok=True) + args.report.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + if not semantic_parity: + raise SystemExit("python and rust outputs differed semantically") + finally: + cleanup_runs(python_runs + rust_runs) + + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/generate_synthetic_results.py b/scripts/generate_synthetic_results.py new file mode 100644 index 0000000..cf8683b --- /dev/null +++ b/scripts/generate_synthetic_results.py @@ -0,0 +1,186 @@ +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +DEFAULT_OUTPUT = Path("generated/synthetic-scan-results-500k.json") +DEFAULT_VT_METADATA_OUTPUT = Path("generated/synthetic-vt-metadata.json") +DEFAULT_RESULT_COUNT = 500_000 +DEFAULT_IP_COUNT = 1_000 + +TEMPLATES = [ + { + "type": "alarm", + "oid": "1.3.6.1.4.1.25623.1.0.147696", + "port": 0, + "protocol": "tcp", + "message": "Installed version: 9.53.3\nFixed version: 9.55\nInstallation path / port: /usr/bin/gs", + "vt_metadata": { + "oid": "1.3.6.1.4.1.25623.1.0.147696", + "name": "Ghostscript 9.50 < 9.55.0 Sandbox Escape Vulnerability - Linux", + "filename": "2022/artifex/gb_ghostscript_sandbox_escape_vuln_sep21_lin.nasl", + "family": "General", + "category": "gather_info", + "references": [{"class": "cve", "id": "CVE-2021-3781"}], + "tag": { + "summary": "Ghostscript is prone to a sandbox escape vulnerability.", + "solution": "Update to version 9.55 or later.", + "severity_vector": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H", + }, + }, + }, + { + "type": "alarm", + "oid": "1.3.6.1.4.1.25623.1.0.50282", + "port": 80, + "protocol": "tcp", + "message": "The remote web server exposes a synthetic HTTP service banner useful for enrichment throughput tests.", + "vt_metadata": { + "oid": "1.3.6.1.4.1.25623.1.0.50282", + "name": "Synthetic HTTP Banner Exposure", + "filename": "synthetic/http_banner_exposure.nasl", + "family": "Web application abuses", + "category": "attack", + "references": [{"class": "cve", "id": "CVE-2026-050282"}], + "tag": {"summary": "Synthetic web exposure used for enrichment load tests."}, + }, + }, + { + "type": "alarm", + "oid": "1.3.6.1.4.1.25623.1.0.10662", + "port": 22, + "protocol": "tcp", + "message": "The remote service accepted a synthetic SSH login probe during offline test generation.", + "vt_metadata": { + "oid": "1.3.6.1.4.1.25623.1.0.10662", + "name": "Synthetic SSH Authentication Probe", + "filename": "synthetic/ssh_auth_probe.nasl", + "family": "General", + "category": "gather_info", + "references": [{"class": "cve", "id": "CVE-2026-010662"}], + "tag": {"summary": "Synthetic SSH probe used for enrichment scale testing."}, + }, + }, + { + "type": "alarm", + "oid": "1.3.6.1.4.1.25623.1.0.10330", + "port": 445, + "protocol": "tcp", + "message": "The remote SMB endpoint returned a synthetic fingerprint for enrichment load testing.", + "vt_metadata": { + "oid": "1.3.6.1.4.1.25623.1.0.10330", + "name": "Synthetic SMB Fingerprint", + "filename": "synthetic/smb_fingerprint.nasl", + "family": "Windows", + "category": "gather_info", + "references": [{"class": "cve", "id": "CVE-2026-010330"}], + "tag": {"summary": "Synthetic SMB result for offline enrichment throughput tests."}, + }, + }, + { + "type": "log", + "oid": "1.3.6.1.4.1.25623.1.0.117628", + "port": 21, + "protocol": "tcp", + "message": "FTP is enabled on the remote SSH service.", + "vt_metadata": { + "oid": "1.3.6.1.4.1.25623.1.0.117628", + "name": "Synthetic FTP-on-SSH Detection", + "filename": "synthetic/ftp_on_ssh_detection.nasl", + "family": "General", + "category": "gather_info", + "references": [{"class": "cve", "id": "CVE-2026-117628"}], + "tag": {"summary": "Synthetic informational result used to vary enrichment output."}, + }, + }, +] + + +def ip_for(index: int) -> str: + block = index // 250 + host = index % 250 + 1 + return f"10.42.{block}.{host}" + + +def build_result(result_id: int, host_index: int, per_host_index: int) -> dict[str, object]: + template = TEMPLATES[(host_index * 7 + per_host_index) % len(TEMPLATES)] + ip_address = ip_for(host_index) + hostname = f"synthetic-host-{host_index + 1:04d}.lab" + return { + "id": result_id, + "type": template["type"], + "ip_address": ip_address, + "hostname": hostname, + "oid": template["oid"], + "port": template["port"], + "protocol": template["protocol"], + "message": ( + f"{template['message']}\n" + f"Synthetic target: {hostname} ({ip_address})\n" + f"Synthetic result slot: {per_host_index + 1}" + ), + } + + +def generate_payload(*, result_count: int, ip_count: int) -> dict[str, object]: + if result_count <= 0: + raise ValueError("result_count must be greater than 0") + if ip_count <= 0: + raise ValueError("ip_count must be greater than 0") + if result_count % ip_count != 0: + raise ValueError("result_count must be evenly divisible by ip_count") + + results_per_ip = result_count // ip_count + results: list[dict[str, object]] = [] + result_id = 1 + for host_index in range(ip_count): + for per_host_index in range(results_per_ip): + results.append(build_result(result_id, host_index, per_host_index)) + result_id += 1 + return { + "scan_id": "synthetic-enrichment-load-test", + "generated_by": "scripts/generate_synthetic_results.py", + "result_count": result_count, + "ip_count": ip_count, + "results_per_ip": results_per_ip, + "results": results, + } + + +def generate_vt_metadata() -> list[dict[str, object]]: + return [template["vt_metadata"] for template in TEMPLATES] + + +def main() -> int: + parser = argparse.ArgumentParser( + description="Generate deterministic synthetic OpenVAS-style results and VT metadata" + ) + parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT) + parser.add_argument( + "--vt-metadata-output", + type=Path, + default=DEFAULT_VT_METADATA_OUTPUT, + help="Write a matching synthetic vt-metadata JSON file", + ) + parser.add_argument("--result-count", type=int, default=DEFAULT_RESULT_COUNT) + parser.add_argument("--ip-count", type=int, default=DEFAULT_IP_COUNT) + args = parser.parse_args() + + payload = generate_payload(result_count=args.result_count, ip_count=args.ip_count) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(payload), encoding="utf-8") + + vt_metadata = generate_vt_metadata() + args.vt_metadata_output.parent.mkdir(parents=True, exist_ok=True) + args.vt_metadata_output.write_text(json.dumps(vt_metadata), encoding="utf-8") + + print( + f"wrote {args.result_count} results across {args.ip_count} IPs to {args.output}\n" + f"wrote {len(vt_metadata)} VT metadata entries to {args.vt_metadata_output}" + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/scan_examples/enrichment.py b/src/scan_examples/enrichment.py index ff9dfdd..3d6185d 100644 --- a/src/scan_examples/enrichment.py +++ b/src/scan_examples/enrichment.py @@ -3,6 +3,7 @@ from __future__ import annotations import argparse +import gzip import json import os import shutil @@ -223,7 +224,12 @@ def dump_pretty_enriched_results(enriched_results: list[dict[str, Any]]) -> str: def load_scan_results(results_path: str | Path) -> list[dict[str, Any]]: """Load scanner results from disk and normalize the top-level payload shape.""" - payload = json.loads(Path(results_path).read_text(encoding="utf-8")) + path = Path(results_path) + if path.suffix == ".gz": + with gzip.open(path, "rt", encoding="utf-8") as handle: + payload = json.load(handle) + else: + payload = json.loads(path.read_text(encoding="utf-8")) if isinstance(payload, list): results = payload elif isinstance(payload, dict) and isinstance(payload.get("results"), list): @@ -290,37 +296,53 @@ def resolve_enrichment_engine( return selected -def _run_rust_enrichment( +def _rust_enrichment_command( *, results_path: str | Path, vt_metadata_path: str | Path | None = None, scap_path: str | Path | None = None, notus_path: str | Path | None = None, rust_bin: str | Path | None = None, -) -> list[dict[str, Any]]: - """Invoke the Rust enrichment CLI and parse its JSON output.""" + output_path: str | Path | None = None, +) -> list[str]: + """Build the Rust enrichment CLI command line.""" binary = resolve_rust_enrichment_binary(rust_bin) if binary is None: raise FileNotFoundError( "Rust enrichment engine requested but scan-enrich-results binary was not found" ) + command = [str(binary), "--results", str(results_path)] + if output_path is not None: + command.extend(["--output", str(output_path)]) + if vt_metadata_path is not None: + command.extend(["--vt-metadata", str(vt_metadata_path)]) + if notus_path is not None: + command.extend(["--notus-path", str(notus_path)]) + if scap_path is not None: + command.extend(["--scap-path", str(scap_path)]) + return command + + +def _run_rust_enrichment( + *, + results_path: str | Path, + vt_metadata_path: str | Path | None = None, + scap_path: str | Path | None = None, + notus_path: str | Path | None = None, + rust_bin: str | Path | None = None, +) -> list[dict[str, Any]]: + """Invoke the Rust enrichment CLI and parse its JSON output.""" with tempfile.TemporaryDirectory(prefix="scan-enrich-rust-") as tmpdir: output_path = Path(tmpdir) / "enriched.json" - command = [ - str(binary), - "--results", - str(results_path), - "--output", - str(output_path), - ] - if vt_metadata_path is not None: - command.extend(["--vt-metadata", str(vt_metadata_path)]) - if notus_path is not None: - command.extend(["--notus-path", str(notus_path)]) - if scap_path is not None: - command.extend(["--scap-path", str(scap_path)]) - + command = _rust_enrichment_command( + results_path=results_path, + vt_metadata_path=vt_metadata_path, + scap_path=scap_path, + notus_path=notus_path, + rust_bin=rust_bin, + output_path=output_path, + ) completed = subprocess.run( command, check=True, @@ -338,6 +360,28 @@ def _run_rust_enrichment( return payload +def _run_rust_enrichment_passthrough( + *, + results_path: str | Path, + vt_metadata_path: str | Path | None = None, + scap_path: str | Path | None = None, + notus_path: str | Path | None = None, + rust_bin: str | Path | None = None, + output_path: str | Path | None = None, +) -> int: + """Run the Rust CLI directly so large outputs do not round-trip through Python memory.""" + command = _rust_enrichment_command( + results_path=results_path, + vt_metadata_path=vt_metadata_path, + scap_path=scap_path, + notus_path=notus_path, + rust_bin=rust_bin, + output_path=output_path, + ) + subprocess.run(command, check=True) + return 0 + + def enrich_results_python( results: list[dict[str, Any]], vt_index: dict[str, dict[str, Any]] | None, @@ -479,13 +523,23 @@ def main(argv: list[str] | None = None) -> int: args = parser.parse_args(argv) if args.vt_metadata is None and args.notus_path is None: parser.error("at least one of --vt-metadata or --notus-path is required") - enriched = enrich_results_from_files( + + effective_engine = resolve_enrichment_engine(args.engine, rust_bin=args.rust_bin) + if effective_engine == "rust": + return _run_rust_enrichment_passthrough( + results_path=args.results, + vt_metadata_path=args.vt_metadata, + scap_path=args.scap_path, + notus_path=args.notus_path, + rust_bin=args.rust_bin, + output_path=args.output, + ) + + enriched = enrich_results_from_files_python( results_path=args.results, vt_metadata_path=args.vt_metadata, scap_path=args.scap_path, notus_path=args.notus_path, - engine=args.engine, - rust_bin=args.rust_bin, ) rendered = json.dumps(enriched, indent=2, sort_keys=True) if args.output: diff --git a/tests/test_enrichment_cli.py b/tests/test_enrichment_cli.py index af5c2bd..4d2f4b9 100644 --- a/tests/test_enrichment_cli.py +++ b/tests/test_enrichment_cli.py @@ -1,3 +1,4 @@ +import gzip import json import subprocess from pathlib import Path @@ -156,6 +157,65 @@ def test_rust_engine_matches_python_reference_output_for_existing_raw_scan_resul assert rust_payload[2]["vt-metadata-status"] == "missing_oid" +def test_rust_engine_matches_python_reference_output_for_wrapped_results_file(tmp_path): + rust_bin = _ensure_rust_enrichment_binary() + results_path = tmp_path / "wrapped-results.json" + vt_metadata_path = tmp_path / "vt-metadata.json" + results_path.write_text( + json.dumps({"scan_id": "scan-123", "results": [{"id": 1, "oid": "1.2.3"}]}), + encoding="utf-8", + ) + vt_metadata_path.write_text( + json.dumps([{"oid": "1.2.3", "name": "Example VT"}]), + encoding="utf-8", + ) + + python_payload = enrich_results_from_files( + results_path=results_path, + vt_metadata_path=vt_metadata_path, + engine="python", + ) + rust_payload = enrich_results_from_files( + results_path=results_path, + vt_metadata_path=vt_metadata_path, + engine="rust", + rust_bin=rust_bin, + ) + + assert rust_payload == python_payload + assert rust_payload[0]["vt-metadata"]["name"] == "Example VT" + + +def test_rust_engine_matches_python_reference_output_for_gzip_results_file(tmp_path): + rust_bin = _ensure_rust_enrichment_binary() + results_path = tmp_path / "results.json.gz" + vt_metadata_path = tmp_path / "vt-metadata.json" + with gzip.open(results_path, "wt", encoding="utf-8") as handle: + json.dump( + {"scan_id": "scan-123", "results": [{"id": 1, "oid": "1.2.3"}]}, + handle, + ) + vt_metadata_path.write_text( + json.dumps([{"oid": "1.2.3", "name": "Example VT"}]), + encoding="utf-8", + ) + + python_payload = enrich_results_from_files( + results_path=results_path, + vt_metadata_path=vt_metadata_path, + engine="python", + ) + rust_payload = enrich_results_from_files( + results_path=results_path, + vt_metadata_path=vt_metadata_path, + engine="rust", + rust_bin=rust_bin, + ) + + assert rust_payload == python_payload + assert rust_payload[0]["vt-metadata"]["name"] == "Example VT" + + def test_run_rust_enrichment_forwards_stderr_without_corrupting_stdout( monkeypatch, tmp_path, capsys ): @@ -190,6 +250,53 @@ def fake_run(command, check, capture_output, text): assert captured.err == "warning from rust\n" +def test_standalone_enrichment_cli_passthrough_uses_rust_binary(monkeypatch, tmp_path): + results_path = tmp_path / "results.json" + vt_metadata_path = tmp_path / "vt-metadata.json" + output_path = tmp_path / "enriched.json" + results_path.write_text(json.dumps([{"id": 1, "oid": "1.2.3"}]), encoding="utf-8") + vt_metadata_path.write_text( + json.dumps([{"oid": "1.2.3", "name": "Example VT"}]), + encoding="utf-8", + ) + + seen = {} + + def fake_passthrough(**kwargs): + seen.update(kwargs) + output = Path(kwargs["output_path"]) + output.write_text( + json.dumps([{"id": 1, "feed-metadata-source": "vt"}]), + encoding="utf-8", + ) + return 0 + + monkeypatch.setattr( + "scan_examples.enrichment._run_rust_enrichment_passthrough", + fake_passthrough, + ) + + assert ( + main( + [ + "--results", + str(results_path), + "--vt-metadata", + str(vt_metadata_path), + "--engine", + "rust", + "--output", + str(output_path), + ] + ) + == 0 + ) + + assert seen["results_path"] == str(results_path) + assert seen["vt_metadata_path"] == str(vt_metadata_path) + assert Path(output_path).exists() + + def test_standalone_enrichment_cli_writes_json_output(tmp_path): results_path = tmp_path / "results.json" vt_metadata_path = tmp_path / "vt-metadata.json"