use std::net::IpAddr;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use chrono::{DateTime, Utc};
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::client::WebPkiServerVerifier;
use rustls::pki_types::{CertificateDer, ServerName, UnixTime};
use rustls::{ClientConfig, DigitallySignedStruct, RootCertStore, SignatureScheme};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use tokio::time::timeout;
use tokio_rustls::TlsConnector;
use url::Url;
use x509_parser::extensions::GeneralName;
use x509_parser::prelude::*;
use crate::models::{
Category, CheckOutcome, Confidence, ExecutionStatus, Finding, Severity, TlsInfo, Verdict,
};
#[derive(Debug, Clone)]
struct CapturedCert {
der: Vec<u8>,
verify_error: Option<String>,
}
#[derive(Debug)]
struct InspectingVerifier {
inner: Arc<WebPkiServerVerifier>,
captured: Arc<Mutex<Option<CapturedCert>>>,
}
impl ServerCertVerifier for InspectingVerifier {
fn verify_server_cert(
&self,
end_entity: &CertificateDer<'_>,
intermediates: &[CertificateDer<'_>],
server_name: &ServerName<'_>,
ocsp_response: &[u8],
now: UnixTime,
) -> Result<ServerCertVerified, rustls::Error> {
let res = self.inner.verify_server_cert(
end_entity,
intermediates,
server_name,
ocsp_response,
now,
);
let verify_error = res.as_ref().err().map(|e| e.to_string());
if let Ok(mut guard) = self.captured.lock() {
*guard = Some(CapturedCert {
der: end_entity.to_vec(),
verify_error,
});
}
Ok(ServerCertVerified::assertion())
}
fn verify_tls12_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
self.inner.verify_tls12_signature(message, cert, dss)
}
fn verify_tls13_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
self.inner.verify_tls13_signature(message, cert, dss)
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
self.inner.supported_verify_schemes()
}
}
pub async fn inspect_tls(
url: &Url,
timeout_secs: u64,
auth_context: &str,
) -> (Option<TlsInfo>, Vec<Finding>, CheckOutcome) {
let mut findings = Vec::new();
let loc = url.to_string();
if url.scheme() != "https" {
findings.push(Finding {
id: "TLS-NO-HTTPS".into(),
category: Category::TransportTls,
severity: Severity::Critical,
title: "Site is served over unencrypted HTTP (no HTTPS)".into(),
summary: "Traffic, login forms, cookies, and tokens are transmitted in plaintext and can be intercepted or modified in transit.".into(),
evidence: Some(loc.clone()),
remediation: "Configure a TLS certificate (e.g., Let's Encrypt) and enforce a permanent 301/308 redirect from HTTP to HTTPS.".into(),
standard_ref: Some("OWASP ASVS V9.1.1 / WSTG-CRYP-01".into()),
confidence: Confidence::High,
});
return (
None,
findings,
CheckOutcome {
check_id: "tls-inspection".into(),
category: Category::TransportTls,
location: loc,
auth_context: auth_context.to_string(),
status: ExecutionStatus::Completed,
verdict: Verdict::Fail,
reason: Some("plaintext HTTP".into()),
},
);
}
let Some(host) = url.host_str() else {
return (
None,
findings,
CheckOutcome {
check_id: "tls-inspection".into(),
category: Category::TransportTls,
location: loc,
auth_context: auth_context.to_string(),
status: ExecutionStatus::Error,
verdict: Verdict::Inconclusive,
reason: Some("missing host".into()),
},
);
};
let port = url.port_or_known_default().unwrap_or(443);
let addr = format!("{host}:{port}");
let mut root_store = RootCertStore::empty();
root_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
let provider = Arc::new(rustls::crypto::ring::default_provider());
let Ok(inner_verifier) =
WebPkiServerVerifier::builder_with_provider(Arc::new(root_store), provider.clone()).build()
else {
return (
None,
findings,
CheckOutcome {
check_id: "tls-inspection".into(),
category: Category::TransportTls,
location: loc,
auth_context: auth_context.to_string(),
status: ExecutionStatus::Error,
verdict: Verdict::Inconclusive,
reason: Some("verifier build failed".into()),
},
);
};
let captured = Arc::new(Mutex::new(None));
let verifier = Arc::new(InspectingVerifier {
inner: inner_verifier,
captured: captured.clone(),
});
let config = ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
.expect("valid default TLS protocol versions")
.dangerous()
.with_custom_certificate_verifier(verifier)
.with_no_client_auth();
let server_name = match ServerName::try_from(host.to_string()) {
Ok(name) => name,
Err(_) => {
return (
None,
findings,
CheckOutcome {
check_id: "tls-inspection".into(),
category: Category::TransportTls,
location: loc,
auth_context: auth_context.to_string(),
status: ExecutionStatus::Error,
verdict: Verdict::Inconclusive,
reason: Some("invalid server name".into()),
},
);
}
};
let dur = Duration::from_secs(timeout_secs);
let tcp = match timeout(dur, TcpStream::connect(&addr)).await {
Ok(Ok(stream)) => stream,
Ok(Err(e)) => {
findings.push(Finding {
id: "TLS-CONNECT-ERR".into(),
category: Category::TransportTls,
severity: Severity::High,
title: "Failed to establish TLS connection".into(),
summary: format!("Could not connect to {addr} to inspect the TLS certificate: {e}"),
evidence: Some(addr),
remediation: "Verify port 443 reachability, firewall rules, and web server TLS configuration.".into(),
standard_ref: Some("OWASP ASVS V9.1".into()),
confidence: Confidence::High,
});
return (
None,
findings,
CheckOutcome {
check_id: "tls-inspection".into(),
category: Category::TransportTls,
location: loc,
auth_context: auth_context.to_string(),
status: ExecutionStatus::Error,
verdict: Verdict::Inconclusive,
reason: Some(e.to_string()),
},
);
}
Err(_) => {
findings.push(Finding {
id: "TLS-TIMEOUT".into(),
category: Category::TransportTls,
severity: Severity::High,
title: "TLS handshake timed out".into(),
summary: format!("Connection to {addr} exceeded {timeout_secs}s timeout."),
evidence: Some(addr),
remediation: "Check network latency and the TLS termination proxy / load balancer."
.into(),
standard_ref: Some("OWASP ASVS V9.1".into()),
confidence: Confidence::High,
});
return (
None,
findings,
CheckOutcome {
check_id: "tls-inspection".into(),
category: Category::TransportTls,
location: loc,
auth_context: auth_context.to_string(),
status: ExecutionStatus::Error,
verdict: Verdict::Inconclusive,
reason: Some("TLS connect timeout".into()),
},
);
}
};
let connector = TlsConnector::from(Arc::new(config));
let tls_stream = match timeout(dur, connector.connect(server_name, tcp)).await {
Ok(Ok(s)) => s,
Ok(Err(e)) => {
findings.push(Finding {
id: "TLS-HANDSHAKE-ERR".into(),
category: Category::TransportTls,
severity: Severity::High,
title: "TLS handshake failed".into(),
summary: format!(
"Server {addr} rejected the TLS connection or uses unsupported parameters: {e}"
),
evidence: Some(e.to_string()),
remediation:
"Ensure the server supports TLS 1.2 and/or TLS 1.3 with modern cipher suites."
.into(),
standard_ref: Some("OWASP ASVS V9.1.2 / WSTG-CRYP-01".into()),
confidence: Confidence::High,
});
return (
None,
findings,
CheckOutcome {
check_id: "tls-inspection".into(),
category: Category::TransportTls,
location: loc,
auth_context: auth_context.to_string(),
status: ExecutionStatus::Error,
verdict: Verdict::Inconclusive,
reason: Some(e.to_string()),
},
);
}
Err(_) => {
return (
None,
findings,
CheckOutcome {
check_id: "tls-inspection".into(),
category: Category::TransportTls,
location: loc,
auth_context: auth_context.to_string(),
status: ExecutionStatus::Error,
verdict: Verdict::Inconclusive,
reason: Some("TLS handshake timeout".into()),
},
);
}
};
let (_, conn) = tls_stream.get_ref();
let protocol = conn
.protocol_version()
.map(|v| format!("{v:?}"))
.unwrap_or_else(|| "Unknown".into());
let cipher_suite = conn
.negotiated_cipher_suite()
.map(|c| format!("{:?}", c.suite()))
.unwrap_or_else(|| "Unknown".into());
let captured_guard = captured.lock().ok().and_then(|g| g.clone());
let Some(cert_data) = captured_guard else {
return (
None,
findings,
CheckOutcome {
check_id: "tls-inspection".into(),
category: Category::TransportTls,
location: loc,
auth_context: auth_context.to_string(),
status: ExecutionStatus::Error,
verdict: Verdict::Inconclusive,
reason: Some("no peer certificate captured".into()),
},
);
};
let Ok((_, cert)) = X509Certificate::from_der(&cert_data.der) else {
return (
None,
findings,
CheckOutcome {
check_id: "tls-inspection".into(),
category: Category::TransportTls,
location: loc,
auth_context: auth_context.to_string(),
status: ExecutionStatus::Error,
verdict: Verdict::Inconclusive,
reason: Some("X.509 DER parse failed".into()),
},
);
};
let subject = cert.subject().to_string();
let issuer = cert.issuer().to_string();
let not_before_ts = cert.validity().not_before.timestamp();
let not_after_ts = cert.validity().not_after.timestamp();
let not_before = DateTime::from_timestamp(not_before_ts, 0)
.map(|d| d.format("%Y-%m-%d %H:%M UTC").to_string())
.unwrap_or_else(|| not_before_ts.to_string());
let not_after = DateTime::from_timestamp(not_after_ts, 0)
.map(|d| d.format("%Y-%m-%d %H:%M UTC").to_string())
.unwrap_or_else(|| not_after_ts.to_string());
let now_ts = Utc::now().timestamp();
let days_remaining = (not_after_ts - now_ts) / 86_400;
let mut sans = Vec::new();
if let Ok(Some(san_ext)) = cert.subject_alternative_name() {
for name in &san_ext.value.general_names {
match name {
GeneralName::DNSName(dns) => sans.push((*dns).to_string()),
GeneralName::IPAddress(bytes) => {
if let Ok(ip) = <[u8; 4]>::try_from(*bytes).map(IpAddr::from) {
sans.push(ip.to_string());
} else if let Ok(ip) = <[u8; 16]>::try_from(*bytes).map(IpAddr::from) {
sans.push(ip.to_string());
}
}
_ => {}
}
}
}
let hostname_matches = cert_data.verify_error.is_none();
if let Some(err) = &cert_data.verify_error {
findings.push(Finding {
id: "TLS-CERT-UNTRUSTED".into(),
category: Category::TransportTls,
severity: Severity::Critical,
title: "TLS certificate failed trust verification".into(),
summary: format!("Browsers will show a security warning for visitors. Reason: {err}"),
evidence: Some(format!("Subject: {subject} | Issuer: {issuer} | Error: {err}")),
remediation: "Install a valid certificate from a trusted CA (e.g., Let's Encrypt), include the full intermediate chain, and ensure the hostname is listed in SAN.".into(),
standard_ref: Some("OWASP ASVS V9.2.1 / WSTG-CRYP-01".into()),
confidence: Confidence::High,
});
} else if days_remaining < 0 {
findings.push(Finding {
id: "TLS-CERT-EXPIRED".into(),
category: Category::TransportTls,
severity: Severity::Critical,
title: "TLS certificate has expired".into(),
summary: format!("Certificate expired on {not_after} ({} days ago).", -days_remaining),
evidence: Some(format!("notAfter: {not_after}")),
remediation: "Renew the certificate immediately and configure automated renewal (certbot / acme.sh).".into(),
standard_ref: Some("OWASP ASVS V9.2.1 / WSTG-CRYP-01".into()),
confidence: Confidence::High,
});
} else if days_remaining <= 14 {
findings.push(Finding {
id: "TLS-CERT-EXPIRING-SOON".into(),
category: Category::TransportTls,
severity: Severity::High,
title: "TLS certificate expires soon (<= 14 days)".into(),
summary: format!("Certificate expires in {days_remaining} days (on {not_after})."),
evidence: Some(format!("notAfter: {not_after}")),
remediation: "Check automated certificate renewal (certbot renew / cron / systemd timer).".into(),
standard_ref: Some("OWASP ASVS V9.2.1".into()),
confidence: Confidence::High,
});
} else if days_remaining <= 30 {
findings.push(Finding {
id: "TLS-CERT-EXPIRING-30D".into(),
category: Category::TransportTls,
severity: Severity::Low,
title: "TLS certificate expires within 30 days".into(),
summary: format!("{days_remaining} days remaining (until {not_after})."),
evidence: Some(format!("notAfter: {not_after}")),
remediation: "Ensure automated certificate renewal is scheduled and healthy.".into(),
standard_ref: Some("OWASP ASVS V9.2.1".into()),
confidence: Confidence::High,
});
} else {
findings.push(Finding {
id: "TLS-CERT-OK".into(),
category: Category::TransportTls,
severity: Severity::Pass,
title: "TLS certificate is valid and trusted".into(),
summary: format!("Negotiated {protocol}; certificate valid for {days_remaining} more days (until {not_after})."),
evidence: Some(format!("{protocol} | {cipher_suite} | Issuer: {issuer}")),
remediation: String::new(),
standard_ref: Some("OWASP ASVS V9.1 / V9.2".into()),
confidence: Confidence::High,
});
}
if protocol.contains("TLSv1_0") || protocol.contains("TLSv1_1") {
findings.push(Finding {
id: "TLS-LEGACY-PROTOCOL".into(),
category: Category::TransportTls,
severity: Severity::High,
title: "Legacy TLS protocol version negotiated".into(),
summary: format!(
"Negotiated legacy protocol {protocol}, which has known cryptographic weaknesses."
),
evidence: Some(protocol.clone()),
remediation: "Disable TLS 1.0 and TLS 1.1; enable only TLSv1.2 and TLSv1.3.".into(),
standard_ref: Some("OWASP ASVS V9.1.2 / WSTG-CRYP-01".into()),
confidence: Confidence::High,
});
}
let info = TlsInfo {
protocol,
cipher_suite,
subject,
issuer,
sans,
not_before,
not_after,
days_remaining,
hostname_matches,
};
let any_fail = findings
.iter()
.any(|f| f.severity != Severity::Pass && f.severity != Severity::Info);
(
Some(info),
findings,
CheckOutcome {
check_id: "tls-inspection".into(),
category: Category::TransportTls,
location: loc,
auth_context: auth_context.to_string(),
status: ExecutionStatus::Completed,
verdict: if any_fail {
Verdict::Fail
} else {
Verdict::Pass
},
reason: None,
},
)
}
pub async fn check_http_redirect(
https_url: &Url,
auth_context: &str,
) -> (Option<Finding>, CheckOutcome) {
if https_url.scheme() != "https" {
return (
None,
CheckOutcome {
check_id: "http-redirect".into(),
category: Category::TransportTls,
location: https_url.to_string(),
auth_context: auth_context.to_string(),
status: ExecutionStatus::Skipped,
verdict: Verdict::NotApplicable,
reason: Some("target scheme is not https".into()),
},
);
}
let mut http_url = https_url.clone();
if http_url.set_scheme("http").is_err() {
return (
None,
CheckOutcome {
check_id: "http-redirect".into(),
category: Category::TransportTls,
location: https_url.to_string(),
auth_context: auth_context.to_string(),
status: ExecutionStatus::Error,
verdict: Verdict::Inconclusive,
reason: Some("failed to construct http URL".into()),
},
);
}
if https_url.port() == Some(443) {
let _ = http_url.set_port(None);
}
let no_redir = match reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.timeout(Duration::from_secs(6))
.build()
{
Ok(c) => c,
Err(e) => {
return (
None,
CheckOutcome {
check_id: "http-redirect".into(),
category: Category::TransportTls,
location: http_url.to_string(),
auth_context: auth_context.to_string(),
status: ExecutionStatus::Error,
verdict: Verdict::Inconclusive,
reason: Some(e.to_string()),
},
);
}
};
let resp = match no_redir
.get(http_url.as_str())
.header(reqwest::header::USER_AGENT, "web-vuln-scanner")
.send()
.await
{
Ok(r) => r,
Err(_) => {
return (
Some(Finding {
id: "TLS-HTTP-CLOSED".into(),
category: Category::TransportTls,
severity: Severity::Info,
title: "HTTP port (80) is not reachable".into(),
summary: "Port 80 is closed or unreachable. Visitors typing http:// will not be redirected unless HSTS Preload is active.".into(),
evidence: Some(http_url.to_string()),
remediation: "Optionally configure a lightweight 301 redirect from HTTP to HTTPS.".into(),
standard_ref: Some("OWASP ASVS V9.1.1".into()),
confidence: Confidence::Medium,
}),
CheckOutcome {
check_id: "http-redirect".into(),
category: Category::TransportTls,
location: http_url.to_string(),
auth_context: auth_context.to_string(),
status: ExecutionStatus::Completed,
verdict: Verdict::Pass,
reason: Some("port 80 unreachable".into()),
},
);
}
};
let status = resp.status();
let location = resp
.headers()
.get(reqwest::header::LOCATION)
.and_then(|v| v.to_str().ok())
.unwrap_or("");
if status.is_redirection() && location.starts_with("https://") {
(
Some(Finding {
id: "TLS-HTTP-REDIRECT-OK".into(),
category: Category::TransportTls,
severity: Severity::Pass,
title: "HTTP redirects cleanly to HTTPS".into(),
summary: format!("HTTP request returned status {status} -> {location}."),
evidence: Some(format!("{http_url} -> {status} {location}")),
remediation: String::new(),
standard_ref: Some("OWASP ASVS V9.1.1".into()),
confidence: Confidence::High,
}),
CheckOutcome {
check_id: "http-redirect".into(),
category: Category::TransportTls,
location: http_url.to_string(),
auth_context: auth_context.to_string(),
status: ExecutionStatus::Completed,
verdict: Verdict::Pass,
reason: None,
},
)
} else if status.is_success() {
(
Some(Finding {
id: "TLS-HTTP-NO-REDIRECT".into(),
category: Category::TransportTls,
severity: Severity::Medium,
title: "Site serves content over plain HTTP without redirecting to HTTPS".into(),
summary: "Accessing http:// does not upgrade the user to https://, enabling SSL stripping / downgrade attacks.".into(),
evidence: Some(format!("{http_url} -> HTTP {status}")),
remediation: "Add a 301/308 redirect rule from http:// to https:// in Nginx/Caddy/Cloudflare.".into(),
standard_ref: Some("OWASP ASVS V9.1.1 / WSTG-CRYP-01".into()),
confidence: Confidence::High,
}),
CheckOutcome {
check_id: "http-redirect".into(),
category: Category::TransportTls,
location: http_url.to_string(),
auth_context: auth_context.to_string(),
status: ExecutionStatus::Completed,
verdict: Verdict::Fail,
reason: None,
},
)
} else {
(
None,
CheckOutcome {
check_id: "http-redirect".into(),
category: Category::TransportTls,
location: http_url.to_string(),
auth_context: auth_context.to_string(),
status: ExecutionStatus::Completed,
verdict: Verdict::Pass,
reason: Some(format!("HTTP {status}")),
},
)
}
}
fn build_client_hello(major: u8, minor: u8, sni_host: Option<&str>) -> Vec<u8> {
let mut ext = Vec::new();
if let Some(host) = sni_host {
if host.parse::<IpAddr>().is_err() && !host.is_empty() && host.len() < 250 {
let host_bytes = host.as_bytes();
let list_len = (host_bytes.len() + 3) as u16;
let ext_len = list_len + 2;
ext.extend_from_slice(&[0x00, 0x00]); ext.extend_from_slice(&ext_len.to_be_bytes());
ext.extend_from_slice(&list_len.to_be_bytes());
ext.push(0x00); ext.extend_from_slice(&(host_bytes.len() as u16).to_be_bytes());
ext.extend_from_slice(host_bytes);
}
}
let ciphers: &[u8] = &[
0xc0, 0x2f, 0xc0, 0x13, 0xc0, 0x14, 0x00, 0x9c, 0x00, 0x2f, 0x00, 0x35, ];
let mut body = Vec::new();
body.push(major);
body.push(minor);
body.extend_from_slice(&[0x42; 32]); body.push(0x00); body.extend_from_slice(&(ciphers.len() as u16).to_be_bytes());
body.extend_from_slice(ciphers);
body.push(0x01); body.push(0x00); if !ext.is_empty() {
body.extend_from_slice(&(ext.len() as u16).to_be_bytes());
body.extend_from_slice(&ext);
}
let mut handshake = Vec::with_capacity(body.len() + 4);
handshake.push(0x01); let bl = body.len() as u32;
handshake.push(((bl >> 16) & 0xff) as u8);
handshake.push(((bl >> 8) & 0xff) as u8);
handshake.push((bl & 0xff) as u8);
handshake.extend_from_slice(&body);
let mut record = Vec::with_capacity(handshake.len() + 5);
record.push(0x16); record.push(0x03);
record.push(0x01); record.extend_from_slice(&(handshake.len() as u16).to_be_bytes());
record.extend_from_slice(&handshake);
record
}
async fn accepts_legacy_tls_version(
host: &str,
port: u16,
minor: u8,
dur: Duration,
) -> Result<bool, String> {
let addr = format!("{host}:{port}");
let mut stream = timeout(dur, TcpStream::connect(&addr))
.await
.map_err(|_| "connect timeout".to_string())?
.map_err(|e| e.to_string())?;
let hello = build_client_hello(0x03, minor, Some(host));
timeout(dur, stream.write_all(&hello))
.await
.map_err(|_| "write timeout".to_string())?
.map_err(|e| e.to_string())?;
let mut buf = [0u8; 64];
let n = match timeout(dur, stream.read(&mut buf)).await {
Ok(Ok(n)) => n,
_ => return Ok(false),
};
if n >= 11 && buf[0] == 0x16 && buf[5] == 0x02 {
return Ok(buf[9] == 0x03 && buf[10] == minor);
}
Ok(false)
}
pub async fn probe_legacy_tls_versions(
url: &Url,
timeout_secs: u64,
auth_context: &str,
) -> (Vec<Finding>, CheckOutcome) {
let loc = url.to_string();
if url.scheme() != "https" {
return (
Vec::new(),
CheckOutcome {
check_id: "tls-legacy-versions".into(),
category: Category::TransportTls,
location: loc,
auth_context: auth_context.to_string(),
status: ExecutionStatus::Completed,
verdict: Verdict::NotApplicable,
reason: Some("plaintext HTTP target".into()),
},
);
}
let Some(host) = url.host_str() else {
return (
Vec::new(),
CheckOutcome {
check_id: "tls-legacy-versions".into(),
category: Category::TransportTls,
location: loc,
auth_context: auth_context.to_string(),
status: ExecutionStatus::Error,
verdict: Verdict::Inconclusive,
reason: Some("missing host".into()),
},
);
};
let port = url.port_or_known_default().unwrap_or(443);
let dur = Duration::from_secs(timeout_secs.clamp(1, 5));
let mut accepted = Vec::new();
let mut probe_err: Option<String> = None;
for (minor, label) in [(0x01u8, "TLS 1.0"), (0x02u8, "TLS 1.1")] {
match accepts_legacy_tls_version(host, port, minor, dur).await {
Ok(true) => accepted.push(label),
Ok(false) => {}
Err(e) => probe_err = Some(e),
}
}
if !accepted.is_empty() {
let joined = accepted.join(", ");
return (
vec![Finding {
id: "TLS-LEGACY-PROTOCOL".into(),
category: Category::TransportTls,
severity: Severity::High,
title: format!("Deprecated TLS protocol enabled: {joined}"),
summary: "Server negotiated deprecated TLS 1.0/1.1 protocols, which have known cryptographic weaknesses and violate modern compliance baselines.".into(),
evidence: Some(format!("{host}:{port} accepted {joined}")),
remediation: "Disable TLS 1.0 and TLS 1.1 on the reverse proxy / CDN and allow only TLS 1.2 and TLS 1.3.".into(),
standard_ref: Some("OWASP ASVS V9.1.2 / WSTG-CRYP-01".into()),
confidence: Confidence::High,
}],
CheckOutcome {
check_id: "tls-legacy-versions".into(),
category: Category::TransportTls,
location: loc,
auth_context: auth_context.to_string(),
status: ExecutionStatus::Completed,
verdict: Verdict::Fail,
reason: Some(joined),
},
);
}
if let Some(err) = probe_err {
return (
Vec::new(),
CheckOutcome {
check_id: "tls-legacy-versions".into(),
category: Category::TransportTls,
location: loc,
auth_context: auth_context.to_string(),
status: ExecutionStatus::Error,
verdict: Verdict::Inconclusive,
reason: Some(err),
},
);
}
(
vec![Finding {
id: "TLS-LEGACY-DISABLED".into(),
category: Category::TransportTls,
severity: Severity::Pass,
title: "Deprecated TLS 1.0 and TLS 1.1 are disabled".into(),
summary: format!(
"TLS 1.0 and TLS 1.1 handshake probes were rejected on {host}:{port}."
),
evidence: None,
remediation: String::new(),
standard_ref: Some("OWASP ASVS V9.1.2".into()),
confidence: Confidence::High,
}],
CheckOutcome {
check_id: "tls-legacy-versions".into(),
category: Category::TransportTls,
location: loc,
auth_context: auth_context.to_string(),
status: ExecutionStatus::Completed,
verdict: Verdict::Pass,
reason: None,
},
)
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::net::TcpListener;
#[tokio::test]
async fn detects_legacy_tls_10_server_hello() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
for _ in 0..2 {
let Ok((mut sock, _)) = listener.accept().await else {
break;
};
let mut req = [0u8; 256];
let n = sock.read(&mut req).await.unwrap_or(0);
if n >= 11 && req[9] == 0x03 && req[10] == 0x01 {
let sh: [u8; 11] = [
0x16, 0x03, 0x01, 0x00, 0x07, 0x02, 0x00, 0x00, 0x03, 0x03, 0x01,
];
let _ = sock.write_all(&sh).await;
} else {
let alert: [u8; 7] = [0x15, 0x03, 0x02, 0x00, 0x02, 0x02, 0x46];
let _ = sock.write_all(&alert).await;
}
}
});
let url = Url::parse(&format!("https://127.0.0.1:{}/", addr.port())).unwrap();
let (findings, outcome) = probe_legacy_tls_versions(&url, 3, "anonymous").await;
assert_eq!(outcome.verdict, Verdict::Fail);
assert!(findings.iter().any(|f| f.id == "TLS-LEGACY-PROTOCOL"));
}
}