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
}
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());
}
}