website-vulnerability-scanner 0.2.0

Cross-platform defensive website security & configuration scanner with GUI and CLI reports.
Documentation
use std::net::IpAddr;
use std::time::Duration;

use hickory_resolver::error::{ResolveError, ResolveErrorKind};
use hickory_resolver::proto::rr::RecordType;
use hickory_resolver::TokioAsyncResolver;
use tokio::time::timeout;
use url::Url;

fn is_no_records(err: &ResolveError) -> bool {
    matches!(err.kind(), ResolveErrorKind::NoRecordsFound { .. })
}

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

fn is_skippable_host(host: &str) -> bool {
    let lower = host.to_ascii_lowercase();
    if lower == "localhost"
        || lower.ends_with(".localhost")
        || lower.ends_with(".local")
        || lower.ends_with(".invalid")
        || lower.ends_with(".test")
    {
        return true;
    }
    lower.parse::<IpAddr>().is_ok()
}

fn parent_domain(host: &str) -> Option<String> {
    let parts: Vec<&str> = host.trim_end_matches('.').split('.').collect();
    if parts.len() > 2 {
        Some(parts[1..].join("."))
    } else {
        None
    }
}

enum DnsLookupResult<T> {
    Found(T),
    NotFound,
    Failed(String),
}

pub async fn check_dns_hygiene(url: &Url, auth_context: &str) -> (Vec<Finding>, Vec<CheckOutcome>) {
    let mut findings = Vec::new();
    let mut outcomes = Vec::new();

    let Some(host) = url.host_str() else {
        return (findings, outcomes);
    };
    if is_skippable_host(host) {
        outcomes.push(CheckOutcome {
            check_id: "dns-hygiene".into(),
            category: Category::DnsEmail,
            location: host.to_string(),
            auth_context: auth_context.to_string(),
            status: ExecutionStatus::Skipped,
            verdict: Verdict::NotApplicable,
            reason: Some("local or IP host".into()),
        });
        return (findings, outcomes);
    }

    let resolver = match TokioAsyncResolver::tokio_from_system_conf() {
        Ok(r) => r,
        Err(e) => {
            outcomes.push(CheckOutcome {
                check_id: "dns-hygiene".into(),
                category: Category::DnsEmail,
                location: host.to_string(),
                auth_context: auth_context.to_string(),
                status: ExecutionStatus::Error,
                verdict: Verdict::Inconclusive,
                reason: Some(format!("DNS resolver init error: {e}")),
            });
            return (findings, outcomes);
        }
    };

    let dur = Duration::from_secs(4);
    let fqdn = format!("{}.", host.trim_end_matches('.'));
    let mut any_error: Option<String> = None;

    // 1. CAA check
    let mut caa_records: Vec<String> = Vec::new();
    let mut caa_ok = true;
    match timeout(dur, resolver.lookup(&fqdn, RecordType::CAA)).await {
        Ok(Ok(lookup)) => {
            for rdata in lookup.iter() {
                caa_records.push(rdata.to_string());
            }
        }
        Ok(Err(e)) if is_no_records(&e) => {}
        Ok(Err(e)) => {
            caa_ok = false;
            any_error = Some(format!("CAA lookup error: {e}"));
        }
        Err(_) => {
            caa_ok = false;
            any_error = Some("CAA lookup timed out".into());
        }
    }

    if caa_ok && caa_records.is_empty() {
        if let Some(parent) = parent_domain(host) {
            let parent_fqdn = format!("{parent}.");
            if let Ok(Ok(lookup)) =
                timeout(dur, resolver.lookup(&parent_fqdn, RecordType::CAA)).await
            {
                for rdata in lookup.iter() {
                    caa_records.push(rdata.to_string());
                }
            }
        }
    }

    if caa_ok {
        if caa_records.is_empty() {
            findings.push(Finding {
                id: "DNS-CAA-MISSING".into(),
                category: Category::DnsEmail,
                severity: Severity::Info,
                title: "Missing DNS CAA record to restrict TLS certificate issuance".into(),
                summary: "A CAA record (RFC 8659) restricts which Certificate Authorities may issue TLS certificates for your domain.".into(),
                evidence: Some(format!("Domain: {host}")),
                remediation: format!("{host}. IN CAA 0 issue \"letsencrypt.org\""),
                standard_ref: Some("RFC 8659 / OWASP ASVS V9.2".into()),
                confidence: Confidence::High,
            });
        } else {
            findings.push(Finding {
                id: "DNS-CAA-OK".into(),
                category: Category::DnsEmail,
                severity: Severity::Pass,
                title: "DNS CAA record is configured".into(),
                summary: "Authorized Certificate Authorities are restricted via DNS CAA.".into(),
                evidence: Some(caa_records.join("; ")),
                remediation: String::new(),
                standard_ref: Some("RFC 8659".into()),
                confidence: Confidence::High,
            });
        }
    }

    // 2. SPF TXT check
    match find_spf_record(&resolver, host, dur).await {
        DnsLookupResult::Found(spf) => {
            if spf.to_ascii_lowercase().contains("+all") {
                findings.push(Finding {
                    id: "DNS-SPF-PERMISSIVE".into(),
                    category: Category::DnsEmail,
                    severity: Severity::Medium,
                    title: "SPF record contains overly permissive '+all'".into(),
                    summary: "+all allows any IP address on the internet to send email claiming to be from your domain.".into(),
                    evidence: Some(spf),
                    remediation: "Replace `+all` with `~all` or `-all`.".into(),
                    standard_ref: Some("RFC 7208".into()),
                    confidence: Confidence::High,
                });
            } else {
                findings.push(Finding {
                    id: "DNS-SPF-OK".into(),
                    category: Category::DnsEmail,
                    severity: Severity::Pass,
                    title: "DNS SPF record is configured".into(),
                    summary: "Authorized mail senders are declared via SPF.".into(),
                    evidence: Some(spf),
                    remediation: String::new(),
                    standard_ref: Some("RFC 7208".into()),
                    confidence: Confidence::High,
                });
            }
        }
        DnsLookupResult::NotFound => {
            findings.push(Finding {
                id: "DNS-SPF-MISSING".into(),
                category: Category::DnsEmail,
                severity: Severity::Low,
                title: "Missing DNS SPF record".into(),
                summary: "Without an SPF record, third parties can more easily spoof email from your domain.".into(),
                evidence: Some(format!("Domain: {host}")),
                remediation: "v=spf1 -all (if domain does not send email) or list authorized SMTP servers.".into(),
                standard_ref: Some("RFC 7208".into()),
                confidence: Confidence::High,
            });
        }
        DnsLookupResult::Failed(err) => {
            if any_error.is_none() {
                any_error = Some(err);
            }
        }
    }

    // 3. DMARC TXT check
    match find_dmarc_record(&resolver, host, dur).await {
        DnsLookupResult::Found(dmarc) => {
            let lower = dmarc.to_ascii_lowercase();
            if lower.contains("p=none") {
                findings.push(Finding {
                    id: "DNS-DMARC-NONE".into(),
                    category: Category::DnsEmail,
                    severity: Severity::Low,
                    title: "DMARC policy is set to monitoring only (p=none)".into(),
                    summary:
                        "With p=none, spoofing emails are reported but not quarantined or rejected."
                            .into(),
                    evidence: Some(dmarc),
                    remediation:
                        "After validating reports, upgrade policy to `p=quarantine` or `p=reject`."
                            .into(),
                    standard_ref: Some("RFC 7489".into()),
                    confidence: Confidence::High,
                });
            } else {
                findings.push(Finding {
                    id: "DNS-DMARC-OK".into(),
                    category: Category::DnsEmail,
                    severity: Severity::Pass,
                    title: "DMARC policy is enforced".into(),
                    summary: "Domain is protected with an enforcing DMARC policy.".into(),
                    evidence: Some(dmarc),
                    remediation: String::new(),
                    standard_ref: Some("RFC 7489".into()),
                    confidence: Confidence::High,
                });
            }
        }
        DnsLookupResult::NotFound => {
            findings.push(Finding {
                id: "DNS-DMARC-MISSING".into(),
                category: Category::DnsEmail,
                severity: Severity::Low,
                title: format!("Missing DNS DMARC record (_dmarc.{host})"),
                summary: "DMARC instructs receiving mail servers how to handle spoofed mail failing SPF/DKIM.".into(),
                evidence: Some(format!("_dmarc.{host}")),
                remediation: "v=DMARC1; p=quarantine; rua=mailto:dmarc@yourdomain".into(),
                standard_ref: Some("RFC 7489".into()),
                confidence: Confidence::High,
            });
        }
        DnsLookupResult::Failed(err) => {
            if any_error.is_none() {
                any_error = Some(err);
            }
        }
    }

    if let Some(err) = any_error {
        outcomes.push(CheckOutcome {
            check_id: "dns-hygiene".into(),
            category: Category::DnsEmail,
            location: host.to_string(),
            auth_context: auth_context.to_string(),
            status: ExecutionStatus::Error,
            verdict: Verdict::Inconclusive,
            reason: Some(err),
        });
    } else {
        let any_fail = findings
            .iter()
            .any(|f| f.severity != Severity::Pass && f.severity != Severity::Info);
        outcomes.push(CheckOutcome {
            check_id: "dns-hygiene".into(),
            category: Category::DnsEmail,
            location: host.to_string(),
            auth_context: auth_context.to_string(),
            status: ExecutionStatus::Completed,
            verdict: if any_fail {
                Verdict::Fail
            } else {
                Verdict::Pass
            },
            reason: None,
        });
    }

    (findings, outcomes)
}

