use std::collections::BTreeSet;
use std::fmt;
use std::str::FromStr;
use std::sync::OnceLock;
use crate::model::confidence::Confidence;
use crate::model::finding::{
ClaimId, DetectionClass, DetectionId, Excerpt, Finding, Reference, Severity, Standing, Version,
};
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum TlsVersion {
Ssl30,
Tls10,
Tls11,
Tls12,
Tls13,
}
impl TlsVersion {
pub const ALL: &'static [Self] = &[
Self::Ssl30,
Self::Tls10,
Self::Tls11,
Self::Tls12,
Self::Tls13,
];
pub const fn code(self) -> u16 {
match self {
Self::Ssl30 => 0x0300,
Self::Tls10 => 0x0301,
Self::Tls11 => 0x0302,
Self::Tls12 => 0x0303,
Self::Tls13 => 0x0304,
}
}
pub const fn from_code(code: u16) -> Option<Self> {
match code {
0x0300 => Some(Self::Ssl30),
0x0301 => Some(Self::Tls10),
0x0302 => Some(Self::Tls11),
0x0303 => Some(Self::Tls12),
0x0304 => Some(Self::Tls13),
_ => None,
}
}
pub const fn name(self) -> &'static str {
match self {
Self::Ssl30 => "SSLv3",
Self::Tls10 => "TLSv1.0",
Self::Tls11 => "TLSv1.1",
Self::Tls12 => "TLSv1.2",
Self::Tls13 => "TLSv1.3",
}
}
pub const fn is_deprecated(self) -> bool {
matches!(self, Self::Ssl30 | Self::Tls10 | Self::Tls11)
}
pub const fn severity(self) -> Option<Severity> {
match self {
Self::Ssl30 => Some(Severity::High),
Self::Tls10 | Self::Tls11 => Some(Severity::Medium),
Self::Tls12 | Self::Tls13 => None,
}
}
pub const fn deprecated_by(self) -> Option<&'static str> {
match self {
Self::Ssl30 => Some("RFC 7568"),
Self::Tls10 | Self::Tls11 => Some("RFC 8996"),
Self::Tls12 | Self::Tls13 => None,
}
}
}
impl fmt::Display for TlsVersion {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
#[error(
"unknown TLS version '{input}', expected one of: {}",
TlsVersion::expected()
)]
pub struct UnknownTlsVersion {
pub input: String,
}
impl TlsVersion {
fn expected() -> String {
Self::ALL
.iter()
.map(|version| version.name())
.collect::<Vec<_>>()
.join(", ")
}
}
impl FromStr for TlsVersion {
type Err = UnknownTlsVersion;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let name = s.trim().to_ascii_lowercase();
Self::ALL
.iter()
.copied()
.find(|version| version.name().to_ascii_lowercase() == name)
.ok_or_else(|| UnknownTlsVersion {
input: s.to_string(),
})
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum KeyExchange {
Ecdhe,
Dhe,
Rsa,
Ecdh,
Anonymous,
Negotiated,
}
impl KeyExchange {
pub const fn is_forward_secret(self) -> bool {
matches!(
self,
Self::Ecdhe | Self::Dhe | Self::Anonymous | Self::Negotiated
)
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Authentication {
Rsa,
Ecdsa,
Dss,
Anonymous,
Negotiated,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum BulkCipher {
AesGcm(u16),
AesCcm {
bits: u16,
short_tag: bool,
},
ChaCha20Poly1305,
AesCbc(u16),
CamelliaCbc(u16),
TripleDes,
Des,
Rc4,
SeedCbc,
IdeaCbc,
Null,
}
impl BulkCipher {
pub const fn is_aead(self) -> bool {
matches!(
self,
Self::AesGcm(_) | Self::AesCcm { .. } | Self::ChaCha20Poly1305
)
}
pub const fn is_cbc(self) -> bool {
matches!(
self,
Self::AesCbc(_)
| Self::CamelliaCbc(_)
| Self::TripleDes
| Self::Des
| Self::SeedCbc
| Self::IdeaCbc
)
}
pub const fn has_64_bit_block(self) -> bool {
matches!(self, Self::TripleDes | Self::Des | Self::IdeaCbc)
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Mac {
Aead,
Md5,
Sha1,
Sha256,
Sha384,
Null,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum SuiteFault {
NoForwardSecrecy,
Sha1Mac,
CbcMode,
SmallBlock,
Rc4,
Md5Mac,
Export,
Anonymous,
NullCipher,
}
impl SuiteFault {
pub const ALL: &'static [Self] = &[
Self::NoForwardSecrecy,
Self::Sha1Mac,
Self::CbcMode,
Self::SmallBlock,
Self::Rc4,
Self::Md5Mac,
Self::Export,
Self::Anonymous,
Self::NullCipher,
];
pub const fn name(self) -> &'static str {
match self {
Self::NoForwardSecrecy => "no_forward_secrecy",
Self::Sha1Mac => "sha1_mac",
Self::CbcMode => "cbc_mode",
Self::SmallBlock => "small_block",
Self::Rc4 => "rc4",
Self::Md5Mac => "md5_mac",
Self::Export => "export_grade",
Self::Anonymous => "anonymous",
Self::NullCipher => "null_cipher",
}
}
pub const fn summary(self) -> &'static str {
match self {
Self::NoForwardSecrecy => {
"the server's long-term key decrypts every session recorded under it"
}
Self::Sha1Mac => "records are authenticated with HMAC-SHA-1",
Self::CbcMode => "CBC with a separate MAC, the construction behind Lucky13 and BEAST",
Self::SmallBlock => "a 64-bit block, which Sweet32 recovers plaintext from",
Self::Rc4 => "RC4, prohibited by RFC 7465",
Self::Md5Mac => "records are authenticated with HMAC-MD5",
Self::Export => "a deliberately shortened key, from the export era",
Self::Anonymous => "nothing authenticates the server",
Self::NullCipher => "records are not encrypted",
}
}
pub const fn severity(self) -> Severity {
match self {
Self::NullCipher | Self::Anonymous | Self::Export => Severity::High,
Self::Rc4 | Self::SmallBlock | Self::Md5Mac => Severity::Medium,
Self::CbcMode | Self::Sha1Mac | Self::NoForwardSecrecy => Severity::Low,
}
}
pub const fn is_disqualifying(self) -> bool {
matches!(
self,
Self::SmallBlock
| Self::Rc4
| Self::Md5Mac
| Self::Export
| Self::Anonymous
| Self::NullCipher
)
}
}
impl fmt::Display for SuiteFault {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum SuiteStrength {
Strong,
Weak,
Insecure,
}
impl SuiteStrength {
pub const ALL: &'static [Self] = &[Self::Strong, Self::Weak, Self::Insecure];
pub const fn name(self) -> &'static str {
match self {
Self::Strong => "strong",
Self::Weak => "weak",
Self::Insecure => "insecure",
}
}
}
impl fmt::Display for SuiteStrength {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CipherSuite {
code: u16,
name: &'static str,
kex: KeyExchange,
auth: Authentication,
cipher: BulkCipher,
mac: Mac,
export: bool,
}
impl CipherSuite {
pub const fn code(self) -> u16 {
self.code
}
pub const fn name(self) -> &'static str {
self.name
}
pub const fn key_exchange(self) -> KeyExchange {
self.kex
}
pub const fn authentication(self) -> Authentication {
self.auth
}
pub const fn bulk_cipher(self) -> BulkCipher {
self.cipher
}
pub const fn mac(self) -> Mac {
self.mac
}
pub const fn is_export(self) -> bool {
self.export
}
pub const fn is_forward_secret(self) -> bool {
self.kex.is_forward_secret()
}
pub const fn has_fault(self, fault: SuiteFault) -> bool {
match fault {
SuiteFault::NoForwardSecrecy => !self.kex.is_forward_secret(),
SuiteFault::Sha1Mac => matches!(self.mac, Mac::Sha1),
SuiteFault::CbcMode => self.cipher.is_cbc(),
SuiteFault::SmallBlock => self.cipher.has_64_bit_block(),
SuiteFault::Rc4 => matches!(self.cipher, BulkCipher::Rc4),
SuiteFault::Md5Mac => matches!(self.mac, Mac::Md5),
SuiteFault::Export => self.export,
SuiteFault::Anonymous => matches!(self.auth, Authentication::Anonymous),
SuiteFault::NullCipher => matches!(self.cipher, BulkCipher::Null),
}
}
pub fn faults(self) -> Vec<SuiteFault> {
SuiteFault::ALL
.iter()
.copied()
.filter(|fault| self.has_fault(*fault))
.collect()
}
pub fn worst_fault(self) -> Option<SuiteFault> {
SuiteFault::ALL
.iter()
.copied()
.rev()
.find(|fault| self.has_fault(*fault))
}
pub fn strength(self) -> SuiteStrength {
match self.worst_fault() {
None => SuiteStrength::Strong,
Some(fault) if fault.is_disqualifying() => SuiteStrength::Insecure,
Some(_) => SuiteStrength::Weak,
}
}
pub const fn is_offered_under(self, version: TlsVersion) -> bool {
let tls13_suite = matches!(self.kex, KeyExchange::Negotiated);
match version {
TlsVersion::Tls13 => tls13_suite,
TlsVersion::Ssl30 | TlsVersion::Tls10 | TlsVersion::Tls11 => {
!tls13_suite && matches!(self.mac, Mac::Md5 | Mac::Sha1 | Mac::Null)
}
TlsVersion::Tls12 => !tls13_suite,
}
}
pub fn from_code(code: u16) -> Option<Self> {
Self::ALL.iter().copied().find(|suite| suite.code == code)
}
}
impl fmt::Display for CipherSuite {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name)
}
}
macro_rules! suite {
($code:literal, $name:literal, $kex:expr, $auth:expr, $cipher:expr, $mac:expr) => {
CipherSuite {
code: $code,
name: $name,
kex: $kex,
auth: $auth,
cipher: $cipher,
mac: $mac,
export: false,
}
};
(export $code:literal, $name:literal, $kex:expr, $auth:expr, $cipher:expr, $mac:expr) => {
CipherSuite {
code: $code,
name: $name,
kex: $kex,
auth: $auth,
cipher: $cipher,
mac: $mac,
export: true,
}
};
}
use Authentication as A;
use BulkCipher as C;
use KeyExchange as K;
use Mac as M;
impl CipherSuite {
pub const ALL: &'static [Self] = &[
suite!(
0x1302,
"TLS_AES_256_GCM_SHA384",
K::Negotiated,
A::Negotiated,
C::AesGcm(256),
M::Aead
),
suite!(
0x1303,
"TLS_CHACHA20_POLY1305_SHA256",
K::Negotiated,
A::Negotiated,
C::ChaCha20Poly1305,
M::Aead
),
suite!(
0x1301,
"TLS_AES_128_GCM_SHA256",
K::Negotiated,
A::Negotiated,
C::AesGcm(128),
M::Aead
),
suite!(
0x1304,
"TLS_AES_128_CCM_SHA256",
K::Negotiated,
A::Negotiated,
C::AesCcm {
bits: 128,
short_tag: false
},
M::Aead
),
suite!(
0x1305,
"TLS_AES_128_CCM_8_SHA256",
K::Negotiated,
A::Negotiated,
C::AesCcm {
bits: 128,
short_tag: true
},
M::Aead
),
suite!(
0xC030,
"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
K::Ecdhe,
A::Rsa,
C::AesGcm(256),
M::Aead
),
suite!(
0xC02C,
"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
K::Ecdhe,
A::Ecdsa,
C::AesGcm(256),
M::Aead
),
suite!(
0xC02F,
"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
K::Ecdhe,
A::Rsa,
C::AesGcm(128),
M::Aead
),
suite!(
0xC02B,
"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
K::Ecdhe,
A::Ecdsa,
C::AesGcm(128),
M::Aead
),
suite!(
0xCCA8,
"TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
K::Ecdhe,
A::Rsa,
C::ChaCha20Poly1305,
M::Aead
),
suite!(
0xCCA9,
"TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256",
K::Ecdhe,
A::Ecdsa,
C::ChaCha20Poly1305,
M::Aead
),
suite!(
0x009F,
"TLS_DHE_RSA_WITH_AES_256_GCM_SHA384",
K::Dhe,
A::Rsa,
C::AesGcm(256),
M::Aead
),
suite!(
0x009E,
"TLS_DHE_RSA_WITH_AES_128_GCM_SHA256",
K::Dhe,
A::Rsa,
C::AesGcm(128),
M::Aead
),
suite!(
0xCCAA,
"TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
K::Dhe,
A::Rsa,
C::ChaCha20Poly1305,
M::Aead
),
suite!(
0x009D,
"TLS_RSA_WITH_AES_256_GCM_SHA384",
K::Rsa,
A::Rsa,
C::AesGcm(256),
M::Aead
),
suite!(
0x009C,
"TLS_RSA_WITH_AES_128_GCM_SHA256",
K::Rsa,
A::Rsa,
C::AesGcm(128),
M::Aead
),
suite!(
0xC028,
"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384",
K::Ecdhe,
A::Rsa,
C::AesCbc(256),
M::Sha384
),
suite!(
0xC024,
"TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384",
K::Ecdhe,
A::Ecdsa,
C::AesCbc(256),
M::Sha384
),
suite!(
0xC027,
"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",
K::Ecdhe,
A::Rsa,
C::AesCbc(128),
M::Sha256
),
suite!(
0xC023,
"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256",
K::Ecdhe,
A::Ecdsa,
C::AesCbc(128),
M::Sha256
),
suite!(
0x006B,
"TLS_DHE_RSA_WITH_AES_256_CBC_SHA256",
K::Dhe,
A::Rsa,
C::AesCbc(256),
M::Sha256
),
suite!(
0x0067,
"TLS_DHE_RSA_WITH_AES_128_CBC_SHA256",
K::Dhe,
A::Rsa,
C::AesCbc(128),
M::Sha256
),
suite!(
0x003D,
"TLS_RSA_WITH_AES_256_CBC_SHA256",
K::Rsa,
A::Rsa,
C::AesCbc(256),
M::Sha256
),
suite!(
0x003C,
"TLS_RSA_WITH_AES_128_CBC_SHA256",
K::Rsa,
A::Rsa,
C::AesCbc(128),
M::Sha256
),
suite!(
0x006A,
"TLS_DHE_DSS_WITH_AES_256_CBC_SHA256",
K::Dhe,
A::Dss,
C::AesCbc(256),
M::Sha256
),
suite!(
0x0040,
"TLS_DHE_DSS_WITH_AES_128_CBC_SHA256",
K::Dhe,
A::Dss,
C::AesCbc(128),
M::Sha256
),
suite!(
0xC014,
"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
K::Ecdhe,
A::Rsa,
C::AesCbc(256),
M::Sha1
),
suite!(
0xC00A,
"TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
K::Ecdhe,
A::Ecdsa,
C::AesCbc(256),
M::Sha1
),
suite!(
0xC013,
"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
K::Ecdhe,
A::Rsa,
C::AesCbc(128),
M::Sha1
),
suite!(
0xC009,
"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
K::Ecdhe,
A::Ecdsa,
C::AesCbc(128),
M::Sha1
),
suite!(
0x0039,
"TLS_DHE_RSA_WITH_AES_256_CBC_SHA",
K::Dhe,
A::Rsa,
C::AesCbc(256),
M::Sha1
),
suite!(
0x0033,
"TLS_DHE_RSA_WITH_AES_128_CBC_SHA",
K::Dhe,
A::Rsa,
C::AesCbc(128),
M::Sha1
),
suite!(
0x0038,
"TLS_DHE_DSS_WITH_AES_256_CBC_SHA",
K::Dhe,
A::Dss,
C::AesCbc(256),
M::Sha1
),
suite!(
0x0032,
"TLS_DHE_DSS_WITH_AES_128_CBC_SHA",
K::Dhe,
A::Dss,
C::AesCbc(128),
M::Sha1
),
suite!(
0x0035,
"TLS_RSA_WITH_AES_256_CBC_SHA",
K::Rsa,
A::Rsa,
C::AesCbc(256),
M::Sha1
),
suite!(
0x002F,
"TLS_RSA_WITH_AES_128_CBC_SHA",
K::Rsa,
A::Rsa,
C::AesCbc(128),
M::Sha1
),
suite!(
0xC00F,
"TLS_ECDH_RSA_WITH_AES_256_CBC_SHA",
K::Ecdh,
A::Rsa,
C::AesCbc(256),
M::Sha1
),
suite!(
0xC00E,
"TLS_ECDH_RSA_WITH_AES_128_CBC_SHA",
K::Ecdh,
A::Rsa,
C::AesCbc(128),
M::Sha1
),
suite!(
0xC005,
"TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA",
K::Ecdh,
A::Ecdsa,
C::AesCbc(256),
M::Sha1
),
suite!(
0xC004,
"TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA",
K::Ecdh,
A::Ecdsa,
C::AesCbc(128),
M::Sha1
),
suite!(
0x0088,
"TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA",
K::Dhe,
A::Rsa,
C::CamelliaCbc(256),
M::Sha1
),
suite!(
0x0084,
"TLS_RSA_WITH_CAMELLIA_256_CBC_SHA",
K::Rsa,
A::Rsa,
C::CamelliaCbc(256),
M::Sha1
),
suite!(
0x0045,
"TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA",
K::Dhe,
A::Rsa,
C::CamelliaCbc(128),
M::Sha1
),
suite!(
0x0041,
"TLS_RSA_WITH_CAMELLIA_128_CBC_SHA",
K::Rsa,
A::Rsa,
C::CamelliaCbc(128),
M::Sha1
),
suite!(
0x0096,
"TLS_RSA_WITH_SEED_CBC_SHA",
K::Rsa,
A::Rsa,
C::SeedCbc,
M::Sha1
),
suite!(
0xC012,
"TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA",
K::Ecdhe,
A::Rsa,
C::TripleDes,
M::Sha1
),
suite!(
0xC008,
"TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA",
K::Ecdhe,
A::Ecdsa,
C::TripleDes,
M::Sha1
),
suite!(
0x0016,
"TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA",
K::Dhe,
A::Rsa,
C::TripleDes,
M::Sha1
),
suite!(
0x0013,
"TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA",
K::Dhe,
A::Dss,
C::TripleDes,
M::Sha1
),
suite!(
0x000A,
"TLS_RSA_WITH_3DES_EDE_CBC_SHA",
K::Rsa,
A::Rsa,
C::TripleDes,
M::Sha1
),
suite!(
0xC00D,
"TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA",
K::Ecdh,
A::Rsa,
C::TripleDes,
M::Sha1
),
suite!(
0x0007,
"TLS_RSA_WITH_IDEA_CBC_SHA",
K::Rsa,
A::Rsa,
C::IdeaCbc,
M::Sha1
),
suite!(
0xC011,
"TLS_ECDHE_RSA_WITH_RC4_128_SHA",
K::Ecdhe,
A::Rsa,
C::Rc4,
M::Sha1
),
suite!(
0xC007,
"TLS_ECDHE_ECDSA_WITH_RC4_128_SHA",
K::Ecdhe,
A::Ecdsa,
C::Rc4,
M::Sha1
),
suite!(
0x0005,
"TLS_RSA_WITH_RC4_128_SHA",
K::Rsa,
A::Rsa,
C::Rc4,
M::Sha1
),
suite!(
0x0004,
"TLS_RSA_WITH_RC4_128_MD5",
K::Rsa,
A::Rsa,
C::Rc4,
M::Md5
),
suite!(
0xC016,
"TLS_ECDH_anon_WITH_RC4_128_SHA",
K::Anonymous,
A::Anonymous,
C::Rc4,
M::Sha1
),
suite!(
0x0018,
"TLS_DH_anon_WITH_RC4_128_MD5",
K::Anonymous,
A::Anonymous,
C::Rc4,
M::Md5
),
suite!(
0x006D,
"TLS_DH_anon_WITH_AES_256_CBC_SHA256",
K::Anonymous,
A::Anonymous,
C::AesCbc(256),
M::Sha256
),
suite!(
0x006C,
"TLS_DH_anon_WITH_AES_128_CBC_SHA256",
K::Anonymous,
A::Anonymous,
C::AesCbc(128),
M::Sha256
),
suite!(
0x003A,
"TLS_DH_anon_WITH_AES_256_CBC_SHA",
K::Anonymous,
A::Anonymous,
C::AesCbc(256),
M::Sha1
),
suite!(
0x0034,
"TLS_DH_anon_WITH_AES_128_CBC_SHA",
K::Anonymous,
A::Anonymous,
C::AesCbc(128),
M::Sha1
),
suite!(
0xC019,
"TLS_ECDH_anon_WITH_AES_256_CBC_SHA",
K::Anonymous,
A::Anonymous,
C::AesCbc(256),
M::Sha1
),
suite!(
0xC018,
"TLS_ECDH_anon_WITH_AES_128_CBC_SHA",
K::Anonymous,
A::Anonymous,
C::AesCbc(128),
M::Sha1
),
suite!(
0x001B,
"TLS_DH_anon_WITH_3DES_EDE_CBC_SHA",
K::Anonymous,
A::Anonymous,
C::TripleDes,
M::Sha1
),
suite!(
0xC017,
"TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA",
K::Anonymous,
A::Anonymous,
C::TripleDes,
M::Sha1
),
suite!(
0x003B,
"TLS_RSA_WITH_NULL_SHA256",
K::Rsa,
A::Rsa,
C::Null,
M::Sha256
),
suite!(
0x0002,
"TLS_RSA_WITH_NULL_SHA",
K::Rsa,
A::Rsa,
C::Null,
M::Sha1
),
suite!(
0x0001,
"TLS_RSA_WITH_NULL_MD5",
K::Rsa,
A::Rsa,
C::Null,
M::Md5
),
suite!(
0xC010,
"TLS_ECDHE_RSA_WITH_NULL_SHA",
K::Ecdhe,
A::Rsa,
C::Null,
M::Sha1
),
suite!(
0xC006,
"TLS_ECDHE_ECDSA_WITH_NULL_SHA",
K::Ecdhe,
A::Ecdsa,
C::Null,
M::Sha1
),
suite!(
0xC001,
"TLS_ECDH_ECDSA_WITH_NULL_SHA",
K::Ecdh,
A::Ecdsa,
C::Null,
M::Sha1
),
suite!(
0xC00B,
"TLS_ECDH_RSA_WITH_NULL_SHA",
K::Ecdh,
A::Rsa,
C::Null,
M::Sha1
),
suite!(
0xC015,
"TLS_ECDH_anon_WITH_NULL_SHA",
K::Anonymous,
A::Anonymous,
C::Null,
M::Sha1
),
suite!(export 0x0003, "TLS_RSA_EXPORT_WITH_RC4_40_MD5", K::Rsa, A::Rsa, C::Rc4, M::Md5),
suite!(export 0x0006, "TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5", K::Rsa, A::Rsa, C::Des, M::Md5),
suite!(export 0x0008, "TLS_RSA_EXPORT_WITH_DES40_CBC_SHA", K::Rsa, A::Rsa, C::Des, M::Sha1),
suite!(export 0x0014, "TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", K::Dhe, A::Rsa, C::Des, M::Sha1),
suite!(export 0x0011, "TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA", K::Dhe, A::Dss, C::Des, M::Sha1),
suite!(export 0x0017, "TLS_DH_anon_EXPORT_WITH_RC4_40_MD5", K::Anonymous, A::Anonymous, C::Rc4, M::Md5),
suite!(export 0x0019, "TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA", K::Anonymous, A::Anonymous, C::Des, M::Sha1),
suite!(
0x0009,
"TLS_RSA_WITH_DES_CBC_SHA",
K::Rsa,
A::Rsa,
C::Des,
M::Sha1
),
suite!(
0x0015,
"TLS_DHE_RSA_WITH_DES_CBC_SHA",
K::Dhe,
A::Rsa,
C::Des,
M::Sha1
),
suite!(
0x0012,
"TLS_DHE_DSS_WITH_DES_CBC_SHA",
K::Dhe,
A::Dss,
C::Des,
M::Sha1
),
suite!(
0x001A,
"TLS_DH_anon_WITH_DES_CBC_SHA",
K::Anonymous,
A::Anonymous,
C::Des,
M::Sha1
),
];
pub fn offered_under(version: TlsVersion) -> impl Iterator<Item = Self> {
Self::ALL
.iter()
.copied()
.filter(move |suite| suite.is_offered_under(version))
}
pub const MOST_OFFERED_UNDER_ONE_VERSION: usize = {
let mut most = 0;
let mut version = 0;
while version < TlsVersion::ALL.len() {
let mut offered = 0;
let mut suite = 0;
while suite < Self::ALL.len() {
if Self::ALL[suite].is_offered_under(TlsVersion::ALL[version]) {
offered += 1;
}
suite += 1;
}
if offered > most {
most = offered;
}
version += 1;
}
most
};
}
#[must_use]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VersionSupport {
version: TlsVersion,
suites: Vec<CipherSuite>,
unrecognised: Vec<u16>,
}
impl VersionSupport {
pub fn new(version: TlsVersion, suites: Vec<CipherSuite>, unrecognised: Vec<u16>) -> Self {
Self {
version,
suites,
unrecognised,
}
}
pub fn version(&self) -> TlsVersion {
self.version
}
pub fn suites(&self) -> &[CipherSuite] {
&self.suites
}
pub fn unrecognised(&self) -> &[u16] {
&self.unrecognised
}
pub fn weakest(&self) -> Option<SuiteStrength> {
self.suites.iter().map(|suite| suite.strength()).max()
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Interruption {
Unanswered,
Stopped,
FileLimit,
}
impl Interruption {
pub const ALL: &'static [Self] = &[Self::Unanswered, Self::Stopped, Self::FileLimit];
pub const fn name(self) -> &'static str {
match self {
Self::Unanswered => "unanswered",
Self::Stopped => "stopped",
Self::FileLimit => "file-limit",
}
}
pub(crate) fn from_name(name: &str) -> Option<Self> {
Self::ALL.iter().copied().find(|cause| cause.name() == name)
}
}
impl fmt::Display for Interruption {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
#[must_use]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UnfinishedVersion {
version: TlsVersion,
interruption: Interruption,
}
impl UnfinishedVersion {
pub fn new(version: TlsVersion, interruption: Interruption) -> Self {
Self {
version,
interruption,
}
}
pub fn version(&self) -> TlsVersion {
self.version
}
pub fn interruption(&self) -> Interruption {
self.interruption
}
}
#[must_use]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TlsSupport {
versions: Vec<VersionSupport>,
unfinished: Vec<UnfinishedVersion>,
}
impl TlsSupport {
pub fn new() -> Self {
Self::default()
}
pub fn record(&mut self, support: VersionSupport) {
let at = self
.versions
.partition_point(|held| held.version < support.version);
match self.versions.get(at) {
Some(held) if held.version == support.version => self.versions[at] = support,
_ => self.versions.insert(at, support),
}
}
pub fn accepting(mut self, support: VersionSupport) -> Self {
self.record(support);
self
}
pub fn record_unfinished(&mut self, unfinished: UnfinishedVersion) {
let at = self
.unfinished
.partition_point(|held| held.version < unfinished.version);
match self.unfinished.get(at) {
Some(held) if held.version == unfinished.version => self.unfinished[at] = unfinished,
_ => self.unfinished.insert(at, unfinished),
}
}
pub fn leaving_unfinished(mut self, unfinished: UnfinishedVersion) -> Self {
self.record_unfinished(unfinished);
self
}
pub(crate) fn merge(&mut self, other: TlsSupport) {
if other.is_empty() {
return;
}
if self.is_empty() {
*self = other;
return;
}
let named: BTreeSet<TlsVersion> = [&*self, &other]
.into_iter()
.flat_map(|record| {
let accepted = record.versions.iter().map(|held| held.version);
let unfinished = record.unfinished.iter().map(|held| held.version);
accepted.chain(unfinished)
})
.collect();
let taken: Vec<TlsVersion> = named
.into_iter()
.filter(|version| other.account(*version).supersedes(&self.account(*version)))
.collect();
let TlsSupport {
versions,
unfinished,
} = other;
self.versions.retain(|held| !taken.contains(&held.version));
self.unfinished
.retain(|held| !taken.contains(&held.version));
for held in versions {
if taken.contains(&held.version) {
self.record(held);
}
}
for held in unfinished {
if taken.contains(&held.version) {
self.record_unfinished(held);
}
}
}
fn account(&self, version: TlsVersion) -> Account {
let found = self
.versions
.iter()
.find(|held| held.version == version)
.map(|held| {
let named = held.suites.iter().map(|suite| suite.code());
named.chain(held.unrecognised.iter().copied()).collect()
})
.unwrap_or_default();
let finished = !self.unfinished.iter().any(|held| held.version == version);
Account { finished, found }
}
pub fn versions(&self) -> &[VersionSupport] {
&self.versions
}
pub fn unfinished(&self) -> &[UnfinishedVersion] {
&self.unfinished
}
pub fn is_complete(&self) -> bool {
self.unfinished.is_empty()
}
pub fn is_empty(&self) -> bool {
self.versions.is_empty() && self.unfinished.is_empty()
}
pub fn accepts(&self, version: TlsVersion) -> bool {
self.versions.iter().any(|held| held.version == version)
}
pub fn floor(&self) -> Option<TlsVersion> {
self.versions.first().map(|held| held.version)
}
pub fn ceiling(&self) -> Option<TlsVersion> {
self.versions.last().map(|held| held.version)
}
pub fn deprecated_versions(&self) -> impl Iterator<Item = TlsVersion> + '_ {
self.versions
.iter()
.map(|held| held.version)
.filter(|version| version.is_deprecated())
}
pub fn suites(&self) -> Vec<CipherSuite> {
let mut all: Vec<CipherSuite> = self
.versions
.iter()
.flat_map(|held| held.suites.iter().copied())
.collect();
all.sort_unstable_by_key(|suite| suite.code());
all.dedup();
all
}
pub fn weakest(&self) -> Option<SuiteStrength> {
self.versions
.iter()
.filter_map(VersionSupport::weakest)
.max()
}
pub fn faults(&self) -> Vec<SuiteFault> {
SuiteFault::ALL
.iter()
.copied()
.filter(|fault| {
self.versions
.iter()
.flat_map(|held| held.suites.iter())
.any(|suite| suite.has_fault(*fault))
})
.collect()
}
}
struct Account {
finished: bool,
found: BTreeSet<u16>,
}
impl Account {
fn supersedes(&self, standing: &Account) -> bool {
let further = match (self.finished, standing.finished) {
(_, true) => false,
(true, false) => true,
(false, false) => self.found.len() > standing.found.len(),
};
further && self.found.is_superset(&standing.found)
}
}
const DETECTION: &str = "zond:tls";
fn detection_id() -> DetectionId {
static ID: OnceLock<DetectionId> = OnceLock::new();
ID.get_or_init(|| {
let version = env!("CARGO_PKG_VERSION")
.parse::<Version>()
.unwrap_or(Version::new(0, 0, 0));
let mut census = String::with_capacity(CipherSuite::ALL.len() * 64);
for &suite in CipherSuite::ALL {
use std::fmt::Write;
let _ = write!(
census,
"{:04x}:{}:{};",
suite.code(),
suite.name(),
suite.strength().name()
);
}
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(DETECTION, version, hash).expect("the identifier is a non-empty literal")
})
.clone()
}
impl TlsSupport {
pub fn findings(&self) -> Vec<Finding> {
let mut findings = Vec::new();
for version in self.deprecated_versions() {
let Some(severity) = version.severity() else {
continue;
};
let withdrawn_by = version.deprecated_by().unwrap_or("a published standard");
let Ok(finding) = Finding::new(
detection_id(),
format!("{version} is still accepted"),
severity,
Confidence::Certain,
DetectionClass::ActiveBenign,
) else {
continue;
};
let mut finding = finding.with_excerpt(Excerpt::new(format!(
"the endpoint answered a {version} hello by selecting a suite under it; \
{withdrawn_by} withdrew it"
)));
if let Some(reference) = rfc_reference(withdrawn_by) {
finding = finding.with_reference(reference);
}
findings.push(finding);
}
for fault in self.faults() {
let mut carriers: Vec<&'static str> = Vec::new();
for held in &self.versions {
for suite in &held.suites {
if suite.has_fault(fault) && !carriers.contains(&suite.name()) {
carriers.push(suite.name());
}
}
}
let Ok(finding) = Finding::new(
detection_id(),
format!("cipher suites accepted with {}", fault.summary()),
fault.severity(),
Confidence::Certain,
DetectionClass::ActiveBenign,
) else {
continue;
};
let mut finding = finding.with_excerpt(Excerpt::new(format!(
"{} of the accepted suites carry this: {}",
carriers.len(),
carriers.join(", ")
)));
if let Some(reference) = fault_reference(fault) {
finding = finding.with_reference(reference);
}
findings.push(finding);
}
findings
}
pub(crate) fn standing(&self, finding: &Finding, basis: &TlsSupport) -> Option<Standing> {
if finding.detection().id() != DETECTION {
return None;
}
let claim = finding.claim_id();
let rests_on = basis.resting(&claim);
if rests_on.is_empty() {
return None;
}
if self.claims().contains(&claim) {
Some(Standing::Upheld)
} else if rests_on
.into_iter()
.any(|version| self.leaves_open(version))
{
Some(Standing::Unsettled)
} else {
Some(Standing::Overturned)
}
}
pub(crate) fn restate(&self, finding: &Finding, basis: &TlsSupport) -> Option<Excerpt> {
let claim = finding.claim_id();
let excerpt = |record: &TlsSupport| {
record
.findings()
.into_iter()
.find(|drawn| drawn.claim_id() == claim)
.map(|drawn| drawn.excerpt().clone())
};
let restated = match self.standing(finding, basis)? {
Standing::Upheld => excerpt(self),
Standing::Unsettled => excerpt(&TlsSupport {
versions: basis
.versions
.iter()
.filter(|held| self.leaves_open(held.version))
.cloned()
.collect(),
unfinished: Vec::new(),
}),
Standing::Overturned => None,
}?;
(excerpt(basis).as_ref() != Some(&restated)).then_some(restated)
}
fn resting(&self, claim: &ClaimId) -> Vec<TlsVersion> {
self.versions
.iter()
.filter(|held| {
let alone = TlsSupport::new().accepting((*held).clone());
alone.claims().contains(claim)
})
.map(|held| held.version)
.collect()
}
fn leaves_open(&self, version: TlsVersion) -> bool {
self.is_empty() || self.unfinished.iter().any(|held| held.version == version)
}
fn claims(&self) -> BTreeSet<ClaimId> {
self.findings().iter().map(Finding::claim_id).collect()
}
}
fn rfc_reference(document: &str) -> Option<Reference> {
let number = document.strip_prefix("RFC ")?;
Some(Reference::url(format!(
"https://www.rfc-editor.org/rfc/rfc{number}"
)))
}
fn fault_reference(fault: SuiteFault) -> Option<Reference> {
match fault {
SuiteFault::Rc4 => Some(Reference::url("https://www.rfc-editor.org/rfc/rfc7465")),
SuiteFault::SmallBlock => Reference::cve("CVE-2016-2183"),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeSet;
#[test]
fn every_suite_has_a_number_of_its_own() {
let mut seen = BTreeSet::new();
for &suite in CipherSuite::ALL {
assert!(
seen.insert(suite.code()),
"0x{:04X} is registered twice, the second as {}",
suite.code(),
suite.name()
);
}
}
#[test]
fn every_suite_has_a_name_of_its_own() {
let mut seen = BTreeSet::new();
for &suite in CipherSuite::ALL {
assert!(seen.insert(suite.name()), "{} is registered twice", suite);
}
}
#[test]
fn every_suite_describes_what_its_name_says() {
for &suite in CipherSuite::ALL {
let name = suite.name();
if matches!(suite.key_exchange(), KeyExchange::Negotiated) {
assert!(
!name.contains("_WITH_"),
"{name} is a 1.3 suite and should not name a key exchange"
);
assert!(suite.bulk_cipher().is_aead(), "{name} must be AEAD");
assert_eq!(suite.mac(), Mac::Aead, "{name} carries no separate MAC");
continue;
}
let (kex_part, cipher_part) = name
.strip_prefix("TLS_")
.and_then(|rest| rest.split_once("_WITH_"))
.unwrap_or_else(|| panic!("{name} is not an IANA suite name"));
let expected_kex = if kex_part.starts_with("ECDHE_") {
KeyExchange::Ecdhe
} else if kex_part.starts_with("DHE_") {
KeyExchange::Dhe
} else if kex_part.contains("anon") {
KeyExchange::Anonymous
} else if kex_part.starts_with("ECDH_") {
KeyExchange::Ecdh
} else {
KeyExchange::Rsa
};
assert_eq!(suite.key_exchange(), expected_kex, "key exchange of {name}");
let expected_auth = if kex_part.contains("anon") {
Authentication::Anonymous
} else if kex_part.contains("ECDSA") {
Authentication::Ecdsa
} else if kex_part.contains("DSS") {
Authentication::Dss
} else {
Authentication::Rsa
};
assert_eq!(
suite.authentication(),
expected_auth,
"authentication of {name}"
);
assert_eq!(
suite.is_export(),
kex_part.contains("EXPORT"),
"export grade of {name}"
);
let expected_mac = if cipher_part.ends_with("_SHA256") {
Mac::Sha256
} else if cipher_part.ends_with("_SHA384") {
Mac::Sha384
} else if cipher_part.ends_with("_SHA") {
Mac::Sha1
} else if cipher_part.ends_with("_MD5") {
Mac::Md5
} else {
panic!("{name} names no MAC this test can read")
};
let expected_mac = match suite.bulk_cipher().is_aead() {
true => Mac::Aead,
false => expected_mac,
};
assert_eq!(suite.mac(), expected_mac, "MAC of {name}");
let cipher = suite.bulk_cipher();
let claims = |needle: &str| cipher_part.contains(needle);
match cipher {
C::AesGcm(bits) => {
assert!(claims("AES_") && claims("_GCM_"), "cipher of {name}");
assert!(claims(&bits.to_string()), "key size of {name}");
}
C::AesCbc(bits) => {
assert!(claims("AES_") && claims("_CBC_"), "cipher of {name}");
assert!(claims(&bits.to_string()), "key size of {name}");
}
C::CamelliaCbc(bits) => {
assert!(claims("CAMELLIA_") && claims("_CBC_"), "cipher of {name}");
assert!(claims(&bits.to_string()), "key size of {name}");
}
C::ChaCha20Poly1305 => assert!(claims("CHACHA20_POLY1305"), "cipher of {name}"),
C::TripleDes => assert!(claims("3DES_EDE_CBC"), "cipher of {name}"),
C::Des => assert!(
claims("DES") || claims("RC2"),
"cipher of {name} is not a DES-class cipher"
),
C::Rc4 => assert!(claims("RC4_"), "cipher of {name}"),
C::SeedCbc => assert!(claims("SEED_CBC"), "cipher of {name}"),
C::IdeaCbc => assert!(claims("IDEA_CBC"), "cipher of {name}"),
C::Null => assert!(claims("NULL"), "cipher of {name}"),
C::AesCcm { .. } => panic!("{name} is a CCM suite outside TLS 1.3"),
}
}
}
#[test]
fn a_suite_is_graded_by_the_worst_thing_about_it() {
let named = |name: &str| {
CipherSuite::ALL
.iter()
.copied()
.find(|suite| suite.name() == name)
.unwrap_or_else(|| panic!("{name} is in the registry"))
};
let strong = named("TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384");
assert_eq!(strong.strength(), SuiteStrength::Strong);
assert!(strong.faults().is_empty());
let no_fs = named("TLS_RSA_WITH_AES_128_GCM_SHA256");
assert_eq!(no_fs.strength(), SuiteStrength::Weak);
assert_eq!(no_fs.faults(), vec![SuiteFault::NoForwardSecrecy]);
let cbc = named("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA");
assert_eq!(cbc.strength(), SuiteStrength::Weak);
assert_eq!(
cbc.faults(),
vec![SuiteFault::Sha1Mac, SuiteFault::CbcMode],
"both faults are reported, not only the worst"
);
let sweet32 = named("TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA");
assert_eq!(sweet32.strength(), SuiteStrength::Insecure);
assert_eq!(sweet32.worst_fault(), Some(SuiteFault::SmallBlock));
for name in [
"TLS_RSA_WITH_RC4_128_SHA",
"TLS_DH_anon_WITH_AES_128_CBC_SHA",
"TLS_RSA_WITH_NULL_SHA",
"TLS_RSA_EXPORT_WITH_RC4_40_MD5",
] {
assert_eq!(
named(name).strength(),
SuiteStrength::Insecure,
"{name} is not usable"
);
}
}
#[test]
fn an_anonymous_suite_is_not_reported_as_lacking_forward_secrecy() {
let anon = CipherSuite::from_code(0x0034).expect("TLS_DH_anon_WITH_AES_128_CBC_SHA");
assert!(anon.is_forward_secret());
assert!(!anon.has_fault(SuiteFault::NoForwardSecrecy));
assert!(anon.has_fault(SuiteFault::Anonymous));
}
#[test]
fn each_version_is_offered_the_suites_it_can_express() {
let thirteen: Vec<_> = CipherSuite::offered_under(TlsVersion::Tls13).collect();
assert_eq!(thirteen.len(), 5, "RFC 8446 §B.4 defines five");
assert!(thirteen.iter().all(
|suite| suite.name().starts_with("TLS_A") || suite.name().starts_with("TLS_CHACHA")
));
for version in [TlsVersion::Ssl30, TlsVersion::Tls10, TlsVersion::Tls11] {
for suite in CipherSuite::offered_under(version) {
assert!(
matches!(suite.mac(), Mac::Md5 | Mac::Sha1 | Mac::Null),
"{suite} needs the TLS 1.2 PRF and cannot be offered under {version}"
);
}
}
let twelve: Vec<_> = CipherSuite::offered_under(TlsVersion::Tls12).collect();
assert_eq!(
twelve.len(),
CipherSuite::ALL.len() - 5,
"everything but the 1.3 suites"
);
}
#[test]
fn every_version_round_trips_through_its_number_and_its_name() {
for &version in TlsVersion::ALL {
assert_eq!(TlsVersion::from_code(version.code()), Some(version));
assert_eq!(version.to_string().parse(), Ok(version));
}
assert_eq!(TlsVersion::from_code(0x0305), None);
assert!("TLSv1.4".parse::<TlsVersion>().is_err());
}
#[test]
fn the_deprecated_versions_are_the_ones_a_standard_withdrew() {
for &version in TlsVersion::ALL {
assert_eq!(
version.is_deprecated(),
version.deprecated_by().is_some(),
"{version} must cite a document exactly when it is deprecated"
);
}
assert_eq!(TlsVersion::Ssl30.deprecated_by(), Some("RFC 7568"));
assert_eq!(TlsVersion::Tls10.deprecated_by(), Some("RFC 8996"));
assert_eq!(TlsVersion::Tls11.deprecated_by(), Some("RFC 8996"));
assert_eq!(TlsVersion::Tls12.deprecated_by(), None);
assert_eq!(TlsVersion::Tls13.deprecated_by(), None);
}
#[test]
fn every_suite_is_found_by_its_number() {
for &suite in CipherSuite::ALL {
assert_eq!(CipherSuite::from_code(suite.code()), Some(suite));
}
assert_eq!(CipherSuite::from_code(0xFFFF), None);
}
#[test]
fn the_grade_follows_from_the_worst_fault_for_every_suite() {
for &suite in CipherSuite::ALL {
let expected = match suite.worst_fault() {
None => SuiteStrength::Strong,
Some(fault) if fault.is_disqualifying() => SuiteStrength::Insecure,
Some(_) => SuiteStrength::Weak,
};
assert_eq!(suite.strength(), expected, "grade of {suite}");
for fault in suite.faults() {
assert!(suite.has_fault(fault), "{suite} reported {fault} it lacks");
}
}
}
fn suite(code: u16) -> CipherSuite {
CipherSuite::from_code(code).expect("a suite in the registry")
}
#[test]
fn recorded_versions_are_ordered_oldest_first() {
let support = TlsSupport::new()
.accepting(VersionSupport::new(TlsVersion::Tls13, vec![], vec![]))
.accepting(VersionSupport::new(TlsVersion::Tls10, vec![], vec![]))
.accepting(VersionSupport::new(TlsVersion::Tls12, vec![], vec![]));
let order: Vec<_> = support.versions().iter().map(|v| v.version()).collect();
assert_eq!(
order,
vec![TlsVersion::Tls10, TlsVersion::Tls12, TlsVersion::Tls13]
);
assert_eq!(support.floor(), Some(TlsVersion::Tls10));
assert_eq!(support.ceiling(), Some(TlsVersion::Tls13));
}
#[test]
fn recording_a_version_twice_keeps_one_entry() {
let mut support = TlsSupport::new();
support.record(VersionSupport::new(TlsVersion::Tls12, vec![], vec![]));
support.record(VersionSupport::new(
TlsVersion::Tls12,
vec![suite(0xC030)],
vec![],
));
assert_eq!(support.versions().len(), 1);
assert_eq!(support.suites().len(), 1);
}
#[test]
fn a_version_never_settled_is_neither_accepted_nor_nothing() {
let support = TlsSupport::new().leaving_unfinished(UnfinishedVersion::new(
TlsVersion::Tls10,
Interruption::Unanswered,
));
assert!(!support.accepts(TlsVersion::Tls10));
assert!(support.findings().is_empty(), "nothing was established");
assert!(!support.is_complete());
assert!(
!support.is_empty(),
"a walk the endpoint cut short is a fact about it"
);
}
#[test]
fn every_interruption_round_trips_through_its_name() {
for &cause in Interruption::ALL {
assert_eq!(Interruption::from_name(cause.name()), Some(cause));
}
assert_eq!(Interruption::from_name("abandoned"), None);
}
fn finished(suites: &[u16]) -> TlsSupport {
TlsSupport::new().accepting(VersionSupport::new(
TlsVersion::Tls12,
suites.iter().map(|code| suite(*code)).collect(),
vec![],
))
}
fn cut_short(suites: &[u16], why: Interruption) -> TlsSupport {
let support =
TlsSupport::new().leaving_unfinished(UnfinishedVersion::new(TlsVersion::Tls12, why));
if suites.is_empty() {
return support;
}
support.accepting(VersionSupport::new(
TlsVersion::Tls12,
suites.iter().map(|code| suite(*code)).collect(),
vec![],
))
}
fn folded(on_record: &TlsSupport, other: &TlsSupport) -> TlsSupport {
let mut folded = on_record.clone();
folded.merge(other.clone());
folded
}
#[test]
fn a_finished_walk_stands_over_a_cut_short_one_whichever_is_on_record() {
let whole = finished(&[0xC030, 0xC02F, 0x000A]);
let floor = cut_short(&[0xC030], Interruption::Stopped);
assert_eq!(folded(&whole, &floor), whole);
assert_eq!(folded(&floor, &whole), whole);
}
#[test]
fn a_walk_that_found_what_the_other_does_not_list_is_not_displaced() {
let whole = finished(&[0xC030, 0xC02F]);
let changed = cut_short(&[0x000A], Interruption::Unanswered);
assert_eq!(folded(&changed, &whole), changed);
}
#[test]
fn of_two_cut_short_walks_the_one_that_got_further_stands() {
let short = cut_short(&[0xC030], Interruption::Stopped);
let further = cut_short(&[0xC030, 0xC02F], Interruption::Unanswered);
assert_eq!(folded(&short, &further), further);
assert_eq!(folded(&further, &short), further);
}
#[test]
fn a_refused_version_stands_over_one_never_settled() {
let thirteen = VersionSupport::new(TlsVersion::Tls13, vec![suite(0x1301)], vec![]);
let refused = TlsSupport::new().accepting(thirteen.clone());
let unsettled = cut_short(&[], Interruption::Unanswered).accepting(thirteen);
assert_eq!(folded(&unsettled, &refused), refused);
}
#[test]
fn a_record_nobody_enumerated_displaces_nothing() {
let whole = finished(&[0xC030]);
assert_eq!(folded(&whole, &TlsSupport::new()), whole);
assert_eq!(folded(&TlsSupport::new(), &whole), whole);
}
#[test]
fn a_suite_accepted_twice_is_counted_once() {
let support = TlsSupport::new()
.accepting(VersionSupport::new(
TlsVersion::Tls11,
vec![suite(0x002F)],
vec![],
))
.accepting(VersionSupport::new(
TlsVersion::Tls12,
vec![suite(0x002F)],
vec![],
));
assert_eq!(support.suites().len(), 1);
}
#[test]
fn a_sound_endpoint_produces_no_findings() {
let support = TlsSupport::new()
.accepting(VersionSupport::new(
TlsVersion::Tls13,
vec![suite(0x1302)],
vec![],
))
.accepting(VersionSupport::new(
TlsVersion::Tls12,
vec![suite(0xC030), suite(0xC02B)],
vec![],
));
assert_eq!(support.weakest(), Some(SuiteStrength::Strong));
assert!(support.faults().is_empty());
assert!(support.findings().is_empty());
}
#[test]
fn a_withdrawn_version_is_reported_on_its_own_terms() {
let support = TlsSupport::new().accepting(VersionSupport::new(
TlsVersion::Tls10,
vec![suite(0x002F)],
vec![],
));
let findings = support.findings();
let version_finding = findings
.iter()
.find(|finding| finding.title().contains("TLSv1.0"))
.expect("the version is reported");
assert_eq!(version_finding.severity(), Severity::Medium);
assert!(
version_finding
.references()
.any(|reference| matches!(reference, Reference::Url(url) if url.contains("8996"))),
"the finding cites the document that withdrew the version"
);
}
#[test]
fn one_fault_across_many_suites_is_one_finding() {
let rc4: Vec<CipherSuite> = CipherSuite::ALL
.iter()
.copied()
.filter(|suite| suite.has_fault(SuiteFault::Rc4) && !suite.is_export())
.collect();
assert!(rc4.len() > 3, "the registry carries several RC4 suites");
let support = TlsSupport::new().accepting(VersionSupport::new(
TlsVersion::Tls12,
rc4.clone(),
vec![],
));
let rc4_findings: Vec<_> = support
.findings()
.into_iter()
.filter(|finding| finding.title().contains("RC4"))
.collect();
assert_eq!(rc4_findings.len(), 1, "one problem, one finding");
assert!(
rc4_findings[0]
.excerpt()
.as_str()
.contains("TLS_RSA_WITH_RC4_128_SHA"),
"the suites are carried in the excerpt for whoever needs them"
);
}
#[test]
fn a_suite_accepted_under_several_versions_is_listed_once() {
let rc4 = CipherSuite::ALL
.iter()
.copied()
.find(|suite| suite.has_fault(SuiteFault::Rc4) && !suite.is_export())
.expect("the registry carries an RC4 suite");
let support = TlsSupport::new()
.accepting(VersionSupport::new(TlsVersion::Tls10, vec![rc4], vec![]))
.accepting(VersionSupport::new(TlsVersion::Tls11, vec![rc4], vec![]))
.accepting(VersionSupport::new(TlsVersion::Tls12, vec![rc4], vec![]));
let excerpt = support
.findings()
.into_iter()
.find(|finding| finding.title().contains("RC4"))
.expect("the RC4 fault is one finding")
.excerpt()
.as_str()
.to_string();
assert_eq!(
excerpt.matches(rc4.name()).count(),
1,
"the suite is named once across three versions: {excerpt}"
);
assert!(
excerpt.starts_with("1 of the accepted suites"),
"and the count matches the list: {excerpt}"
);
}
#[test]
fn no_tls_fault_is_reported_as_critical() {
for &fault in SuiteFault::ALL {
assert!(
fault.severity() < Severity::Critical,
"{fault} reached critical"
);
}
assert_eq!(SuiteFault::NullCipher.severity(), Severity::High);
assert_eq!(SuiteFault::Rc4.severity(), Severity::Medium);
assert_eq!(SuiteFault::CbcMode.severity(), Severity::Low);
}
#[test]
fn every_finding_carries_the_registry_it_was_drawn_from() {
let support = TlsSupport::new().accepting(VersionSupport::new(
TlsVersion::Ssl30,
vec![suite(0x0004)],
vec![],
));
let findings = support.findings();
assert!(!findings.is_empty());
for finding in &findings {
assert_eq!(finding.detection().id(), "zond:tls");
assert_eq!(
finding.detection().content_hash().len(),
64,
"a SHA-256 of the registry, in hex"
);
}
}
#[test]
fn every_finding_survives_being_filed_against_one_port() {
use crate::model::port::{Port, PortState, Protocol};
let mut support = TlsSupport::new();
for version in [TlsVersion::Ssl30, TlsVersion::Tls10, TlsVersion::Tls11] {
let carriers: Vec<CipherSuite> = SuiteFault::ALL
.iter()
.copied()
.filter_map(|fault| {
CipherSuite::offered_under(version).find(|suite| suite.has_fault(fault))
})
.collect();
support.record(VersionSupport::new(version, carriers, vec![]));
}
let findings = support.findings();
assert_eq!(
findings.len(),
support.faults().len() + 3,
"one per fault, plus one per withdrawn version"
);
let mut port = Port::new(443, Protocol::Tcp, PortState::Open);
for finding in findings.clone() {
port.add_finding(finding);
}
assert_eq!(
port.findings().count(),
findings.len(),
"two findings collapsed into one claim and the difference was lost"
);
}
#[test]
fn a_claim_is_overturned_only_where_every_walk_it_rests_on_finished() {
use TlsVersion::{Tls10, Tls12};
let rc4 = suite(0x0005);
let basis = TlsSupport::new()
.accepting(VersionSupport::new(Tls10, vec![rc4], vec![]))
.accepting(VersionSupport::new(Tls12, vec![rc4], vec![]));
let claim = basis
.findings()
.into_iter()
.find(|finding| finding.title().contains("RC4"))
.expect("the basis draws an RC4 claim");
let strong = VersionSupport::new(Tls12, vec![suite(0xC030)], vec![]);
let refused_and_finished = TlsSupport::new().accepting(strong.clone());
let refused_and_cut_short = refused_and_finished
.clone()
.leaving_unfinished(UnfinishedVersion::new(Tls12, Interruption::Stopped));
let still_accepted =
TlsSupport::new().accepting(VersionSupport::new(Tls12, vec![rc4], vec![]));
assert_eq!(
refused_and_finished.standing(&claim, &basis),
Some(Standing::Overturned)
);
assert_eq!(
refused_and_cut_short.standing(&claim, &basis),
Some(Standing::Unsettled),
"TLS 1.0 is settled, but the TLS 1.2 walk may have stopped short of RC4"
);
assert_eq!(
TlsSupport::new().standing(&claim, &basis),
Some(Standing::Unsettled),
"a record with nothing in it made no walk"
);
assert_eq!(
still_accepted.standing(&claim, &basis),
Some(Standing::Upheld)
);
}
#[test]
fn a_claim_these_rules_do_not_draw_has_no_standing() {
let basis = TlsSupport::new().accepting(VersionSupport::new(
TlsVersion::Tls10,
vec![suite(0x002F)],
vec![],
));
let foreign = Finding::new(
detection_id(),
"a claim worded by other rules",
Severity::Low,
Confidence::Certain,
DetectionClass::ActiveBenign,
)
.expect("a titled finding");
assert_eq!(TlsSupport::new().standing(&foreign, &basis), None);
}
#[test]
fn the_detection_identity_names_this_build() {
let id = detection_id();
let expected: Version = env!("CARGO_PKG_VERSION").parse().expect("a valid version");
assert_eq!(id.version(), expected);
}
}