diff --git a/Cargo.toml b/Cargo.toml index 667da18..a0669ea 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,29 +1,14 @@ -[package] -name = "webpki-roots" -version = "0.26.0" +[workspace] +members = ["webpki-ccadb", "webpki-roots"] + +[workspace.package] edition = "2018" -readme = "README.md" -license = "MPL-2.0" -description = "Mozilla's CA root certificates for use with webpki" homepage = "https://github.com/rustls/webpki-roots" repository = "https://github.com/rustls/webpki-roots" -[dependencies] -pki-types = { package = "rustls-pki-types", version = "1", default-features = false } - -[dev-dependencies] -chrono = { version = "0.4.26", default-features = false, features = ["clock"] } -csv = "1.2.2" +[workspace.dependencies] hex = "0.4.3" -num-bigint = "0.4.3" -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"] } +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 310ce7c..8046826 100644 --- a/README.md +++ b/README.md @@ -1,20 +1,25 @@ -# webpki-roots -This is a crate containing Mozilla's root certificates for use with +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. -This crate is inspired by [certifi.io](https://certifi.io/en/latest/) and +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/). [![webpki-roots](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-roots.svg)](https://crates.io/crates/webpki-roots) # License -The underlying data is MPL-licensed, and `src/lib.rs` +The underlying data is MPL-licensed, and `webpki-roots/src/lib.rs` is therefore a derived work. # Regenerating sources -Sources are generated in an integration test, in `tests/codegen.rs`. The test +Sources are generated in an integration test, in `webpki-roots/tests/codegen.rs`. The test will fail if the sources are out of date relative to upstream, and update -`src/lib.rs` if so. The code is generated in deterministic order so changes +`webpki-roots/src/lib.rs` if so. The code is generated in deterministic order so changes to the source should only result from upstream changes. 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/tests/data/DigiCertGlobalRootCA.pem b/webpki-ccadb/src/data/DigiCertGlobalRootCA.pem similarity index 100% rename from tests/data/DigiCertGlobalRootCA.pem rename to webpki-ccadb/src/data/DigiCertGlobalRootCA.pem diff --git a/tests/codegen.rs b/webpki-ccadb/src/lib.rs similarity index 60% rename from tests/codegen.rs rename to webpki-ccadb/src/lib.rs index 927387e..4b883a4 100644 --- a/tests/codegen.rs +++ b/webpki-ccadb/src/lib.rs @@ -1,20 +1,16 @@ -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 x509_parser::prelude::AttributeTypeAndValue; -use x509_parser::x509::X509Name; -#[tokio::test] -async fn new_generated_code_is_fresh() { +// 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. // @@ -28,12 +24,12 @@ async fn new_generated_code_is_fresh() { // 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/`. + // 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-roots/v{}", env!("CARGO_PKG_VERSION"))) + .user_agent(format!("webpki-ccadb/v{}", env!("CARGO_PKG_VERSION"))) .add_root_certificate(root) .build() .unwrap(); @@ -78,127 +74,7 @@ async fn new_generated_code_is_fresh() { } } - let mut code = String::with_capacity(256 * 1_024); - code.push_str(HEADER); - code.push_str("pub const TLS_SERVER_ROOTS: &[TrustAnchor] = &[\n"); - let (mut subject, mut spki, mut name_constraints) = - (String::new(), String::new(), String::new()); - - for (_, root) in tls_roots_map { - // Verify the DER FP matches the metadata FP. - let der = root.der(); - let calculated_fp = digest::digest(&digest::SHA256, &der); - let metadata_fp = hex::decode(&root.sha256_fingerprint).expect("malformed fingerprint"); - assert_eq!(calculated_fp.as_ref(), metadata_fp.as_slice()); - - let ta_der = CertificateDer::from(der.as_ref()); - let ta = anchor_from_trusted_cert(&ta_der).expect("malformed trust anchor der"); - subject.clear(); - for &b in ta.subject.as_ref() { - write!(&mut subject, "{}", escape_default(b)).unwrap(); - } - - spki.clear(); - for &b in ta.subject_public_key_info.as_ref() { - write!(&mut spki, "{}", escape_default(b)).unwrap(); - } - - name_constraints.clear(); - if let Some(nc) = &root.mozilla_applied_constraints() { - for &b in nc.iter() { - write!(&mut name_constraints, "{}", escape_default(b)).unwrap(); - } - } - - let (_, parsed_cert) = - x509_parser::parse_x509_certificate(&der).expect("malformed x509 der"); - let issuer = name_to_string(parsed_cert.issuer()); - let subject_str = name_to_string(parsed_cert.subject()); - let label = root.common_name_or_certificate_name.clone(); - let serial = root.serial().to_string(); - let sha256_fp = root.sha256_fp(); - - // Write comment - code.push_str(" /*\n"); - code.push_str(&format!(" * Issuer: {}\n", issuer)); - code.push_str(&format!(" * Subject: {}\n", subject_str)); - code.push_str(&format!(" * Label: {:?}\n", label)); - code.push_str(&format!(" * Serial: {}\n", serial)); - code.push_str(&format!(" * SHA256 Fingerprint: {}\n", sha256_fp)); - for ln in root.pem().lines() { - code.push_str(" * "); - code.push_str(ln.trim()); - code.push('\n'); - } - code.push_str(" */\n"); - - // Write the code - code.push_str(" TrustAnchor {\n"); - code.write_fmt(format_args!( - " subject: Der::from_slice(b\"{subject}\"),\n" - )) - .unwrap(); - code.write_fmt(format_args!( - " subject_public_key_info: Der::from_slice(b\"{spki}\"),\n" - )) - .unwrap(); - match name_constraints.is_empty() { - false => code - .write_fmt(format_args!( - " name_constraints: Some(Der::from_slice(b\"{name_constraints}\"))\n" - )) - .unwrap(), - true => code.push_str(" name_constraints: None\n"), - } - code.push_str(" },\n\n"); - } - code.push_str("];\n"); - - // Check that the generated code matches the checked-in code - let old = fs::read_to_string("src/lib.rs").unwrap(); - if old != code { - fs::write("src/lib.rs", code).unwrap(); - panic!("generated code changed"); - } -} - -/// The built-in x509_parser::X509Name Display impl uses a different sort order than -/// the one historically used by mkcert.org^[0]. We re-create that sort order here to -/// avoid unnecessary churn in the generated code. -/// -/// [0]: -fn name_to_string(name: &X509Name) -> String { - let mut ret = String::with_capacity(256); - - if let Some(cn) = name - .iter_common_name() - .next() - .and_then(|cn| cn.as_str().ok()) - { - write!(ret, "CN={}", cn).unwrap(); - } - - let mut append_attrs = |attrs: Vec<&AttributeTypeAndValue>, label| { - let str_parts = attrs - .iter() - .filter_map(|attr| match attr.as_str() { - Ok(s) => Some(s), - Err(_) => None, - }) - .collect::>() - .join("/"); - if !str_parts.is_empty() { - if !ret.is_empty() { - ret.push(' '); - } - write!(ret, "{}={}", label, str_parts).unwrap(); - } - }; - - append_attrs(name.iter_organization().collect(), "O"); - append_attrs(name.iter_organizational_unit().collect(), "OU"); - - ret + tls_roots_map } #[derive(Debug, Clone, Hash, Eq, PartialEq, Deserialize)] @@ -252,7 +128,7 @@ impl CertificateMetadata { /// 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> { + pub fn mozilla_applied_constraints(&self) -> Option> { if self.mozilla_applied_constraints.is_empty() { return None; } @@ -308,7 +184,7 @@ impl CertificateMetadata { /// 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> { + pub fn der(&self) -> CertificateDer<'static> { rustls_pemfile::certs(&mut self.pem().as_bytes()) .next() .unwrap() @@ -338,7 +214,7 @@ impl CertificateMetadata { /// Returns the PEM metadata for the certificate with the leading/trailing single quotes /// removed. - fn pem(&self) -> &str { + pub fn pem(&self) -> &str { self.pem_info.as_str().trim_matches('\'') } } @@ -374,38 +250,3 @@ impl From<&str> for TrustBits { } } } - -const HEADER: &str = r#"//! A compiled-in copy of the root certificates trusted by Mozilla. -//! -//! To use this library with rustls 0.22: -//! -//! ```rust -//! let root_store = rustls::RootCertStore { -//! roots: webpki_roots::TLS_SERVER_ROOTS.iter().cloned().collect(), -//! }; -//! ``` -//! -//! This library is suitable for use in applications that can always be recompiled and instantly deployed. -//! For applications that are deployed to end-users and cannot be recompiled, or which need certification -//! before deployment, consider a library that loads certificates at runtime, like -//! [rustls-native-certs](https://docs.rs/rustls-native-certs). -// -// This library is automatically generated from the Mozilla -// IncludedCACertificateReportPEMCSV report via ccadb.org. Don't edit it. -// -// The generation is done deterministically so you can verify it -// yourself by inspecting and re-running the generation process. - -#![no_std] -#![forbid(unsafe_code, unstable_features)] -#![deny( - trivial_casts, - trivial_numeric_casts, - unused_import_braces, - unused_extern_crates, - unused_qualifications -)] - -use pki_types::{Der, TrustAnchor}; - -"#; diff --git a/webpki-roots/Cargo.toml b/webpki-roots/Cargo.toml new file mode 100644 index 0000000..518b437 --- /dev/null +++ b/webpki-roots/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "webpki-roots" +version = "0.26.0" +edition = { workspace = true } +readme = "README.md" +license = "MPL-2.0" +homepage = { workspace = true } +repository = { workspace = true } +description = "Mozilla's CA root certificates for use with webpki" + +[dependencies] +pki-types = { workspace = true } + +[dev-dependencies] +hex = { workspace = true } +percent-encoding = "2.3" +rcgen = "0.11.1" +ring = "0.17.0" +rustls = "0.22" +tokio = { version = "1", features = ["macros", "rt-multi-thread"] } +webpki = { workspace = true } +webpki-ccadb = { path = "../webpki-ccadb" } +x509-parser = { workspace = true } +yasna = { workspace = true } diff --git a/LICENSE b/webpki-roots/LICENSE similarity index 100% rename from LICENSE rename to webpki-roots/LICENSE diff --git a/webpki-roots/README.md b/webpki-roots/README.md new file mode 100644 index 0000000..310ce7c --- /dev/null +++ b/webpki-roots/README.md @@ -0,0 +1,20 @@ +# webpki-roots +This is a crate containing Mozilla's root certificates for use with +the [webpki](https://github.com/rustls/webpki) or +[rustls](https://github.com/rustls/rustls) crates. + +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-roots](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-roots.svg)](https://crates.io/crates/webpki-roots) + +# License +The underlying data is MPL-licensed, and `src/lib.rs` +is therefore a derived work. + +# Regenerating sources +Sources are generated in an integration test, in `tests/codegen.rs`. The test +will fail if the sources are out of date relative to upstream, and update +`src/lib.rs` if so. The code is generated in deterministic order so changes +to the source should only result from upstream changes. diff --git a/src/lib.rs b/webpki-roots/src/lib.rs similarity index 100% rename from src/lib.rs rename to webpki-roots/src/lib.rs diff --git a/webpki-roots/tests/codegen.rs b/webpki-roots/tests/codegen.rs new file mode 100644 index 0000000..fb67dbc --- /dev/null +++ b/webpki-roots/tests/codegen.rs @@ -0,0 +1,171 @@ +use std::ascii::escape_default; +use std::fmt::Write; +use std::fs; + +use pki_types::CertificateDer; +use ring::digest; +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() { + 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"); + let (mut subject, mut spki, mut name_constraints) = + (String::new(), String::new(), String::new()); + + for (_, root) in tls_roots_map { + // Verify the DER FP matches the metadata FP. + let der = root.der(); + let calculated_fp = digest::digest(&digest::SHA256, &der); + let metadata_fp = hex::decode(&root.sha256_fingerprint).expect("malformed fingerprint"); + assert_eq!(calculated_fp.as_ref(), metadata_fp.as_slice()); + + let ta_der = CertificateDer::from(der.as_ref()); + let ta = anchor_from_trusted_cert(&ta_der).expect("malformed trust anchor der"); + subject.clear(); + for &b in ta.subject.as_ref() { + write!(&mut subject, "{}", escape_default(b)).unwrap(); + } + + spki.clear(); + for &b in ta.subject_public_key_info.as_ref() { + write!(&mut spki, "{}", escape_default(b)).unwrap(); + } + + name_constraints.clear(); + if let Some(nc) = &root.mozilla_applied_constraints() { + for &b in nc.iter() { + write!(&mut name_constraints, "{}", escape_default(b)).unwrap(); + } + } + + let (_, parsed_cert) = + x509_parser::parse_x509_certificate(&der).expect("malformed x509 der"); + let issuer = name_to_string(parsed_cert.issuer()); + let subject_str = name_to_string(parsed_cert.subject()); + let label = root.common_name_or_certificate_name.clone(); + let serial = root.serial().to_string(); + let sha256_fp = root.sha256_fp(); + + // Write comment + code.push_str(" /*\n"); + code.push_str(&format!(" * Issuer: {}\n", issuer)); + code.push_str(&format!(" * Subject: {}\n", subject_str)); + code.push_str(&format!(" * Label: {:?}\n", label)); + code.push_str(&format!(" * Serial: {}\n", serial)); + code.push_str(&format!(" * SHA256 Fingerprint: {}\n", sha256_fp)); + for ln in root.pem().lines() { + code.push_str(" * "); + code.push_str(ln.trim()); + code.push('\n'); + } + code.push_str(" */\n"); + + // Write the code + code.push_str(" TrustAnchor {\n"); + code.write_fmt(format_args!( + " subject: Der::from_slice(b\"{subject}\"),\n" + )) + .unwrap(); + code.write_fmt(format_args!( + " subject_public_key_info: Der::from_slice(b\"{spki}\"),\n" + )) + .unwrap(); + match name_constraints.is_empty() { + false => code + .write_fmt(format_args!( + " name_constraints: Some(Der::from_slice(b\"{name_constraints}\"))\n" + )) + .unwrap(), + true => code.push_str(" name_constraints: None\n"), + } + code.push_str(" },\n\n"); + } + code.push_str("];\n"); + + // Check that the generated code matches the checked-in code + let old = fs::read_to_string("src/lib.rs").unwrap(); + if old != code { + fs::write("src/lib.rs", code).unwrap(); + panic!("generated code changed"); + } +} + +/// The built-in x509_parser::X509Name Display impl uses a different sort order than +/// the one historically used by mkcert.org^[0]. We re-create that sort order here to +/// avoid unnecessary churn in the generated code. +/// +/// [0]: +fn name_to_string(name: &X509Name) -> String { + let mut ret = String::with_capacity(256); + + if let Some(cn) = name + .iter_common_name() + .next() + .and_then(|cn| cn.as_str().ok()) + { + write!(ret, "CN={}", cn).unwrap(); + } + + let mut append_attrs = |attrs: Vec<&AttributeTypeAndValue>, label| { + let str_parts = attrs + .iter() + .filter_map(|attr| match attr.as_str() { + Ok(s) => Some(s), + Err(_) => None, + }) + .collect::>() + .join("/"); + if !str_parts.is_empty() { + if !ret.is_empty() { + ret.push(' '); + } + write!(ret, "{}={}", label, str_parts).unwrap(); + } + }; + + append_attrs(name.iter_organization().collect(), "O"); + append_attrs(name.iter_organizational_unit().collect(), "OU"); + + ret +} + +const HEADER: &str = r#"//! A compiled-in copy of the root certificates trusted by Mozilla. +//! +//! To use this library with rustls 0.22: +//! +//! ```rust +//! let root_store = rustls::RootCertStore { +//! roots: webpki_roots::TLS_SERVER_ROOTS.iter().cloned().collect(), +//! }; +//! ``` +//! +//! This library is suitable for use in applications that can always be recompiled and instantly deployed. +//! For applications that are deployed to end-users and cannot be recompiled, or which need certification +//! before deployment, consider a library that loads certificates at runtime, like +//! [rustls-native-certs](https://docs.rs/rustls-native-certs). +// +// This library is automatically generated from the Mozilla +// IncludedCACertificateReportPEMCSV report via ccadb.org. Don't edit it. +// +// The generation is done deterministically so you can verify it +// yourself by inspecting and re-running the generation process. + +#![no_std] +#![forbid(unsafe_code, unstable_features)] +#![deny( + trivial_casts, + trivial_numeric_casts, + unused_import_braces, + unused_extern_crates, + unused_qualifications +)] + +use pki_types::{Der, TrustAnchor}; + +"#; diff --git a/tests/data/tubitak/inter.der b/webpki-roots/tests/data/tubitak/inter.der similarity index 100% rename from tests/data/tubitak/inter.der rename to webpki-roots/tests/data/tubitak/inter.der diff --git a/tests/data/tubitak/root.der b/webpki-roots/tests/data/tubitak/root.der similarity index 100% rename from tests/data/tubitak/root.der rename to webpki-roots/tests/data/tubitak/root.der diff --git a/tests/data/tubitak/subj.der b/webpki-roots/tests/data/tubitak/subj.der similarity index 100% rename from tests/data/tubitak/subj.der rename to webpki-roots/tests/data/tubitak/subj.der diff --git a/tests/verify.rs b/webpki-roots/tests/verify.rs similarity index 100% rename from tests/verify.rs rename to webpki-roots/tests/verify.rs