Skip to main content

website_vulnerability_scanner/
models.rs

1use clap::ValueEnum;
2use serde::{Deserialize, Serialize};
3
4pub const SCHEMA_VERSION: &str = "2.0.0";
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum, Serialize, Deserialize, Default)]
7#[serde(rename_all = "lowercase")]
8pub enum ScanProfile {
9    #[default]
10    Web,
11    Api,
12}
13
14impl ScanProfile {
15    pub fn label(self) -> &'static str {
16        match self {
17            ScanProfile::Web => "Web Site",
18            ScanProfile::Api => "REST/JSON API",
19        }
20    }
21}
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum, Serialize, Deserialize, Default)]
24#[serde(rename_all = "lowercase")]
25pub enum ReportAudience {
26    Executive,
27    #[default]
28    Developer,
29    Security,
30}
31
32impl ReportAudience {
33    pub fn label(self) -> &'static str {
34        match self {
35            ReportAudience::Executive => "Owner / Executive",
36            ReportAudience::Developer => "Developer",
37            ReportAudience::Security => "Security / Auditor",
38        }
39    }
40}
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
43#[serde(rename_all = "lowercase")]
44pub enum Severity {
45    Critical,
46    High,
47    Medium,
48    Low,
49    Info,
50    Pass,
51}
52
53impl Severity {
54    pub fn rank(self) -> u8 {
55        match self {
56            Severity::Critical => 5,
57            Severity::High => 4,
58            Severity::Medium => 3,
59            Severity::Low => 2,
60            Severity::Info => 1,
61            Severity::Pass => 0,
62        }
63    }
64
65    pub fn label(self) -> &'static str {
66        match self {
67            Severity::Critical => "CRITICAL",
68            Severity::High => "HIGH",
69            Severity::Medium => "MEDIUM",
70            Severity::Low => "LOW",
71            Severity::Info => "INFO",
72            Severity::Pass => "PASS",
73        }
74    }
75
76    pub fn css_class(self) -> &'static str {
77        match self {
78            Severity::Critical => "critical",
79            Severity::High => "high",
80            Severity::Medium => "medium",
81            Severity::Low => "low",
82            Severity::Info => "info",
83            Severity::Pass => "pass",
84        }
85    }
86}
87
88#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
89pub enum FailThreshold {
90    Critical,
91    High,
92    Medium,
93    Low,
94}
95
96impl FailThreshold {
97    pub fn matches(self, severity: Severity) -> bool {
98        let min_rank = match self {
99            FailThreshold::Critical => Severity::Critical.rank(),
100            FailThreshold::High => Severity::High.rank(),
101            FailThreshold::Medium => Severity::Medium.rank(),
102            FailThreshold::Low => Severity::Low.rank(),
103        };
104        severity.rank() >= min_rank
105    }
106}
107
108#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
109#[serde(rename_all = "snake_case")]
110pub enum Category {
111    TransportTls,
112    SecurityHeaders,
113    HttpProtocol,
114    Cookies,
115    Cors,
116    DnsEmail,
117    InformationDisclosure,
118    SecretsAndLeaks,
119    ApiSecurity,
120    ClientHtml,
121    ExposedFiles,
122    Availability,
123}
124
125impl Category {
126    pub fn label(self) -> &'static str {
127        match self {
128            Category::TransportTls => "TLS / HTTPS",
129            Category::SecurityHeaders => "Security Headers",
130            Category::HttpProtocol => "HTTP & Caching",
131            Category::Cookies => "Cookies",
132            Category::Cors => "CORS Policy",
133            Category::DnsEmail => "DNS & Email",
134            Category::InformationDisclosure => "Information Disclosure",
135            Category::SecretsAndLeaks => "Secrets & Data Leaks",
136            Category::ApiSecurity => "API & Auth Hygiene",
137            Category::ClientHtml => "Client & HTML Components",
138            Category::ExposedFiles => "Exposed Files & Metadata",
139            Category::Availability => "Availability",
140        }
141    }
142}
143
144#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
145#[serde(rename_all = "snake_case")]
146pub enum ExecutionStatus {
147    #[default]
148    Completed,
149    Skipped,
150    Error,
151    Cancelled,
152}
153
154impl ExecutionStatus {
155    pub fn label(self) -> &'static str {
156        match self {
157            ExecutionStatus::Completed => "completed",
158            ExecutionStatus::Skipped => "skipped",
159            ExecutionStatus::Error => "error",
160            ExecutionStatus::Cancelled => "cancelled",
161        }
162    }
163}
164
165#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
166#[serde(rename_all = "snake_case")]
167pub enum Verdict {
168    #[default]
169    Pass,
170    Fail,
171    Inconclusive,
172    NotApplicable,
173}
174
175#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
176#[serde(rename_all = "lowercase")]
177pub enum Confidence {
178    #[default]
179    High,
180    Medium,
181    Low,
182}
183
184impl Confidence {
185    pub fn label(self) -> &'static str {
186        match self {
187            Confidence::High => "high",
188            Confidence::Medium => "medium",
189            Confidence::Low => "low",
190        }
191    }
192}
193
194#[derive(Debug, Clone, Serialize, Deserialize)]
195pub struct CheckOutcome {
196    pub check_id: String,
197    pub category: Category,
198    pub location: String,
199    pub auth_context: String,
200    pub status: ExecutionStatus,
201    pub verdict: Verdict,
202    #[serde(default)]
203    pub reason: Option<String>,
204}
205
206#[derive(Debug, Clone, Serialize, Deserialize)]
207pub struct Finding {
208    pub id: String,
209    pub category: Category,
210    pub severity: Severity,
211    pub title: String,
212    pub summary: String,
213    pub evidence: Option<String>,
214    pub remediation: String,
215    #[serde(default)]
216    pub standard_ref: Option<String>,
217    #[serde(default)]
218    pub confidence: Confidence,
219}
220
221#[derive(Debug, Clone, Serialize, Deserialize)]
222pub struct FindingInstance {
223    pub fingerprint: String,
224    pub finding_id: String,
225    pub category: Category,
226    pub severity: Severity,
227    pub confidence: Confidence,
228    pub location: String,
229    pub auth_context: String,
230    pub title: String,
231    pub summary: String,
232    pub evidence: Option<String>,
233    pub remediation: String,
234    #[serde(default)]
235    pub standard_ref: Option<String>,
236}
237
238/// Computes a deterministic 64-bit FNV-1a hex fingerprint for a finding instance.
239pub fn compute_fingerprint(
240    rule_id: &str,
241    target: &str,
242    location: &str,
243    auth_context: &str,
244) -> String {
245    let mut hash: u64 = 0xcbf29ce484222325;
246    for part in [rule_id, "|", target, "|", location, "|", auth_context] {
247        for b in part.as_bytes() {
248            hash ^= u64::from(*b);
249            hash = hash.wrapping_mul(0x100000001b3);
250        }
251    }
252    format!("fp-{hash:016x}")
253}
254
255#[derive(Debug, Clone, Default, Serialize, Deserialize)]
256pub struct CoverageSummary {
257    pub total_checks: usize,
258    pub completed: usize,
259    pub skipped: usize,
260    pub errors: usize,
261    pub cancelled: usize,
262    pub not_applicable: usize,
263    pub coverage_percent: u8,
264    pub is_preliminary: bool,
265}
266
267impl CoverageSummary {
268    pub fn from_outcomes(outcomes: &[CheckOutcome], cancelled: bool) -> Self {
269        let mut summary = Self::default();
270        for o in outcomes {
271            if o.verdict == Verdict::NotApplicable {
272                summary.not_applicable += 1;
273                continue;
274            }
275            summary.total_checks += 1;
276            match o.status {
277                ExecutionStatus::Completed => summary.completed += 1,
278                ExecutionStatus::Skipped => summary.skipped += 1,
279                ExecutionStatus::Error => summary.errors += 1,
280                ExecutionStatus::Cancelled => summary.cancelled += 1,
281            }
282        }
283        summary.coverage_percent = (summary.completed * 100)
284            .checked_div(summary.total_checks)
285            .map_or(if cancelled { 0 } else { 100 }, |v| v.min(100) as u8);
286        summary.is_preliminary = cancelled
287            || summary.errors > 0
288            || summary.cancelled > 0
289            || summary.coverage_percent < 100;
290        summary
291    }
292}
293
294#[derive(Debug, Clone, Serialize, Deserialize)]
295pub struct ScorePenalty {
296    pub finding_id: String,
297    pub title: String,
298    pub severity: Severity,
299    pub points: u8,
300}
301
302#[derive(Debug, Clone, Serialize, Deserialize)]
303pub struct TlsInfo {
304    pub protocol: String,
305    pub cipher_suite: String,
306    pub subject: String,
307    pub issuer: String,
308    pub sans: Vec<String>,
309    pub not_before: String,
310    pub not_after: String,
311    pub days_remaining: i64,
312    pub hostname_matches: bool,
313}
314
315#[derive(Debug, Clone, Default, Serialize, Deserialize)]
316pub struct SeverityCounts {
317    pub critical: usize,
318    pub high: usize,
319    pub medium: usize,
320    pub low: usize,
321    pub info: usize,
322    pub pass: usize,
323}
324
325impl SeverityCounts {
326    pub fn from_findings(findings: &[Finding]) -> Self {
327        let mut counts = Self::default();
328        for f in findings {
329            match f.severity {
330                Severity::Critical => counts.critical += 1,
331                Severity::High => counts.high += 1,
332                Severity::Medium => counts.medium += 1,
333                Severity::Low => counts.low += 1,
334                Severity::Info => counts.info += 1,
335                Severity::Pass => counts.pass += 1,
336            }
337        }
338        counts
339    }
340}
341
342#[derive(Debug, Clone, Serialize, Deserialize)]
343pub struct ScanReport {
344    #[serde(default = "default_schema_v1")]
345    pub schema_version: String,
346    #[serde(default)]
347    pub engine_version: String,
348    pub target: String,
349    pub final_url: String,
350    pub scanned_at: String,
351    pub duration_ms: u128,
352    pub status_code: Option<u16>,
353    #[serde(default)]
354    pub profile: ScanProfile,
355    #[serde(default = "default_auth_ctx")]
356    pub auth_context: String,
357    #[serde(default)]
358    pub run_status: ExecutionStatus,
359    #[serde(default)]
360    pub cancelled: bool,
361    pub pages_scanned: usize,
362    pub crawled_urls: Vec<String>,
363    pub score: u8,
364    pub grade: String,
365    #[serde(default)]
366    pub score_breakdown: Vec<ScorePenalty>,
367    #[serde(default)]
368    pub coverage: CoverageSummary,
369    #[serde(default)]
370    pub outcomes: Vec<CheckOutcome>,
371    #[serde(default)]
372    pub instances: Vec<FindingInstance>,
373    pub tls: Option<TlsInfo>,
374    pub findings: Vec<Finding>,
375    pub counts: SeverityCounts,
376}
377
378fn default_schema_v1() -> String {
379    "1.0.0".to_string()
380}
381
382fn default_auth_ctx() -> String {
383    "anonymous".to_string()
384}
385
386#[derive(Debug, Clone, Serialize, Deserialize)]
387pub struct MultiScanReport {
388    #[serde(default = "default_schema_v1")]
389    pub schema_version: String,
390    #[serde(default)]
391    pub engine_version: String,
392    pub tool: String,
393    pub version: String,
394    pub generated_at: String,
395    #[serde(default)]
396    pub cancelled: bool,
397    pub reports: Vec<ScanReport>,
398}
399
400#[derive(Debug, Clone)]
401pub struct ScanConfig {
402    pub timeout_secs: u64,
403    pub concurrency: usize,
404    pub max_pages: usize,
405    pub max_requests: usize,
406    pub max_body_bytes: usize,
407    pub profile: ScanProfile,
408    pub skip_paths: bool,
409    pub skip_dns: bool,
410    pub user_agent: String,
411    pub auth_context: String,
412    pub openapi_path: Option<String>,
413    pub custom_rules: Vec<crate::rules::CustomRule>,
414    pub custom_advisories: Vec<crate::advisories::AdvisoryEntry>,
415    pub auth_headers: Vec<(String, String)>,
416    pub check_legacy_tls: bool,
417    pub check_unauth_access: bool,
418}
419
420impl Default for ScanConfig {
421    fn default() -> Self {
422        Self {
423            timeout_secs: 10,
424            concurrency: 6,
425            max_pages: 10,
426            max_requests: 120,
427            max_body_bytes: 512 * 1024,
428            profile: ScanProfile::Web,
429            skip_paths: false,
430            skip_dns: false,
431            user_agent: format!("web-vuln-scanner/{}", env!("CARGO_PKG_VERSION")),
432            auth_context: "anonymous".to_string(),
433            openapi_path: None,
434            custom_rules: Vec::new(),
435            custom_advisories: Vec::new(),
436            auth_headers: Vec::new(),
437            check_legacy_tls: true,
438            check_unauth_access: true,
439        }
440    }
441}