async fn find_spf_record(
    resolver: &TokioAsyncResolver,
    host: &str,
    dur: Duration,
) -> DnsLookupResult<String> {
    let mut candidates = vec![host.trim_end_matches('.').to_string()];
    if let Some(p) = parent_domain(host) {
        candidates.push(p);
    }
    let mut had_error: Option<String> = None;
    for dom in candidates {
        let fqdn = format!("{dom}.");
        match timeout(dur, resolver.txt_lookup(&fqdn)).await {
            Ok(Ok(txt)) => {
                for r in txt.iter() {
                    let s = r.to_string();
                    if s.to_ascii_lowercase().starts_with("v=spf1") {
                        return DnsLookupResult::Found(s);
                    }
                }
            }
            Ok(Err(e)) if is_no_records(&e) => {}
            Ok(Err(e)) => had_error = Some(format!("SPF lookup error: {e}")),
            Err(_) => had_error = Some("SPF lookup timed out".into()),
        }
    }
    if let Some(err) = had_error {
        DnsLookupResult::Failed(err)
    } else {
        DnsLookupResult::NotFound
    }
}

async fn find_dmarc_record(
    resolver: &TokioAsyncResolver,
    host: &str,
    dur: Duration,
) -> DnsLookupResult<String> {
    let mut candidates = vec![format!("_dmarc.{}.", host.trim_end_matches('.'))];
    if let Some(p) = parent_domain(host) {
        candidates.push(format!("_dmarc.{p}."));
    }
    let mut had_error: Option<String> = None;
    for fqdn in candidates {
        match timeout(dur, resolver.txt_lookup(&fqdn)).await {
            Ok(Ok(txt)) => {
                for r in txt.iter() {
                    let s = r.to_string();
                    if s.to_ascii_lowercase().starts_with("v=dmarc1") {
                        return DnsLookupResult::Found(s);
                    }
                }
            }
            Ok(Err(e)) if is_no_records(&e) => {}
            Ok(Err(e)) => had_error = Some(format!("DMARC lookup error: {e}")),
            Err(_) => had_error = Some("DMARC lookup timed out".into()),
        }
    }
    if let Some(err) = had_error {
        DnsLookupResult::Failed(err)
    } else {
        DnsLookupResult::NotFound
    }
}

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

    #[test]
    fn skips_local_and_ip_hosts() {
        assert!(is_skippable_host("localhost"));
        assert!(is_skippable_host("127.0.0.1"));
        assert!(is_skippable_host("::1"));
        assert!(is_skippable_host("app.local"));
        assert!(is_skippable_host("demo.invalid"));
        assert!(!is_skippable_host("example.com"));
    }
}