diff --git a/Cargo.toml b/Cargo.toml index 3bcc738..a0669ea 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,2 +1,14 @@ [workspace] -members = ["webpki-roots"] +members = ["webpki-ccadb", "webpki-roots"] + +[workspace.package] +edition = "2018" +homepage = "https://github.com/rustls/webpki-roots" +repository = "https://github.com/rustls/webpki-roots" + +[workspace.dependencies] +hex = "0.4.3" +pki-types = { package = "rustls-pki-types", version = "1", default-features = false } +webpki = { package = "rustls-webpki", version = "0.102", features = ["alloc"] } +x509-parser = "0.15.1" +yasna = "0.5.2" diff --git a/README.md b/README.md index f5370fa..8046826 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,13 @@ -This workspace contains the crate webpki-roots. +This workspace contains the crates webpki-roots and webpki-ccadb. The webpki-roots crate contains Mozilla's root certificates for use with the [webpki](https://github.com/rustls/webpki) or [rustls](https://github.com/rustls/rustls) crates. +The webpki-ccadb crate populates the root certificates for the webpki-roots crate +using the data provided by the [Common CA Database (CCADB)](https://www.ccadb.org/). +Inspired by [certifi.io](https://certifi.io/en/latest/). + The webpki-roots crate is inspired by [certifi.io](https://certifi.io/en/latest/) and uses the data provided by the [Common CA Database (CCADB)](https://www.ccadb.org/). diff --git a/webpki-ccadb/Cargo.toml b/webpki-ccadb/Cargo.toml new file mode 100644 index 0000000..8522b63 --- /dev/null +++ b/webpki-ccadb/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "webpki-ccadb" +version = "0.1.0" +edition = { workspace = true } +readme = "README.md" +license = "MIT OR Apache-2.0" +homepage = { workspace = true } +repository = { workspace = true } +description = "Common CA Database (CCADB) interface for use with webpki-roots" + +[dependencies] +chrono = { version = "0.4.26", default-features = false, features = ["clock"] } +csv = "1.2.2" +hex = { workspace = true } +num-bigint = "0.4.3" +pki-types = { workspace = true } +reqwest = { version = "0.11", features = ["rustls-tls-manual-roots"] } +rustls-pemfile = "2.0.0" +serde = { version = "1.0.183", features = ["derive"] } +webpki = { workspace = true } +x509-parser = { workspace = true } +yasna = { workspace = true } diff --git a/webpki-ccadb/LICENSE-APACHE b/webpki-ccadb/LICENSE-APACHE new file mode 100644 index 0000000..5449729 --- /dev/null +++ b/webpki-ccadb/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright 2023 Dirkjan Ochtman + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/webpki-ccadb/LICENSE-MIT b/webpki-ccadb/LICENSE-MIT new file mode 100644 index 0000000..f8cdbfd --- /dev/null +++ b/webpki-ccadb/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2023 Dirkjan Ochtman + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/webpki-ccadb/README.md b/webpki-ccadb/README.md new file mode 100644 index 0000000..6a58da6 --- /dev/null +++ b/webpki-ccadb/README.md @@ -0,0 +1,9 @@ +# webpki-ccadb +This is a crate to fetch Mozilla's root certificates for use with +[webpki-roots](https://github.com/rustls/webpki-roots) crate. + +This crate is inspired by [certifi.io](https://certifi.io/en/latest/) and +uses the data provided by the [Common CA Database (CCADB)](https://www.ccadb.org/). + +[![webpki-ccadb](https://github.com/rustls/webpki-roots/actions/workflows/build.yml/badge.svg?branch=main)](https://github.com/rustls/webpki-roots/actions/workflows/build.yml) +[![Crate](https://img.shields.io/crates/v/webpki-ccadb.svg)](https://crates.io/crates/webpki-ccadb) diff --git a/webpki-roots/tests/data/DigiCertGlobalRootCA.pem b/webpki-ccadb/src/data/DigiCertGlobalRootCA.pem similarity index 100% rename from webpki-roots/tests/data/DigiCertGlobalRootCA.pem rename to webpki-ccadb/src/data/DigiCertGlobalRootCA.pem diff --git a/webpki-ccadb/src/lib.rs b/webpki-ccadb/src/lib.rs new file mode 100644 index 0000000..4b883a4 --- /dev/null +++ b/webpki-ccadb/src/lib.rs @@ -0,0 +1,252 @@ +use std::cmp::Ordering; +use std::collections::{BTreeMap, HashSet}; + +use chrono::{NaiveDate, Utc}; +use num_bigint::BigUint; +use pki_types::CertificateDer; +use serde::Deserialize; + +// Fetch root certificate data from the CCADB server. +// +// Returns an ordered BTreeMap of the root certificates, keyed by the SHA256 fingerprint of the +// certificate. Panics if there are any duplicate fingerprints. +pub async fn fetch_ccadb_roots() -> BTreeMap { + // Configure a Reqwest client that only trusts the CA certificate expected to be the + // root of trust for the CCADB server. + // + // If we see Unknown CA TLS validation failures from the Reqwest client in the future it + // likely indicates that the upstream service has changed certificate authorities. In this + // case the vendored root CA will need to be updated. You can find the current root in use with + // Chrome by: + // 1. Navigating to `https://ccadb-public.secure.force.com/mozilla/` + // 2. Clicking the lock icon. + // 3. Clicking "Connection is secure" + // 4. Clicking "Certificate is valid" + // 5. Clicking the "Details" tab. + // 6. Selecting the topmost "System Trust" entry. + // 7. Clicking "Export..." and saving the certificate to `webpki-roots/webpki-ccadb/src/data/`. + // 8. Committing the updated .pem root CA, and updating the `include_bytes!` path. + let root = include_bytes!("data/DigiCertGlobalRootCA.pem"); + let root = reqwest::Certificate::from_pem(root).unwrap(); + let client = reqwest::Client::builder() + .user_agent(format!("webpki-ccadb/v{}", env!("CARGO_PKG_VERSION"))) + .add_root_certificate(root) + .build() + .unwrap(); + + let ccadb_url = + "https://ccadb-public.secure.force.com/mozilla/IncludedCACertificateReportPEMCSV"; + eprintln!("fetching {ccadb_url}..."); + + let req = client.get(ccadb_url).build().unwrap(); + let csv_data = client + .execute(req) + .await + .expect("failed to fetch CSV") + .text() + .await + .unwrap(); + + // Parse the CSV metadata. + let metadata = csv::ReaderBuilder::new() + .has_headers(true) + .from_reader(csv_data.as_bytes()) + .into_deserialize::() + .collect::, _>>() + .unwrap(); + + // Filter for just roots with the TLS trust bit that are not distrusted as of today's date. + let trusted_tls_roots = metadata + .into_iter() + .filter(|root| root.trusted_for_tls(&Utc::now().naive_utc().date())) + .collect::>(); + + // Create an ordered BTreeMap of the roots, panicking for any duplicates. + let mut tls_roots_map = BTreeMap::new(); + for root in trusted_tls_roots { + match tls_roots_map.get(&root.sha256_fingerprint) { + Some(_) => { + panic!("duplicate fingerprint {}", root.sha256_fingerprint); + } + None => { + tls_roots_map.insert(root.sha256_fingerprint.clone(), root); + } + } + } + + tls_roots_map +} + +#[derive(Debug, Clone, Hash, Eq, PartialEq, Deserialize)] +pub struct CertificateMetadata { + #[serde(rename = "Common Name or Certificate Name")] + pub common_name_or_certificate_name: String, + + #[serde(rename = "Certificate Serial Number")] + pub certificate_serial_number: String, + + #[serde(rename = "SHA-256 Fingerprint")] + pub sha256_fingerprint: String, + + #[serde(rename = "Trust Bits")] + pub trust_bits: String, + + #[serde(rename = "Distrust for TLS After Date")] + pub distrust_for_tls_after_date: String, + + #[serde(rename = "Mozilla Applied Constraints")] + pub mozilla_applied_constraints: String, + + #[serde(rename = "PEM Info")] + pub pem_info: String, +} + +impl CertificateMetadata { + /// Returns true iff the certificate has valid TrustBits that include TrustBits::Websites, + /// and the certificate has no distrust for TLS after date, or has a valid distrust + /// for TLS after date that is in the future compared to `now`. In all other cases this function + /// returns false. + fn trusted_for_tls(&self, now: &NaiveDate) -> bool { + let has_tls_trust_bit = self.trust_bits().contains(&TrustBits::Websites); + + match (has_tls_trust_bit, self.tls_distrust_after()) { + // No website trust bit - not trusted for tls. + (false, _) => false, + // Has website trust bit, no distrust after - trusted for tls. + (true, None) => true, + // Trust bit, populated distrust after - need to check date to decide. + (true, Some(tls_distrust_after)) => { + match now.cmp(&tls_distrust_after).is_ge() { + // We're past the distrust date - skip. + true => false, + // We haven't yet reached the distrust date - include. + false => true, + } + } + } + } + + /// Return the Mozilla applied constraints for the certificate (if any). The constraints + /// will be encoded in the DER form expected by the webpki crate's TrustAnchor representation. + pub fn mozilla_applied_constraints(&self) -> Option> { + if self.mozilla_applied_constraints.is_empty() { + return None; + } + + // NOTE: To date there's only one CA with a applied constraints value, and it has only one + // permitted subtree constraint imposed. It's not clear how multiple constraints would be + // expressed. This method makes a best guess but may need to be revisited in the future. + // https://groups.google.com/a/ccadb.org/g/public/c/TlDivISPVT4/m/jbWGuM4YAgAJ + let included_subtrees = self.mozilla_applied_constraints.split(','); + + // Important: the webpki representation of name constraints elides: + // - the outer BITSTRING of the X.509 extension value. + // - the outer NameConstraints SEQUENCE over the permitted/excluded subtrees. + // + // See https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.10 + let der = yasna::construct_der(|writer| { + // permittedSubtrees [0] + writer.write_tagged_implicit(yasna::Tag::context(0), |writer| { + // GeneralSubtrees + writer.write_sequence(|writer| { + for included_subtree in included_subtrees { + // base GeneralName + writer.next().write_sequence(|writer| { + writer + .next() + // DnsName + .write_tagged_implicit(yasna::Tag::context(2), |writer| { + writer + .write_ia5_string(included_subtree.trim_start_matches('*')) + }) + }) + // minimum [0] (absent, 0 default) + // maximum [1] (must be omitted). + } + }) + }) + }); + + Some(der) + } + + /// Return the NaiveDate after which this certificate should not be trusted for TLS (if any). + /// Panics if there is a distrust for TLS after date value that can not be parsed. + fn tls_distrust_after(&self) -> Option { + match &self.distrust_for_tls_after_date { + date if date.is_empty() => None, + date => Some( + NaiveDate::parse_from_str(date, "%Y.%m.%d") + .unwrap_or_else(|_| panic!("invalid distrust for tls after date: {:?}", date)), + ), + } + } + + /// Returns the DER encoding of the certificate contained in the metadata PEM. Panics if + /// there is an error, or no certificate in the PEM content. + pub fn der(&self) -> CertificateDer<'static> { + rustls_pemfile::certs(&mut self.pem().as_bytes()) + .next() + .unwrap() + .expect("invalid PEM") + } + + /// Returns the serial number for the certificate. Panics if the certificate serial number + /// from the metadata can not be parsed as a base 16 unsigned big integer. + pub fn serial(&self) -> BigUint { + BigUint::parse_bytes(self.certificate_serial_number.as_bytes(), 16) + .expect("invalid certificate serial number") + } + + /// Returns the colon separated string with the metadata SHA256 fingerprint for the + /// certificate. Panics if the sha256 fingerprint from the metadata can't be decoded. + pub fn sha256_fp(&self) -> String { + x509_parser::utils::format_serial( + &hex::decode(&self.sha256_fingerprint).expect("invalid sha256 fingerprint"), + ) + } + + /// Returns the set of trust bits expressed for this certificate. Panics if the raw + /// trust bits are invalid/unknown. + fn trust_bits(&self) -> HashSet { + self.trust_bits.split(';').map(TrustBits::from).collect() + } + + /// Returns the PEM metadata for the certificate with the leading/trailing single quotes + /// removed. + pub fn pem(&self) -> &str { + self.pem_info.as_str().trim_matches('\'') + } +} + +impl PartialOrd for CertificateMetadata { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.sha256_fingerprint.cmp(&other.sha256_fingerprint)) + } +} + +impl Ord for CertificateMetadata { + fn cmp(&self, other: &Self) -> Ordering { + self.sha256_fingerprint.cmp(&other.sha256_fingerprint) + } +} + +#[derive(Debug, Hash, Eq, PartialEq, Clone, Copy)] +#[non_exhaustive] +/// TrustBits describe the possible Mozilla root certificate trust bits. +pub enum TrustBits { + /// certificate is trusted for Websites (e.g. TLS). + Websites, + /// certificate is trusted for Email (e.g. S/MIME). + Email, +} + +impl From<&str> for TrustBits { + fn from(value: &str) -> Self { + match value { + "Websites" => TrustBits::Websites, + "Email" => TrustBits::Email, + val => panic!("unknown trust bit: {:?}", val), + } + } +} diff --git a/webpki-roots/Cargo.toml b/webpki-roots/Cargo.toml index fe6b0b4..518b437 100644 --- a/webpki-roots/Cargo.toml +++ b/webpki-roots/Cargo.toml @@ -1,29 +1,24 @@ [package] name = "webpki-roots" version = "0.26.0" -edition = "2018" +edition = { workspace = true } readme = "README.md" license = "MPL-2.0" -homepage = "https://github.com/rustls/webpki-roots" -repository = "https://github.com/rustls/webpki-roots" +homepage = { workspace = true } +repository = { workspace = true } description = "Mozilla's CA root certificates for use with webpki" [dependencies] -pki-types = { package = "rustls-pki-types", version = "1", default-features = false } +pki-types = { workspace = true } [dev-dependencies] -chrono = { version = "0.4.26", default-features = false, features = ["clock"] } -csv = "1.2.2" -hex = "0.4.3" -num-bigint = "0.4.3" +hex = { workspace = true } percent-encoding = "2.3" rcgen = "0.11.1" -reqwest = { version = "0.11", features = ["rustls-tls-manual-roots"] } ring = "0.17.0" -rustls-pemfile = "2.0.0" rustls = "0.22" -serde = { version = "1.0.183", features = ["derive"] } tokio = { version = "1", features = ["macros", "rt-multi-thread"] } -webpki = { package = "rustls-webpki", version = "0.102", features = ["alloc"] } -x509-parser = "0.15.1" -yasna = "0.5.2" +webpki = { workspace = true } +webpki-ccadb = { path = "../webpki-ccadb" } +x509-parser = { workspace = true } +yasna = { workspace = true } diff --git a/webpki-roots/tests/codegen.rs b/webpki-roots/tests/codegen.rs index 927387e..fb67dbc 100644 --- a/webpki-roots/tests/codegen.rs +++ b/webpki-roots/tests/codegen.rs @@ -1,83 +1,17 @@ use std::ascii::escape_default; -use std::cmp::Ordering; -use std::collections::{BTreeMap, HashSet}; use std::fmt::Write; use std::fs; -use chrono::{NaiveDate, Utc}; -use num_bigint::BigUint; use pki_types::CertificateDer; use ring::digest; -use serde::Deserialize; use webpki::anchor_from_trusted_cert; +use webpki_ccadb::fetch_ccadb_roots; use x509_parser::prelude::AttributeTypeAndValue; use x509_parser::x509::X509Name; #[tokio::test] async fn new_generated_code_is_fresh() { - // Configure a Reqwest client that only trusts the CA certificate expected to be the - // root of trust for the CCADB server. - // - // If we see Unknown CA TLS validation failures from the Reqwest client in the future it - // likely indicates that the upstream service has changed certificate authorities. In this - // case the vendored root CA will need to be updated. You can find the current root in use with - // Chrome by: - // 1. Navigating to `https://ccadb-public.secure.force.com/mozilla/` - // 2. Clicking the lock icon. - // 3. Clicking "Connection is secure" - // 4. Clicking "Certificate is valid" - // 5. Clicking the "Details" tab. - // 6. Selecting the topmost "System Trust" entry. - // 7. Clicking "Export..." and saving the certificate to `webpki-roots/tests/data/`. - // 8. Committing the updated .pem root CA, and updating the `include_bytes!` path. - let root = include_bytes!("data/DigiCertGlobalRootCA.pem"); - let root = reqwest::Certificate::from_pem(root).unwrap(); - let client = reqwest::Client::builder() - .user_agent(format!("webpki-roots/v{}", env!("CARGO_PKG_VERSION"))) - .add_root_certificate(root) - .build() - .unwrap(); - - let ccadb_url = - "https://ccadb-public.secure.force.com/mozilla/IncludedCACertificateReportPEMCSV"; - eprintln!("fetching {ccadb_url}..."); - - let req = client.get(ccadb_url).build().unwrap(); - let csv_data = client - .execute(req) - .await - .expect("failed to fetch CSV") - .text() - .await - .unwrap(); - - // Parse the CSV metadata. - let metadata = csv::ReaderBuilder::new() - .has_headers(true) - .from_reader(csv_data.as_bytes()) - .into_deserialize::() - .collect::, _>>() - .unwrap(); - - // Filter for just roots with the TLS trust bit that are not distrusted as of today's date. - let trusted_tls_roots = metadata - .into_iter() - .filter(|root| root.trusted_for_tls(&Utc::now().naive_utc().date())) - .collect::>(); - - // Create an ordered BTreeMap of the roots, panicking for any duplicates. - let mut tls_roots_map = BTreeMap::new(); - for root in trusted_tls_roots { - match tls_roots_map.get(&root.sha256_fingerprint) { - Some(_) => { - panic!("duplicate fingerprint {}", root.sha256_fingerprint); - } - None => { - tls_roots_map.insert(root.sha256_fingerprint.clone(), root); - } - } - } - + let tls_roots_map = fetch_ccadb_roots().await; let mut code = String::with_capacity(256 * 1_024); code.push_str(HEADER); code.push_str("pub const TLS_SERVER_ROOTS: &[TrustAnchor] = &[\n"); @@ -201,180 +135,6 @@ fn name_to_string(name: &X509Name) -> String { ret } -#[derive(Debug, Clone, Hash, Eq, PartialEq, Deserialize)] -pub struct CertificateMetadata { - #[serde(rename = "Common Name or Certificate Name")] - pub common_name_or_certificate_name: String, - - #[serde(rename = "Certificate Serial Number")] - pub certificate_serial_number: String, - - #[serde(rename = "SHA-256 Fingerprint")] - pub sha256_fingerprint: String, - - #[serde(rename = "Trust Bits")] - pub trust_bits: String, - - #[serde(rename = "Distrust for TLS After Date")] - pub distrust_for_tls_after_date: String, - - #[serde(rename = "Mozilla Applied Constraints")] - pub mozilla_applied_constraints: String, - - #[serde(rename = "PEM Info")] - pub pem_info: String, -} - -impl CertificateMetadata { - /// Returns true iff the certificate has valid TrustBits that include TrustBits::Websites, - /// and the certificate has no distrust for TLS after date, or has a valid distrust - /// for TLS after date that is in the future compared to `now`. In all other cases this function - /// returns false. - fn trusted_for_tls(&self, now: &NaiveDate) -> bool { - let has_tls_trust_bit = self.trust_bits().contains(&TrustBits::Websites); - - match (has_tls_trust_bit, self.tls_distrust_after()) { - // No website trust bit - not trusted for tls. - (false, _) => false, - // Has website trust bit, no distrust after - trusted for tls. - (true, None) => true, - // Trust bit, populated distrust after - need to check date to decide. - (true, Some(tls_distrust_after)) => { - match now.cmp(&tls_distrust_after).is_ge() { - // We're past the distrust date - skip. - true => false, - // We haven't yet reached the distrust date - include. - false => true, - } - } - } - } - - /// Return the Mozilla applied constraints for the certificate (if any). The constraints - /// will be encoded in the DER form expected by the webpki crate's TrustAnchor representation. - fn mozilla_applied_constraints(&self) -> Option> { - if self.mozilla_applied_constraints.is_empty() { - return None; - } - - // NOTE: To date there's only one CA with a applied constraints value, and it has only one - // permitted subtree constraint imposed. It's not clear how multiple constraints would be - // expressed. This method makes a best guess but may need to be revisited in the future. - // https://groups.google.com/a/ccadb.org/g/public/c/TlDivISPVT4/m/jbWGuM4YAgAJ - let included_subtrees = self.mozilla_applied_constraints.split(','); - - // Important: the webpki representation of name constraints elides: - // - the outer BITSTRING of the X.509 extension value. - // - the outer NameConstraints SEQUENCE over the permitted/excluded subtrees. - // - // See https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.10 - let der = yasna::construct_der(|writer| { - // permittedSubtrees [0] - writer.write_tagged_implicit(yasna::Tag::context(0), |writer| { - // GeneralSubtrees - writer.write_sequence(|writer| { - for included_subtree in included_subtrees { - // base GeneralName - writer.next().write_sequence(|writer| { - writer - .next() - // DnsName - .write_tagged_implicit(yasna::Tag::context(2), |writer| { - writer - .write_ia5_string(included_subtree.trim_start_matches('*')) - }) - }) - // minimum [0] (absent, 0 default) - // maximum [1] (must be omitted). - } - }) - }) - }); - - Some(der) - } - - /// Return the NaiveDate after which this certificate should not be trusted for TLS (if any). - /// Panics if there is a distrust for TLS after date value that can not be parsed. - fn tls_distrust_after(&self) -> Option { - match &self.distrust_for_tls_after_date { - date if date.is_empty() => None, - date => Some( - NaiveDate::parse_from_str(date, "%Y.%m.%d") - .unwrap_or_else(|_| panic!("invalid distrust for tls after date: {:?}", date)), - ), - } - } - - /// Returns the DER encoding of the certificate contained in the metadata PEM. Panics if - /// there is an error, or no certificate in the PEM content. - fn der(&self) -> CertificateDer<'static> { - rustls_pemfile::certs(&mut self.pem().as_bytes()) - .next() - .unwrap() - .expect("invalid PEM") - } - - /// Returns the serial number for the certificate. Panics if the certificate serial number - /// from the metadata can not be parsed as a base 16 unsigned big integer. - pub fn serial(&self) -> BigUint { - BigUint::parse_bytes(self.certificate_serial_number.as_bytes(), 16) - .expect("invalid certificate serial number") - } - - /// Returns the colon separated string with the metadata SHA256 fingerprint for the - /// certificate. Panics if the sha256 fingerprint from the metadata can't be decoded. - pub fn sha256_fp(&self) -> String { - x509_parser::utils::format_serial( - &hex::decode(&self.sha256_fingerprint).expect("invalid sha256 fingerprint"), - ) - } - - /// Returns the set of trust bits expressed for this certificate. Panics if the raw - /// trust bits are invalid/unknown. - fn trust_bits(&self) -> HashSet { - self.trust_bits.split(';').map(TrustBits::from).collect() - } - - /// Returns the PEM metadata for the certificate with the leading/trailing single quotes - /// removed. - fn pem(&self) -> &str { - self.pem_info.as_str().trim_matches('\'') - } -} - -impl PartialOrd for CertificateMetadata { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.sha256_fingerprint.cmp(&other.sha256_fingerprint)) - } -} - -impl Ord for CertificateMetadata { - fn cmp(&self, other: &Self) -> Ordering { - self.sha256_fingerprint.cmp(&other.sha256_fingerprint) - } -} - -#[derive(Debug, Hash, Eq, PartialEq, Clone, Copy)] -#[non_exhaustive] -/// TrustBits describe the possible Mozilla root certificate trust bits. -pub enum TrustBits { - /// certificate is trusted for Websites (e.g. TLS). - Websites, - /// certificate is trusted for Email (e.g. S/MIME). - Email, -} - -impl From<&str> for TrustBits { - fn from(value: &str) -> Self { - match value { - "Websites" => TrustBits::Websites, - "Email" => TrustBits::Email, - val => panic!("unknown trust bit: {:?}", val), - } - } -} - const HEADER: &str = r#"//! A compiled-in copy of the root certificates trusted by Mozilla. //! //! To use this library with rustls 0.22: