website-vulnerability-scanner 0.2.0

Cross-platform defensive website security & configuration scanner with GUI and CLI reports.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
use reqwest::header::HeaderMap;

use crate::models::{Category, Confidence, Finding, Severity};

fn header_str(headers: &HeaderMap, name: &str) -> Option<String> {
    headers
        .get(name)
        .and_then(|v| v.to_str().ok())
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
}

pub fn analyze_headers(headers: &HeaderMap, is_https: bool) -> Vec<Finding> {
    let mut findings = Vec::new();

    if is_https {
        match header_str(headers, "strict-transport-security") {
            None => findings.push(Finding {
                id: "HDR-HSTS-MISSING".into(),
                category: Category::SecurityHeaders,
                severity: Severity::Medium,
                title: "Missing Strict-Transport-Security (HSTS) header".into(),
                summary: "Without HSTS, browsers may initially connect over plain HTTP on first navigation, risking SSL stripping.".into(),
                evidence: None,
                remediation: "Strict-Transport-Security: max-age=31536000; includeSubDomains".into(),
                standard_ref: Some("OWASP Secure Headers / ASVS V14.4.5 / WSTG-CONF-07".into()),
                confidence: Confidence::High,
            }),
            Some(val) => {
                let lower = val.to_ascii_lowercase();
                let max_age = parse_hsts_max_age(&lower);
                if max_age.unwrap_or(0) < 15_552_000 {
                    findings.push(Finding {
                        id: "HDR-HSTS-SHORT".into(),
                        category: Category::SecurityHeaders,
                        severity: Severity::Low,
                        title: "HSTS max-age is too short (< 180 days)".into(),
                        summary: "Recommended HSTS max-age is at least 1 year (31536000 seconds).".into(),
                        evidence: Some(format!("Strict-Transport-Security: {val}")),
                        remediation: "Strict-Transport-Security: max-age=31536000; includeSubDomains".into(),
                        standard_ref: Some("OWASP Secure Headers / ASVS V14.4.5".into()),
                        confidence: Confidence::High,
                    });
                } else {
                    findings.push(Finding {
                        id: "HDR-HSTS-OK".into(),
                        category: Category::SecurityHeaders,
                        severity: Severity::Pass,
                        title: "HSTS header is properly configured".into(),
                        summary: "Browsers enforce HTTPS on subsequent visits.".into(),
                        evidence: Some(format!("Strict-Transport-Security: {val}")),
                        remediation: String::new(),
                        standard_ref: Some("OWASP Secure Headers / ASVS V14.4.5".into()),
                        confidence: Confidence::High,
                    });
                    if !lower.contains("includesubdomains") {
                        findings.push(Finding {
                            id: "HDR-HSTS-NO-SUBDOMAINS".into(),
                            category: Category::SecurityHeaders,
                            severity: Severity::Info,
                            title: "HSTS header omits includeSubDomains".into(),
                            summary: "If all subdomains support HTTPS, adding includeSubDomains protects them from downgrade attacks.".into(),
                            evidence: Some(format!("Strict-Transport-Security: {val}")),
                            remediation: "Strict-Transport-Security: max-age=31536000; includeSubDomains".into(),
                            standard_ref: Some("OWASP Secure Headers".into()),
                            confidence: Confidence::High,
                        });
                    }
                }
            }
        }
    }

    let csp_val = header_str(headers, "content-security-policy");
    let mut csp_has_frame_ancestors = false;
    match &csp_val {
        None => findings.push(Finding {
            id: "HDR-CSP-MISSING".into(),
            category: Category::SecurityHeaders,
            severity: Severity::Medium,
            title: "Missing Content-Security-Policy (CSP) header".into(),
            summary: "CSP restricts allowed script, style, and frame sources, significantly mitigating XSS and unwanted script injection.".into(),
            evidence: None,
            remediation: "Content-Security-Policy: default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'".into(),
            standard_ref: Some("OWASP Secure Headers / ASVS V14.4.3 / WSTG-CLNT-03".into()),
            confidence: Confidence::High,
        }),
        Some(csp) => {
            let lower = csp.to_ascii_lowercase();
            csp_has_frame_ancestors = lower.contains("frame-ancestors");
            let mut weaknesses = Vec::new();

            if lower.contains("'unsafe-inline'") {
                weaknesses.push("'unsafe-inline' allows inline scripts/styles");
            }
            if lower.contains("'unsafe-eval'") {
                weaknesses.push("'unsafe-eval' allows eval()");
            }
            if has_wildcard_script_src(&lower) {
                weaknesses.push("wildcard '*' in script-src or default-src");
            }
            if lower.contains("http://") {
                weaknesses.push("insecure http:// source allowed");
            }
            if !lower.contains("object-src") {
                weaknesses.push("missing object-src 'none'");
            }
            if !lower.contains("base-uri") {
                weaknesses.push("missing base-uri 'self'");
            }

            if weaknesses.is_empty() {
                findings.push(Finding {
                    id: "HDR-CSP-OK".into(),
                    category: Category::SecurityHeaders,
                    severity: Severity::Pass,
                    title: "Content-Security-Policy is configured".into(),
                    summary: "No obvious permissive directives ('unsafe-inline', 'unsafe-eval', '*') or missing baseline restrictions detected.".into(),
                    evidence: Some(truncate_evidence(csp, 220)),
                    remediation: String::new(),
                    standard_ref: Some("OWASP Secure Headers / ASVS V14.4.3".into()),
                    confidence: Confidence::High,
                });
            } else {
                findings.push(Finding {
                    id: "HDR-CSP-WEAK".into(),
                    category: Category::SecurityHeaders,
                    severity: Severity::Low,
                    title: "Content-Security-Policy can be hardened".into(),
                    summary: format!("Detected: {}. This weakens CSP defense-in-depth.", weaknesses.join("; ")),
                    evidence: Some(truncate_evidence(csp, 240)),
                    remediation: "Replace 'unsafe-inline'/'unsafe-eval' with nonces or SHA hashes, and include `object-src 'none'; base-uri 'self'`.".into(),
                    standard_ref: Some("OWASP Secure Headers / ASVS V14.4.3".into()),
                    confidence: Confidence::High,
                });
            }
        }
    }

    match header_str(headers, "x-frame-options") {
        None if !csp_has_frame_ancestors => findings.push(Finding {
            id: "HDR-XFO-MISSING".into(),
            category: Category::SecurityHeaders,
            severity: Severity::Medium,
            title: "Missing Clickjacking protection (X-Frame-Options / frame-ancestors)".into(),
            summary: "The site can be embedded in an <iframe> on third-party sites, exposing users to UI redressing / clickjacking.".into(),
            evidence: None,
            remediation: "X-Frame-Options: SAMEORIGIN (or Content-Security-Policy: frame-ancestors 'self')".into(),
            standard_ref: Some("OWASP Secure Headers / ASVS V14.4.7 / WSTG-CLNT-09".into()),
            confidence: Confidence::High,
        }),
        Some(xfo) => {
            let upper = xfo.to_ascii_uppercase();
            if upper == "DENY" || upper == "SAMEORIGIN" {
                findings.push(Finding {
                    id: "HDR-XFO-OK".into(),
                    category: Category::SecurityHeaders,
                    severity: Severity::Pass,
                    title: "Clickjacking protection is configured".into(),
                    summary: "Embedding the page in third-party iframes is restricted.".into(),
                    evidence: Some(format!("X-Frame-Options: {xfo}")),
                    remediation: String::new(),
                    standard_ref: Some("OWASP Secure Headers / ASVS V14.4.7".into()),
                    confidence: Confidence::High,
                });
            } else {
                findings.push(Finding {
                    id: "HDR-XFO-INVALID".into(),
                    category: Category::SecurityHeaders,
                    severity: Severity::Low,
                    title: "Non-standard X-Frame-Options value".into(),
                    summary: format!("Value '{xfo}' may be ignored by modern browsers (expected DENY or SAMEORIGIN)."),
                    evidence: Some(format!("X-Frame-Options: {xfo}")),
                    remediation: "X-Frame-Options: DENY (or CSP frame-ancestors 'none')".into(),
                    standard_ref: Some("OWASP Secure Headers / WSTG-CLNT-09".into()),
                    confidence: Confidence::High,
                });
            }
        }
        None => {
            findings.push(Finding {
                id: "HDR-FRAME-ANCESTORS-OK".into(),
                category: Category::SecurityHeaders,
                severity: Severity::Pass,
                title: "Clickjacking protection configured via CSP frame-ancestors".into(),
                summary: "CSP frame-ancestors restricts iframe embedding.".into(),
                evidence: None,
                remediation: String::new(),
                standard_ref: Some("OWASP Secure Headers / ASVS V14.4.7".into()),
                confidence: Confidence::High,
            });
        }
    }

    match header_str(headers, "x-content-type-options") {
        Some(val) if val.eq_ignore_ascii_case("nosniff") => findings.push(Finding {
            id: "HDR-XCTO-OK".into(),
            category: Category::SecurityHeaders,
            severity: Severity::Pass,
            title: "X-Content-Type-Options: nosniff is set".into(),
            summary: "Prevents MIME-type sniffing by browsers.".into(),
            evidence: Some(format!("X-Content-Type-Options: {val}")),
            remediation: String::new(),
            standard_ref: Some("OWASP Secure Headers / ASVS V14.4.4".into()),
            confidence: Confidence::High,
        }),
        other => findings.push(Finding {
            id: "HDR-XCTO-MISSING".into(),
            category: Category::SecurityHeaders,
            severity: Severity::Low,
            title: "Missing or invalid X-Content-Type-Options header".into(),
            summary: "Without 'nosniff', browsers may MIME-sniff non-executable responses as scripts or HTML.".into(),
            evidence: other.map(|v| format!("X-Content-Type-Options: {v}")),
            remediation: "X-Content-Type-Options: nosniff".into(),
            standard_ref: Some("OWASP Secure Headers / ASVS V14.4.4".into()),
            confidence: Confidence::High,
        }),
    }

    match header_str(headers, "referrer-policy") {
        None => findings.push(Finding {
            id: "HDR-REFERRER-MISSING".into(),
            category: Category::SecurityHeaders,
            severity: Severity::Low,
            title: "Missing Referrer-Policy header".into(),
            summary: "Without Referrer-Policy, URL paths or query parameters may leak to external sites via the Referer header.".into(),
            evidence: None,
            remediation: "Referrer-Policy: strict-origin-when-cross-origin".into(),
            standard_ref: Some("OWASP Secure Headers / ASVS V14.4.6".into()),
            confidence: Confidence::High,
        }),
        Some(val) => {
            let lower = val.to_ascii_lowercase();
            if lower.contains("unsafe-url") {
                findings.push(Finding {
                    id: "HDR-REFERRER-UNSAFE".into(),
                    category: Category::SecurityHeaders,
                    severity: Severity::Medium,
                    title: "Unsafe Referrer-Policy (unsafe-url)".into(),
                    summary: "unsafe-url sends full URLs including query strings to any third-party origin.".into(),
                    evidence: Some(format!("Referrer-Policy: {val}")),
                    remediation: "Referrer-Policy: strict-origin-when-cross-origin".into(),
                    standard_ref: Some("OWASP Secure Headers / ASVS V14.4.6".into()),
                    confidence: Confidence::High,
                });
            } else {
                findings.push(Finding {
                    id: "HDR-REFERRER-OK".into(),
                    category: Category::SecurityHeaders,
                    severity: Severity::Pass,
                    title: "Referrer-Policy header is set".into(),
                    summary: "Referer leakage is controlled.".into(),
                    evidence: Some(format!("Referrer-Policy: {val}")),
                    remediation: String::new(),
                    standard_ref: Some("OWASP Secure Headers / ASVS V14.4.6".into()),
                    confidence: Confidence::High,
                });
            }
        }
    }

    match header_str(headers, "permissions-policy") {
        None => findings.push(Finding {
            id: "HDR-PERMISSIONS-MISSING".into(),
            category: Category::SecurityHeaders,
            severity: Severity::Low,
            title: "Missing Permissions-Policy header".into(),
            summary: "Explicitly disabling unused browser features (camera, microphone, geolocation) reduces risk from third-party scripts.".into(),
            evidence: None,
            remediation: "Permissions-Policy: camera=(), microphone=(), geolocation=()".into(),
            standard_ref: Some("OWASP Secure Headers".into()),
            confidence: Confidence::High,
        }),
        Some(val) => findings.push(Finding {
            id: "HDR-PERMISSIONS-OK".into(),
            category: Category::SecurityHeaders,
            severity: Severity::Pass,
            title: "Permissions-Policy header is set".into(),
            summary: "Browser feature permissions are restricted.".into(),
            evidence: Some(truncate_evidence(&format!("Permissions-Policy: {val}"), 200)),
            remediation: String::new(),
            standard_ref: Some("OWASP Secure Headers".into()),
            confidence: Confidence::High,
        }),
    }

    if header_str(headers, "cross-origin-opener-policy").is_none() {
        findings.push(Finding {
            id: "HDR-COOP-INFO".into(),
            category: Category::SecurityHeaders,
            severity: Severity::Info,
            title: "Cross-Origin-Opener-Policy (COOP) is not set".into(),
            summary: "Optional hardening header that isolates browsing context groups from cross-origin windows.".into(),
            evidence: None,
            remediation: "Cross-Origin-Opener-Policy: same-origin".into(),
            standard_ref: Some("OWASP Secure Headers".into()),
            confidence: Confidence::High,
        });
    }

    if header_str(headers, "cross-origin-resource-policy").is_none() {
        findings.push(Finding {
            id: "HDR-CORP-INFO".into(),
            category: Category::SecurityHeaders,
            severity: Severity::Info,
            title: "Cross-Origin-Resource-Policy (CORP) is not set".into(),
            summary: "CORP restricts cross-origin embedding/loading of your resources to mitigate side-channel leaks.".into(),
            evidence: None,
            remediation: "Cross-Origin-Resource-Policy: same-origin".into(),
            standard_ref: Some("OWASP Secure Headers".into()),
            confidence: Confidence::High,
        });
    }

    if let Some(server) = header_str(headers, "server") {
        let has_version = server.chars().any(|c| c.is_ascii_digit()) && server.contains('/');
        if has_version {
            findings.push(Finding {
                id: "INFO-SERVER-VERSION".into(),
                category: Category::InformationDisclosure,
                severity: Severity::Low,
                title: "Server header discloses exact software version".into(),
                summary: "Exposing exact web server versions makes it easier to fingerprint specific software releases.".into(),
                evidence: Some(format!("Server: {server}")),
                remediation: "Suppress version details (e.g., `server_tokens off;` in Nginx or `ServerTokens Prod` in Apache).".into(),
                standard_ref: Some("OWASP ASVS V14.3.3 / WSTG-INFO-02".into()),
                confidence: Confidence::High,
            });
        }
    }

    for leak_header in [
        "x-powered-by",
        "x-aspnet-version",
        "x-aspnetmvc-version",
        "x-generator",
    ] {
        if let Some(val) = header_str(headers, leak_header) {
            findings.push(Finding {
                id: format!("INFO-{}", leak_header.to_ascii_uppercase()),
                category: Category::InformationDisclosure,
                severity: Severity::Low,
                title: format!("Header {leak_header} discloses backend technology"),
                summary: "Revealing framework or runtime details helps attackers tailor targeted probes.".into(),
                evidence: Some(format!("{leak_header}: {val}")),
                remediation: format!("Strip the {leak_header} header in application middleware or reverse proxy configuration."),
                standard_ref: Some("OWASP ASVS V14.3.3 / WSTG-INFO-08".into()),
                confidence: Confidence::High,
            });
        }
    }

    findings
}

