use core::fmt;
use zeroize::Zeroizing;
use crate::credentials::{self, PASSWORD_STRING_CHARSET};
pub use crate::credentials::{
AUTHORIZATION_KEY_MAX_BYTES, AUTHORIZATION_KEY_MIN_BYTES, BASIC_AUTH_INTEROPERABLE_MAX_LEN,
BASIC_AUTH_MAX_LEN, BASIC_AUTH_MIN_LEN, CredentialError,
};
use crate::types::Identity;
use crate::version::Version;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum SecurityProfile {
Unsecured,
BasicAuth,
TlsBasicAuth,
TlsClientCertificate,
}
impl SecurityProfile {
#[must_use]
pub const fn number(self) -> u8 {
match self {
SecurityProfile::Unsecured => 0,
SecurityProfile::BasicAuth => 1,
SecurityProfile::TlsBasicAuth => 2,
SecurityProfile::TlsClientCertificate => 3,
}
}
#[must_use]
pub const fn from_number(number: u8) -> Option<Self> {
Some(match number {
0 => SecurityProfile::Unsecured,
1 => SecurityProfile::BasicAuth,
2 => SecurityProfile::TlsBasicAuth,
3 => SecurityProfile::TlsClientCertificate,
_ => return None,
})
}
#[must_use]
pub const fn is_transport_encrypted(self) -> bool {
!matches!(
self,
SecurityProfile::Unsecured | SecurityProfile::BasicAuth
)
}
#[must_use]
pub const fn uses_basic_auth(self) -> bool {
matches!(
self,
SecurityProfile::BasicAuth | SecurityProfile::TlsBasicAuth
)
}
}
impl fmt::Display for SecurityProfile {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "security profile {}", self.number())
}
}
#[derive(Clone)]
pub struct BasicAuthPassword {
secret: Zeroizing<Vec<u8>>,
}
impl BasicAuthPassword {
pub fn utf8(password: impl Into<String>) -> Result<Self, CredentialError> {
let password = password.into();
credentials::check_password(&password, BASIC_AUTH_MAX_LEN)?;
Ok(Self {
secret: Zeroizing::new(password.into_bytes()),
})
}
pub fn hex(key: &str) -> Result<Self, CredentialError> {
Ok(Self {
secret: Zeroizing::new(credentials::authorization_key_octets(key)?),
})
}
pub fn generate(version: Version) -> Result<Self, CredentialError> {
const ACCEPT_BELOW: u8 = 213;
if version == Version::V1_6 {
let mut octets = Zeroizing::new(vec![0u8; AUTHORIZATION_KEY_MAX_BYTES]);
getrandom::fill(&mut octets).map_err(|_| CredentialError::Entropy)?;
return Ok(Self { secret: octets });
}
let mut secret = Zeroizing::new(Vec::with_capacity(BASIC_AUTH_INTEROPERABLE_MAX_LEN));
let mut pool = Zeroizing::new([0u8; 64]);
while secret.len() < BASIC_AUTH_INTEROPERABLE_MAX_LEN {
getrandom::fill(&mut *pool).map_err(|_| CredentialError::Entropy)?;
for &byte in pool.iter().filter(|b| **b < ACCEPT_BELOW) {
if secret.len() == BASIC_AUTH_INTEROPERABLE_MAX_LEN {
break;
}
secret.push(PASSWORD_STRING_CHARSET[usize::from(byte % 71)]);
}
}
Ok(Self { secret })
}
pub fn configuration_value(
&self,
version: Version,
) -> Result<ConfigurationValue, CredentialError> {
const DIGITS: &[u8; 16] = b"0123456789abcdef";
if version == Version::V1_6 {
let len = self.secret.len();
if !(AUTHORIZATION_KEY_MIN_BYTES..=AUTHORIZATION_KEY_MAX_BYTES).contains(&len) {
return Err(CredentialError::KeyLength(len));
}
let mut text = Zeroizing::new(String::with_capacity(len * 2));
for byte in self.secret.iter() {
text.push(char::from(DIGITS[usize::from(byte >> 4)]));
text.push(char::from(DIGITS[usize::from(byte & 0x0f)]));
}
return Ok(ConfigurationValue(text));
}
let text = core::str::from_utf8(&self.secret).map_err(|error| {
CredentialError::Character(char::from(self.secret[error.valid_up_to()]))
})?;
credentials::check_password(text, BASIC_AUTH_MAX_LEN)?;
Ok(ConfigurationValue(Zeroizing::new(text.to_owned())))
}
#[must_use]
pub fn raw(bytes: impl Into<Vec<u8>>) -> Self {
Self {
secret: Zeroizing::new(bytes.into()),
}
}
pub fn for_version(version: Version, secret: &str) -> Result<Self, CredentialError> {
match version {
Version::V1_6 => Self::hex(secret),
_ => Self::utf8(secret),
}
}
#[must_use]
pub fn as_bytes(&self) -> &[u8] {
&self.secret
}
#[must_use]
pub fn verify(&self, candidate: &[u8]) -> bool {
constant_time_eq(&self.secret, candidate)
}
}
pub struct ConfigurationValue(Zeroizing<String>);
impl ConfigurationValue {
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl core::ops::Deref for ConfigurationValue {
type Target = str;
fn deref(&self) -> &str {
&self.0
}
}
impl fmt::Debug for ConfigurationValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("ConfigurationValue(<redacted>)")
}
}
impl fmt::Debug for BasicAuthPassword {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("BasicAuthPassword(<redacted>)")
}
}
#[must_use]
pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
if a.len() != b.len() {
return false;
}
let mut diff = 0u8;
for (x, y) in a.iter().zip(b) {
diff |= x ^ y;
}
diff == 0
}
#[must_use]
pub fn basic_auth_header(identity: &Identity, password: &BasicAuthPassword) -> String {
use base64::Engine as _;
let mut credentials = Vec::new();
credentials.extend_from_slice(identity.as_str().as_bytes());
credentials.push(b':');
credentials.extend_from_slice(password.as_bytes());
let credentials = Zeroizing::new(credentials);
format!(
"Basic {}",
base64::engine::general_purpose::STANDARD.encode(&*credentials)
)
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum Credentials {
None,
Basic {
user: String,
password: Zeroizing<Vec<u8>>,
},
ClientCertificate {
der: Vec<u8>,
},
}
impl Credentials {
#[must_use]
pub fn from_authorization_header(value: &str) -> Self {
use base64::Engine as _;
let Some(encoded) = value
.strip_prefix("Basic ")
.or_else(|| value.strip_prefix("basic "))
else {
return Credentials::None;
};
let Ok(decoded) = base64::engine::general_purpose::STANDARD.decode(encoded.trim()) else {
return Credentials::None;
};
match decoded.iter().position(|byte| *byte == b':') {
Some(index) => {
let (user, password) = decoded.split_at(index);
match core::str::from_utf8(user) {
Ok(user) => Credentials::Basic {
user: user.to_owned(),
password: Zeroizing::new(password[1..].to_vec()),
},
Err(_) => Credentials::None,
}
}
None => Credentials::None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_16_authorization_key_is_hex_and_a_2x_password_is_utf8() {
let legacy = BasicAuthPassword::hex("000102030405060708090a0b0c0d0e0f").unwrap();
assert_eq!(legacy.as_bytes(), &(0..16).collect::<Vec<u8>>()[..]);
assert_eq!(
BasicAuthPassword::hex("xyz").unwrap_err(),
CredentialError::NotHex
);
assert_eq!(
BasicAuthPassword::hex("0001020304").unwrap_err(),
CredentialError::KeyLength(5)
);
assert_eq!(
BasicAuthPassword::hex(&"ab".repeat(21)).unwrap_err(),
CredentialError::KeyLength(21)
);
assert!(BasicAuthPassword::hex(&"ab".repeat(20)).is_ok());
let modern = BasicAuthPassword::utf8("0123456789abcdef").unwrap();
assert_eq!(modern.as_bytes(), b"0123456789abcdef");
assert_eq!(
BasicAuthPassword::utf8("short").unwrap_err(),
CredentialError::PasswordLength(5)
);
assert!(BasicAuthPassword::utf8("x".repeat(41)).is_ok());
assert!(BasicAuthPassword::utf8("x".repeat(64)).is_ok());
assert!(BasicAuthPassword::utf8("x".repeat(65)).is_err());
}
#[test]
fn a_generated_password_round_trips_through_its_configuration_value() {
for version in [Version::V1_6, Version::V2_0_1, Version::V2_1] {
for _ in 0..1_000 {
let password = BasicAuthPassword::generate(version).unwrap();
let value = password.configuration_value(version).unwrap();
let back = BasicAuthPassword::for_version(version, &value).unwrap();
assert!(
back.verify(password.as_bytes()),
"{version}: {}",
value.as_str()
);
}
}
let legacy = BasicAuthPassword::generate(Version::V1_6).unwrap();
assert_eq!(legacy.as_bytes().len(), AUTHORIZATION_KEY_MAX_BYTES);
let key = legacy.configuration_value(Version::V1_6).unwrap();
assert_eq!(key.len(), 40);
assert!(
key.bytes()
.all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
);
let modern = BasicAuthPassword::generate(Version::V2_1).unwrap();
assert_eq!(modern.as_bytes().len(), BASIC_AUTH_INTEROPERABLE_MAX_LEN);
}
#[test]
fn generated_characters_are_uniform_over_the_charset() {
let mut counts = [0u32; 256];
for _ in 0..10_000 {
for &byte in BasicAuthPassword::generate(Version::V2_0_1)
.unwrap()
.as_bytes()
{
counts[usize::from(byte)] += 1;
}
}
let expected = 400_000.0 / 71.0;
let mut chi_square = 0.0;
for &c in PASSWORD_STRING_CHARSET {
let observed = f64::from(counts[usize::from(c)]);
assert!(observed > 0.0, "{} never generated", char::from(c));
chi_square += (observed - expected).powi(2) / expected;
}
let outside: u32 = (0u8..=255)
.filter(|b| !PASSWORD_STRING_CHARSET.contains(b))
.map(|b| counts[usize::from(b)])
.sum();
assert_eq!(outside, 0);
assert!(chi_square < 120.0, "chi-square {chi_square}");
}
#[test]
fn a_configuration_value_follows_the_version_rules() {
let passphrase = BasicAuthPassword::raw("sixteen-byte-key");
assert_eq!(
&*passphrase.configuration_value(Version::V1_6).unwrap(),
"7369787465656e2d627974652d6b6579"
);
assert_eq!(
BasicAuthPassword::raw("fifteen-byte-ky")
.configuration_value(Version::V1_6)
.unwrap_err(),
CredentialError::KeyLength(15)
);
assert_eq!(
BasicAuthPassword::raw([0u8; 21].to_vec())
.configuration_value(Version::V1_6)
.unwrap_err(),
CredentialError::KeyLength(21)
);
let modern = BasicAuthPassword::utf8("0123456789abcdef").unwrap();
assert_eq!(
&*modern.configuration_value(Version::V2_0_1).unwrap(),
"0123456789abcdef"
);
assert_eq!(
BasicAuthPassword::raw([0xff; 16].to_vec())
.configuration_value(Version::V2_0_1)
.unwrap_err(),
CredentialError::Character('\u{ff}')
);
assert_eq!(format!("{modern:?}"), "BasicAuthPassword(<redacted>)");
let value = BasicAuthPassword::generate(Version::V2_0_1)
.unwrap()
.configuration_value(Version::V2_0_1)
.unwrap();
assert_eq!(format!("{value:?}"), "ConfigurationValue(<redacted>)");
assert!(!format!("{value:?}").contains(value.as_str()));
}
#[test]
fn a_2x_password_outside_the_charset_is_refused_by_name() {
assert_eq!(
BasicAuthPassword::utf8("0123456789abcde!").unwrap_err(),
CredentialError::Character('!')
);
assert_eq!(
BasicAuthPassword::for_version(Version::V2_1, "0123456789 abcdef").unwrap_err(),
CredentialError::Character(' ')
);
}
#[test]
fn basic_auth_round_trips_through_the_header() {
let identity = Identity::new("CS-0001").unwrap();
let password = BasicAuthPassword::utf8("0123456789abcdef").unwrap();
let header = basic_auth_header(&identity, &password);
let parsed = Credentials::from_authorization_header(&header);
let Credentials::Basic {
user,
password: bytes,
} = parsed
else {
panic!("{parsed:?}")
};
assert_eq!(user, "CS-0001");
assert!(password.verify(&bytes));
assert!(!password.verify(b"0123456789abcdee"));
}
#[test]
fn profiles_report_what_they_secure() {
assert!(!SecurityProfile::BasicAuth.is_transport_encrypted());
assert!(SecurityProfile::TlsBasicAuth.is_transport_encrypted());
assert!(!SecurityProfile::TlsClientCertificate.uses_basic_auth());
assert_eq!(
SecurityProfile::from_number(3),
Some(SecurityProfile::TlsClientCertificate)
);
assert_eq!(SecurityProfile::from_number(4), None);
}
}