1use chrono::{DateTime, Utc};
4use serde::{Deserialize, Serialize};
5use std::collections::{BTreeMap, HashMap};
6use std::net::{IpAddr, SocketAddr};
7use std::path::PathBuf;
8use std::time::Duration;
9use uuid::Uuid;
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
13#[serde(rename_all = "lowercase")]
14pub enum Severity {
15 Info,
17 Low,
19 Medium,
21 High,
23 Critical,
25}
26
27impl Severity {
28 pub fn score(&self) -> u8 {
30 match self {
31 Severity::Info => 0,
32 Severity::Low => 1,
33 Severity::Medium => 2,
34 Severity::High => 3,
35 Severity::Critical => 4,
36 }
37 }
38}
39
40impl std::fmt::Display for Severity {
41 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42 match self {
43 Severity::Info => write!(f, "info"),
44 Severity::Low => write!(f, "low"),
45 Severity::Medium => write!(f, "medium"),
46 Severity::High => write!(f, "high"),
47 Severity::Critical => write!(f, "critical"),
48 }
49 }
50}
51
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
54#[serde(rename_all = "lowercase")]
55pub enum TemplateLanguage {
56 Yaml,
58 Python,
60 Rust,
62 Shell,
64 JavaScript,
66 C,
68 Cpp,
70 Java,
72 Go,
74 Ruby,
76 Perl,
78 Php,
80}
81
82impl std::fmt::Display for TemplateLanguage {
83 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84 match self {
85 TemplateLanguage::Yaml => write!(f, "yaml"),
86 TemplateLanguage::Python => write!(f, "python"),
87 TemplateLanguage::Rust => write!(f, "rust"),
88 TemplateLanguage::Shell => write!(f, "shell"),
89 TemplateLanguage::JavaScript => write!(f, "javascript"),
90 TemplateLanguage::C => write!(f, "c"),
91 TemplateLanguage::Cpp => write!(f, "cpp"),
92 TemplateLanguage::Java => write!(f, "java"),
93 TemplateLanguage::Go => write!(f, "go"),
94 TemplateLanguage::Ruby => write!(f, "ruby"),
95 TemplateLanguage::Perl => write!(f, "perl"),
96 TemplateLanguage::Php => write!(f, "php"),
97 }
98 }
99}
100
101#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
103#[serde(rename_all = "lowercase")]
104pub enum Protocol {
105 Http,
107 Https,
109 Tcp,
111 Udp,
113 Dns,
115 Ssh,
117 Ftp,
119 Smtp,
121 Smb,
123 Rdp,
125 Custom(String),
127 Cli,
132}
133
134impl std::fmt::Display for Protocol {
135 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
136 match self {
137 Protocol::Http => write!(f, "http"),
138 Protocol::Https => write!(f, "https"),
139 Protocol::Tcp => write!(f, "tcp"),
140 Protocol::Udp => write!(f, "udp"),
141 Protocol::Dns => write!(f, "dns"),
142 Protocol::Ssh => write!(f, "ssh"),
143 Protocol::Ftp => write!(f, "ftp"),
144 Protocol::Smtp => write!(f, "smtp"),
145 Protocol::Smb => write!(f, "smb"),
146 Protocol::Rdp => write!(f, "rdp"),
147 Protocol::Custom(name) => write!(f, "{}", name),
148 Protocol::Cli => write!(f, "cli"),
149 }
150 }
151}
152
153#[derive(Debug, Clone, Serialize, Deserialize)]
155pub struct Target {
156 pub id: Uuid,
158 pub address: String,
160 pub port: Option<u16>,
162 pub protocol: Protocol,
164 pub metadata: HashMap<String, String>,
166}
167
168impl Target {
169 pub fn new<S: Into<String>>(address: S, protocol: Protocol) -> Self {
171 Self {
172 id: Uuid::new_v4(),
173 address: address.into(),
174 port: None,
175 protocol,
176 metadata: HashMap::new(),
177 }
178 }
179
180 pub fn with_port<S: Into<String>>(address: S, port: u16, protocol: Protocol) -> Self {
182 Self {
183 id: Uuid::new_v4(),
184 address: address.into(),
185 port: Some(port),
186 protocol,
187 metadata: HashMap::new(),
188 }
189 }
190
191 pub fn url(&self) -> String {
193 match &self.protocol {
194 Protocol::Http | Protocol::Https => {
195 let scheme = if self.protocol == Protocol::Https {
196 "https"
197 } else {
198 "http"
199 };
200 if let Some(port) = self.port {
201 format!("{}://{}:{}", scheme, self.address, port)
202 } else {
203 format!("{}://{}", scheme, self.address)
204 }
205 }
206 _ => {
207 if let Some(port) = self.port {
208 format!("{}:{}", self.address, port)
209 } else {
210 self.address.clone()
211 }
212 }
213 }
214 }
215
216 pub fn socket_addr(&self) -> Option<SocketAddr> {
218 if let Ok(ip) = self.address.parse::<IpAddr>() {
219 Some(SocketAddr::new(ip, self.port.unwrap_or(0)))
220 } else {
221 None
222 }
223 }
224
225 pub fn with_both_schemes(&self) -> Vec<Target> {
228 if matches!(self.protocol, Protocol::Http | Protocol::Https) {
229 vec![
230 Target {
231 protocol: Protocol::Http,
232 ..self.clone()
233 },
234 Target {
235 protocol: Protocol::Https,
236 ..self.clone()
237 },
238 ]
239 } else {
240 vec![self.clone()]
241 }
242 }
243
244 pub fn infer_scheme(&self) -> Protocol {
246 match self.port {
247 Some(443) | Some(8443) => Protocol::Https,
248 Some(80) | Some(8080) | Some(8000) => Protocol::Http,
249 _ => self.protocol.clone(),
250 }
251 }
252}
253
254#[derive(Debug, Clone, Serialize, Deserialize)]
256pub struct Context {
257 pub scan_id: Uuid,
259 pub aggressive_mode: bool,
261 pub stealth_mode: bool,
263 pub max_retries: u32,
265 pub timeout: Duration,
267 pub variables: HashMap<String, String>,
269 pub rate_limit: Option<u32>,
271 pub additional_ports: Vec<u16>,
273 pub override_ports: Option<Vec<u16>>,
275 #[serde(default)]
277 pub headers: Vec<(String, String)>,
278 #[serde(default)]
280 pub cookies: Vec<(String, String)>,
281
282 #[serde(default)]
288 pub probe_argv: Vec<String>,
289 #[serde(default)]
292 pub probe_stdin_file: Option<PathBuf>,
293 #[serde(default)]
296 pub probe_input_dir: Option<PathBuf>,
297 #[serde(default)]
300 pub probe_env: Vec<(String, String)>,
301 #[serde(default)]
305 pub require_instrumentation: bool,
306 #[serde(default)]
318 pub instrumentation_provenance: BTreeMap<String, Vec<String>>,
319}
320
321impl Default for Context {
322 fn default() -> Self {
323 Self {
324 scan_id: Uuid::new_v4(),
325 aggressive_mode: false,
326 stealth_mode: false,
327 max_retries: 1,
328 timeout: Duration::from_secs(30),
329 variables: HashMap::new(),
330 rate_limit: None,
331 additional_ports: Vec::new(),
332 override_ports: None,
333 headers: Vec::new(),
334 cookies: Vec::new(),
335 probe_argv: Vec::new(),
336 probe_stdin_file: None,
337 probe_input_dir: None,
338 probe_env: Vec::new(),
339 require_instrumentation: false,
340 instrumentation_provenance: BTreeMap::new(),
341 }
342 }
343}
344
345#[derive(Debug, Clone, Serialize, Deserialize)]
347pub struct Evidence {
348 pub request: Option<String>,
350 pub response: Option<String>,
352 pub matched_patterns: Vec<String>,
354 pub data: HashMap<String, serde_json::Value>,
356 pub timestamp: DateTime<Utc>,
358}
359
360impl Evidence {
361 pub fn new() -> Self {
363 Self {
364 request: None,
365 response: None,
366 matched_patterns: Vec::new(),
367 data: HashMap::new(),
368 timestamp: Utc::now(),
369 }
370 }
371
372 pub fn add_match(&mut self, pattern: String) {
374 self.matched_patterns.push(pattern);
375 }
376
377 pub fn add_data<K: Into<String>>(&mut self, key: K, value: serde_json::Value) {
379 self.data.insert(key.into(), value);
380 }
381}
382
383impl Default for Evidence {
384 fn default() -> Self {
385 Self::new()
386 }
387}
388
389#[derive(Debug, Clone, Serialize, Deserialize)]
391pub struct Finding {
392 #[serde(default, skip_serializing_if = "Option::is_none")]
394 pub verdict_source: Option<String>,
395 pub id: Uuid,
397 pub target: String,
399 pub template_id: String,
401 pub severity: Severity,
403 pub confidence: u8,
405 pub title: String,
407 pub description: String,
409 pub evidence: Evidence,
411 pub cve_ids: Vec<String>,
413 pub cwe_ids: Vec<String>,
415 pub cvss_score: Option<f32>,
417 pub remediation: Option<String>,
419 pub references: Vec<String>,
421 pub tags: Vec<String>,
423 pub timestamp: DateTime<Utc>,
425}
426
427impl Finding {
428 pub fn new<S: Into<String>>(
430 target: S,
431 template_id: S,
432 severity: Severity,
433 title: S,
434 description: S,
435 ) -> Self {
436 Self {
437 id: Uuid::new_v4(),
438 target: target.into(),
439 template_id: template_id.into(),
440 verdict_source: None,
441 severity,
442 confidence: 90,
443 title: title.into(),
444 description: description.into(),
445 evidence: Evidence::new(),
446 cve_ids: Vec::new(),
447 cwe_ids: Vec::new(),
448 cvss_score: None,
449 remediation: None,
450 references: Vec::new(),
451 tags: Vec::new(),
452 timestamp: Utc::now(),
453 }
454 }
455
456 pub fn with_confidence(mut self, confidence: u8) -> Self {
458 self.confidence = confidence.min(100);
459 self
460 }
461
462 pub fn with_evidence(mut self, evidence: Evidence) -> Self {
464 self.evidence = evidence;
465 self
466 }
467
468 pub fn add_cve<S: Into<String>>(mut self, cve_id: S) -> Self {
470 self.cve_ids.push(cve_id.into());
471 self
472 }
473
474 pub fn add_cwe<S: Into<String>>(mut self, cwe_id: S) -> Self {
476 self.cwe_ids.push(cwe_id.into());
477 self
478 }
479
480 pub fn with_cvss_score(mut self, score: f32) -> Self {
482 self.cvss_score = Some(score);
483 self
484 }
485}
486
487#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
494#[serde(rename_all = "lowercase")]
495pub enum ExecutionStatus {
496 Confirmed,
498 Refuted,
500 Errored,
502 Skipped,
505 #[serde(rename = "timed-out")]
507 TimedOut,
508}
509
510impl std::fmt::Display for ExecutionStatus {
511 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
512 let s = match self {
513 ExecutionStatus::Confirmed => "confirmed",
514 ExecutionStatus::Refuted => "refuted",
515 ExecutionStatus::Errored => "errored",
516 ExecutionStatus::Skipped => "skipped",
517 ExecutionStatus::TimedOut => "timed-out",
518 };
519 f.write_str(s)
520 }
521}
522
523impl ExecutionStatus {
524 pub fn parse(s: &str) -> Option<Self> {
529 match s.trim().to_lowercase().as_str() {
530 "confirmed" | "confirm" => Some(ExecutionStatus::Confirmed),
531 "refuted" | "refute" | "not-reproduced" => Some(ExecutionStatus::Refuted),
532 "errored" | "error" => Some(ExecutionStatus::Errored),
533 "skipped" | "skip" => Some(ExecutionStatus::Skipped),
534 "timed-out" | "timedout" | "timeout" => Some(ExecutionStatus::TimedOut),
535 _ => None,
536 }
537 }
538
539 pub const ALL: [ExecutionStatus; 5] = [
541 ExecutionStatus::Confirmed,
542 ExecutionStatus::Refuted,
543 ExecutionStatus::Skipped,
544 ExecutionStatus::Errored,
545 ExecutionStatus::TimedOut,
546 ];
547}
548
549#[derive(Debug, Clone, Serialize, Deserialize)]
556pub struct ExecutionRecord {
557 pub target: String,
559 #[serde(default)]
561 pub target_kind: String,
562 pub template_id: String,
564 pub status: ExecutionStatus,
566 #[serde(default)]
570 pub declared_by_template: bool,
571 pub findings: usize,
573 #[serde(default)]
575 pub exit_code: Option<i32>,
576 #[serde(default)]
578 pub detail: Option<String>,
579 #[serde(default)]
581 pub duration_ms: u64,
582}
583
584#[derive(Debug, Clone, Default, Serialize, Deserialize)]
586pub struct ScanStatistics {
587 pub targets_scanned: usize,
589 pub templates_executed: usize,
591 pub findings_by_severity: HashMap<Severity, usize>,
593 pub network_requests: Option<usize>,
596 #[serde(default)]
598 pub network_requests_measured: usize,
599 pub data_transferred: u64,
601 pub duration: Duration,
603 pub success_rate: f64,
605}
606
607#[derive(Debug, Clone, Serialize, Deserialize)]
609pub struct ScanResults {
610 #[serde(default, skip_serializing_if = "Option::is_none")]
612 pub probe_results: Option<serde_json::Value>,
613 pub scan_id: Uuid,
615 pub started_at: DateTime<Utc>,
617 pub completed_at: Option<DateTime<Utc>>,
619 pub findings: Vec<Finding>,
621 pub statistics: ScanStatistics,
623 pub errors: Vec<String>,
625 #[serde(default)]
628 pub executions: Vec<ExecutionRecord>,
629}
630
631impl ScanResults {
632 pub fn add_discovery_issues(&mut self, issues: Vec<crate::template::TemplateLoadIssue>) {
635 for issue in issues {
636 let (status, detail) = if let Some(error) = issue.error {
637 let detail = format!(
638 "Failed to load template '{}': {}",
639 issue.path.display(),
640 error
641 );
642 self.errors.push(detail.clone());
643 (ExecutionStatus::Errored, detail)
644 } else {
645 (ExecutionStatus::Skipped, "skipped-non-template".to_string())
646 };
647 self.executions.push(ExecutionRecord {
648 target: String::new(),
649 target_kind: String::new(),
650 template_id: issue.path.display().to_string(),
651 status,
652 declared_by_template: false,
653 findings: 0,
654 exit_code: None,
655 detail: Some(detail),
656 duration_ms: 0,
657 });
658 }
659 }
660
661 pub fn new(scan_id: Uuid) -> Self {
663 Self {
664 scan_id,
665 probe_results: None,
666 started_at: Utc::now(),
667 completed_at: None,
668 findings: Vec::new(),
669 statistics: ScanStatistics::default(),
670 errors: Vec::new(),
671 executions: Vec::new(),
672 }
673 }
674
675 pub fn add_finding(&mut self, finding: Finding) {
677 *self
678 .statistics
679 .findings_by_severity
680 .entry(finding.severity)
681 .or_insert(0) += 1;
682 self.findings.push(finding);
683 }
684
685 pub fn complete(&mut self) {
687 self.completed_at = Some(Utc::now());
688 if let Some(completed) = self.completed_at {
689 self.statistics.duration = (completed - self.started_at)
690 .to_std()
691 .unwrap_or(Duration::from_secs(0));
692 }
693 }
694
695 pub fn critical_findings(&self) -> Vec<&Finding> {
697 self.findings
698 .iter()
699 .filter(|f| f.severity == Severity::Critical)
700 .collect()
701 }
702
703 pub fn high_findings(&self) -> Vec<&Finding> {
705 self.findings
706 .iter()
707 .filter(|f| f.severity == Severity::High)
708 .collect()
709 }
710}
711
712#[derive(Debug, Clone, Serialize, Deserialize)]
714pub struct TemplateMetadata {
715 pub id: String,
717 pub name: String,
719 pub author: AuthorInfo,
721 pub severity: Severity,
723 pub description: String,
725 #[serde(default)]
727 pub cve_ids: Vec<String>,
728 #[serde(default)]
730 pub cwe_ids: Vec<String>,
731 pub cvss_score: Option<f32>,
733 #[serde(default)]
735 pub tags: Vec<String>,
736 pub language: TemplateLanguage,
738 #[serde(default)]
740 pub file_path: PathBuf,
741 #[serde(default = "default_datetime")]
743 pub created: DateTime<Utc>,
744 #[serde(default = "default_datetime")]
746 pub updated: DateTime<Utc>,
747 #[serde(default = "default_version")]
749 pub version: String,
750 pub confidence: Option<u8>,
752
753 #[serde(default)]
758 pub context_vars: Vec<String>,
759
760 #[serde(default)]
762 pub vuln_class: Option<String>,
763
764 #[serde(default)]
766 pub hypothesis_tags: Vec<String>,
767
768 #[serde(default)]
770 pub batch_group: Option<String>,
771
772 #[serde(default)]
774 pub auto_probe: bool,
775
776 #[serde(default)]
780 pub allow_nonzero_exit: bool,
781
782 #[serde(default)]
794 pub oracles: Vec<String>,
795
796 #[serde(default)]
801 pub target_kinds: Vec<String>,
802}
803
804#[derive(Debug, Clone, Serialize, Deserialize)]
806pub struct AuthorInfo {
807 pub name: String,
809 pub email: Option<String>,
811 pub github: Option<String>,
813}
814
815fn default_datetime() -> DateTime<Utc> {
817 Utc::now()
818}
819
820fn default_version() -> String {
821 "1.0".to_string()
822}
823
824#[cfg(test)]
825mod tests {
826 use super::*;
827
828 #[test]
829 fn execution_status_round_trips_through_json() {
830 for status in ExecutionStatus::ALL {
831 let json = serde_json::to_string(&status).unwrap();
832 assert_eq!(json, format!("\"{}\"", status));
835 let back: ExecutionStatus = serde_json::from_str(&json).unwrap();
836 assert_eq!(back, status);
837 }
838 }
839
840 #[test]
841 fn execution_status_parses_the_declared_vocabulary() {
842 assert_eq!(
843 ExecutionStatus::parse("REFUTED"),
844 Some(ExecutionStatus::Refuted)
845 );
846 assert_eq!(
847 ExecutionStatus::parse(" not-reproduced "),
848 Some(ExecutionStatus::Refuted)
849 );
850 assert_eq!(
851 ExecutionStatus::parse("timeout"),
852 Some(ExecutionStatus::TimedOut)
853 );
854 assert_eq!(ExecutionStatus::parse("refuuted"), None);
855 assert_eq!(ExecutionStatus::parse(""), None);
856 }
857
858 #[test]
860 fn scan_results_without_an_executions_field_still_deserialise() {
861 let legacy = r#"{
862 "scan_id": "00000000-0000-0000-0000-000000000000",
863 "started_at": "2026-01-01T00:00:00Z",
864 "completed_at": null,
865 "findings": [],
866 "statistics": {
867 "targets_scanned": 0,
868 "templates_executed": 0,
869 "findings_by_severity": {},
870 "network_requests": 0,
871 "data_transferred": 0,
872 "duration": {"secs": 0, "nanos": 0},
873 "success_rate": 0.0
874 },
875 "errors": []
876 }"#;
877 let results: ScanResults = serde_json::from_str(legacy).unwrap();
878 assert!(results.executions.is_empty());
879 }
880
881 #[test]
882 fn test_severity_ordering() {
883 assert!(Severity::Critical > Severity::High);
884 assert!(Severity::High > Severity::Medium);
885 assert!(Severity::Medium > Severity::Low);
886 assert!(Severity::Low > Severity::Info);
887 }
888
889 #[test]
890 fn test_target_url() {
891 let target = Target::with_port("example.com", 443, Protocol::Https);
892 assert_eq!(target.url(), "https://example.com:443");
893
894 let target = Target::new("example.com", Protocol::Http);
895 assert_eq!(target.url(), "http://example.com");
896 }
897
898 #[test]
899 fn test_finding_creation() {
900 let finding = Finding::new(
901 "192.168.1.1",
902 "CVE-2024-1234",
903 Severity::Critical,
904 "Test Finding",
905 "Test description",
906 );
907 assert_eq!(finding.severity, Severity::Critical);
908 assert_eq!(finding.confidence, 90);
909 }
910}