1use alloc::string::String;
46use alloc::sync::Arc;
47#[cfg(feature = "tokio")]
50use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
51use rustls::crypto::CryptoProvider;
52#[cfg(feature = "tokio")]
53use rustls::crypto::{verify_tls12_signature, verify_tls13_signature};
54use rustls::pki_types::CertificateDer;
55#[cfg(feature = "tokio")]
56use rustls::pki_types::{ServerName, UnixTime};
57#[cfg(feature = "tokio")]
58use rustls::{DigitallySignedStruct, Error as TlsError, RootCertStore, SignatureScheme};
59
60use super::proto::HmacBinding;
61
62#[derive(Clone, Copy, PartialEq, Eq, Hash)]
69pub struct Fingerprint([u8; 32]);
70
71impl Fingerprint {
72 #[must_use]
74 pub fn of(der: &CertificateDer<'_>) -> Self {
75 use sha2::Digest as _;
76 let digest = sha2::Sha256::digest(der.as_ref());
77 let mut bytes = [0u8; 32];
78 bytes.copy_from_slice(&digest);
79 Self(bytes)
80 }
81
82 pub fn parse(hex: &str) -> Result<Self, Error> {
84 match HmacBinding::from_hex_fingerprint(hex)? {
85 HmacBinding::LeafFingerprint(bytes) => {
86 let mut out = [0u8; 32];
87 if bytes.len() != 32 {
88 return Err(Error::Fingerprint);
89 }
90 out.copy_from_slice(&bytes);
91 Ok(Self(out))
92 }
93 HmacBinding::DomainName(_) => Err(Error::Fingerprint),
94 }
95 }
96
97 #[must_use]
100 pub const fn from_bytes(bytes: [u8; 32]) -> Self {
101 Self(bytes)
102 }
103
104 #[must_use]
106 pub const fn as_bytes(&self) -> &[u8; 32] {
107 &self.0
108 }
109
110 #[must_use]
116 pub fn to_hex(&self) -> String {
117 use core::fmt::Write as _;
118 let mut out = String::with_capacity(64);
119 for b in &self.0 {
120 let _ = write!(out, "{b:02x}");
122 }
123 out
124 }
125
126 #[must_use]
128 pub fn binding(&self) -> HmacBinding {
129 HmacBinding::LeafFingerprint(self.0.to_vec())
130 }
131
132 #[must_use]
137 pub fn matches(&self, other: &Self) -> bool {
138 use subtle::ConstantTimeEq as _;
139 self.0.ct_eq(&other.0).into()
140 }
141}
142
143impl core::fmt::Debug for Fingerprint {
144 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
145 write!(f, "Fingerprint({})", self.to_hex())
146 }
147}
148
149impl core::fmt::Display for Fingerprint {
150 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
151 f.write_str(&self.to_hex())
152 }
153}
154
155#[cfg(feature = "tokio")]
156#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
157#[derive(Debug, Clone)]
159pub struct CapturedIdentity {
160 pub leaf: Fingerprint,
162 pub root: Fingerprint,
177 pub chain: Vec<CertificateDer<'static>>,
179}
180
181#[cfg(feature = "tokio")]
182#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
183#[derive(Debug, Clone)]
185pub enum TlsPolicy {
186 Web,
193 Pinned(Fingerprint),
196 LanPairingOnly,
207}
208
209#[cfg(feature = "tokio")]
210impl TlsPolicy {
211 #[must_use]
213 pub const fn authenticates(&self) -> bool {
214 !matches!(self, TlsPolicy::LanPairingOnly)
215 }
216}
217
218#[cfg(feature = "tokio")]
219#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
220#[derive(Debug, Clone)]
225pub struct TlsClient {
226 config: Arc<rustls::ClientConfig>,
227 captured: Arc<Capture>,
228}
229
230#[cfg(feature = "tokio")]
231impl TlsClient {
232 pub fn new(policy: &TlsPolicy) -> Result<Self, Error> {
234 let provider = default_provider()?;
235 let captured = Arc::new(Capture::default());
236
237 let builder = rustls::ClientConfig::builder_with_provider(provider.clone())
238 .with_safe_default_protocol_versions()
239 .map_err(|e| Error::Tls(e.to_string()))?;
240
241 let config = match policy {
242 TlsPolicy::Web => {
243 let inner = rustls_platform_verifier::Verifier::new(provider)
244 .map_err(|e| Error::Tls(e.to_string()))?;
245 builder
246 .dangerous()
247 .with_custom_certificate_verifier(Arc::new(Recording {
248 inner: Verifier::Real(Arc::new(inner)),
249 captured: captured.clone(),
250 }))
251 .with_no_client_auth()
252 }
253 TlsPolicy::Pinned(pin) => builder
254 .dangerous()
255 .with_custom_certificate_verifier(Arc::new(Recording {
256 inner: Verifier::Pinned {
257 pin: *pin,
258 provider,
259 },
260 captured: captured.clone(),
261 }))
262 .with_no_client_auth(),
263 TlsPolicy::LanPairingOnly => builder
264 .dangerous()
265 .with_custom_certificate_verifier(Arc::new(Recording {
266 inner: Verifier::AcceptAnything(provider),
267 captured: captured.clone(),
268 }))
269 .with_no_client_auth(),
270 };
271
272 Ok(Self {
273 config: Arc::new(config),
274 captured,
275 })
276 }
277
278 #[must_use]
280 pub fn config(&self) -> Arc<rustls::ClientConfig> {
281 self.config.clone()
282 }
283
284 #[must_use]
286 pub fn captured(&self) -> Option<CapturedIdentity> {
287 self.captured.get()
288 }
289
290 #[must_use]
296 pub fn binding(&self) -> Option<HmacBinding> {
297 self.captured.get().map(|c| c.leaf.binding())
298 }
299
300 #[must_use]
307 pub fn identity_is_stable(&self) -> bool {
308 !self.captured.changed()
309 }
310}
311
312#[cfg(feature = "tokio")]
313#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
314#[derive(Debug, Default)]
315struct Capture {
316 inner: std::sync::Mutex<Option<CapturedIdentity>>,
317 changed: core::sync::atomic::AtomicBool,
318}
319
320#[cfg(feature = "tokio")]
321impl Capture {
322 fn set(&self, identity: CapturedIdentity) {
323 let Ok(mut slot) = self.inner.lock() else {
324 self.changed
327 .store(true, core::sync::atomic::Ordering::Relaxed);
328 return;
329 };
330 if let Some(previous) = slot.as_ref()
331 && !previous.leaf.matches(&identity.leaf)
332 {
333 self.changed
334 .store(true, core::sync::atomic::Ordering::Relaxed);
335 }
336 *slot = Some(identity);
337 }
338
339 fn get(&self) -> Option<CapturedIdentity> {
340 self.inner.lock().ok()?.clone()
341 }
342
343 fn changed(&self) -> bool {
344 self.changed.load(core::sync::atomic::Ordering::Relaxed)
345 }
346}
347
348#[cfg(feature = "tokio")]
349#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
350#[derive(Debug)]
351enum Verifier {
352 Real(Arc<dyn ServerCertVerifier>),
353 Pinned {
354 pin: Fingerprint,
355 provider: Arc<CryptoProvider>,
356 },
357 AcceptAnything(Arc<CryptoProvider>),
358}
359
360#[cfg(feature = "tokio")]
361impl Verifier {
362 fn provider(&self) -> Option<&Arc<CryptoProvider>> {
365 match self {
366 Verifier::Real(_) => None,
367 Verifier::Pinned { provider, .. } | Verifier::AcceptAnything(provider) => {
368 Some(provider)
369 }
370 }
371 }
372}
373
374#[cfg(feature = "tokio")]
377fn verify_pinned(
378 pin: &Fingerprint,
379 provider: &Arc<CryptoProvider>,
380 end_entity: &CertificateDer<'_>,
381 intermediates: &[CertificateDer<'_>],
382 server_name: &ServerName<'_>,
383 ocsp_response: &[u8],
384 now: UnixTime,
385) -> Result<ServerCertVerified, TlsError> {
386 if Fingerprint::of(end_entity).matches(pin) {
389 return Ok(ServerCertVerified::assertion());
390 }
391 let Some(anchor) = intermediates
392 .iter()
393 .find(|cert| Fingerprint::of(cert).matches(pin))
394 else {
395 return Err(TlsError::InvalidCertificate(
396 rustls::CertificateError::UnknownIssuer,
397 ));
398 };
399 let mut roots = RootCertStore::empty();
400 roots
401 .add(anchor.clone().into_owned())
402 .map_err(|_| TlsError::InvalidCertificate(rustls::CertificateError::BadEncoding))?;
403 let verifier = rustls::client::WebPkiServerVerifier::builder_with_provider(
404 Arc::new(roots),
405 provider.clone(),
406 )
407 .build()
408 .map_err(|e| TlsError::General(e.to_string()))?;
409 verifier.verify_server_cert(end_entity, intermediates, server_name, ocsp_response, now)
410}
411
412#[cfg(feature = "tokio")]
413#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
414#[derive(Debug)]
416struct Recording {
417 inner: Verifier,
418 captured: Arc<Capture>,
419}
420
421#[cfg(feature = "tokio")]
422impl ServerCertVerifier for Recording {
423 fn verify_server_cert(
424 &self,
425 end_entity: &CertificateDer<'_>,
426 intermediates: &[CertificateDer<'_>],
427 server_name: &ServerName<'_>,
428 ocsp_response: &[u8],
429 now: UnixTime,
430 ) -> Result<ServerCertVerified, TlsError> {
431 let leaf = end_entity.clone().into_owned();
432 let mut chain = alloc::vec![leaf.clone()];
433 chain.extend(intermediates.iter().map(|c| c.clone().into_owned()));
434 self.captured.set(CapturedIdentity {
438 leaf: Fingerprint::of(end_entity),
439 root: Fingerprint::of(chain.last().unwrap_or(&leaf)),
440 chain,
441 });
442
443 match &self.inner {
444 Verifier::Real(inner) => {
445 inner.verify_server_cert(end_entity, intermediates, server_name, ocsp_response, now)
446 }
447 Verifier::Pinned { pin, provider } => verify_pinned(
448 pin,
449 provider,
450 end_entity,
451 intermediates,
452 server_name,
453 ocsp_response,
454 now,
455 ),
456 Verifier::AcceptAnything(_) => Ok(ServerCertVerified::assertion()),
459 }
460 }
461
462 fn verify_tls12_signature(
463 &self,
464 message: &[u8],
465 cert: &CertificateDer<'_>,
466 dss: &DigitallySignedStruct,
467 ) -> Result<HandshakeSignatureValid, TlsError> {
468 match (&self.inner, self.inner.provider()) {
469 (Verifier::Real(inner), _) => inner.verify_tls12_signature(message, cert, dss),
470 (_, Some(provider)) => verify_tls12_signature(
473 message,
474 cert,
475 dss,
476 &provider.signature_verification_algorithms,
477 ),
478 (_, None) => Err(TlsError::General("no signature verifier".into())),
479 }
480 }
481
482 fn verify_tls13_signature(
483 &self,
484 message: &[u8],
485 cert: &CertificateDer<'_>,
486 dss: &DigitallySignedStruct,
487 ) -> Result<HandshakeSignatureValid, TlsError> {
488 match (&self.inner, self.inner.provider()) {
489 (Verifier::Real(inner), _) => inner.verify_tls13_signature(message, cert, dss),
490 (_, Some(provider)) => verify_tls13_signature(
493 message,
494 cert,
495 dss,
496 &provider.signature_verification_algorithms,
497 ),
498 (_, None) => Err(TlsError::General("no signature verifier".into())),
499 }
500 }
501
502 fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
503 match (&self.inner, self.inner.provider()) {
504 (Verifier::Real(inner), _) => inner.supported_verify_schemes(),
505 (_, Some(provider)) => provider
506 .signature_verification_algorithms
507 .supported_schemes(),
508 (_, None) => Vec::new(),
509 }
510 }
511}
512
513pub fn default_provider() -> Result<Arc<CryptoProvider>, Error> {
519 if let Some(provider) = CryptoProvider::get_default() {
524 return Ok(provider.clone());
525 }
526
527 #[cfg(feature = "tls-aws-lc-rs")]
530 let bundled = Some(rustls::crypto::aws_lc_rs::default_provider());
531 #[cfg(all(feature = "tls-ring", not(feature = "tls-aws-lc-rs")))]
532 let bundled = Some(rustls::crypto::ring::default_provider());
533 #[cfg(not(any(feature = "tls-ring", feature = "tls-aws-lc-rs")))]
534 let bundled: Option<CryptoProvider> = None;
535
536 let Some(provider) = bundled else {
537 return Err(Error::Tls(
538 "no TLS crypto provider: build with the `tls-ring` or `tls-aws-lc-rs` feature, \
539 or install one yourself with rustls::crypto::CryptoProvider::install_default"
540 .to_string(),
541 ));
542 };
543 let _ = provider.install_default();
545 CryptoProvider::get_default()
546 .cloned()
547 .ok_or_else(|| Error::Tls("no crypto provider could be installed".to_string()))
548}
549
550#[cfg(all(
559 feature = "connect-server",
560 any(feature = "tls-ring", feature = "tls-aws-lc-rs")
561))]
562#[cfg_attr(
563 docsrs,
564 doc(cfg(all(
565 feature = "connect-server",
566 any(feature = "tls-ring", feature = "tls-aws-lc-rs")
567 )))
568)]
569#[derive(Debug)]
570pub struct SelfSignedEndpoint {
571 pub ca: CertificateDer<'static>,
573 pub chain: Vec<CertificateDer<'static>>,
575 pub key: rustls::pki_types::PrivateKeyDer<'static>,
577 pub leaf: Fingerprint,
579}
580
581#[cfg(all(
582 feature = "connect-server",
583 any(feature = "tls-ring", feature = "tls-aws-lc-rs")
584))]
585impl SelfSignedEndpoint {
586 pub fn generate(names: impl IntoIterator<Item = String>) -> Result<Self, Error> {
593 use rcgen::{
594 BasicConstraints, CertificateParams, DnType, IsCa, KeyPair, KeyUsagePurpose, SanType,
595 };
596
597 let names: Vec<String> = names.into_iter().collect();
598 let Some(primary) = names.first().cloned() else {
599 return Err(Error::Tls(
600 "a certificate needs at least one name".to_string(),
601 ));
602 };
603
604 let ca_key = KeyPair::generate().map_err(|e| Error::Tls(e.to_string()))?;
605 let mut ca_params = CertificateParams::default();
606 ca_params.is_ca = IsCa::Ca(BasicConstraints::Constrained(0));
607 ca_params.key_usages = alloc::vec![
608 KeyUsagePurpose::KeyCertSign,
609 KeyUsagePurpose::CrlSign,
610 KeyUsagePurpose::DigitalSignature,
611 ];
612 ca_params
613 .distinguished_name
614 .push(DnType::CommonName, "s2-kit LAN endpoint CA");
615 let ca_cert = ca_params
616 .self_signed(&ca_key)
617 .map_err(|e| Error::Tls(e.to_string()))?;
618
619 let leaf_key = KeyPair::generate().map_err(|e| Error::Tls(e.to_string()))?;
620 let mut leaf_params = CertificateParams::default();
621 leaf_params
622 .distinguished_name
623 .push(DnType::CommonName, primary);
624 for name in &names {
625 let san = match name.parse::<core::net::IpAddr>() {
626 Ok(ip) => SanType::IpAddress(ip),
627 Err(_) => SanType::DnsName(
628 name.clone()
629 .try_into()
630 .map_err(|_| Error::Tls(alloc::format!("{name} is not a usable name")))?,
631 ),
632 };
633 leaf_params.subject_alt_names.push(san);
634 }
635 let issuer = rcgen::Issuer::new(ca_params, ca_key);
636 let leaf_cert = leaf_params
637 .signed_by(&leaf_key, &issuer)
638 .map_err(|e| Error::Tls(e.to_string()))?;
639
640 let leaf_der = leaf_cert.der().clone();
641 let ca_der = ca_cert.der().clone();
642 Ok(Self {
643 leaf: Fingerprint::of(&leaf_der),
644 chain: alloc::vec![leaf_der, ca_der.clone()],
645 ca: ca_der,
646 key: rustls::pki_types::PrivateKeyDer::Pkcs8(leaf_key.serialize_der().into()),
647 })
648 }
649
650 pub fn server_config(&self) -> Result<Arc<rustls::ServerConfig>, Error> {
652 let provider = default_provider()?;
653 let config = rustls::ServerConfig::builder_with_provider(provider)
654 .with_safe_default_protocol_versions()
655 .map_err(|e| Error::Tls(e.to_string()))?
656 .with_no_client_auth()
657 .with_single_cert(self.chain.clone(), self.key.clone_key())
658 .map_err(|e| Error::Tls(e.to_string()))?;
659 Ok(Arc::new(config))
660 }
661}
662
663#[derive(Debug, thiserror::Error)]
665#[non_exhaustive]
666pub enum Error {
667 #[error("not a SHA-256 certificate fingerprint")]
669 Fingerprint,
670 #[error("TLS: {0}")]
672 Tls(String),
673}
674
675impl From<super::proto::ConnectError> for Error {
676 fn from(_: super::proto::ConnectError) -> Self {
677 Error::Fingerprint
678 }
679}
680
681use alloc::string::ToString as _;
682
683#[cfg(test)]
684mod tests {
685 use super::*;
686
687 #[test]
688 fn a_fingerprint_round_trips_through_the_form_tools_print() {
689 let der = CertificateDer::from(alloc::vec![1u8, 2, 3, 4]);
690 let fp = Fingerprint::of(&der);
691 let text = fp.to_hex();
692 assert_eq!(text.len(), 64, "32 bytes, plain hexadecimal");
693 assert_eq!(text, text.to_lowercase());
694 assert_eq!(Fingerprint::parse(&text).unwrap(), fp);
695 let colons = text
697 .as_bytes()
698 .chunks(2)
699 .map(|pair| core::str::from_utf8(pair).unwrap().to_uppercase())
700 .collect::<Vec<_>>()
701 .join(":");
702 assert_eq!(Fingerprint::parse(&colons).unwrap(), fp);
703 assert!(fp.matches(&Fingerprint::of(&der)));
704 }
705
706 #[test]
707 fn a_fingerprint_is_the_binding_the_hmac_takes() {
708 let der = CertificateDer::from(alloc::vec![9u8; 64]);
709 let fp = Fingerprint::of(&der);
710 let HmacBinding::LeafFingerprint(bytes) = fp.binding() else {
711 panic!("a leaf fingerprint binds as a leaf fingerprint");
712 };
713 assert_eq!(bytes.len(), 32);
716 assert_eq!(&bytes[..], fp.as_bytes());
717 }
718
719 #[test]
720 fn something_that_is_not_a_fingerprint_is_refused() {
721 assert!(Fingerprint::parse("").is_err());
722 assert!(Fingerprint::parse("AA:BB").is_err());
723 assert!(Fingerprint::parse("not hexadecimal at all").is_err());
724 assert!(Fingerprint::parse(&"zz".repeat(32)).is_err());
726 }
727
728 #[cfg(feature = "tokio")]
729 #[test]
730 fn only_one_policy_declines_to_authenticate_and_it_says_so() {
731 assert!(TlsPolicy::Web.authenticates());
732 assert!(!TlsPolicy::LanPairingOnly.authenticates());
733 let der = CertificateDer::from(alloc::vec![1u8, 2, 3]);
734 assert!(TlsPolicy::Pinned(Fingerprint::of(&der)).authenticates());
735 }
736
737 #[cfg(feature = "tokio")]
741 #[test]
742 fn a_provider_is_chosen_explicitly_and_never_by_the_library() {
743 #[cfg(any(feature = "tls-ring", feature = "tls-aws-lc-rs"))]
747 {
748 let first = default_provider().expect("a bundled provider");
749 let second = default_provider().expect("the same provider again");
752 assert!(Arc::ptr_eq(&first, &second));
753 assert!(
754 CryptoProvider::get_default().is_some(),
755 "and it is the process-wide default afterwards"
756 );
757 }
758 #[cfg(not(any(feature = "tls-ring", feature = "tls-aws-lc-rs")))]
760 {
761 if CryptoProvider::get_default().is_none() {
762 assert!(matches!(default_provider(), Err(Error::Tls(_))));
763 }
764 }
765 }
766
767 #[cfg(all(
768 feature = "tokio",
769 any(feature = "tls-ring", feature = "tls-aws-lc-rs")
770 ))]
771 #[test]
772 fn every_policy_builds_a_usable_configuration() {
773 assert!(TlsClient::new(&TlsPolicy::Web).is_ok());
774 assert!(TlsClient::new(&TlsPolicy::LanPairingOnly).is_ok());
775 let client = TlsClient::new(&TlsPolicy::LanPairingOnly).unwrap();
778 assert!(client.captured().is_none());
779 assert!(client.binding().is_none());
780 assert!(client.identity_is_stable());
781 }
782
783 #[cfg(all(
787 feature = "tokio",
788 not(any(feature = "tls-ring", feature = "tls-aws-lc-rs"))
789 ))]
790 #[test]
791 fn with_no_provider_every_policy_fails_the_same_readable_way() {
792 if CryptoProvider::get_default().is_some() {
793 return; }
795 for policy in [TlsPolicy::Web, TlsPolicy::LanPairingOnly] {
796 match TlsClient::new(&policy) {
797 Err(Error::Tls(message)) => {
798 assert!(message.contains("tls-ring"), "unhelpful message: {message}");
799 assert!(message.contains("install_default"), "{message}");
800 }
801 other => panic!("expected a readable TLS error, got {:?}", other.is_ok()),
802 }
803 }
804 }
805
806 #[cfg(feature = "tokio")]
807 #[test]
808 fn a_changed_leaf_mid_attempt_is_noticed() {
809 let capture = Capture::default();
810 let one = CertificateDer::from(alloc::vec![1u8; 32]);
811 let two = CertificateDer::from(alloc::vec![2u8; 32]);
812 let identity = |der: &CertificateDer<'static>| CapturedIdentity {
813 leaf: Fingerprint::of(der),
814 root: Fingerprint::of(der),
815 chain: alloc::vec![der.clone()],
816 };
817 capture.set(identity(&one));
818 assert!(!capture.changed());
819 capture.set(identity(&one));
820 assert!(!capture.changed(), "the same certificate twice is fine");
821 capture.set(identity(&two));
822 assert!(capture.changed(), "a different one is not");
823 }
824
825 #[cfg(feature = "connect-server")]
826 #[test]
827 fn a_lan_endpoint_can_mint_the_certificate_the_specification_expects() {
828 let endpoint =
829 SelfSignedEndpoint::generate(["EVSE1038.local".to_string(), "127.0.0.1".to_string()])
830 .expect("a self-signed CA and leaf");
831
832 assert_eq!(endpoint.chain.len(), 2);
834 assert_eq!(endpoint.chain[1], endpoint.ca);
835 assert_eq!(endpoint.leaf, Fingerprint::of(&endpoint.chain[0]));
837 assert_ne!(endpoint.leaf, Fingerprint::of(&endpoint.ca));
838 assert!(endpoint.server_config().is_ok());
839
840 #[cfg(feature = "tokio")]
842 assert!(TlsClient::new(&TlsPolicy::Pinned(Fingerprint::of(&endpoint.ca))).is_ok());
843 }
844
845 #[cfg(feature = "connect-server")]
846 #[test]
847 fn a_certificate_needs_a_name() {
848 assert!(SelfSignedEndpoint::generate([]).is_err());
849 }
850}