/// Checks `Cache-Control` when a response contains authentication/session signals (cookies or password forms).
pub fn analyze_caching(
    headers: &HeaderMap,
    has_password_form: bool,
    page_url: &str,
) -> Option<Finding> {
    let sets_cookie = headers.get("set-cookie").is_some();
    if !sets_cookie && !has_password_form {
        return None;
    }

    let cc = header_str(headers, "cache-control")
        .unwrap_or_default()
        .to_ascii_lowercase();
    if cc.contains("no-store") {
        return None;
    }

    Some(Finding {
        id: "HTTP-CACHE-SENSITIVE".into(),
        category: Category::HttpProtocol,
        severity: if has_password_form {
            Severity::Medium
        } else {
            Severity::Low
        },
        title: "Missing `Cache-Control: no-store` on page with password form or Set-Cookie".into(),
        summary: "Pages handling login forms or setting session cookies should prevent caching in shared proxies and browser history.".into(),
        evidence: Some(format!(
            "{page_url} | Cache-Control: {}",
            if cc.is_empty() { "<missing>" } else { &cc }
        )),
        remediation: "Cache-Control: no-store, max-age=0".into(),
        standard_ref: Some("OWASP ASVS V8.3.4 / WSTG-ATHN-06".into()),
        confidence: Confidence::High,
    })
}

fn parse_hsts_max_age(lower_hsts: &str) -> Option<u64> {
    for part in lower_hsts.split(';') {
        let trimmed = part.trim();
        if let Some(rest) = trimmed.strip_prefix("max-age=") {
            let clean = rest.trim().trim_matches('"');
            if let Ok(n) = clean.parse::<u64>() {
                return Some(n);
            }
        }
    }
    None
}

fn has_wildcard_script_src(lower_csp: &str) -> bool {
    for directive in lower_csp.split(';') {
        let tokens: Vec<&str> = directive.split_whitespace().collect();
        if let Some(name) = tokens.first() {
            if (*name == "script-src" || *name == "default-src") && tokens[1..].contains(&"*") {
                return true;
            }
        }
    }
    false
}

fn truncate_evidence(s: &str, max_chars: usize) -> String {
    if s.chars().count() <= max_chars {
        s.to_string()
    } else {
        let cut: String = s.chars().take(max_chars).collect();
        format!("{cut}…")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use reqwest::header::{HeaderName, HeaderValue};

    #[test]
    fn hsts_parser_works() {
        assert_eq!(
            parse_hsts_max_age("max-age=31536000; includesubdomains"),
            Some(31536000)
        );
        assert_eq!(parse_hsts_max_age("max-age=\"86400\""), Some(86400));
        assert_eq!(parse_hsts_max_age("includesubdomains"), None);
    }

    #[test]
    fn wildcard_csp_detected_only_in_script_or_default() {
        assert!(has_wildcard_script_src("default-src *; img-src 'self'"));
        assert!(has_wildcard_script_src(
            "default-src 'self'; script-src https: *"
        ));
        assert!(!has_wildcard_script_src("default-src 'self'; img-src *"));
    }

    #[test]
    fn flags_missing_headers_and_version_leak() {
        let mut map = HeaderMap::new();
        map.insert(
            HeaderName::from_static("server"),
            HeaderValue::from_static("nginx/1.22.1"),
        );
        map.insert(
            HeaderName::from_static("x-powered-by"),
            HeaderValue::from_static("PHP/8.2"),
        );

        let findings = analyze_headers(&map, true);
        assert!(findings.iter().any(|f| f.id == "HDR-HSTS-MISSING"));
        assert!(findings.iter().any(|f| f.id == "HDR-CSP-MISSING"));
        assert!(findings.iter().any(|f| f.id == "HDR-XFO-MISSING"));
        assert!(findings.iter().any(|f| f.id == "INFO-SERVER-VERSION"));
        assert!(findings.iter().any(|f| f.id == "INFO-X-POWERED-BY"));
    }

    #[test]
    fn flags_sensitive_page_without_no_store() {
        let map = HeaderMap::new();
        let f = analyze_caching(&map, true, "https://example.com/login");
        assert!(f.is_some());
        assert_eq!(f.unwrap().id, "HTTP-CACHE-SENSITIVE");

        let mut safe_map = HeaderMap::new();
        safe_map.insert(
            HeaderName::from_static("cache-control"),
            HeaderValue::from_static("no-store, max-age=0"),
        );
        assert!(analyze_caching(&safe_map, true, "https://example.com/login").is_none());
    }
}