rustls/verify.rs
1use alloc::vec::Vec;
2use core::fmt::Debug;
3
4use pki_types::{CertificateDer, ServerName, UnixTime};
5
6use crate::enums::SignatureScheme;
7use crate::error::{Error, InvalidMessage};
8use crate::msgs::base::PayloadU16;
9use crate::msgs::codec::{Codec, Reader};
10use crate::msgs::handshake::DistinguishedName;
11
12// Marker types. These are used to bind the fact some verification
13// (certificate chain or handshake signature) has taken place into
14// protocol states. We use this to have the compiler check that there
15// are no 'goto fail'-style elisions of important checks before we
16// reach the traffic stage.
17//
18// These types are public, but cannot be directly constructed. This
19// means their origins can be precisely determined by looking
20// for their `assertion` constructors.
21
22/// Zero-sized marker type representing verification of a signature.
23#[derive(Debug)]
24pub struct HandshakeSignatureValid(());
25
26impl HandshakeSignatureValid {
27 /// Make a `HandshakeSignatureValid`
28 pub fn assertion() -> Self {
29 Self(())
30 }
31}
32
33#[derive(Debug)]
34pub(crate) struct FinishedMessageVerified(());
35
36impl FinishedMessageVerified {
37 pub(crate) fn assertion() -> Self {
38 Self(())
39 }
40}
41
42/// Zero-sized marker type representing verification of a server cert chain.
43#[allow(unreachable_pub)]
44#[derive(Debug)]
45pub struct ServerCertVerified(());
46
47#[allow(unreachable_pub)]
48impl ServerCertVerified {
49 /// Make a `ServerCertVerified`
50 pub fn assertion() -> Self {
51 Self(())
52 }
53}
54
55/// Zero-sized marker type representing verification of a client cert chain.
56#[derive(Debug)]
57pub struct ClientCertVerified(());
58
59impl ClientCertVerified {
60 /// Make a `ClientCertVerified`
61 pub fn assertion() -> Self {
62 Self(())
63 }
64}
65
66/// Something that can verify a server certificate chain, and verify
67/// signatures made by certificates.
68#[allow(unreachable_pub)]
69pub trait ServerCertVerifier: Debug + Send + Sync {
70 /// Verify the end-entity certificate `end_entity` is valid for the
71 /// hostname `dns_name` and chains to at least one trust anchor.
72 ///
73 /// `intermediates` contains all certificates other than `end_entity` that
74 /// were sent as part of the server's [Certificate] message. It is in the
75 /// same order that the server sent them and may be empty.
76 ///
77 /// Note that none of the certificates have been parsed yet, so it is the responsibility of
78 /// the implementer to handle invalid data. It is recommended that the implementer returns
79 /// [`Error::InvalidCertificate`] containing [`CertificateError::BadEncoding`] when these cases are encountered.
80 ///
81 /// [Certificate]: https://datatracker.ietf.org/doc/html/rfc8446#section-4.4.2
82 /// [`CertificateError::BadEncoding`]: crate::error::CertificateError::BadEncoding
83 fn verify_server_cert(
84 &self,
85 end_entity: &CertificateDer<'_>,
86 intermediates: &[CertificateDer<'_>],
87 server_name: &ServerName<'_>,
88 ocsp_response: &[u8],
89 now: UnixTime,
90 ) -> Result<ServerCertVerified, Error>;
91
92 /// Verify a signature allegedly by the given server certificate.
93 ///
94 /// `message` is not hashed, and needs hashing during the verification.
95 /// The signature and algorithm are within `dss`. `cert` contains the
96 /// public key to use.
97 ///
98 /// `cert` has already been validated by [`ServerCertVerifier::verify_server_cert`].
99 ///
100 /// If and only if the signature is valid, return `Ok(HandshakeSignatureValid)`.
101 /// Otherwise, return an error -- rustls will send an alert and abort the
102 /// connection.
103 ///
104 /// This method is only called for TLS1.2 handshakes. Note that, in TLS1.2,
105 /// SignatureSchemes such as `SignatureScheme::ECDSA_NISTP256_SHA256` are not
106 /// in fact bound to the specific curve implied in their name.
107 fn verify_tls12_signature(
108 &self,
109 message: &[u8],
110 cert: &CertificateDer<'_>,
111 dss: &DigitallySignedStruct,
112 ) -> Result<HandshakeSignatureValid, Error>;
113
114 /// Verify a signature allegedly by the given server certificate.
115 ///
116 /// This method is only called for TLS1.3 handshakes.
117 ///
118 /// This method is very similar to `verify_tls12_signature`: but note the
119 /// tighter ECDSA SignatureScheme semantics -- e.g. `SignatureScheme::ECDSA_NISTP256_SHA256`
120 /// must only validate signatures using public keys on the right curve --
121 /// rustls does not enforce this requirement for you.
122 ///
123 /// `cert` has already been validated by [`ServerCertVerifier::verify_server_cert`].
124 ///
125 /// If and only if the signature is valid, return `Ok(HandshakeSignatureValid)`.
126 /// Otherwise, return an error -- rustls will send an alert and abort the
127 /// connection.
128 fn verify_tls13_signature(
129 &self,
130 message: &[u8],
131 cert: &CertificateDer<'_>,
132 dss: &DigitallySignedStruct,
133 ) -> Result<HandshakeSignatureValid, Error>;
134
135 /// Return the list of SignatureSchemes that this verifier will handle,
136 /// in `verify_tls12_signature` and `verify_tls13_signature` calls.
137 ///
138 /// This should be in priority order, with the most preferred first.
139 fn supported_verify_schemes(&self) -> Vec<SignatureScheme>;
140
141 /// Returns whether this verifier requires raw public keys as defined
142 /// in [RFC 7250](https://tools.ietf.org/html/rfc7250).
143 fn requires_raw_public_keys(&self) -> bool {
144 false
145 }
146
147 /// Return the [`DistinguishedName`]s of certificate authorities that this verifier trusts.
148 ///
149 /// If specified, will be sent as the [`certificate_authorities`] extension in ClientHello.
150 /// Note that this is only applicable to TLS 1.3.
151 ///
152 /// [`certificate_authorities`]: https://datatracker.ietf.org/doc/html/rfc8446#section-4.2.4
153 fn root_hint_subjects(&self) -> Option<&[DistinguishedName]> {
154 None
155 }
156}
157
158/// Something that can verify a client certificate chain
159#[allow(unreachable_pub)]
160pub trait ClientCertVerifier: Debug + Send + Sync {
161 /// Returns `true` to enable the server to request a client certificate and
162 /// `false` to skip requesting a client certificate. Defaults to `true`.
163 fn offer_client_auth(&self) -> bool {
164 true
165 }
166
167 /// Return `true` to require a client certificate and `false` to make
168 /// client authentication optional.
169 /// Defaults to `self.offer_client_auth()`.
170 fn client_auth_mandatory(&self) -> bool {
171 self.offer_client_auth()
172 }
173
174 /// Returns `true` to request an OCSP response for the client's leaf certificate.
175 ///
176 /// This sends an empty `status_request` extension in TLS 1.3 CertificateRequest.
177 fn request_client_ocsp(&self) -> bool {
178 false
179 }
180
181 /// Returns the [`DistinguishedName`] [subjects] that the server will hint to clients to
182 /// identify acceptable authentication trust anchors.
183 ///
184 /// These hint values help the client pick a client certificate it believes the server will
185 /// accept. The hints must be DER-encoded X.500 distinguished names, per [RFC 5280 A.1]. They
186 /// are sent in the [`certificate_authorities`] extension of a [`CertificateRequest`] message
187 /// when [ClientCertVerifier::offer_client_auth] is true. When an empty list is sent the client
188 /// should always provide a client certificate if it has one.
189 ///
190 /// Generally this list should contain the [`DistinguishedName`] of each root trust
191 /// anchor in the root cert store that the server is configured to use for authenticating
192 /// presented client certificates.
193 ///
194 /// In some circumstances this list may be customized to include [`DistinguishedName`] entries
195 /// that do not correspond to a trust anchor in the server's root cert store. For example,
196 /// the server may be configured to trust a root CA that cross-signed an issuer certificate
197 /// that the client considers a trust anchor. From the server's perspective the cross-signed
198 /// certificate is an intermediate, and not present in the server's root cert store. The client
199 /// may have the cross-signed certificate configured as a trust anchor, and be unaware of the
200 /// root CA that cross-signed it. If the server's hints list only contained the subjects of the
201 /// server's root store the client would consider a client certificate issued by the cross-signed
202 /// issuer unacceptable, since its subject was not hinted. To avoid this circumstance the server
203 /// should customize the hints list to include the subject of the cross-signed issuer in addition
204 /// to the subjects from the root cert store.
205 ///
206 /// [subjects]: https://datatracker.ietf.org/doc/html/rfc5280#section-4.1.2.6
207 /// [RFC 5280 A.1]: https://www.rfc-editor.org/rfc/rfc5280#appendix-A.1
208 /// [`CertificateRequest`]: https://datatracker.ietf.org/doc/html/rfc8446#section-4.3.2
209 /// [`certificate_authorities`]: https://datatracker.ietf.org/doc/html/rfc8446#section-4.2.4
210 fn root_hint_subjects(&self) -> &[DistinguishedName];
211
212 /// Verify the end-entity certificate `end_entity` is valid, acceptable,
213 /// and chains to at least one of the trust anchors trusted by
214 /// this verifier.
215 ///
216 /// `intermediates` contains the intermediate certificates the
217 /// client sent along with the end-entity certificate; it is in the same
218 /// order that the peer sent them and may be empty.
219 ///
220 /// Note that none of the certificates have been parsed yet, so it is the responsibility of
221 /// the implementer to handle invalid data. It is recommended that the implementer returns
222 /// an [InvalidCertificate] error with the [BadEncoding] variant when these cases are encountered.
223 ///
224 /// [InvalidCertificate]: Error#variant.InvalidCertificate
225 /// [BadEncoding]: crate::CertificateError#variant.BadEncoding
226 fn verify_client_cert(
227 &self,
228 end_entity: &CertificateDer<'_>,
229 intermediates: &[CertificateDer<'_>],
230 now: UnixTime,
231 ) -> Result<ClientCertVerified, Error>;
232
233 /// Verify a client certificate chain together with its stapled OCSP response.
234 ///
235 /// The default preserves compatibility for existing verifiers. Implementations that return
236 /// `true` from [`Self::request_client_ocsp`] should override this method.
237 fn verify_client_cert_with_ocsp(
238 &self,
239 end_entity: &CertificateDer<'_>,
240 intermediates: &[CertificateDer<'_>],
241 ocsp_response: &[u8],
242 now: UnixTime,
243 ) -> Result<ClientCertVerified, Error> {
244 let _ = ocsp_response;
245 self.verify_client_cert(end_entity, intermediates, now)
246 }
247
248 /// Verify a signature allegedly by the given client certificate.
249 ///
250 /// `message` is not hashed, and needs hashing during the verification.
251 /// The signature and algorithm are within `dss`. `cert` contains the
252 /// public key to use.
253 ///
254 /// `cert` has already been validated by [`ClientCertVerifier::verify_client_cert`].
255 ///
256 /// If and only if the signature is valid, return `Ok(HandshakeSignatureValid)`.
257 /// Otherwise, return an error -- rustls will send an alert and abort the
258 /// connection.
259 ///
260 /// This method is only called for TLS1.2 handshakes. Note that, in TLS1.2,
261 /// SignatureSchemes such as `SignatureScheme::ECDSA_NISTP256_SHA256` are not
262 /// in fact bound to the specific curve implied in their name.
263 fn verify_tls12_signature(
264 &self,
265 message: &[u8],
266 cert: &CertificateDer<'_>,
267 dss: &DigitallySignedStruct,
268 ) -> Result<HandshakeSignatureValid, Error>;
269
270 /// Verify a signature allegedly by the given client certificate.
271 ///
272 /// This method is only called for TLS1.3 handshakes.
273 ///
274 /// This method is very similar to `verify_tls12_signature`, but note the
275 /// tighter ECDSA SignatureScheme semantics in TLS 1.3. For example,
276 /// `SignatureScheme::ECDSA_NISTP256_SHA256`
277 /// must only validate signatures using public keys on the right curve --
278 /// rustls does not enforce this requirement for you.
279 fn verify_tls13_signature(
280 &self,
281 message: &[u8],
282 cert: &CertificateDer<'_>,
283 dss: &DigitallySignedStruct,
284 ) -> Result<HandshakeSignatureValid, Error>;
285
286 /// Return the list of SignatureSchemes that this verifier will handle,
287 /// in `verify_tls12_signature` and `verify_tls13_signature` calls.
288 ///
289 /// This should be in priority order, with the most preferred first.
290 fn supported_verify_schemes(&self) -> Vec<SignatureScheme>;
291
292 /// Returns whether this verifier requires raw public keys as defined
293 /// in [RFC 7250](https://tools.ietf.org/html/rfc7250).
294 fn requires_raw_public_keys(&self) -> bool {
295 false
296 }
297}
298
299/// Turns off client authentication.
300///
301/// In contrast to using
302/// `WebPkiClientVerifier::builder(roots).allow_unauthenticated().build()`, the `NoClientAuth`
303/// `ClientCertVerifier` will not offer client authentication at all, vs offering but not
304/// requiring it.
305#[derive(Debug)]
306pub struct NoClientAuth;
307
308impl ClientCertVerifier for NoClientAuth {
309 fn offer_client_auth(&self) -> bool {
310 false
311 }
312
313 fn root_hint_subjects(&self) -> &[DistinguishedName] {
314 unimplemented!();
315 }
316
317 fn verify_client_cert(
318 &self,
319 _end_entity: &CertificateDer<'_>,
320 _intermediates: &[CertificateDer<'_>],
321 _now: UnixTime,
322 ) -> Result<ClientCertVerified, Error> {
323 unimplemented!();
324 }
325
326 fn verify_tls12_signature(
327 &self,
328 _message: &[u8],
329 _cert: &CertificateDer<'_>,
330 _dss: &DigitallySignedStruct,
331 ) -> Result<HandshakeSignatureValid, Error> {
332 unimplemented!();
333 }
334
335 fn verify_tls13_signature(
336 &self,
337 _message: &[u8],
338 _cert: &CertificateDer<'_>,
339 _dss: &DigitallySignedStruct,
340 ) -> Result<HandshakeSignatureValid, Error> {
341 unimplemented!();
342 }
343
344 fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
345 unimplemented!();
346 }
347}
348
349/// This type combines a [`SignatureScheme`] and a signature payload produced with that scheme.
350#[derive(Debug, Clone)]
351pub struct DigitallySignedStruct {
352 /// The [`SignatureScheme`] used to produce the signature.
353 pub scheme: SignatureScheme,
354 sig: PayloadU16,
355}
356
357impl DigitallySignedStruct {
358 pub(crate) fn new(scheme: SignatureScheme, sig: Vec<u8>) -> Self {
359 Self {
360 scheme,
361 sig: PayloadU16::new(sig),
362 }
363 }
364
365 /// Get the signature.
366 pub fn signature(&self) -> &[u8] {
367 &self.sig.0
368 }
369}
370
371impl Codec<'_> for DigitallySignedStruct {
372 fn encode(&self, bytes: &mut Vec<u8>) {
373 self.scheme.encode(bytes);
374 self.sig.encode(bytes);
375 }
376
377 fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> {
378 let scheme = SignatureScheme::read(r)?;
379 let sig = PayloadU16::read(r)?;
380
381 Ok(Self { scheme, sig })
382 }
383}
384
385#[test]
386fn assertions_are_debug() {
387 use std::format;
388
389 assert_eq!(
390 format!("{:?}", ClientCertVerified::assertion()),
391 "ClientCertVerified(())"
392 );
393 assert_eq!(
394 format!("{:?}", HandshakeSignatureValid::assertion()),
395 "HandshakeSignatureValid(())"
396 );
397 assert_eq!(
398 format!("{:?}", FinishedMessageVerified::assertion()),
399 "FinishedMessageVerified(())"
400 );
401 assert_eq!(
402 format!("{:?}", ServerCertVerified::assertion()),
403 "ServerCertVerified(())"
404 );
405}