Skip to main content

rustls_upki/
lib.rs

1#![doc = include_str!("../README.md")]
2#![warn(missing_docs)]
3
4use core::fmt;
5use std::path::PathBuf;
6use std::sync::Arc;
7
8use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
9use rustls::crypto::hash::{Hash, HashAlgorithm};
10use rustls::crypto::{CryptoProvider, verify_tls12_signature, verify_tls13_signature};
11use rustls::pki_types::{CertificateDer, ServerName, UnixTime};
12use rustls::{
13    CertRevocationListError, CertificateError, DigitallySignedStruct, DistinguishedName,
14    ExtendedKeyPurpose, RootCertStore, SignatureScheme, SupportedCipherSuite,
15};
16use upki::revocation::{
17    self, CertSerial, CtTimestamp, IssuerSpkiHash, RevocationCheckInput, RevocationStatus, Store,
18};
19use upki::{self, Config, ConfigPath};
20use webpki::{EndEntityCert, ExtendedKeyUsage, InvalidNameContext, VerifiedPath};
21
22/// A [`ServerCertVerifier`] that uses upki to check revocation status of server certificates.
23pub struct ServerVerifier {
24    provider: Arc<CryptoProvider>,
25    sha256: &'static dyn Hash,
26    roots: Arc<RootCertStore>,
27    config: Config,
28    policy: Policy,
29}
30
31impl ServerVerifier {
32    /// Make a verifier that checks revocation status using upki.
33    ///
34    /// This first verifies the certificate using the `webpki` crate, against the supplied `roots`.
35    /// This uses cryptography specified in `provider`.
36    ///
37    /// `config_path` points to where the upki configuration file can be found -- if it is
38    /// [`None`] then it is searched for in usual places.  The configuration file is read and kept
39    /// in memory during this construction, so later changes to it will not be respected.
40    ///
41    /// A certificate which is acceptable in the normal way, issued by one of the `roots` and
42    /// valid for the given server name, is then checked for revocation.  `policy` controls
43    /// whether failures in this process are hard errors.
44    pub fn new(
45        policy: Policy,
46        config_path: Option<PathBuf>,
47        roots: Arc<RootCertStore>,
48        provider: Arc<CryptoProvider>,
49    ) -> Result<Self, rustls::Error> {
50        let sha256 = provider
51            .cipher_suites
52            .iter()
53            .find_map(|scs| {
54                let hash = match scs {
55                    SupportedCipherSuite::Tls12(tls12) => tls12.common.hash_provider,
56                    SupportedCipherSuite::Tls13(tls13) => tls13.common.hash_provider,
57                };
58
59                match hash.algorithm() {
60                    HashAlgorithm::SHA256 => Some(hash),
61                    _ => None,
62                }
63            })
64            .expect("no cipher suites supported with SHA256");
65
66        let config = ConfigPath::new(config_path)
67            .and_then(|path| Config::from_file_or_user_default(&path))
68            .map_err(|report| rustls::Error::General(report.to_string()))?;
69
70        // Pre-roll storage to check it works, and bring (eg. permanent configuration) errors
71        // to forefront prior to any networking.
72        let store = Store::from_config(&config);
73        if let Err(revocation::Error::NoData { .. }) = store.validate() {
74            let _ = policy.missing_data.as_result()?;
75        };
76
77        Ok(Self {
78            provider,
79            sha256,
80            roots,
81            config,
82            policy,
83        })
84    }
85
86    /// Determine the revocation status of `ee`.
87    ///
88    /// This should have been determined to be issued by a trusted root.  `verified_path`
89    /// proves this.
90    ///
91    /// This returns errors only for hard failure cases.
92    fn check_revocation_status(
93        &self,
94        verified_path: &VerifiedPath<'_>,
95    ) -> Result<RevocationStatus, rustls::Error> {
96        let issuer_spki = verified_path.issuer_spki();
97        let issuer_spki_hash = self.sha256.hash(&issuer_spki);
98        let issuer_spki_hash = issuer_spki_hash
99            .as_ref()
100            .try_into()
101            .expect("sha256 must have a 32-byte output");
102
103        let mut sct_timestamps = vec![];
104        let sct_iter = verified_path
105            .end_entity()
106            .sct_log_timestamps();
107        for ts in sct_iter.map_err(sct_error)? {
108            let ts = ts.map_err(sct_error)?;
109            sct_timestamps.push(CtTimestamp {
110                log_id: ts.log_id,
111                timestamp: ts.timestamp_ms,
112            });
113        }
114
115        // Lacking SCTs means we cannot check revocation, and the certificate
116        // probably is not publicly trusted anyway.
117        if sct_timestamps.is_empty() {
118            return self.policy.cert_has_no_scts.as_result();
119        }
120
121        let input = RevocationCheckInput::new(
122            CertSerial(
123                verified_path
124                    .end_entity()
125                    .serial()
126                    .to_vec(),
127            ),
128            IssuerSpkiHash(issuer_spki_hash),
129            sct_timestamps,
130        );
131
132        match Store::from_config(&self.config).check(&input) {
133            Ok(rs) => Ok(rs),
134            Err(revocation::Error::NoData { .. }) => self.policy.missing_data.as_result(),
135            Err(e) => Err(rustls::Error::General(e.to_string())),
136        }
137    }
138}
139
140impl ServerCertVerifier for ServerVerifier {
141    fn verify_server_cert(
142        &self,
143        end_entity: &CertificateDer<'_>,
144        intermediates: &[CertificateDer<'_>],
145        server_name: &ServerName<'_>,
146        _ocsp_response: &[u8],
147        now: UnixTime,
148    ) -> Result<ServerCertVerified, rustls::Error> {
149        let ee = EndEntityCert::try_from(end_entity).map_err(webpki_error)?;
150
151        let verified_path = ee
152            .verify_for_usage(
153                self.provider
154                    .signature_verification_algorithms
155                    .all,
156                &self.roots.roots,
157                intermediates,
158                now,
159                &ExtendedKeyUsage::server_auth(),
160                None,
161                None,
162            )
163            .map_err(webpki_error)?;
164
165        ee.verify_is_valid_for_subject_name(server_name)
166            .map_err(webpki_error)?;
167
168        match self.check_revocation_status(&verified_path)? {
169            RevocationStatus::NotRevoked => Ok(ServerCertVerified::assertion()),
170            RevocationStatus::NotCoveredByRevocationData => self
171                .policy
172                .cert_not_covered
173                .as_result()
174                .map(|_| ServerCertVerified::assertion()),
175            RevocationStatus::CertainlyRevoked => Err(CertificateError::Revoked.into()),
176        }
177    }
178
179    fn verify_tls12_signature(
180        &self,
181        message: &[u8],
182        cert: &CertificateDer<'_>,
183        dss: &DigitallySignedStruct,
184    ) -> Result<HandshakeSignatureValid, rustls::Error> {
185        verify_tls12_signature(
186            message,
187            cert,
188            dss,
189            &self
190                .provider
191                .signature_verification_algorithms,
192        )
193    }
194
195    fn verify_tls13_signature(
196        &self,
197        message: &[u8],
198        cert: &CertificateDer<'_>,
199        dss: &DigitallySignedStruct,
200    ) -> Result<HandshakeSignatureValid, rustls::Error> {
201        verify_tls13_signature(
202            message,
203            cert,
204            dss,
205            &self
206                .provider
207                .signature_verification_algorithms,
208        )
209    }
210
211    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
212        self.provider
213            .signature_verification_algorithms
214            .supported_schemes()
215    }
216
217    fn root_hint_subjects(&self) -> Option<&[DistinguishedName]> {
218        None
219    }
220}
221
222impl fmt::Debug for ServerVerifier {
223    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
224        let Self {
225            provider,
226            roots,
227            policy,
228            sha256: _,
229            config,
230        } = self;
231
232        f.debug_struct("ServerVerifier")
233            .field("provider", &provider)
234            .field("roots", &roots)
235            .field("config", &config)
236            .field("policy", &policy)
237            .finish_non_exhaustive()
238    }
239}
240
241/// Controls the error behavior of this crate.
242#[derive(Debug)]
243pub struct Policy {
244    /// What to do if upki filter data is missing
245    pub missing_data: Outcome,
246
247    /// What to do if upki filter data does not cover a certificate
248    ///
249    /// A certificate can be not covered by the crlite filter if:
250    ///
251    /// - the data is out of date, perhaps because it has not been fetched recently.
252    /// - the data does not cover the certificate, because the backend processing does not cover
253    ///   it (at the time of writing, this is the case for some certifcates).
254    pub cert_not_covered: Outcome,
255
256    /// What to do if certificate was not logged in CT
257    pub cert_has_no_scts: Outcome,
258}
259
260impl Default for Policy {
261    fn default() -> Self {
262        Self {
263            missing_data: Outcome::Error(rustls::Error::General("upki data is missing".into())),
264            cert_not_covered: Outcome::Allowed,
265            cert_has_no_scts: Outcome::Allowed,
266        }
267    }
268}
269
270/// For a given item in a [`Policy`], controls what the outcome is.
271#[derive(Debug)]
272pub enum Outcome {
273    /// It's not an error.
274    Allowed,
275
276    /// The certificate is treated as revoked.
277    TreatAsRevoked,
278
279    /// The given error is returned.
280    Error(rustls::Error),
281}
282
283impl Outcome {
284    fn as_result(&self) -> Result<RevocationStatus, rustls::Error> {
285        match self {
286            Self::Allowed => Ok(RevocationStatus::NotCoveredByRevocationData),
287            Self::TreatAsRevoked => Err(CertificateError::Revoked.into()),
288            Self::Error(err) => Err(err.clone()),
289        }
290    }
291}
292
293fn sct_error(error: webpki::sct::Error) -> rustls::Error {
294    let message = match error {
295        webpki::sct::Error::MalformedSct => "malformed sct",
296        webpki::sct::Error::UnsupportedSctVersion => "unsupported sct version",
297        _ => "unknown sct error",
298    };
299
300    rustls::Error::General(message.into())
301}
302
303fn webpki_error(error: webpki::Error) -> rustls::Error {
304    use webpki::Error::*;
305    match error {
306        BadDer | BadDerTime | TrailingData(_) => CertificateError::BadEncoding.into(),
307        CertNotValidYet { time, not_before } => {
308            CertificateError::NotValidYetContext { time, not_before }.into()
309        }
310        CertExpired { time, not_after } => {
311            CertificateError::ExpiredContext { time, not_after }.into()
312        }
313        InvalidCertValidity => CertificateError::Expired.into(),
314        UnknownIssuer => CertificateError::UnknownIssuer.into(),
315        CertNotValidForName(InvalidNameContext {
316            expected,
317            presented,
318        }) => CertificateError::NotValidForNameContext {
319            expected,
320            presented,
321        }
322        .into(),
323        CertRevoked => CertificateError::Revoked.into(),
324        UnknownRevocationStatus => CertificateError::UnknownRevocationStatus.into(),
325        CrlExpired { time, next_update } => {
326            CertificateError::ExpiredRevocationListContext { time, next_update }.into()
327        }
328        IssuerNotCrlSigner => CertRevocationListError::IssuerInvalidForCrl.into(),
329
330        InvalidSignatureForPublicKey => CertificateError::BadSignature.into(),
331        UnsupportedSignatureAlgorithm(cx) => {
332            CertificateError::UnsupportedSignatureAlgorithmContext {
333                signature_algorithm_id: cx.signature_algorithm_id,
334                supported_algorithms: cx.supported_algorithms,
335            }
336            .into()
337        }
338        UnsupportedSignatureAlgorithmForPublicKey(cx) => {
339            CertificateError::UnsupportedSignatureAlgorithmForPublicKeyContext {
340                signature_algorithm_id: cx.signature_algorithm_id,
341                public_key_algorithm_id: cx.public_key_algorithm_id,
342            }
343            .into()
344        }
345
346        InvalidCrlSignatureForPublicKey => CertRevocationListError::BadSignature.into(),
347        UnsupportedCrlSignatureAlgorithm(cx) => {
348            CertRevocationListError::UnsupportedSignatureAlgorithmContext {
349                signature_algorithm_id: cx.signature_algorithm_id,
350                supported_algorithms: cx.supported_algorithms,
351            }
352            .into()
353        }
354        UnsupportedCrlSignatureAlgorithmForPublicKey(cx) => {
355            CertRevocationListError::UnsupportedSignatureAlgorithmForPublicKeyContext {
356                signature_algorithm_id: cx.signature_algorithm_id,
357                public_key_algorithm_id: cx.public_key_algorithm_id,
358            }
359            .into()
360        }
361
362        RequiredEkuNotFound(webpki::RequiredEkuNotFoundContext { required, present }) => {
363            rustls::Error::from(CertificateError::InvalidPurposeContext {
364                required: ekp_for_values(required.oid_values()),
365                presented: present
366                    .into_iter()
367                    .map(|eku| ekp_for_values(eku.into_iter()))
368                    .collect(),
369            })
370        }
371
372        _ => CertificateError::Other(rustls::OtherError(Arc::new(error))).into(),
373    }
374}
375
376pub(crate) fn ekp_for_values(values: impl Iterator<Item = usize>) -> ExtendedKeyPurpose {
377    let values = values.collect::<Vec<_>>();
378    match &*values {
379        ExtendedKeyUsage::CLIENT_AUTH_REPR => ExtendedKeyPurpose::ClientAuth,
380        ExtendedKeyUsage::SERVER_AUTH_REPR => ExtendedKeyPurpose::ServerAuth,
381        _ => ExtendedKeyPurpose::Other(values),
382    }
383}