website-vulnerability-scanner 0.2.0

Cross-platform defensive website security & configuration scanner with GUI and CLI reports.
Documentation
use scraper::{Html, Selector};
use url::Url;

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

pub fn has_password_input(body: &str) -> bool {
    let doc = Html::parse_document(body);
    Selector::parse("input[type=\"password\"]")
        .map(|sel| doc.select(&sel).next().is_some())
        .unwrap_or(false)
}

pub fn extract_same_origin_script_urls(body: &str, page_url: &Url, limit: usize) -> Vec<Url> {
    let doc = Html::parse_document(body);
    let mut urls = Vec::new();
    let mut seen = std::collections::HashSet::new();
    if let Ok(sel) = Selector::parse("script[src]") {
        for el in doc.select(&sel) {
            if let Some(src) = el.value().attr("src") {
                if let Ok(resolved) = page_url.join(src.trim()) {
                    if resolved.scheme() == page_url.scheme()
                        && resolved.host_str().map(|s| s.to_ascii_lowercase())
                            == page_url.host_str().map(|s| s.to_ascii_lowercase())
                        && resolved.port_or_known_default() == page_url.port_or_known_default()
                        && seen.insert(resolved.as_str().to_string())
                    {
                        urls.push(resolved);
                        if urls.len() >= limit {
                            break;
                        }
                    }
                }
            }
        }
    }
    urls
}

pub fn analyze_html(body: &str, page_url: &Url) -> Vec<Finding> {
    analyze_html_with_advisories(body, page_url, &[])
}

