use std::net::IpAddr;
use std::sync::{Arc, OnceLock};
use crate::model::confidence::Confidence;
use crate::model::finding::{
DetectionClass, DetectionId, Excerpt, Finding, Reference, Severity, Standing, Version,
};
use crate::model::tls::TlsSupport;
use std::time::{Duration, SystemTime};
#[must_use]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Security {
tls_version: Option<Arc<str>>,
cipher_suite: Option<Arc<str>>,
alpn: Vec<Arc<str>>,
certificate: Option<CertificateInfo>,
support: TlsSupport,
}
impl Security {
pub fn new() -> Self {
Self {
tls_version: None,
cipher_suite: None,
alpn: Vec::new(),
certificate: None,
support: TlsSupport::new(),
}
}
pub fn support(&self) -> &TlsSupport {
&self.support
}
pub fn set_support(&mut self, support: TlsSupport) {
self.support = support;
}
pub fn with_support(mut self, support: TlsSupport) -> Self {
self.support = support;
self
}
pub fn tls_version(&self) -> Option<&str> {
self.tls_version.as_deref()
}
pub fn cipher_suite(&self) -> Option<&str> {
self.cipher_suite.as_deref()
}
pub fn alpn(&self) -> &[Arc<str>] {
&self.alpn
}
pub fn certificate(&self) -> Option<&CertificateInfo> {
self.certificate.as_ref()
}
pub fn with_tls_version(mut self, version: impl Into<Arc<str>>) -> Self {
self.tls_version = Some(version.into());
self
}
pub fn with_cipher_suite(mut self, cipher: impl Into<Arc<str>>) -> Self {
self.cipher_suite = Some(cipher.into());
self
}
pub fn add_alpn(&mut self, protocol: impl Into<Arc<str>>) {
let protocol = protocol.into();
if !self.alpn.contains(&protocol) {
self.alpn.push(protocol);
}
}
pub fn with_alpn(mut self, protocol: impl Into<Arc<str>>) -> Self {
self.add_alpn(protocol);
self
}
pub fn with_certificate(mut self, cert: CertificateInfo) -> Self {
self.certificate = Some(cert);
self
}
pub fn merge(&mut self, other: Security) {
let Security {
tls_version,
cipher_suite,
alpn,
certificate,
support,
} = other;
self.tls_version = self.tls_version.take().or(tls_version);
self.cipher_suite = self.cipher_suite.take().or(cipher_suite);
self.certificate = self.certificate.take().or(certificate);
self.support.merge(support);
for protocol in alpn {
if !self.alpn.contains(&protocol) {
self.alpn.push(protocol);
}
}
}
pub(crate) fn standing(&self, finding: &Finding, basis: &Security) -> Option<Standing> {
if finding.detection().id() == CERTIFICATE_DETECTION {
fn fingerprint(security: &Security) -> Option<&str> {
security
.certificate
.as_ref()
.map(CertificateInfo::fingerprint_sha256)
.filter(|fingerprint| !fingerprint.is_empty())
}
let then = fingerprint(basis)?;
return Some(match fingerprint(self) {
Some(now) if now == then => Standing::Upheld,
Some(_) => Standing::Overturned,
None => Standing::Unsettled,
});
}
self.support.standing(finding, &basis.support)
}
pub(crate) fn restate(&self, finding: &Finding, basis: &Security) -> Option<Excerpt> {
if finding.detection().id() == CERTIFICATE_DETECTION {
return None;
}
self.support.restate(finding, &basis.support)
}
pub fn is_cert_valid(&self) -> bool {
self.is_cert_valid_at(SystemTime::now())
}
pub fn is_cert_valid_at(&self, target_time: SystemTime) -> bool {
self.certificate
.as_ref()
.is_some_and(|c| target_time >= c.validity_start() && target_time <= c.validity_end())
}
pub fn is_cert_expiring(&self, threshold: Duration) -> bool {
self.is_cert_expiring_at(threshold, SystemTime::now())
}
pub fn is_cert_expiring_at(&self, threshold: Duration, at: SystemTime) -> bool {
self.certificate.as_ref().is_some_and(|c| {
if at < c.validity_start() || at > c.validity_end() {
return false;
}
match at.checked_add(threshold) {
Some(horizon) => c.validity_end() < horizon,
None => true,
}
})
}
}
impl Default for Security {
fn default() -> Self {
Self::new()
}
}
pub const MAX_SANS_PER_CERTIFICATE: usize = 100;
#[must_use]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CertificateInfo {
common_name: Arc<str>,
sans: Vec<Arc<str>>,
issuer: Arc<str>,
validity_start: SystemTime,
validity_end: SystemTime,
pubkey_type: Arc<str>,
pubkey_bits: u32,
fingerprint_sha256: Arc<str>,
}
impl CertificateInfo {
pub fn new(
common_name: impl Into<Arc<str>>,
issuer: impl Into<Arc<str>>,
validity_start: SystemTime,
validity_end: SystemTime,
fingerprint_sha256: impl Into<Arc<str>>,
) -> Self {
Self {
common_name: common_name.into(),
sans: Vec::new(),
issuer: issuer.into(),
validity_start,
validity_end,
pubkey_type: Arc::from("unknown"),
pubkey_bits: 0,
fingerprint_sha256: fingerprint_sha256.into(),
}
}
pub fn with_sans(mut self, sans: impl IntoIterator<Item = Arc<str>>) -> Self {
self.sans = sans.into_iter().take(MAX_SANS_PER_CERTIFICATE).collect();
self
}
pub fn with_public_key(mut self, kind: impl Into<Arc<str>>, bits: u32) -> Self {
self.pubkey_type = kind.into();
self.pubkey_bits = bits;
self
}
pub fn common_name(&self) -> &str {
&self.common_name
}
pub fn sans(&self) -> &[Arc<str>] {
&self.sans
}
pub fn issuer(&self) -> &str {
&self.issuer
}
pub fn validity_start(&self) -> SystemTime {
self.validity_start
}
pub fn validity_end(&self) -> SystemTime {
self.validity_end
}
pub fn pubkey_type(&self) -> &str {
&self.pubkey_type
}
pub fn pubkey_bits(&self) -> u32 {
self.pubkey_bits
}
pub fn fingerprint_sha256(&self) -> &str {
&self.fingerprint_sha256
}
pub fn findings(&self, at: SystemTime) -> Vec<Finding> {
let mut findings = Vec::new();
let id = certificate_detection_id();
if at > self.validity_end
&& let Ok(finding) = Finding::new(
id.clone(),
"TLS certificate has expired",
Severity::Medium,
Confidence::Certain,
DetectionClass::Passive,
)
{
findings.push(
finding
.with_excerpt(Excerpt::new(format!(
"the certificate for {} is past its validity window",
self.common_name
)))
.with_reference(Reference::Cwe(324)),
);
}
if !self.common_name.is_empty()
&& self.issuer.eq_ignore_ascii_case(self.common_name.as_ref())
&& let Ok(finding) = Finding::new(
id.clone(),
"TLS certificate is self-signed",
Severity::Low,
Confidence::Probable,
DetectionClass::Passive,
)
{
findings.push(
finding
.with_excerpt(Excerpt::new(format!(
"issuer and subject are both {}",
self.common_name
)))
.with_reference(Reference::Cwe(295)),
);
}
if self.pubkey_type.eq_ignore_ascii_case("RSA")
&& self.pubkey_bits < 2048
&& let Ok(finding) = Finding::new(
id,
"TLS certificate uses a weak RSA key",
Severity::Medium,
Confidence::Certain,
DetectionClass::Passive,
)
{
findings.push(
finding
.with_excerpt(Excerpt::new(format!(
"the RSA public key is {} bits, below the 2048-bit floor",
self.pubkey_bits
)))
.with_reference(Reference::Cwe(326)),
);
}
findings
}
pub fn covers(&self, name: &str) -> bool {
let name = name.strip_suffix('.').unwrap_or(name);
if let Ok(address) = name.parse::<IpAddr>() {
return self
.sans
.iter()
.any(|san| san.parse::<IpAddr>() == Ok(address));
}
self.sans
.iter()
.filter(|san| san.parse::<IpAddr>().is_err())
.any(|san| dns_name_covers(san, name))
}
pub fn name_mismatch(&self, name: &str) -> Option<Finding> {
if self.sans.len() >= MAX_SANS_PER_CERTIFICATE || self.covers(name) {
return None;
}
let bare = name.strip_suffix('.').unwrap_or(name);
let only_common_name = dns_name_covers(&self.common_name, bare);
let excerpt = if only_common_name {
format!("{name} is named only in the subject common name, which clients do not read")
} else {
match self.sans.as_slice() {
[] => format!("asked for {name}; the certificate lists no alternative names"),
[first, rest @ ..] => {
let more = match rest.len() {
0 => String::new(),
1 => format!(" and {}", rest[0]),
n => format!(" and {n} more"),
};
format!("asked for {name}; the certificate names {first}{more}")
}
}
};
Finding::new(
certificate_detection_id(),
"TLS certificate does not match the host name",
Severity::Medium,
Confidence::Certain,
DetectionClass::Passive,
)
.ok()
.map(|finding| {
finding
.with_excerpt(Excerpt::new(excerpt))
.with_reference(Reference::Cwe(297))
})
}
}
fn dns_name_covers(pattern: &str, name: &str) -> bool {
let pattern = pattern.strip_suffix('.').unwrap_or(pattern);
match pattern.strip_prefix("*.") {
Some(parent) => name.split_once('.').is_some_and(|(label, rest)| {
!label.is_empty() && !parent.is_empty() && rest.eq_ignore_ascii_case(parent)
}),
None => !pattern.is_empty() && pattern.eq_ignore_ascii_case(name),
}
}
const CERTIFICATE_DETECTION: &str = "zond:certificate";
fn certificate_detection_id() -> DetectionId {
static ID: OnceLock<DetectionId> = OnceLock::new();
ID.get_or_init(|| {
let version = env!("CARGO_PKG_VERSION")
.parse::<Version>()
.unwrap_or_else(|_| Version::new(0, 0, 0));
let census = "expired;self-signed;weak-rsa-key;name-mismatch";
let digest = ring::digest::digest(&ring::digest::SHA256, census.as_bytes());
let mut hash = String::with_capacity(digest.as_ref().len() * 2);
for byte in digest.as_ref() {
use std::fmt::Write;
let _ = write!(hash, "{byte:02x}");
}
DetectionId::new(CERTIFICATE_DETECTION, version, hash)
.expect("the identifier is a non-empty literal")
})
.clone()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_certificates_names_are_held_to_the_bound() {
let many: Vec<Arc<str>> = (0..MAX_SANS_PER_CERTIFICATE * 3)
.map(|i| Arc::from(format!("n{i}.example").as_str()))
.collect();
let cert = CertificateInfo::new(
"host.example",
"Internal CA",
SystemTime::now(),
SystemTime::now(),
"deadbeef",
)
.with_sans(many);
assert_eq!(cert.sans().len(), MAX_SANS_PER_CERTIFICATE);
assert_eq!(
cert.common_name(),
"host.example",
"the certificate survives its own name list"
);
assert_eq!(
cert.sans()[0].as_ref(),
"n0.example",
"the first names kept"
);
}
fn mock_cert(start_offset: i64, end_offset: i64) -> CertificateInfo {
let now = SystemTime::now();
let start = if start_offset < 0 {
now - Duration::from_secs(start_offset.unsigned_abs())
} else {
now + Duration::from_secs(start_offset as u64)
};
let end = if end_offset < 0 {
now - Duration::from_secs(end_offset.unsigned_abs())
} else {
now + Duration::from_secs(end_offset as u64)
};
CertificateInfo::new("test.local", "Local CA", start, end, "deadbeef")
.with_sans([Arc::from("*.test.local")])
.with_public_key("RSA", 2048)
}
#[test]
fn a_record_carries_what_the_handshake_agreed() {
let sec = Security::new()
.with_tls_version("TLSv1.3")
.with_cipher_suite("TLS_AES_256_GCM_SHA384")
.with_alpn("h2")
.with_alpn("http/1.1");
assert_eq!(sec.tls_version(), Some("TLSv1.3"));
assert_eq!(sec.cipher_suite(), Some("TLS_AES_256_GCM_SHA384"));
assert_eq!(sec.alpn().len(), 2);
}
#[test]
fn a_merge_fills_the_gaps_without_displacing_what_is_recorded() {
let mut s1 = Security::new()
.with_tls_version("TLSv1.2")
.with_alpn("http/1.1");
let s2 = Security::new()
.with_cipher_suite("AES128-GCM")
.with_alpn("h2")
.with_alpn("http/1.1");
s1.merge(s2);
assert_eq!(s1.tls_version(), Some("TLSv1.2"));
assert_eq!(s1.cipher_suite(), Some("AES128-GCM"));
assert_eq!(s1.alpn().len(), 2);
assert!(s1.alpn().iter().any(|p| &**p == "h2"));
}
#[test]
fn validity_and_expiry_are_both_answerable_at_a_caller_chosen_time() {
let day = Duration::from_secs(86_400);
let scanned_at = SystemTime::UNIX_EPOCH + day * 365;
let security = Security::new().with_certificate(CertificateInfo::new(
"test.local",
"Local CA",
scanned_at - day * 30,
scanned_at + day * 10,
"deadbeef",
));
assert!(security.is_cert_valid_at(scanned_at));
assert!(
security.is_cert_expiring_at(day * 30, scanned_at),
"ten days left"
);
assert!(!security.is_cert_expiring_at(day * 5, scanned_at));
let read_at = scanned_at + day * 365;
assert!(!security.is_cert_valid_at(read_at));
assert!(!security.is_cert_expiring_at(day * 30, read_at));
}
#[test]
fn an_expired_certificate_is_not_reported_as_one_about_to_expire() {
let valid_cert = mock_cert(-864000, 864000);
let sec_valid = Security::new().with_certificate(valid_cert);
assert!(sec_valid.is_cert_valid());
assert!(!sec_valid.is_cert_expiring(Duration::from_secs(86400 * 5)));
assert!(sec_valid.is_cert_expiring(Duration::from_secs(86400 * 15)));
let expired_cert = mock_cert(-864000, -432000);
let sec_expired = Security::new().with_certificate(expired_cert);
assert!(!sec_expired.is_cert_valid());
assert!(!sec_expired.is_cert_expiring(Duration::from_secs(86400 * 30)));
let future_cert = mock_cert(86400, 864000);
let sec_future = Security::new().with_certificate(future_cert);
assert!(!sec_future.is_cert_valid());
}
#[test]
fn a_clean_certificate_has_no_posture_findings() {
let now = SystemTime::now();
let cert = CertificateInfo::new(
"web.example",
"Example Root CA",
now - Duration::from_secs(86_400 * 30),
now + Duration::from_secs(86_400 * 300),
"deadbeef",
)
.with_public_key("RSA", 2048);
assert!(cert.findings(now).is_empty());
}
#[test]
fn certificate_posture_reports_expiry_self_signing_and_a_weak_key() {
let now = SystemTime::now();
let id = "zond:certificate";
let expired = CertificateInfo::new(
"web.example",
"Example Root CA",
now - Duration::from_secs(86_400 * 400),
now - Duration::from_secs(86_400 * 30),
"aa",
)
.with_public_key("RSA", 2048);
let findings = expired.findings(now);
assert_eq!(findings.len(), 1, "expired alone");
assert_eq!(findings[0].detection().id(), id);
assert_eq!(findings[0].severity(), Severity::Medium);
assert!(findings[0].title().contains("expired"));
let self_signed = CertificateInfo::new(
"box.local",
"box.local",
now - Duration::from_secs(86_400 * 30),
now + Duration::from_secs(86_400 * 300),
"bb",
)
.with_public_key("RSA", 2048);
let findings = self_signed.findings(now);
assert_eq!(findings.len(), 1, "self-signed alone");
assert_eq!(findings[0].severity(), Severity::Low);
assert!(findings[0].title().contains("self-signed"));
let weak = CertificateInfo::new(
"legacy.example",
"Example Root CA",
now - Duration::from_secs(86_400 * 30),
now + Duration::from_secs(86_400 * 300),
"cc",
)
.with_public_key("RSA", 1024);
let findings = weak.findings(now);
assert_eq!(findings.len(), 1, "weak key alone");
assert_eq!(findings[0].severity(), Severity::Medium);
assert!(findings[0].title().contains("weak RSA key"));
}
#[test]
fn a_256_bit_elliptic_curve_key_is_not_read_as_weak() {
let now = SystemTime::now();
let cert = CertificateInfo::new(
"ec.example",
"Example Root CA",
now - Duration::from_secs(86_400 * 30),
now + Duration::from_secs(86_400 * 300),
"dd",
)
.with_public_key("EC", 256);
assert!(cert.findings(now).is_empty());
}
fn naming(common_name: &str, names: &[&str]) -> CertificateInfo {
let now = SystemTime::now();
CertificateInfo::new(
common_name,
"Example Root CA",
now - Duration::from_secs(86_400 * 30),
now + Duration::from_secs(86_400 * 300),
"ee",
)
.with_sans(names.iter().map(|name| Arc::from(*name)))
.with_public_key("RSA", 2048)
}
#[test]
fn a_certificate_covers_the_names_a_client_would_accept_it_for() {
let cert = naming("ignored.example", &["www.example.com", "*.api.example.com"]);
assert!(cert.covers("www.example.com"));
assert!(cert.covers("WWW.Example.COM."), "case and a trailing dot");
assert!(cert.covers("v1.api.example.com"), "a wildcard, one label");
assert!(!cert.covers("example.com"));
assert!(
!cert.covers("api.example.com"),
"a wildcard needs its label"
);
assert!(!cert.covers("a.v1.api.example.com"), "and only one");
assert!(
!cert.covers("ignored.example"),
"the common name is not read"
);
let addressed = naming("", &["192.0.2.7", "2001:db8::7"]);
assert!(addressed.covers("192.0.2.7"));
assert!(addressed.covers("2001:db8:0::7"), "compared as addresses");
assert!(!addressed.covers("192.0.2.8"));
}
#[test]
fn a_certificate_not_naming_the_host_asked_for_is_a_mismatch() {
let cert = naming("web.example", &["web.example", "www.web.example"]);
assert!(cert.name_mismatch("web.example").is_none());
let finding = cert
.name_mismatch("shop.example")
.expect("a certificate for another site is a mismatch");
assert_eq!(finding.detection().id(), "zond:certificate");
assert_eq!(finding.severity(), Severity::Medium);
assert!(finding.title().contains("host name"));
let excerpt = finding.excerpt().as_str();
assert!(excerpt.contains("shop.example"), "{excerpt}");
assert!(excerpt.contains("web.example"), "{excerpt}");
let legacy = naming("legacy.example", &[]);
let finding = legacy
.name_mismatch("legacy.example")
.expect("a name in the common name alone does not cover it");
let excerpt = finding.excerpt().as_str();
assert!(excerpt.contains("common name"), "{excerpt}");
let many: Vec<String> = (0..MAX_SANS_PER_CERTIFICATE)
.map(|i| format!("n{i}.example"))
.collect();
let many: Vec<&str> = many.iter().map(String::as_str).collect();
assert!(
naming("", &many)
.name_mismatch("elsewhere.example")
.is_none()
);
}
}