use alloc::string::String;
use alloc::sync::Arc;
#[cfg(feature = "tokio")]
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::crypto::CryptoProvider;
#[cfg(feature = "tokio")]
use rustls::crypto::{verify_tls12_signature, verify_tls13_signature};
use rustls::pki_types::CertificateDer;
#[cfg(feature = "tokio")]
use rustls::pki_types::{ServerName, UnixTime};
#[cfg(feature = "tokio")]
use rustls::{DigitallySignedStruct, Error as TlsError, RootCertStore, SignatureScheme};
use super::proto::HmacBinding;
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Fingerprint([u8; 32]);
impl Fingerprint {
#[must_use]
pub fn of(der: &CertificateDer<'_>) -> Self {
use sha2::Digest as _;
let digest = sha2::Sha256::digest(der.as_ref());
let mut bytes = [0u8; 32];
bytes.copy_from_slice(&digest);
Self(bytes)
}
pub fn parse(hex: &str) -> Result<Self, Error> {
match HmacBinding::from_hex_fingerprint(hex)? {
HmacBinding::LeafFingerprint(bytes) => {
let mut out = [0u8; 32];
if bytes.len() != 32 {
return Err(Error::Fingerprint);
}
out.copy_from_slice(&bytes);
Ok(Self(out))
}
HmacBinding::DomainName(_) => Err(Error::Fingerprint),
}
}
#[must_use]
pub const fn from_bytes(bytes: [u8; 32]) -> Self {
Self(bytes)
}
#[must_use]
pub const fn as_bytes(&self) -> &[u8; 32] {
&self.0
}
#[must_use]
pub fn to_hex(&self) -> String {
use core::fmt::Write as _;
let mut out = String::with_capacity(64);
for b in &self.0 {
let _ = write!(out, "{b:02x}");
}
out
}
#[must_use]
pub fn binding(&self) -> HmacBinding {
HmacBinding::LeafFingerprint(self.0.to_vec())
}
#[must_use]
pub fn matches(&self, other: &Self) -> bool {
use subtle::ConstantTimeEq as _;
self.0.ct_eq(&other.0).into()
}
}
impl core::fmt::Debug for Fingerprint {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "Fingerprint({})", self.to_hex())
}
}
impl core::fmt::Display for Fingerprint {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(&self.to_hex())
}
}
#[cfg(feature = "tokio")]
#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
#[derive(Debug, Clone)]
pub struct CapturedIdentity {
pub leaf: Fingerprint,
pub root: Fingerprint,
pub chain: Vec<CertificateDer<'static>>,
}
#[cfg(feature = "tokio")]
#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
#[derive(Debug, Clone)]
pub enum TlsPolicy {
Web,
Pinned(Fingerprint),
LanPairingOnly,
}
#[cfg(feature = "tokio")]
impl TlsPolicy {
#[must_use]
pub const fn authenticates(&self) -> bool {
!matches!(self, TlsPolicy::LanPairingOnly)
}
}
#[cfg(feature = "tokio")]
#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
#[derive(Debug, Clone)]
pub struct TlsClient {
config: Arc<rustls::ClientConfig>,
captured: Arc<Capture>,
}
#[cfg(feature = "tokio")]
impl TlsClient {
pub fn new(policy: &TlsPolicy) -> Result<Self, Error> {
let provider = default_provider()?;
let captured = Arc::new(Capture::default());
let builder = rustls::ClientConfig::builder_with_provider(provider.clone())
.with_safe_default_protocol_versions()
.map_err(|e| Error::Tls(e.to_string()))?;
let config = match policy {
TlsPolicy::Web => {
let inner = rustls_platform_verifier::Verifier::new(provider)
.map_err(|e| Error::Tls(e.to_string()))?;
builder
.dangerous()
.with_custom_certificate_verifier(Arc::new(Recording {
inner: Verifier::Real(Arc::new(inner)),
captured: captured.clone(),
}))
.with_no_client_auth()
}
TlsPolicy::Pinned(pin) => builder
.dangerous()
.with_custom_certificate_verifier(Arc::new(Recording {
inner: Verifier::Pinned {
pin: *pin,
provider,
},
captured: captured.clone(),
}))
.with_no_client_auth(),
TlsPolicy::LanPairingOnly => builder
.dangerous()
.with_custom_certificate_verifier(Arc::new(Recording {
inner: Verifier::AcceptAnything(provider),
captured: captured.clone(),
}))
.with_no_client_auth(),
};
Ok(Self {
config: Arc::new(config),
captured,
})
}
#[must_use]
pub fn config(&self) -> Arc<rustls::ClientConfig> {
self.config.clone()
}
#[must_use]
pub fn captured(&self) -> Option<CapturedIdentity> {
self.captured.get()
}
#[must_use]
pub fn binding(&self) -> Option<HmacBinding> {
self.captured.get().map(|c| c.leaf.binding())
}
#[must_use]
pub fn identity_is_stable(&self) -> bool {
!self.captured.changed()
}
}
#[cfg(feature = "tokio")]
#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
#[derive(Debug, Default)]
struct Capture {
inner: std::sync::Mutex<Option<CapturedIdentity>>,
changed: core::sync::atomic::AtomicBool,
}
#[cfg(feature = "tokio")]
impl Capture {
fn set(&self, identity: CapturedIdentity) {
let Ok(mut slot) = self.inner.lock() else {
self.changed
.store(true, core::sync::atomic::Ordering::Relaxed);
return;
};
if let Some(previous) = slot.as_ref()
&& !previous.leaf.matches(&identity.leaf)
{
self.changed
.store(true, core::sync::atomic::Ordering::Relaxed);
}
*slot = Some(identity);
}
fn get(&self) -> Option<CapturedIdentity> {
self.inner.lock().ok()?.clone()
}
fn changed(&self) -> bool {
self.changed.load(core::sync::atomic::Ordering::Relaxed)
}
}
#[cfg(feature = "tokio")]
#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
#[derive(Debug)]
enum Verifier {
Real(Arc<dyn ServerCertVerifier>),
Pinned {
pin: Fingerprint,
provider: Arc<CryptoProvider>,
},
AcceptAnything(Arc<CryptoProvider>),
}
#[cfg(feature = "tokio")]
impl Verifier {
fn provider(&self) -> Option<&Arc<CryptoProvider>> {
match self {
Verifier::Real(_) => None,
Verifier::Pinned { provider, .. } | Verifier::AcceptAnything(provider) => {
Some(provider)
}
}
}
}
#[cfg(feature = "tokio")]
fn verify_pinned(
pin: &Fingerprint,
provider: &Arc<CryptoProvider>,
end_entity: &CertificateDer<'_>,
intermediates: &[CertificateDer<'_>],
server_name: &ServerName<'_>,
ocsp_response: &[u8],
now: UnixTime,
) -> Result<ServerCertVerified, TlsError> {
if Fingerprint::of(end_entity).matches(pin) {
return Ok(ServerCertVerified::assertion());
}
let Some(anchor) = intermediates
.iter()
.find(|cert| Fingerprint::of(cert).matches(pin))
else {
return Err(TlsError::InvalidCertificate(
rustls::CertificateError::UnknownIssuer,
));
};
let mut roots = RootCertStore::empty();
roots
.add(anchor.clone().into_owned())
.map_err(|_| TlsError::InvalidCertificate(rustls::CertificateError::BadEncoding))?;
let verifier = rustls::client::WebPkiServerVerifier::builder_with_provider(
Arc::new(roots),
provider.clone(),
)
.build()
.map_err(|e| TlsError::General(e.to_string()))?;
verifier.verify_server_cert(end_entity, intermediates, server_name, ocsp_response, now)
}
#[cfg(feature = "tokio")]
#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
#[derive(Debug)]
struct Recording {
inner: Verifier,
captured: Arc<Capture>,
}
#[cfg(feature = "tokio")]
impl ServerCertVerifier for Recording {
fn verify_server_cert(
&self,
end_entity: &CertificateDer<'_>,
intermediates: &[CertificateDer<'_>],
server_name: &ServerName<'_>,
ocsp_response: &[u8],
now: UnixTime,
) -> Result<ServerCertVerified, TlsError> {
let leaf = end_entity.clone().into_owned();
let mut chain = alloc::vec![leaf.clone()];
chain.extend(intermediates.iter().map(|c| c.clone().into_owned()));
self.captured.set(CapturedIdentity {
leaf: Fingerprint::of(end_entity),
root: Fingerprint::of(chain.last().unwrap_or(&leaf)),
chain,
});
match &self.inner {
Verifier::Real(inner) => {
inner.verify_server_cert(end_entity, intermediates, server_name, ocsp_response, now)
}
Verifier::Pinned { pin, provider } => verify_pinned(
pin,
provider,
end_entity,
intermediates,
server_name,
ocsp_response,
now,
),
Verifier::AcceptAnything(_) => Ok(ServerCertVerified::assertion()),
}
}
fn verify_tls12_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, TlsError> {
match (&self.inner, self.inner.provider()) {
(Verifier::Real(inner), _) => inner.verify_tls12_signature(message, cert, dss),
(_, Some(provider)) => verify_tls12_signature(
message,
cert,
dss,
&provider.signature_verification_algorithms,
),
(_, None) => Err(TlsError::General("no signature verifier".into())),
}
}
fn verify_tls13_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, TlsError> {
match (&self.inner, self.inner.provider()) {
(Verifier::Real(inner), _) => inner.verify_tls13_signature(message, cert, dss),
(_, Some(provider)) => verify_tls13_signature(
message,
cert,
dss,
&provider.signature_verification_algorithms,
),
(_, None) => Err(TlsError::General("no signature verifier".into())),
}
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
match (&self.inner, self.inner.provider()) {
(Verifier::Real(inner), _) => inner.supported_verify_schemes(),
(_, Some(provider)) => provider
.signature_verification_algorithms
.supported_schemes(),
(_, None) => Vec::new(),
}
}
}
pub fn default_provider() -> Result<Arc<CryptoProvider>, Error> {
if let Some(provider) = CryptoProvider::get_default() {
return Ok(provider.clone());
}
#[cfg(feature = "tls-aws-lc-rs")]
let bundled = Some(rustls::crypto::aws_lc_rs::default_provider());
#[cfg(all(feature = "tls-ring", not(feature = "tls-aws-lc-rs")))]
let bundled = Some(rustls::crypto::ring::default_provider());
#[cfg(not(any(feature = "tls-ring", feature = "tls-aws-lc-rs")))]
let bundled: Option<CryptoProvider> = None;
let Some(provider) = bundled else {
return Err(Error::Tls(
"no TLS crypto provider: build with the `tls-ring` or `tls-aws-lc-rs` feature, \
or install one yourself with rustls::crypto::CryptoProvider::install_default"
.to_string(),
));
};
let _ = provider.install_default();
CryptoProvider::get_default()
.cloned()
.ok_or_else(|| Error::Tls("no crypto provider could be installed".to_string()))
}
#[cfg(all(
feature = "connect-server",
any(feature = "tls-ring", feature = "tls-aws-lc-rs")
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "connect-server",
any(feature = "tls-ring", feature = "tls-aws-lc-rs")
)))
)]
#[derive(Debug)]
pub struct SelfSignedEndpoint {
pub ca: CertificateDer<'static>,
pub chain: Vec<CertificateDer<'static>>,
pub key: rustls::pki_types::PrivateKeyDer<'static>,
pub leaf: Fingerprint,
}
#[cfg(all(
feature = "connect-server",
any(feature = "tls-ring", feature = "tls-aws-lc-rs")
))]
impl SelfSignedEndpoint {
pub fn generate(names: impl IntoIterator<Item = String>) -> Result<Self, Error> {
use rcgen::{
BasicConstraints, CertificateParams, DnType, IsCa, KeyPair, KeyUsagePurpose, SanType,
};
let names: Vec<String> = names.into_iter().collect();
let Some(primary) = names.first().cloned() else {
return Err(Error::Tls(
"a certificate needs at least one name".to_string(),
));
};
let ca_key = KeyPair::generate().map_err(|e| Error::Tls(e.to_string()))?;
let mut ca_params = CertificateParams::default();
ca_params.is_ca = IsCa::Ca(BasicConstraints::Constrained(0));
ca_params.key_usages = alloc::vec![
KeyUsagePurpose::KeyCertSign,
KeyUsagePurpose::CrlSign,
KeyUsagePurpose::DigitalSignature,
];
ca_params
.distinguished_name
.push(DnType::CommonName, "s2-kit LAN endpoint CA");
let ca_cert = ca_params
.self_signed(&ca_key)
.map_err(|e| Error::Tls(e.to_string()))?;
let leaf_key = KeyPair::generate().map_err(|e| Error::Tls(e.to_string()))?;
let mut leaf_params = CertificateParams::default();
leaf_params
.distinguished_name
.push(DnType::CommonName, primary);
for name in &names {
let san = match name.parse::<core::net::IpAddr>() {
Ok(ip) => SanType::IpAddress(ip),
Err(_) => SanType::DnsName(
name.clone()
.try_into()
.map_err(|_| Error::Tls(alloc::format!("{name} is not a usable name")))?,
),
};
leaf_params.subject_alt_names.push(san);
}
let issuer = rcgen::Issuer::new(ca_params, ca_key);
let leaf_cert = leaf_params
.signed_by(&leaf_key, &issuer)
.map_err(|e| Error::Tls(e.to_string()))?;
let leaf_der = leaf_cert.der().clone();
let ca_der = ca_cert.der().clone();
Ok(Self {
leaf: Fingerprint::of(&leaf_der),
chain: alloc::vec![leaf_der, ca_der.clone()],
ca: ca_der,
key: rustls::pki_types::PrivateKeyDer::Pkcs8(leaf_key.serialize_der().into()),
})
}
pub fn server_config(&self) -> Result<Arc<rustls::ServerConfig>, Error> {
let provider = default_provider()?;
let config = rustls::ServerConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
.map_err(|e| Error::Tls(e.to_string()))?
.with_no_client_auth()
.with_single_cert(self.chain.clone(), self.key.clone_key())
.map_err(|e| Error::Tls(e.to_string()))?;
Ok(Arc::new(config))
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error("not a SHA-256 certificate fingerprint")]
Fingerprint,
#[error("TLS: {0}")]
Tls(String),
}
impl From<super::proto::ConnectError> for Error {
fn from(_: super::proto::ConnectError) -> Self {
Error::Fingerprint
}
}
use alloc::string::ToString as _;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_fingerprint_round_trips_through_the_form_tools_print() {
let der = CertificateDer::from(alloc::vec![1u8, 2, 3, 4]);
let fp = Fingerprint::of(&der);
let text = fp.to_hex();
assert_eq!(text.len(), 64, "32 bytes, plain hexadecimal");
assert_eq!(text, text.to_lowercase());
assert_eq!(Fingerprint::parse(&text).unwrap(), fp);
let colons = text
.as_bytes()
.chunks(2)
.map(|pair| core::str::from_utf8(pair).unwrap().to_uppercase())
.collect::<Vec<_>>()
.join(":");
assert_eq!(Fingerprint::parse(&colons).unwrap(), fp);
assert!(fp.matches(&Fingerprint::of(&der)));
}
#[test]
fn a_fingerprint_is_the_binding_the_hmac_takes() {
let der = CertificateDer::from(alloc::vec![9u8; 64]);
let fp = Fingerprint::of(&der);
let HmacBinding::LeafFingerprint(bytes) = fp.binding() else {
panic!("a leaf fingerprint binds as a leaf fingerprint");
};
assert_eq!(bytes.len(), 32);
assert_eq!(&bytes[..], fp.as_bytes());
}
#[test]
fn something_that_is_not_a_fingerprint_is_refused() {
assert!(Fingerprint::parse("").is_err());
assert!(Fingerprint::parse("AA:BB").is_err());
assert!(Fingerprint::parse("not hexadecimal at all").is_err());
assert!(Fingerprint::parse(&"zz".repeat(32)).is_err());
}
#[cfg(feature = "tokio")]
#[test]
fn only_one_policy_declines_to_authenticate_and_it_says_so() {
assert!(TlsPolicy::Web.authenticates());
assert!(!TlsPolicy::LanPairingOnly.authenticates());
let der = CertificateDer::from(alloc::vec![1u8, 2, 3]);
assert!(TlsPolicy::Pinned(Fingerprint::of(&der)).authenticates());
}
#[cfg(feature = "tokio")]
#[test]
fn a_provider_is_chosen_explicitly_and_never_by_the_library() {
#[cfg(any(feature = "tls-ring", feature = "tls-aws-lc-rs"))]
{
let first = default_provider().expect("a bundled provider");
let second = default_provider().expect("the same provider again");
assert!(Arc::ptr_eq(&first, &second));
assert!(
CryptoProvider::get_default().is_some(),
"and it is the process-wide default afterwards"
);
}
#[cfg(not(any(feature = "tls-ring", feature = "tls-aws-lc-rs")))]
{
if CryptoProvider::get_default().is_none() {
assert!(matches!(default_provider(), Err(Error::Tls(_))));
}
}
}
#[cfg(all(
feature = "tokio",
any(feature = "tls-ring", feature = "tls-aws-lc-rs")
))]
#[test]
fn every_policy_builds_a_usable_configuration() {
assert!(TlsClient::new(&TlsPolicy::Web).is_ok());
assert!(TlsClient::new(&TlsPolicy::LanPairingOnly).is_ok());
let client = TlsClient::new(&TlsPolicy::LanPairingOnly).unwrap();
assert!(client.captured().is_none());
assert!(client.binding().is_none());
assert!(client.identity_is_stable());
}
#[cfg(all(
feature = "tokio",
not(any(feature = "tls-ring", feature = "tls-aws-lc-rs"))
))]
#[test]
fn with_no_provider_every_policy_fails_the_same_readable_way() {
if CryptoProvider::get_default().is_some() {
return; }
for policy in [TlsPolicy::Web, TlsPolicy::LanPairingOnly] {
match TlsClient::new(&policy) {
Err(Error::Tls(message)) => {
assert!(message.contains("tls-ring"), "unhelpful message: {message}");
assert!(message.contains("install_default"), "{message}");
}
other => panic!("expected a readable TLS error, got {:?}", other.is_ok()),
}
}
}
#[cfg(feature = "tokio")]
#[test]
fn a_changed_leaf_mid_attempt_is_noticed() {
let capture = Capture::default();
let one = CertificateDer::from(alloc::vec![1u8; 32]);
let two = CertificateDer::from(alloc::vec![2u8; 32]);
let identity = |der: &CertificateDer<'static>| CapturedIdentity {
leaf: Fingerprint::of(der),
root: Fingerprint::of(der),
chain: alloc::vec![der.clone()],
};
capture.set(identity(&one));
assert!(!capture.changed());
capture.set(identity(&one));
assert!(!capture.changed(), "the same certificate twice is fine");
capture.set(identity(&two));
assert!(capture.changed(), "a different one is not");
}
#[cfg(feature = "connect-server")]
#[test]
fn a_lan_endpoint_can_mint_the_certificate_the_specification_expects() {
let endpoint =
SelfSignedEndpoint::generate(["EVSE1038.local".to_string(), "127.0.0.1".to_string()])
.expect("a self-signed CA and leaf");
assert_eq!(endpoint.chain.len(), 2);
assert_eq!(endpoint.chain[1], endpoint.ca);
assert_eq!(endpoint.leaf, Fingerprint::of(&endpoint.chain[0]));
assert_ne!(endpoint.leaf, Fingerprint::of(&endpoint.ca));
assert!(endpoint.server_config().is_ok());
#[cfg(feature = "tokio")]
assert!(TlsClient::new(&TlsPolicy::Pinned(Fingerprint::of(&endpoint.ca))).is_ok());
}
#[cfg(feature = "connect-server")]
#[test]
fn a_certificate_needs_a_name() {
assert!(SelfSignedEndpoint::generate([]).is_err());
}
}