• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2015-2021 Brian Smith.
2 //
3 // Permission to use, copy, modify, and/or distribute this software for any
4 // purpose with or without fee is hereby granted, provided that the above
5 // copyright notice and this permission notice appear in all copies.
6 //
7 // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
8 // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
10 // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
12 // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
13 // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14 
15 use crate::{
16     cert, name, signed_data, verify_cert, DnsNameRef, Error, SignatureAlgorithm, Time,
17     TlsClientTrustAnchors, TlsServerTrustAnchors,
18 };
19 
20 #[cfg(feature = "alloc")]
21 use alloc::vec::Vec;
22 
23 /// An end-entity certificate.
24 ///
25 /// Server certificate processing in a TLS connection consists of several
26 /// steps. All of these steps are necessary:
27 ///
28 /// * `EndEntityCert.verify_is_valid_tls_server_cert`: Verify that the server's
29 ///   certificate is currently valid *for use by a TLS server*.
30 /// * `EndEntityCert.verify_is_valid_for_dns_name`: Verify that the server's
31 ///   certificate is valid for the host that is being connected to.
32 /// * `EndEntityCert.verify_signature`: Verify that the signature of server's
33 ///   `ServerKeyExchange` message is valid for the server's certificate.
34 ///
35 /// Client certificate processing in a TLS connection consists of analogous
36 /// steps. All of these steps are necessary:
37 ///
38 /// * `EndEntityCert.verify_is_valid_tls_client_cert`: Verify that the client's
39 ///   certificate is currently valid *for use by a TLS client*.
40 /// * `EndEntityCert.verify_is_valid_for_dns_name` or
41 ///   `EndEntityCert.verify_is_valid_for_at_least_one_dns_name`: Verify that the
42 ///   client's certificate is valid for the identity or identities used to
43 ///   identify the client. (Currently client authentication only works when the
44 ///   client is identified by one or more DNS hostnames.)
45 /// * `EndEntityCert.verify_signature`: Verify that the client's signature in
46 ///   its `CertificateVerify` message is valid using the public key from the
47 ///   client's certificate.
48 ///
49 /// Although it would be less error-prone to combine all these steps into a
50 /// single function call, some significant optimizations are possible if the
51 /// three steps are processed separately (in parallel). It does not matter much
52 /// which order the steps are done in, but **all of these steps must completed
53 /// before application data is sent and before received application data is
54 /// processed**. `EndEntityCert::from` is an inexpensive operation and is
55 /// deterministic, so if these tasks are done in multiple threads, it is
56 /// probably best to just call `EndEntityCert::from` multiple times (before each
57 /// operation) for the same DER-encoded ASN.1 certificate bytes.
58 pub struct EndEntityCert<'a> {
59     inner: cert::Cert<'a>,
60 }
61 
62 impl<'a> core::convert::TryFrom<&'a [u8]> for EndEntityCert<'a> {
63     type Error = Error;
64 
65     /// Parse the ASN.1 DER-encoded X.509 encoding of the certificate
66     /// `cert_der`.
try_from(cert_der: &'a [u8]) -> Result<Self, Self::Error>67     fn try_from(cert_der: &'a [u8]) -> Result<Self, Self::Error> {
68         Ok(Self {
69             inner: cert::parse_cert(
70                 untrusted::Input::from(cert_der),
71                 cert::EndEntityOrCa::EndEntity,
72             )?,
73         })
74     }
75 }
76 
77 impl<'a> EndEntityCert<'a> {
inner(&self) -> &cert::Cert78     pub(super) fn inner(&self) -> &cert::Cert {
79         &self.inner
80     }
81 
82     /// Verifies that the end-entity certificate is valid for use by a TLS
83     /// server.
84     ///
85     /// `supported_sig_algs` is the list of signature algorithms that are
86     /// trusted for use in certificate signatures; the end-entity certificate's
87     /// public key is not validated against this list. `trust_anchors` is the
88     /// list of root CAs to trust. `intermediate_certs` is the sequence of
89     /// intermediate certificates that the server sent in the TLS handshake.
90     /// `time` is the time for which the validation is effective (usually the
91     /// current time).
verify_is_valid_tls_server_cert( &self, supported_sig_algs: &[&SignatureAlgorithm], &TlsServerTrustAnchors(trust_anchors): &TlsServerTrustAnchors, intermediate_certs: &[&[u8]], time: Time, ) -> Result<(), Error>92     pub fn verify_is_valid_tls_server_cert(
93         &self,
94         supported_sig_algs: &[&SignatureAlgorithm],
95         &TlsServerTrustAnchors(trust_anchors): &TlsServerTrustAnchors,
96         intermediate_certs: &[&[u8]],
97         time: Time,
98     ) -> Result<(), Error> {
99         verify_cert::build_chain(
100             verify_cert::EKU_SERVER_AUTH,
101             supported_sig_algs,
102             trust_anchors,
103             intermediate_certs,
104             &self.inner,
105             time,
106             0,
107         )
108     }
109 
110     /// Verifies that the end-entity certificate is valid for use by a TLS
111     /// client.
112     ///
113     /// If the certificate is not valid for any of the given names then this
114     /// fails with `Error::CertNotValidForName`.
115     ///
116     /// `supported_sig_algs` is the list of signature algorithms that are
117     /// trusted for use in certificate signatures; the end-entity certificate's
118     /// public key is not validated against this list. `trust_anchors` is the
119     /// list of root CAs to trust. `intermediate_certs` is the sequence of
120     /// intermediate certificates that the client sent in the TLS handshake.
121     /// `cert` is the purported end-entity certificate of the client. `time` is
122     /// the time for which the validation is effective (usually the current
123     /// time).
verify_is_valid_tls_client_cert( &self, supported_sig_algs: &[&SignatureAlgorithm], &TlsClientTrustAnchors(trust_anchors): &TlsClientTrustAnchors, intermediate_certs: &[&[u8]], time: Time, ) -> Result<(), Error>124     pub fn verify_is_valid_tls_client_cert(
125         &self,
126         supported_sig_algs: &[&SignatureAlgorithm],
127         &TlsClientTrustAnchors(trust_anchors): &TlsClientTrustAnchors,
128         intermediate_certs: &[&[u8]],
129         time: Time,
130     ) -> Result<(), Error> {
131         verify_cert::build_chain(
132             verify_cert::EKU_CLIENT_AUTH,
133             supported_sig_algs,
134             trust_anchors,
135             intermediate_certs,
136             &self.inner,
137             time,
138             0,
139         )
140     }
141 
142     /// Verifies that the certificate is valid for the given DNS host name.
verify_is_valid_for_dns_name(&self, dns_name: DnsNameRef) -> Result<(), Error>143     pub fn verify_is_valid_for_dns_name(&self, dns_name: DnsNameRef) -> Result<(), Error> {
144         name::verify_cert_dns_name(&self, dns_name)
145     }
146 
147     /// Verifies that the certificate is valid for at least one of the given DNS
148     /// host names.
149     ///
150     /// If the certificate is not valid for any of the given names then this
151     /// fails with `Error::CertNotValidForName`. Otherwise the DNS names for
152     /// which the certificate is valid are returned.
153     ///
154     /// Requires the `alloc` default feature; i.e. this isn't available in
155     /// `#![no_std]` configurations.
156     #[cfg(feature = "alloc")]
verify_is_valid_for_at_least_one_dns_name<'names, Names>( &self, dns_names: Names, ) -> Result<Vec<DnsNameRef<'names>>, Error> where Names: Iterator<Item = DnsNameRef<'names>>,157     pub fn verify_is_valid_for_at_least_one_dns_name<'names, Names>(
158         &self,
159         dns_names: Names,
160     ) -> Result<Vec<DnsNameRef<'names>>, Error>
161     where
162         Names: Iterator<Item = DnsNameRef<'names>>,
163     {
164         let result: Vec<DnsNameRef<'names>> = dns_names
165             .filter(|n| self.verify_is_valid_for_dns_name(*n).is_ok())
166             .collect();
167         if result.is_empty() {
168             return Err(Error::CertNotValidForName);
169         }
170         Ok(result)
171     }
172 
173     /// Verifies the signature `signature` of message `msg` using the
174     /// certificate's public key.
175     ///
176     /// `signature_alg` is the algorithm to use to
177     /// verify the signature; the certificate's public key is verified to be
178     /// compatible with this algorithm.
179     ///
180     /// For TLS 1.2, `signature` corresponds to TLS's
181     /// `DigitallySigned.signature` and `signature_alg` corresponds to TLS's
182     /// `DigitallySigned.algorithm` of TLS type `SignatureAndHashAlgorithm`. In
183     /// TLS 1.2 a single `SignatureAndHashAlgorithm` may map to multiple
184     /// `SignatureAlgorithm`s. For example, a TLS 1.2
185     /// `ignatureAndHashAlgorithm` of (ECDSA, SHA-256) may map to any or all
186     /// of {`ECDSA_P256_SHA256`, `ECDSA_P384_SHA256`}, depending on how the TLS
187     /// implementation is configured.
188     ///
189     /// For current TLS 1.3 drafts, `signature_alg` corresponds to TLS's
190     /// `algorithm` fields of type `SignatureScheme`. There is (currently) a
191     /// one-to-one correspondence between TLS 1.3's `SignatureScheme` and
192     /// `SignatureAlgorithm`.
verify_signature( &self, signature_alg: &SignatureAlgorithm, msg: &[u8], signature: &[u8], ) -> Result<(), Error>193     pub fn verify_signature(
194         &self,
195         signature_alg: &SignatureAlgorithm,
196         msg: &[u8],
197         signature: &[u8],
198     ) -> Result<(), Error> {
199         signed_data::verify_signature(
200             signature_alg,
201             self.inner.spki.value(),
202             untrusted::Input::from(msg),
203             untrusted::Input::from(signature),
204         )
205     }
206 }
207