tlspuffin/tls/rustls/
verify.rs

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
15/// Which signature verification mechanisms we support.  No particular
16/// order.
17static 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// Marker types.  These are used to bind the fact some verification
33// (certificate chain or handshake signature) has taken place into
34// protocol states.  We use this to have the compiler check that there
35// are no 'goto fail'-style elisions of important checks before we
36// reach the traffic stage.
37//
38// These types are public, but cannot be directly constructed.  This
39// means their origins can be precisely determined by looking
40// for their `assertion` constructors.
41
42/// Zero-sized marker type representing verification of a signature.
43#[derive(Debug)]
44pub struct HandshakeSignatureValid(());
45
46impl HandshakeSignatureValid {
47    /// Make a `HandshakeSignatureValid`
48    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/// Zero-sized marker type representing verification of a server cert chain.
63#[allow(unreachable_pub)]
64#[derive(Debug)]
65pub struct ServerCertVerified(());
66
67#[allow(unreachable_pub)]
68impl ServerCertVerified {
69    /// Make a `ServerCertVerified`
70    pub fn assertion() -> Self {
71        Self(())
72    }
73}
74
75/// Zero-sized marker type representing verification of a client cert chain.
76#[derive(Debug)]
77pub struct ClientCertVerified(());
78
79impl ClientCertVerified {
80    /// Make a `ClientCertVerified`
81    pub fn assertion() -> Self {
82        Self(())
83    }
84}
85
86/// Something that can verify a server certificate chain, and verify
87/// signatures made by certificates.
88#[allow(unreachable_pub)]
89pub trait ServerCertVerifier: Send + Sync {
90    /// Verify the end-entity certificate `end_entity` is valid for the
91    /// hostname `dns_name` and chains to at least one trust anchor.
92    ///
93    /// `intermediates` contains the intermediate certificates the client sent
94    /// along with the end-entity certificate; it is in the same order that the
95    /// peer sent them and may be empty.
96    ///
97    /// `scts` contains the Signed Certificate Timestamps (SCTs) the server
98    /// sent with the certificate, if any.
99    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    /// Verify a signature allegedly by the given server certificate.
110    ///
111    /// `message` is not hashed, and needs hashing during the verification.
112    /// The signature and algorithm are within `dss`.  `cert` contains the
113    /// public key to use.
114    ///
115    /// `cert` is the same certificate that was previously validated by a
116    /// call to `verify_server_cert`.
117    ///
118    /// If and only if the signature is valid, return HandshakeSignatureValid.
119    /// Otherwise, return an error -- rustls will send an alert and abort the
120    /// connection.
121    ///
122    /// This method is only called for TLS1.2 handshakes.  Note that, in TLS1.2,
123    /// SignatureSchemes such as `SignatureScheme::ECDSA_NISTP256_SHA256` are not
124    /// in fact bound to the specific curve implied in their name.
125    ///
126    /// This trait method has a default implementation that uses webpki to verify
127    /// the signature.
128    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    /// Verify a signature allegedly by the given server certificate.
138    ///
139    /// This method is only called for TLS1.3 handshakes.
140    ///
141    /// This method is very similar to `verify_tls12_signature`: but note the
142    /// tighter ECDSA SignatureScheme semantics -- e.g. `SignatureScheme::ECDSA_NISTP256_SHA256`
143    /// must only validate signatures using public keys on the right curve --
144    /// rustls does not enforce this requirement for you.
145    ///
146    /// This trait method has a default implementation that uses webpki to verify
147    /// the signature.
148    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    /// Return the list of SignatureSchemes that this verifier will handle,
158    /// in `verify_tls12_signature` and `verify_tls13_signature` calls.
159    ///
160    /// This should be in priority order, with the most preferred first.
161    ///
162    /// This trait method has a default implementation that reflects the schemes
163    /// supported by webpki.
164    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
165        WebPkiVerifier::verification_schemes()
166    }
167
168    /// Returns `true` if Rustls should ask the server to send SCTs.
169    ///
170    /// Signed Certificate Timestamps (SCTs) are used for Certificate
171    /// Transparency validation.
172    ///
173    /// The default implementation of this function returns true.
174    fn request_scts(&self) -> bool {
175        true
176    }
177}
178
179/// A type which encapsuates a string that is a syntactically valid DNS name.
180#[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/// Something that can verify a client certificate chain
190#[allow(unreachable_pub)]
191pub trait ClientCertVerifier: Send + Sync {
192    /// Returns `true` to enable the server to request a client certificate and
193    /// `false` to skip requesting a client certificate. Defaults to `true`.
194    fn offer_client_auth(&self) -> bool {
195        true
196    }
197
198    /// Return `Some(true)` to require a client certificate and `Some(false)` to make
199    /// client authentication optional. Return `None` to abort the connection.
200    /// Defaults to `Some(self.offer_client_auth())`.
201    fn client_auth_mandatory(&self) -> Option<bool> {
202        Some(self.offer_client_auth())
203    }
204
205    /// Returns the subject names of the client authentication trust anchors to
206    /// share with the client when requesting client authentication.
207    ///
208    /// Return `None` to abort the connection. Return an empty `Vec` to continue
209    /// the handshake without passing a list of CA DNs.
210    fn client_auth_root_subjects(&self) -> Option<DistinguishedNames>;
211
212    /// Verify the end-entity certificate `end_entity` is valid for the
213    /// and chains to at least one of the trust anchors in `roots`.
214    ///
215    /// `intermediates` contains the intermediate certificates the
216    /// client sent along with the end-entity certificate; it is in the same
217    /// order that the peer sent them and may be empty.
218    fn verify_client_cert(
219        &self,
220        end_entity: &Certificate,
221        intermediates: &[Certificate],
222        now: SystemTime,
223    ) -> Result<ClientCertVerified, Error>;
224
225    /// Verify a signature allegedly by the given server certificate.
226    ///
227    /// `message` is not hashed, and needs hashing during the verification.
228    /// The signature and algorithm are within `dss`.  `cert` contains the
229    /// public key to use.
230    ///
231    /// `cert` is the same certificate that was previously validated by a
232    /// call to `verify_server_cert`.
233    ///
234    /// If and only if the signature is valid, return HandshakeSignatureValid.
235    /// Otherwise, return an error -- rustls will send an alert and abort the
236    /// connection.
237    ///
238    /// This method is only called for TLS1.2 handshakes.  Note that, in TLS1.2,
239    /// SignatureSchemes such as `SignatureScheme::ECDSA_NISTP256_SHA256` are not
240    /// in fact bound to the specific curve implied in their name.
241    ///
242    /// This trait method has a default implementation that uses webpki to verify
243    /// the signature.
244    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    /// Verify a signature allegedly by the given server certificate.
254    ///
255    /// This method is only called for TLS1.3 handshakes.
256    ///
257    /// This method is very similar to `verify_tls12_signature`: but note the
258    /// tighter ECDSA SignatureScheme semantics -- e.g. `SignatureScheme::ECDSA_NISTP256_SHA256`
259    /// must only validate signatures using public keys on the right curve --
260    /// rustls does not enforce this requirement for you.
261    ///
262    /// This trait method has a default implementation that uses webpki to verify
263    /// the signature.
264    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    /// Return the list of SignatureSchemes that this verifier will handle,
274    /// in `verify_tls12_signature` and `verify_tls13_signature` calls.
275    ///
276    /// This should be in priority order, with the most preferred first.
277    ///
278    /// This trait method has a default implementation that reflects the schemes
279    /// supported by webpki.
280    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
281        WebPkiVerifier::verification_schemes()
282    }
283}
284
285impl ServerCertVerifier for WebPkiVerifier {
286    /// Will verify the certificate is valid in the following ways:
287    /// - Signed by a  trusted `RootCertStore` CA
288    /// - Not Expired
289    /// - Valid for DNS entry
290    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/// Default `ServerCertVerifier`, see the trait impl for more information.
329#[allow(unreachable_pub)]
330pub struct WebPkiVerifier {
331    roots: RootCertStore,
332    ct_policy: Option<CertificateTransparencyPolicy>,
333}
334
335#[allow(unreachable_pub)]
336impl WebPkiVerifier {
337    /// Constructs a new `WebPkiVerifier`.
338    ///
339    /// `roots` is the set of trust anchors to trust for issuing server certs.
340    ///
341    /// `ct_logs` is the list of logs that are trusted for Certificate
342    /// Transparency. Currently CT log enforcement is opportunistic; see
343    /// <https://github.com/rustls/rustls/issues/479>.
344    pub fn new(roots: RootCertStore, ct_policy: Option<CertificateTransparencyPolicy>) -> Self {
345        Self { roots, ct_policy }
346    }
347
348    /// Returns the signature verification methods supported by
349    /// webpki.
350    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/// Policy for enforcing Certificate Transparency.
366///
367/// Because Certificate Transparency logs are sharded on a per-year basis and can be trusted or
368/// distrusted relatively quickly, rustls stores a validation deadline. Server certificates will
369/// be validated against the configured CT logs until the deadline expires. After the deadline,
370/// certificates will no longer be validated, and a warning message will be logged. The deadline
371/// may vary depending on how often you deploy builds with updated dependencies.
372#[allow(unreachable_pub)]
373pub struct CertificateTransparencyPolicy {
374    logs: &'static [&'static sct::Log<'static>],
375    validation_deadline: SystemTime,
376}
377
378impl CertificateTransparencyPolicy {
379    /// Create a new policy.
380    #[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 we were supplied with some logs, and some SCTs,
427         * but couldn't verify any of them, fail the handshake. */
428        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    // EE cert must appear first.
449    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
462/// A `ClientCertVerifier` that will ensure that every client provides a trusted
463/// certificate, without any name checking.
464pub struct AllowAnyAuthenticatedClient {
465    roots: RootCertStore,
466}
467
468impl AllowAnyAuthenticatedClient {
469    /// Construct a new `AllowAnyAuthenticatedClient`.
470    ///
471    /// `roots` is the list of trust anchors to use for certificate validation.
472    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
505/// A `ClientCertVerifier` that will allow both anonymous and authenticated
506/// clients, without any name checking.
507///
508/// Client authentication will be requested during the TLS handshake. If the
509/// client offers a certificate then this acts like
510/// `AllowAnyAuthenticatedClient`, otherwise this acts like `NoClientAuth`.
511pub struct AllowAnyAnonymousOrAuthenticatedClient {
512    inner: AllowAnyAuthenticatedClient,
513}
514
515impl AllowAnyAnonymousOrAuthenticatedClient {
516    /// Construct a new `AllowAnyAnonymousOrAuthenticatedClient`.
517    ///
518    /// `roots` is the list of trust anchors to use for certificate validation.
519    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
562/// Turns off client authentication.
563pub struct NoClientAuth;
564
565impl NoClientAuth {
566    /// Constructs a `NoClientAuth` and wraps it in an `Arc`.
567    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        // nb. for TLS1.2 the curve is not fixed by SignatureScheme.
609        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    // TLS doesn't itself give us enough info to map to a single webpki::SignatureAlgorithm.
636    // Therefore, convert_algs maps to several and we try them all.
637    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
679/// Constructs the signature message specified in section 4.4.3 of RFC8446.
680pub 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
687/// Constructs the signature message specified in section 4.4.3 of RFC8446.
688pub 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
695/// Constructs the signature message specified in section 4.4.3 of RFC8446.
696pub 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
700/// Constructs the signature message specified in section 4.4.3 of RFC8446.
701pub 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}