pub fn analyze_html_with_advisories(
    body: &str,
    page_url: &Url,
    custom_advisories: &[AdvisoryEntry],
) -> Vec<Finding> {
    let mut findings = Vec::new();
    let doc = Html::parse_document(body);
    let is_https = page_url.scheme() == "https";
    let page_host = page_url.host_str().unwrap_or_default();

    if is_https {
        let mut mixed_urls = Vec::new();
        let resource_selectors = [
            ("script", "src"),
            ("iframe", "src"),
            ("link", "href"),
            ("img", "src"),
            ("form", "action"),
        ];
        for (tag, attr) in resource_selectors {
            if let Ok(sel) = Selector::parse(tag) {
                for el in doc.select(&sel) {
                    if let Some(val) = el.value().attr(attr) {
                        let trimmed = val.trim();
                        if trimmed.to_ascii_lowercase().starts_with("http://") {
                            mixed_urls.push(format!("<{tag} {attr}=\"{trimmed}\">"));
                        }
                    }
                }
            }
        }

        if !mixed_urls.is_empty() {
            let has_active_mixed = mixed_urls.iter().any(|s| {
                s.starts_with("<script") || s.starts_with("<iframe") || s.starts_with("<form")
            });
            findings.push(Finding {
                id: "HTML-MIXED-CONTENT".into(),
                category: Category::ClientHtml,
                severity: if has_active_mixed {
                    Severity::High
                } else {
                    Severity::Medium
                },
                title: "Mixed content detected (http:// resources on https:// page)".into(),
                summary: format!("Found {} resource(s) loaded over http://. Browsers block active mixed content or warn users.", mixed_urls.len()),
                evidence: Some(mixed_urls.into_iter().take(5).collect::<Vec<_>>().join(" | ")),
                remediation: "Update all resource URLs to https:// or relative paths.".into(),
                standard_ref: Some("OWASP ASVS V9.1 / WSTG-CRYP-03".into()),
                confidence: Confidence::High,
            });
        }
    }

    let mut no_sri_scripts = Vec::new();

    if let Ok(sel) = Selector::parse("script[src]") {
        for el in doc.select(&sel) {
            if let Some(src) = el.value().attr("src") {
                let trimmed = src.trim();
                for lib in match_advisories(trimmed, custom_advisories) {
                    findings.push(Finding {
                        id: format!("COMP-OUTDATED-{}", lib.id_suffix),
                        category: Category::ClientHtml,
                        severity: lib.severity,
                        title: format!(
                            "Outdated client-side library detected: {} {}",
                            lib.package, lib.detected_version
                        ),
                        summary: format!(
                            "Version {} detected ({}). {}",
                            lib.detected_version, lib.advisory_id, lib.summary
                        ),
                        evidence: Some(trimmed.to_string()),
                        remediation: format!(
                            "Upgrade {} to a supported version ({}).",
                            lib.package, lib.fixed_in
                        ),
                        standard_ref: Some("OWASP ASVS V14.2.1 / WSTG-INFO".into()),
                        confidence: Confidence::Medium,
                    });
                }
                if let Ok(resolved) = page_url.join(trimmed) {
                    if let Some(script_host) = resolved.host_str() {
                        if !script_host.eq_ignore_ascii_case(page_host)
                            && el.value().attr("integrity").is_none()
                        {
                            no_sri_scripts.push(resolved.to_string());
                        }
                    }
                }
            }
        }
    }

    if !no_sri_scripts.is_empty() {
        findings.push(Finding {
            id: "HTML-MISSING-SRI".into(),
            category: Category::ClientHtml,
            severity: Severity::Low,
            title: "External scripts loaded without Subresource Integrity (SRI)".into(),
            summary: format!("Found {} external <script> tag(s) without an integrity attribute. Compromising the external host could alter script code.", no_sri_scripts.len()),
            evidence: Some(no_sri_scripts.into_iter().take(5).collect::<Vec<_>>().join(", ")),
            remediation: "Add `integrity=\"sha384-...\"` and `crossorigin=\"anonymous\"` to static third-party script tags.".into(),
            standard_ref: Some("OWASP ASVS V14.2.3".into()),
            confidence: Confidence::High,
        });
    }

    let mut unsafe_blank_count = 0usize;
    if let Ok(sel) = Selector::parse("a[target]") {
        for el in doc.select(&sel) {
            if el
                .value()
                .attr("target")
                .map(|v| v.eq_ignore_ascii_case("_blank"))
                .unwrap_or(false)
            {
                let rel = el.value().attr("rel").unwrap_or("").to_ascii_lowercase();
                let has_protection = rel
                    .split_whitespace()
                    .any(|r| r == "noopener" || r == "noreferrer");
                if !has_protection {
                    unsafe_blank_count += 1;
                }
            }
        }
    }
    if unsafe_blank_count > 0 {
        findings.push(Finding {
            id: "HTML-TARGET-BLANK".into(),
            category: Category::ClientHtml,
            severity: Severity::Info,
            title: "Links with target=\"_blank\" missing rel=\"noopener\"".into(),
            summary: format!("Found {unsafe_blank_count} link(s). Adding rel=\"noopener noreferrer\" prevents reverse tabnabbing on older browsers."),
            evidence: Some(format!("count = {unsafe_blank_count}")),
            remediation: "Add rel=\"noopener noreferrer\" to links using target=\"_blank\".".into(),
            standard_ref: Some("OWASP HTML5 Security / WSTG-CLNT".into()),
            confidence: Confidence::High,
        });
    }

    if !is_https {
        if let Ok(sel) = Selector::parse("input[type=\"password\"]") {
            if doc.select(&sel).next().is_some() {
                findings.push(Finding {
                    id: "HTML-PASSWORD-HTTP".into(),
                    category: Category::ClientHtml,
                    severity: Severity::Critical,
                    title: "Password input field served on an HTTP page".into(),
                    summary: "Collecting or submitting passwords over HTTP exposes credentials in plaintext.".into(),
                    evidence: Some(page_url.to_string()),
                    remediation: "Serve all authentication pages strictly over HTTPS.".into(),
                    standard_ref: Some("OWASP ASVS V9.1.1 / WSTG-CRYP-03".into()),
                    confidence: Confidence::High,
                });
            }
        }
    }

    if let (Ok(form_sel), Ok(input_sel)) = (Selector::parse("form"), Selector::parse("input")) {
        let mut post_without_csrf = 0usize;
        for form in doc.select(&form_sel) {
            let method = form.value().attr("method").unwrap_or("get");
            if !method.eq_ignore_ascii_case("post") {
                continue;
            }
            let has_csrf_field = form.select(&input_sel).any(|inp| {
                let typ = inp.value().attr("type").unwrap_or("");
                let name = inp.value().attr("name").unwrap_or("").to_ascii_lowercase();
                typ.eq_ignore_ascii_case("hidden")
                    && [
                        "csrf",
                        "xsrf",
                        "token",
                        "nonce",
                        "authenticity_token",
                        "__requestverificationtoken",
                    ]
                    .iter()
                    .any(|kw| name.contains(kw))
            });
            if !has_csrf_field {
                post_without_csrf += 1;
            }
        }
        if post_without_csrf > 0 {
            findings.push(Finding {
                id: "HTML-FORM-NO-CSRF-FIELD".into(),
                category: Category::ClientHtml,
                severity: Severity::Info,
                title: "POST form without an apparent hidden CSRF token field".into(),
                summary: format!("Found {post_without_csrf} POST form(s) without a hidden csrf/token input. Safe if handled via custom headers/Fetch or SameSite=Strict; otherwise verify CSRF protection."),
                evidence: Some(format!("{page_url} (forms: {post_without_csrf})")),
                remediation: "Use an anti-CSRF synchronizer token or Fetch with custom headers plus SameSite=Lax/Strict.".into(),
                standard_ref: Some("OWASP ASVS V4.2.2 / WSTG-SESS-05".into()),
                confidence: Confidence::Low,
            });
        }
    }

    if let Ok(sel) = Selector::parse("meta[name=\"generator\"]") {
        if let Some(meta) = doc.select(&sel).next() {
            if let Some(content) = meta.value().attr("content") {
                let trimmed = content.trim();
                if !trimmed.is_empty() {
                    findings.push(Finding {
                        id: "INFO-META-GENERATOR".into(),
                        category: Category::InformationDisclosure,
                        severity: Severity::Info,
                        title: "Meta generator tag discloses CMS or site generator".into(),
                        summary: "Disclosing CMS name and version aids passive technology fingerprinting.".into(),
                        evidence: Some(format!("<meta name=\"generator\" content=\"{trimmed}\">")),
                        remediation: "Remove the `generator` meta tag in your CMS or theme settings.".into(),
                        standard_ref: Some("OWASP WSTG-INFO-08".into()),
                        confidence: Confidence::High,
                    });
                }
            }
        }
    }

    let debug_markers = [
        "Traceback (most recent call last):",
        "Whoops! There was an error.",
        "Fatal error: Uncaught",
        "SQLSTATE[",
        "Django tried these URL patterns",
    ];
    for marker in debug_markers {
        if body.contains(marker) {
            findings.push(Finding {
                id: "INFO-DEBUG-TRACE".into(),
                category: Category::InformationDisclosure,
                severity: Severity::High,
                title: "Debug output or stack trace detected in response body".into(),
                summary:
                    "Debug banners leak internal code paths, framework details, or SQL queries."
                        .into(),
                evidence: Some(format!("Matched marker: {marker}")),
                remediation: "Disable debug mode in production and serve generic error pages."
                    .into(),
                standard_ref: Some("OWASP ASVS V7.4.1 / WSTG-ERRH-01".into()),
                confidence: Confidence::High,
            });
            break;
        }
    }

    findings
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn detects_mixed_content_and_missing_sri() {
        let html = r#"
        <html><head>
          <script src="http://cdn.example.com/app.js"></script>
          <script src="https://cdn.other.com/lib.js"></script>
        </head><body>
          <a href="https://ext.test" target="_blank">ext</a>
        </body></html>"#;
        let url = Url::parse("https://mysite.test/").unwrap();
        let findings = analyze_html(html, &url);
        assert!(findings
            .iter()
            .any(|f| f.id == "HTML-MIXED-CONTENT" && f.severity == Severity::High));
        assert!(findings.iter().any(|f| f.id == "HTML-MISSING-SRI"));
        assert!(findings.iter().any(|f| f.id == "HTML-TARGET-BLANK"));
    }

    #[test]
    fn detects_outdated_jquery_and_post_form_without_csrf() {
        let html = r#"
        <html><head>
          <meta name="generator" content="WordPress 6.4">
          <script src="/static/jquery-1.12.4.min.js"></script>
        </head><body>
          <form method="post" action="/login">
            <input type="password" name="pw">
          </form>
        </body></html>"#;
        let url = Url::parse("https://mysite.test/").unwrap();
        let findings = analyze_html(html, &url);
        assert!(findings
            .iter()
            .any(|f| f.id == "COMP-OUTDATED-JQUERY" && f.severity == Severity::High));
        assert!(findings.iter().any(|f| f.id == "HTML-FORM-NO-CSRF-FIELD"));
        assert!(findings.iter().any(|f| f.id == "INFO-META-GENERATOR"));
        assert!(has_password_input(html));
    }
}