webpki/end_entity.rs
1use core::ops::Deref;
2
3use pki_types::{CertificateDer, ServerName, SignatureVerificationAlgorithm};
4
5use crate::error::Error;
6use crate::subject_name::{verify_dns_names, verify_ip_address_names};
7use crate::{DerTypeId, cert, der, sct, signed_data};
8
9/// An end-entity certificate.
10///
11/// Server certificate processing in a TLS connection consists of several
12/// steps. All of these steps are necessary:
13///
14/// * Build a [`VerifiedPath`][crate::VerifiedPath] using a [PathBuilder][crate::PathBuilder]:
15/// verify that the peer's certificate is valid for the current usage scenario. For server
16/// authentication, use [`crate::ExtendedKeyUsage::SERVER_AUTH`].
17/// * [`EndEntityCert::verify_is_valid_for_subject_name()`]: Verify that the server's
18/// certificate is valid for the host or IP address that is being connected to.
19/// * [`EndEntityCert::verify_signature()`]: Verify that the signature of server's
20/// `ServerKeyExchange` message is valid for the server's certificate.
21///
22/// Client certificate processing in a TLS connection consists of analogous
23/// steps. All of these steps are necessary:
24///
25/// * Build a [`VerifiedPath`][crate::VerifiedPath] using a [PathBuilder][crate::PathBuilder]:
26/// verify that the peer's certificate is valid for the current usage scenario. For client
27/// authentication, use [`crate::ExtendedKeyUsage::CLIENT_AUTH`].
28/// * [`EndEntityCert::verify_signature()`]: Verify that the signature of client's
29/// `CertificateVerify` message is valid using the public key from the
30/// client's certificate.
31///
32/// Although it would be less error-prone to combine all these steps into a
33/// single function call, some significant optimizations are possible if the
34/// three steps are processed separately (in parallel). It does not matter much
35/// which order the steps are done in, but **all of these steps must completed
36/// before application data is sent and before received application data is
37/// processed**. The [`TryFrom`] conversion from `&CertificateDer<'_>` is an
38/// inexpensive operation and is deterministic, so if these tasks are done in
39/// multiple threads, it is probably best to just create multiple [`EndEntityCert`]
40/// instances for the same DER-encoded ASN.1 certificate bytes.
41pub struct EndEntityCert<'a> {
42 inner: cert::Cert<'a>,
43}
44
45impl<'a> TryFrom<&'a CertificateDer<'a>> for EndEntityCert<'a> {
46 type Error = Error;
47
48 /// Parse the ASN.1 DER-encoded X.509 encoding of the certificate
49 /// `cert_der`.
50 fn try_from(cert: &'a CertificateDer<'a>) -> Result<Self, Self::Error> {
51 Ok(Self {
52 inner: cert::Cert::from_der(untrusted::Input::from(cert.as_ref()))?,
53 })
54 }
55}
56
57impl EndEntityCert<'_> {
58 /// Verifies that the certificate is valid for the given Subject Name.
59 pub fn verify_is_valid_for_subject_name(
60 &self,
61 server_name: &ServerName<'_>,
62 ) -> Result<(), Error> {
63 match server_name {
64 ServerName::DnsName(dns_name) => verify_dns_names(dns_name, &self.inner),
65 // IP addresses are not compared against the subject field;
66 // only against Subject Alternative Names.
67 ServerName::IpAddress(ip_address) => verify_ip_address_names(ip_address, &self.inner),
68 _ => Err(Error::UnsupportedNameType),
69 }
70 }
71
72 /// Verifies the signature `signature` of message `msg` using the
73 /// certificate's public key.
74 ///
75 /// `signature_alg` is the algorithm to use to
76 /// verify the signature; the certificate's public key is verified to be
77 /// compatible with this algorithm.
78 ///
79 /// For TLS 1.2, `signature` corresponds to TLS's
80 /// `DigitallySigned.signature` and `signature_alg` corresponds to TLS's
81 /// `DigitallySigned.algorithm` of TLS type `SignatureAndHashAlgorithm`. In
82 /// TLS 1.2 a single `SignatureAndHashAlgorithm` may map to multiple
83 /// `SignatureVerificationAlgorithm`s. For example, a TLS 1.2
84 /// `SignatureAndHashAlgorithm` of (ECDSA, SHA-256) may map to any or all
85 /// of {`ECDSA_P256_SHA256`, `ECDSA_P384_SHA256`}, depending on how the TLS
86 /// implementation is configured.
87 ///
88 /// For TLS 1.3 (RFC 8446), `signature_alg` corresponds to TLS's
89 /// `algorithm` field of type `SignatureScheme`. There is (currently) a
90 /// one-to-one correspondence between TLS 1.3's `SignatureScheme` and
91 /// `SignatureVerificationAlgorithm`.
92 pub fn verify_signature(
93 &self,
94 signature_alg: &dyn SignatureVerificationAlgorithm,
95 msg: &[u8],
96 signature: &[u8],
97 ) -> Result<(), Error> {
98 // RFC 5280 section 4.2.1.3 requires the digitalSignature bit to be asserted before the
99 // certificate's public key may be used to verify signatures. Historically the absence of
100 // a KeyUsage extension has been tolerated and treated as if all usages were asserted, so
101 // we only enforce digitalSignature when a KeyUsage extension is present.
102 if let Some(key_usage) = self.inner.key_usage {
103 check_key_usage_digital_signature(key_usage)?;
104 }
105
106 signed_data::verify_signature(
107 signature_alg,
108 self.inner.spki,
109 untrusted::Input::from(msg),
110 untrusted::Input::from(signature),
111 )
112 }
113
114 /// Returns the CT logs that contributed to the SCTs included in the certificate.
115 ///
116 /// Note this method does not verify the SCTs themselves.
117 ///
118 /// If the certificate does not contain an SCT extension, this method returns an empty
119 /// iterator.
120 pub fn sct_log_timestamps<'a>(
121 &'a self,
122 ) -> Result<impl Iterator<Item = Result<sct::LogIdAndTimestamp, sct::Error>> + 'a, sct::Error>
123 {
124 Ok(sct::SctParser::new(self.scts)?.map(|sct| sct.map(|sct| sct.log_id_and_timestamp())))
125 }
126}
127
128/// Check that an end-entity certificate asserts the digitalSignature bit in its KeyUsage extension.
129///
130/// <https://www.rfc-editor.org/info/rfc5280/#section-4.2.1.3>
131fn check_key_usage_digital_signature(key_usage: untrusted::Input<'_>) -> Result<(), Error> {
132 let bit_string = key_usage.read_all(Error::TrailingData(DerTypeId::BitString), |reader| {
133 der::expect_tag(reader, der::Tag::BitString)
134 })?;
135
136 // The KeyUsage extension is a BIT STRING; digitalSignature is bit 0.
137 const DIGITAL_SIGNATURE: usize = 0;
138 match der::bit_string_flags(bit_string)?.bit_set(DIGITAL_SIGNATURE) {
139 true => Ok(()),
140 false => Err(Error::KeyUsageMissingDigitalSignature),
141 }
142}
143
144impl<'a> Deref for EndEntityCert<'a> {
145 type Target = cert::Cert<'a>;
146
147 fn deref(&self) -> &Self::Target {
148 &self.inner
149 }
150}
151
152#[cfg(feature = "alloc")]
153#[cfg(test)]
154mod tests {
155 use alloc::string::ToString;
156
157 use super::*;
158 use crate::test_utils;
159 use crate::test_utils::RCGEN_SIGNATURE_ALG;
160
161 // This test reproduces https://github.com/rustls/webpki/issues/167 --- an
162 // end-entity cert where the common name is a `PrintableString` rather than
163 // a `UTF8String` cannot iterate over its subject alternative names.
164 #[test]
165 fn printable_string_common_name() {
166 const DNS_NAME: &str = "test.example.com";
167
168 let issuer = test_utils::make_issuer("Test");
169
170 let ee_cert = {
171 let mut params = test_utils::end_entity_params(vec![DNS_NAME.to_string()]);
172 // construct a certificate that uses `PrintableString` as the
173 // common name value, rather than `UTF8String`.
174 params.distinguished_name.push(
175 rcgen::DnType::CommonName,
176 rcgen::DnValue::PrintableString(
177 rcgen::string::PrintableString::try_from("example.com").unwrap(),
178 ),
179 );
180 params
181 .signed_by(
182 &rcgen::KeyPair::generate_for(RCGEN_SIGNATURE_ALG).unwrap(),
183 &issuer,
184 )
185 .expect("failed to make ee cert (this is a test bug)")
186 };
187
188 expect_dns_name(ee_cert.der(), DNS_NAME);
189 }
190
191 // This test reproduces https://github.com/rustls/webpki/issues/167 --- an
192 // end-entity cert where the common name is an empty SEQUENCE.
193 #[test]
194 fn empty_sequence_common_name() {
195 let ee_cert_der = {
196 // handcrafted cert DER produced using `ascii2der`, since `rcgen` is
197 // unwilling to generate this particular weird cert.
198 let bytes = include_bytes!("../tests/misc/empty_sequence_common_name.der");
199 CertificateDer::from(&bytes[..])
200 };
201 expect_dns_name(&ee_cert_der, "example.com");
202 }
203
204 fn expect_dns_name(der: &CertificateDer<'_>, name: &str) {
205 let cert =
206 EndEntityCert::try_from(der).expect("should parse end entity certificate correctly");
207
208 let mut names = cert.valid_dns_names();
209 assert_eq!(names.next(), Some(name));
210 assert_eq!(names.next(), None);
211 }
212}