1use std::sync::Arc;
2use std::time::SystemTime;
3
4use ring::digest::Digest;
5
6use crate::tls::rustls::anchors::{OwnedTrustAnchor, RootCertStore};
7use crate::tls::rustls::client::client_conn::ServerName;
8use crate::tls::rustls::error::Error;
9use crate::tls::rustls::key::Certificate;
10use crate::tls::rustls::msgs::enums::SignatureScheme;
11use crate::tls::rustls::msgs::handshake::{DigitallySignedStruct, DistinguishedNames};
12
13type SignatureAlgorithms = &'static [&'static webpki::SignatureAlgorithm];
14
15static SUPPORTED_SIG_ALGS: SignatureAlgorithms = &[
18 &webpki::ECDSA_P256_SHA256,
19 &webpki::ECDSA_P256_SHA384,
20 &webpki::ECDSA_P384_SHA256,
21 &webpki::ECDSA_P384_SHA384,
22 &webpki::ED25519,
23 &webpki::RSA_PSS_2048_8192_SHA256_LEGACY_KEY,
24 &webpki::RSA_PSS_2048_8192_SHA384_LEGACY_KEY,
25 &webpki::RSA_PSS_2048_8192_SHA512_LEGACY_KEY,
26 &webpki::RSA_PKCS1_2048_8192_SHA256,
27 &webpki::RSA_PKCS1_2048_8192_SHA384,
28 &webpki::RSA_PKCS1_2048_8192_SHA512,
29 &webpki::RSA_PKCS1_3072_8192_SHA384,
30];
31
32#[derive(Debug)]
44pub struct HandshakeSignatureValid(());
45
46impl HandshakeSignatureValid {
47 pub fn assertion() -> Self {
49 Self(())
50 }
51}
52
53#[derive(Debug)]
54pub struct FinishedMessageVerified(());
55
56impl FinishedMessageVerified {
57 pub fn assertion() -> Self {
58 Self(())
59 }
60}
61
62#[allow(unreachable_pub)]
64#[derive(Debug)]
65pub struct ServerCertVerified(());
66
67#[allow(unreachable_pub)]
68impl ServerCertVerified {
69 pub fn assertion() -> Self {
71 Self(())
72 }
73}
74
75#[derive(Debug)]
77pub struct ClientCertVerified(());
78
79impl ClientCertVerified {
80 pub fn assertion() -> Self {
82 Self(())
83 }
84}
85
86#[allow(unreachable_pub)]
89pub trait ServerCertVerifier: Send + Sync {
90 fn verify_server_cert(
100 &self,
101 end_entity: &Certificate,
102 intermediates: &[Certificate],
103 server_name: &ServerName,
104 scts: &mut dyn Iterator<Item = &[u8]>,
105 ocsp_response: &[u8],
106 now: SystemTime,
107 ) -> Result<ServerCertVerified, Error>;
108
109 fn verify_tls12_signature(
129 &self,
130 message: &[u8],
131 cert: &Certificate,
132 dss: &DigitallySignedStruct,
133 ) -> Result<HandshakeSignatureValid, Error> {
134 verify_signed_struct(message, cert, dss)
135 }
136
137 fn verify_tls13_signature(
149 &self,
150 message: &[u8],
151 cert: &Certificate,
152 dss: &DigitallySignedStruct,
153 ) -> Result<HandshakeSignatureValid, Error> {
154 verify_tls13(message, cert, dss)
155 }
156
157 fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
165 WebPkiVerifier::verification_schemes()
166 }
167
168 fn request_scts(&self) -> bool {
175 true
176 }
177}
178
179#[derive(Clone, Debug, PartialEq)]
181pub struct DnsName(pub webpki::DnsName);
182
183impl AsRef<str> for DnsName {
184 fn as_ref(&self) -> &str {
185 AsRef::<str>::as_ref(&self.0)
186 }
187}
188
189#[allow(unreachable_pub)]
191pub trait ClientCertVerifier: Send + Sync {
192 fn offer_client_auth(&self) -> bool {
195 true
196 }
197
198 fn client_auth_mandatory(&self) -> Option<bool> {
202 Some(self.offer_client_auth())
203 }
204
205 fn client_auth_root_subjects(&self) -> Option<DistinguishedNames>;
211
212 fn verify_client_cert(
219 &self,
220 end_entity: &Certificate,
221 intermediates: &[Certificate],
222 now: SystemTime,
223 ) -> Result<ClientCertVerified, Error>;
224
225 fn verify_tls12_signature(
245 &self,
246 message: &[u8],
247 cert: &Certificate,
248 dss: &DigitallySignedStruct,
249 ) -> Result<HandshakeSignatureValid, Error> {
250 verify_signed_struct(message, cert, dss)
251 }
252
253 fn verify_tls13_signature(
265 &self,
266 message: &[u8],
267 cert: &Certificate,
268 dss: &DigitallySignedStruct,
269 ) -> Result<HandshakeSignatureValid, Error> {
270 verify_tls13(message, cert, dss)
271 }
272
273 fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
281 WebPkiVerifier::verification_schemes()
282 }
283}
284
285impl ServerCertVerifier for WebPkiVerifier {
286 fn verify_server_cert(
291 &self,
292 end_entity: &Certificate,
293 intermediates: &[Certificate],
294 server_name: &ServerName,
295 scts: &mut dyn Iterator<Item = &[u8]>,
296 ocsp_response: &[u8],
297 now: SystemTime,
298 ) -> Result<ServerCertVerified, Error> {
299 let (cert, chain, trustroots) = prepare(end_entity, intermediates, &self.roots)?;
300 let webpki_now = webpki::Time::try_from(now).map_err(|_| Error::FailedToGetCurrentTime)?;
301
302 let ServerName::DnsName(dns_name) = server_name;
303
304 let cert = cert
305 .verify_is_valid_tls_server_cert(
306 SUPPORTED_SIG_ALGS,
307 &webpki::TlsServerTrustAnchors(&trustroots),
308 &chain,
309 webpki_now,
310 )
311 .map_err(pki_error)
312 .map(|_| cert)?;
313
314 if let Some(policy) = &self.ct_policy {
315 policy.verify(end_entity, now, scts)?;
316 }
317
318 if !ocsp_response.is_empty() {
319 log::trace!("Unvalidated OCSP response: {:?}", ocsp_response.to_vec());
320 }
321
322 cert.verify_is_valid_for_dns_name(dns_name.0.as_ref())
323 .map_err(pki_error)
324 .map(|_| ServerCertVerified::assertion())
325 }
326}
327
328#[allow(unreachable_pub)]
330pub struct WebPkiVerifier {
331 roots: RootCertStore,
332 ct_policy: Option<CertificateTransparencyPolicy>,
333}
334
335#[allow(unreachable_pub)]
336impl WebPkiVerifier {
337 pub fn new(roots: RootCertStore, ct_policy: Option<CertificateTransparencyPolicy>) -> Self {
345 Self { roots, ct_policy }
346 }
347
348 pub fn verification_schemes() -> Vec<SignatureScheme> {
351 vec![
352 SignatureScheme::ECDSA_NISTP384_SHA384,
353 SignatureScheme::ECDSA_NISTP256_SHA256,
354 SignatureScheme::ED25519,
355 SignatureScheme::RSA_PSS_SHA512,
356 SignatureScheme::RSA_PSS_SHA384,
357 SignatureScheme::RSA_PSS_SHA256,
358 SignatureScheme::RSA_PKCS1_SHA512,
359 SignatureScheme::RSA_PKCS1_SHA384,
360 SignatureScheme::RSA_PKCS1_SHA256,
361 ]
362 }
363}
364
365#[allow(unreachable_pub)]
373pub struct CertificateTransparencyPolicy {
374 logs: &'static [&'static sct::Log<'static>],
375 validation_deadline: SystemTime,
376}
377
378impl CertificateTransparencyPolicy {
379 #[allow(unreachable_pub)]
381 pub fn new(
382 logs: &'static [&'static sct::Log<'static>],
383 validation_deadline: SystemTime,
384 ) -> Self {
385 Self {
386 logs,
387 validation_deadline,
388 }
389 }
390
391 fn verify(
392 &self,
393 cert: &Certificate,
394 now: SystemTime,
395 scts: &mut dyn Iterator<Item = &[u8]>,
396 ) -> Result<(), Error> {
397 if self.logs.is_empty() {
398 return Ok(());
399 } else if self.validation_deadline.duration_since(now).is_err() {
400 log::warn!("certificate transparency logs have expired, validation disabled");
401 return Ok(());
402 }
403
404 let now = unix_time_millis(now)?;
405 let mut last_sct_error = None;
406 for sct in scts {
407 match sct::verify_sct(&cert.0, sct, now, self.logs) {
408 Ok(index) => {
409 log::debug!(
410 "Valid SCT signed by {} on {}",
411 self.logs[index].operated_by,
412 self.logs[index].description
413 );
414 return Ok(());
415 }
416 Err(e) => {
417 if e.should_be_fatal() {
418 return Err(Error::InvalidSct(e));
419 }
420 log::debug!("SCT ignored because {:?}", e);
421 last_sct_error = Some(e);
422 }
423 }
424 }
425
426 if let Some(last_sct_error) = last_sct_error {
429 log::warn!("No valid SCTs provided");
430 return Err(Error::InvalidSct(last_sct_error));
431 }
432
433 Ok(())
434 }
435}
436
437type CertChainAndRoots<'a, 'b> = (
438 webpki::EndEntityCert<'a>,
439 Vec<&'a [u8]>,
440 Vec<webpki::TrustAnchor<'b>>,
441);
442
443fn prepare<'a, 'b>(
444 end_entity: &'a Certificate,
445 intermediates: &'a [Certificate],
446 roots: &'b RootCertStore,
447) -> Result<CertChainAndRoots<'a, 'b>, Error> {
448 let cert = webpki::EndEntityCert::try_from(end_entity.0.as_ref()).map_err(pki_error)?;
450
451 let intermediates: Vec<&'a [u8]> = intermediates.iter().map(|cert| cert.0.as_ref()).collect();
452
453 let trustroots: Vec<webpki::TrustAnchor> = roots
454 .roots
455 .iter()
456 .map(OwnedTrustAnchor::to_trust_anchor)
457 .collect();
458
459 Ok((cert, intermediates, trustroots))
460}
461
462pub struct AllowAnyAuthenticatedClient {
465 roots: RootCertStore,
466}
467
468impl AllowAnyAuthenticatedClient {
469 pub fn new(roots: RootCertStore) -> Arc<dyn ClientCertVerifier> {
473 Arc::new(Self { roots })
474 }
475}
476
477impl ClientCertVerifier for AllowAnyAuthenticatedClient {
478 fn offer_client_auth(&self) -> bool {
479 true
480 }
481
482 fn client_auth_root_subjects(&self) -> Option<DistinguishedNames> {
483 Some(self.roots.subjects())
484 }
485
486 fn verify_client_cert(
487 &self,
488 end_entity: &Certificate,
489 intermediates: &[Certificate],
490 now: SystemTime,
491 ) -> Result<ClientCertVerified, Error> {
492 let (cert, chain, trustroots) = prepare(end_entity, intermediates, &self.roots)?;
493 let now = webpki::Time::try_from(now).map_err(|_| Error::FailedToGetCurrentTime)?;
494 cert.verify_is_valid_tls_client_cert(
495 SUPPORTED_SIG_ALGS,
496 &webpki::TlsClientTrustAnchors(&trustroots),
497 &chain,
498 now,
499 )
500 .map_err(pki_error)
501 .map(|_| ClientCertVerified::assertion())
502 }
503}
504
505pub struct AllowAnyAnonymousOrAuthenticatedClient {
512 inner: AllowAnyAuthenticatedClient,
513}
514
515impl AllowAnyAnonymousOrAuthenticatedClient {
516 pub fn new(roots: RootCertStore) -> Arc<dyn ClientCertVerifier> {
520 Arc::new(Self {
521 inner: AllowAnyAuthenticatedClient { roots },
522 })
523 }
524}
525
526impl ClientCertVerifier for AllowAnyAnonymousOrAuthenticatedClient {
527 fn offer_client_auth(&self) -> bool {
528 self.inner.offer_client_auth()
529 }
530
531 fn client_auth_mandatory(&self) -> Option<bool> {
532 Some(false)
533 }
534
535 fn client_auth_root_subjects(&self) -> Option<DistinguishedNames> {
536 self.inner.client_auth_root_subjects()
537 }
538
539 fn verify_client_cert(
540 &self,
541 end_entity: &Certificate,
542 intermediates: &[Certificate],
543 now: SystemTime,
544 ) -> Result<ClientCertVerified, Error> {
545 self.inner
546 .verify_client_cert(end_entity, intermediates, now)
547 }
548}
549
550fn pki_error(error: webpki::Error) -> Error {
551 use webpki::Error::*;
552 match error {
553 BadDer | BadDerTime => Error::InvalidCertificateEncoding,
554 InvalidSignatureForPublicKey => Error::InvalidCertificateSignature,
555 UnsupportedSignatureAlgorithm | UnsupportedSignatureAlgorithmForPublicKey => {
556 Error::InvalidCertificateSignatureType
557 }
558 e => Error::InvalidCertificateData(format!("invalid peer certificate: {}", e)),
559 }
560}
561
562pub struct NoClientAuth;
564
565impl NoClientAuth {
566 pub fn new() -> Arc<dyn ClientCertVerifier> {
568 Arc::new(NoClientAuth)
569 }
570}
571
572impl ClientCertVerifier for NoClientAuth {
573 fn offer_client_auth(&self) -> bool {
574 false
575 }
576
577 fn client_auth_root_subjects(&self) -> Option<DistinguishedNames> {
578 unimplemented!();
579 }
580
581 fn verify_client_cert(
582 &self,
583 _end_entity: &Certificate,
584 _intermediates: &[Certificate],
585 _now: SystemTime,
586 ) -> Result<ClientCertVerified, Error> {
587 unimplemented!();
588 }
589}
590
591static ECDSA_SHA256: SignatureAlgorithms =
592 &[&webpki::ECDSA_P256_SHA256, &webpki::ECDSA_P384_SHA256];
593
594static ECDSA_SHA384: SignatureAlgorithms =
595 &[&webpki::ECDSA_P256_SHA384, &webpki::ECDSA_P384_SHA384];
596
597static ED25519: SignatureAlgorithms = &[&webpki::ED25519];
598
599static RSA_SHA256: SignatureAlgorithms = &[&webpki::RSA_PKCS1_2048_8192_SHA256];
600static RSA_SHA384: SignatureAlgorithms = &[&webpki::RSA_PKCS1_2048_8192_SHA384];
601static RSA_SHA512: SignatureAlgorithms = &[&webpki::RSA_PKCS1_2048_8192_SHA512];
602static RSA_PSS_SHA256: SignatureAlgorithms = &[&webpki::RSA_PSS_2048_8192_SHA256_LEGACY_KEY];
603static RSA_PSS_SHA384: SignatureAlgorithms = &[&webpki::RSA_PSS_2048_8192_SHA384_LEGACY_KEY];
604static RSA_PSS_SHA512: SignatureAlgorithms = &[&webpki::RSA_PSS_2048_8192_SHA512_LEGACY_KEY];
605
606fn convert_scheme(scheme: SignatureScheme) -> Result<SignatureAlgorithms, Error> {
607 match scheme {
608 SignatureScheme::ECDSA_NISTP256_SHA256 => Ok(ECDSA_SHA256),
610 SignatureScheme::ECDSA_NISTP384_SHA384 => Ok(ECDSA_SHA384),
611
612 SignatureScheme::ED25519 => Ok(ED25519),
613
614 SignatureScheme::RSA_PKCS1_SHA256 => Ok(RSA_SHA256),
615 SignatureScheme::RSA_PKCS1_SHA384 => Ok(RSA_SHA384),
616 SignatureScheme::RSA_PKCS1_SHA512 => Ok(RSA_SHA512),
617
618 SignatureScheme::RSA_PSS_SHA256 => Ok(RSA_PSS_SHA256),
619 SignatureScheme::RSA_PSS_SHA384 => Ok(RSA_PSS_SHA384),
620 SignatureScheme::RSA_PSS_SHA512 => Ok(RSA_PSS_SHA512),
621
622 _ => {
623 let error_msg = format!("received unadvertised sig scheme {:?}", scheme);
624 Err(Error::PeerMisbehavedError(error_msg))
625 }
626 }
627}
628
629fn verify_sig_using_any_alg(
630 cert: &webpki::EndEntityCert,
631 algs: SignatureAlgorithms,
632 message: &[u8],
633 sig: &[u8],
634) -> Result<(), webpki::Error> {
635 for alg in algs {
638 match cert.verify_signature(alg, message, sig) {
639 Err(webpki::Error::UnsupportedSignatureAlgorithmForPublicKey) => continue,
640 res => return res,
641 }
642 }
643
644 Err(webpki::Error::UnsupportedSignatureAlgorithmForPublicKey)
645}
646
647fn verify_signed_struct(
648 message: &[u8],
649 cert: &Certificate,
650 dss: &DigitallySignedStruct,
651) -> Result<HandshakeSignatureValid, Error> {
652 let possible_algs = convert_scheme(dss.scheme)?;
653 let cert = webpki::EndEntityCert::try_from(cert.0.as_ref()).map_err(pki_error)?;
654
655 verify_sig_using_any_alg(&cert, possible_algs, message, &dss.sig.0)
656 .map_err(pki_error)
657 .map(|_| HandshakeSignatureValid::assertion())
658}
659
660fn convert_alg_tls13(
661 scheme: SignatureScheme,
662) -> Result<&'static webpki::SignatureAlgorithm, Error> {
663 use crate::tls::rustls::msgs::enums::SignatureScheme::*;
664
665 match scheme {
666 ECDSA_NISTP256_SHA256 => Ok(&webpki::ECDSA_P256_SHA256),
667 ECDSA_NISTP384_SHA384 => Ok(&webpki::ECDSA_P384_SHA384),
668 ED25519 => Ok(&webpki::ED25519),
669 RSA_PSS_SHA256 => Ok(&webpki::RSA_PSS_2048_8192_SHA256_LEGACY_KEY),
670 RSA_PSS_SHA384 => Ok(&webpki::RSA_PSS_2048_8192_SHA384_LEGACY_KEY),
671 RSA_PSS_SHA512 => Ok(&webpki::RSA_PSS_2048_8192_SHA512_LEGACY_KEY),
672 _ => {
673 let error_msg = format!("received unsupported sig scheme {:?}", scheme);
674 Err(Error::PeerMisbehavedError(error_msg))
675 }
676 }
677}
678
679pub fn construct_tls13_client_verify_message(handshake_hash: &Digest) -> Vec<u8> {
681 construct_tls13_verify_message(
682 handshake_hash.as_ref(),
683 b"TLS 1.3, client CertificateVerify\x00",
684 )
685}
686
687pub fn construct_tls13_server_verify_message(handshake_hash: &Digest) -> Vec<u8> {
689 construct_tls13_verify_message(
690 handshake_hash.as_ref(),
691 b"TLS 1.3, server CertificateVerify\x00",
692 )
693}
694
695pub fn construct_tls13_client_verify_message_raw(handshake_hash: &[u8]) -> Vec<u8> {
697 construct_tls13_verify_message(handshake_hash, b"TLS 1.3, client CertificateVerify\x00")
698}
699
700pub fn construct_tls13_server_verify_message_raw(handshake_hash: &[u8]) -> Vec<u8> {
702 construct_tls13_verify_message(handshake_hash, b"TLS 1.3, server CertificateVerify\x00")
703}
704
705fn construct_tls13_verify_message(handshake_hash: &[u8], context_string_with_0: &[u8]) -> Vec<u8> {
706 let mut msg = Vec::new();
707 msg.resize(64, 0x20u8);
708 msg.extend_from_slice(context_string_with_0);
709 msg.extend_from_slice(handshake_hash);
710 msg
711}
712
713fn verify_tls13(
714 msg: &[u8],
715 cert: &Certificate,
716 dss: &DigitallySignedStruct,
717) -> Result<HandshakeSignatureValid, Error> {
718 let alg = convert_alg_tls13(dss.scheme)?;
719
720 let cert = webpki::EndEntityCert::try_from(cert.0.as_ref()).map_err(pki_error)?;
721
722 cert.verify_signature(alg, msg, &dss.sig.0)
723 .map_err(pki_error)
724 .map(|_| HandshakeSignatureValid::assertion())
725}
726
727fn unix_time_millis(now: SystemTime) -> Result<u64, Error> {
728 now.duration_since(std::time::UNIX_EPOCH)
729 .map(|dur| dur.as_secs())
730 .map_err(|_| Error::FailedToGetCurrentTime)
731 .and_then(|secs| secs.checked_mul(1000).ok_or(Error::FailedToGetCurrentTime))
732}
733
734#[cfg(test)]
735mod tests {
736 use super::*;
737
738 #[test_log::test]
739 fn assertions_are_debug() {
740 assert_eq!(
741 format!("{:?}", ClientCertVerified::assertion()),
742 "ClientCertVerified(())"
743 );
744 assert_eq!(
745 format!("{:?}", HandshakeSignatureValid::assertion()),
746 "HandshakeSignatureValid(())"
747 );
748 assert_eq!(
749 format!("{:?}", FinishedMessageVerified::assertion()),
750 "FinishedMessageVerified(())"
751 );
752 assert_eq!(
753 format!("{:?}", ServerCertVerified::assertion()),
754 "ServerCertVerified(())"
755 );
756 }
757}