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 (now, then) = (fingerprint(self)?, fingerprint(basis)?);
return Some(if now == then {
Standing::Upheld
} else {
Standing::Overturned
});
}
self.support.standing(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
}
}
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";
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());
}
}