From 2341203c081876de53592ed455c0822a3c79d149 Mon Sep 17 00:00:00 2001 From: Dirkjan Ochtman Date: Sat, 5 Aug 2023 21:02:16 +0200 Subject: [PATCH 01/13] Initialize Cargo project --- .gitignore | 2 ++ Cargo.toml | 8 ++++++++ src/lib.rs | 14 ++++++++++++++ 3 files changed, 24 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.toml create mode 100644 src/lib.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..4fffb2f8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/target +/Cargo.lock diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 00000000..10fd7778 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "rustls-pki-types" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 00000000..7d12d9af --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,14 @@ +pub fn add(left: usize, right: usize) -> usize { + left + right +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn it_works() { + let result = add(2, 2); + assert_eq!(result, 4); + } +} From b2acb92e66b8a413d82fc8df7d9267fe0fcb58f4 Mon Sep 17 00:00:00 2001 From: Dirkjan Ochtman Date: Thu, 31 Aug 2023 11:08:06 +0200 Subject: [PATCH 02/13] Start collection of basic data types (#1) * Add CI workflows * Extend Cargo metadata * Start collection of basic data types --- .github/workflows/rust.yml | 116 ++++++++++++ Cargo.toml | 15 +- LICENSE-APACHE | 201 +++++++++++++++++++++ LICENSE-MIT | 25 +++ README.md | 40 +++++ src/lib.rs | 357 +++++++++++++++++++++++++++++++++++-- 6 files changed, 742 insertions(+), 12 deletions(-) create mode 100644 .github/workflows/rust.yml create mode 100644 LICENSE-APACHE create mode 100644 LICENSE-MIT create mode 100644 README.md diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml new file mode 100644 index 00000000..c51629ad --- /dev/null +++ b/.github/workflows/rust.yml @@ -0,0 +1,116 @@ +name: rustls + +permissions: + contents: read + +on: + push: + pull_request: + merge_group: + schedule: + - cron: '0 21 * * *' + +jobs: + build: + name: Build + test + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + # test a bunch of toolchains on ubuntu + rust: + - stable + - beta + - nightly + os: [ubuntu-20.04] + # but only stable on macos/windows (slower platforms) + include: + - os: macos-latest + rust: stable + - os: windows-latest + rust: stable + steps: + - name: Checkout sources + uses: actions/checkout@v3 + with: + persist-credentials: false + + - name: Install ${{ matrix.rust }} toolchain + uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ matrix.rust }} + + - name: cargo test (debug; default features) + run: cargo test + env: + RUST_BACKTRACE: 1 + + - name: cargo test (debug; all features) + run: cargo test --all-features + env: + RUST_BACKTRACE: 1 + + - name: cargo test (debug; no default features; no run) + run: cargo test --no-default-features + env: + RUST_BACKTRACE: 1 + + msrv: + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-20.04, macos-latest, windows-latest] + steps: + - name: Checkout sources + uses: actions/checkout@v3 + with: + persist-credentials: false + + - name: Install MSRV toolchain + uses: dtolnay/rust-toolchain@master + with: + toolchain: "1.60" + + - run: cargo check --lib --all-features + + format: + name: Format + runs-on: ubuntu-latest + steps: + - name: Checkout sources + uses: actions/checkout@v3 + with: + persist-credentials: false + - name: Install rust toolchain + uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt + - name: Check formatting + run: cargo fmt --all -- --check + + clippy: + name: Clippy + runs-on: ubuntu-latest + steps: + - name: Checkout sources + uses: actions/checkout@v3 + with: + persist-credentials: false + - name: Install rust toolchain + uses: dtolnay/rust-toolchain@stable + with: + components: clippy + - run: cargo clippy --all-features -- --deny warnings + + semver: + name: Check semver compatibility + runs-on: ubuntu-latest + steps: + - name: Checkout sources + uses: actions/checkout@v3 + with: + persist-credentials: false + + - name: Check semver + uses: obi1kenobi/cargo-semver-checks-action@v2 diff --git a/Cargo.toml b/Cargo.toml index 10fd7778..4c7fe8dc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,18 @@ name = "rustls-pki-types" version = "0.1.0" edition = "2021" +rust-version = "1.60" +license = "MIT OR Apache-2.0" +description = "Shared types for the rustls PKI ecosystem" +documentation = "https://docs.rs/rustls-pki-types" +homepage = "https://github.com/rustls/pki-types" +repository = "https://github.com/rustls/pki-types" +categories = ["network-programming", "data-structures", "cryptography"] -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[features] +default = ["alloc"] +alloc = [] -[dependencies] +[package.metadata.docs.rs] +all-features = true +rustdoc-args = ["--cfg", "docsrs"] diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 00000000..54497297 --- /dev/null +++ b/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/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 00000000..f8cdbfd0 --- /dev/null +++ b/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/README.md b/README.md new file mode 100644 index 00000000..279ec37a --- /dev/null +++ b/README.md @@ -0,0 +1,40 @@ +# rustls-pki-types + +[![Build Status](https://github.com/rustls/pki-types/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/rustls/pki-types/actions/workflows/ci.yml?query=branch%3Amain) +[![Documentation](https://docs.rs/rustls-pki-types/badge.svg)](https://docs.rs/rustls-pki-types/) +[![Chat](https://img.shields.io/discord/976380008299917365?logo=discord)](https://discord.gg/MCSB76RU96) + +This crate provides types for representing X.509 certificates, keys and other types as commonly +used in the rustls ecosystem. It is intended to be used by crates that need to work with such X.509 +types, such as [rustls](https://crates.io/crates/rustls), +[rustls-webpki](https://crates.io/crates/rustls-webpki), +[rustls-pemfile](https://crates.io/crates/rustls-pemfile), and others. + +Some of these crates used to define their own trivial wrappers around DER-encoded bytes. +However, in order to avoid inconvenient dependency edges, these were all disconnected. By +using a common low-level crate of types with long-term stable API, we hope to avoid the +downsides of unnecessary dependency edges while providing interoperability between crates. + +## Features + +- Interoperability between different crates in the rustls ecosystem +- Long-term stable API +- No dependencies +- Support for `no_std` contexts, with optional support for `alloc` + +## DER and PEM + +Many of the types defined in this crate represent DER-encoded data. DER is a binary encoding of +the ASN.1 format commonly used in web PKI specifications. It is a binary encoding, so it is +relatively compact when stored in memory. However, as a binary format, it is not very easy to +work with for humans and in contexts where binary data is inconvenient. For this reason, +many tools and protocols use a ASCII-based encoding of DER, called PEM. In addition to the +base64-encoded DER, PEM objects are delimited by header and footer lines which indicate the type +of object contained in the PEM blob. + +The [rustls-pemfile](https://docs.rs/rustls-pemfile) crate can be used to parse PEM files. + +## Creating new certificates and keys + +This crate does not provide any functionality for creating new certificates or keys. However, +the [rcgen](https://docs.rs/rcgen) crate can be used to create new certificates and keys. diff --git a/src/lib.rs b/src/lib.rs index 7d12d9af..a608db17 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,14 +1,351 @@ -pub fn add(left: usize, right: usize) -> usize { - left + right +//! This crate provides types for representing X.509 certificates, keys and other types as +//! commonly used in the rustls ecosystem. It is intended to be used by crates that need to work +//! with such X.509 types, such as [rustls](https://crates.io/crates/rustls), +//! [rustls-webpki](https://crates.io/crates/rustls-webpki), +//! [rustls-pemfile](https://crates.io/crates/rustls-pemfile), and others. +//! +//! Some of these crates used to define their own trivial wrappers around DER-encoded bytes. +//! However, in order to avoid inconvenient dependency edges, these were all disconnected. By +//! using a common low-level crate of types with long-term stable API, we hope to avoid the +//! downsides of unnecessary dependency edges while providing good interoperability between crates. +//! +//! ## DER and PEM +//! +//! Many of the types defined in this crate represent DER-encoded data. DER is a binary encoding of +//! the ASN.1 format commonly used in web PKI specifications. It is a binary encoding, so it is +//! relatively compact when stored in memory. However, as a binary format, it is not very easy to +//! work with for humans and in contexts where binary data is inconvenient. For this reason, +//! many tools and protocols use a ASCII-based encoding of DER, called PEM. In addition to the +//! base64-encoded DER, PEM objects are delimited by header and footer lines which indicate the type +//! of object contained in the PEM blob. +//! +//! The [rustls-pemfile](https://docs.rs/rustls-pemfile) crate can be used to parse PEM files. +//! +//! ## Creating new certificates and keys +//! +//! This crate does not provide any functionality for creating new certificates or keys. However, +//! the [rcgen](https://docs.rs/rcgen) crate can be used to create new certificates and keys. + +#![no_std] +#![warn(unreachable_pub, clippy::use_self)] +#![deny(missing_docs)] +#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] + +#[cfg(feature = "alloc")] +extern crate alloc; + +#[cfg(feature = "alloc")] +use alloc::vec::Vec; +use core::fmt; +use core::ops::Deref; + +/// A DER-encoded X.509 private key, in one of several formats +/// +/// See variant inner types for more detailed information. +#[non_exhaustive] +#[derive(Debug, PartialEq)] +pub enum PrivateKeyDer<'a> { + /// An RSA private key + Pkcs1(PrivatePkcs1KeyDer<'a>), + /// A Sec1 private key + Sec1(PrivateSec1KeyDer<'a>), + /// A PKCS#8 private key + Pkcs8(PrivatePkcs8KeyDer<'a>), } -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn it_works() { - let result = add(2, 2); - assert_eq!(result, 4); +impl<'a> PrivateKeyDer<'a> { + /// Yield the DER-encoded bytes of the private key + pub fn secret_der(&self) -> &[u8] { + match self { + PrivateKeyDer::Pkcs1(key) => key.secret_pkcs1_der(), + PrivateKeyDer::Sec1(key) => key.secret_sec1_der(), + PrivateKeyDer::Pkcs8(key) => key.secret_pkcs8_der(), + } } } + +impl<'a> From> for PrivateKeyDer<'a> { + fn from(key: PrivatePkcs1KeyDer<'a>) -> Self { + Self::Pkcs1(key) + } +} + +impl<'a> From> for PrivateKeyDer<'a> { + fn from(key: PrivateSec1KeyDer<'a>) -> Self { + Self::Sec1(key) + } +} + +impl<'a> From> for PrivateKeyDer<'a> { + fn from(key: PrivatePkcs8KeyDer<'a>) -> Self { + Self::Pkcs8(key) + } +} + +/// A DER-encoded plaintext RSA private key; as specified in PKCS#1/RFC 3447 +/// +/// RSA private keys are identified in PEM context as `RSA PRIVATE KEY` and when stored in a +/// file usually use a `.pem` or `.key` extension. For more on PEM files, refer to the crate +/// documentation. +#[derive(PartialEq)] +pub struct PrivatePkcs1KeyDer<'a>(Der<'a>); + +impl PrivatePkcs1KeyDer<'_> { + /// Yield the DER-encoded bytes of the private key + pub fn secret_pkcs1_der(&self) -> &[u8] { + self.0.as_ref() + } +} + +impl<'a> From<&'a [u8]> for PrivatePkcs1KeyDer<'a> { + fn from(slice: &'a [u8]) -> Self { + Self(Der(DerInner::Borrowed(slice))) + } +} + +#[cfg(feature = "alloc")] +impl<'a> From> for PrivatePkcs1KeyDer<'a> { + fn from(vec: Vec) -> Self { + Self(Der(DerInner::Owned(vec))) + } +} + +impl fmt::Debug for PrivatePkcs1KeyDer<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("PrivatePkcs1KeyDer") + .field(&"[secret key elided]") + .finish() + } +} + +/// A Sec1-encoded plaintext private key; as specified in RFC 5915 +/// +/// Sec1 private keys are identified in PEM context as `EC PRIVATE KEY` and when stored in a +/// file usually use a `.pem` or `.key` extension. For more on PEM files, refer to the crate +/// documentation. +#[derive(PartialEq)] +pub struct PrivateSec1KeyDer<'a>(Der<'a>); + +impl PrivateSec1KeyDer<'_> { + /// Yield the DER-encoded bytes of the private key + pub fn secret_sec1_der(&self) -> &[u8] { + self.0.as_ref() + } +} + +impl<'a> From<&'a [u8]> for PrivateSec1KeyDer<'a> { + fn from(slice: &'a [u8]) -> Self { + Self(Der(DerInner::Borrowed(slice))) + } +} + +#[cfg(feature = "alloc")] +impl<'a> From> for PrivateSec1KeyDer<'a> { + fn from(vec: Vec) -> Self { + Self(Der(DerInner::Owned(vec))) + } +} + +impl fmt::Debug for PrivateSec1KeyDer<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("PrivatePkcs1KeyDer") + .field(&"[secret key elided]") + .finish() + } +} + +/// A DER-encoded plaintext private key; as specified in PKCS#8/RFC 5958 +/// +/// PKCS#8 private keys are identified in PEM context as `PRIVATE KEY` and when stored in a +/// file usually use a `.pem` or `.key` extension. For more on PEM files, refer to the crate +/// documentation. +#[derive(PartialEq)] +pub struct PrivatePkcs8KeyDer<'a>(Der<'a>); + +impl PrivatePkcs8KeyDer<'_> { + /// Yield the DER-encoded bytes of the private key + pub fn secret_pkcs8_der(&self) -> &[u8] { + self.0.as_ref() + } +} + +impl<'a> From<&'a [u8]> for PrivatePkcs8KeyDer<'a> { + fn from(slice: &'a [u8]) -> Self { + Self(Der(DerInner::Borrowed(slice))) + } +} + +#[cfg(feature = "alloc")] +impl<'a> From> for PrivatePkcs8KeyDer<'a> { + fn from(vec: Vec) -> Self { + Self(Der(DerInner::Owned(vec))) + } +} + +impl fmt::Debug for PrivatePkcs8KeyDer<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("PrivatePkcs1KeyDer") + .field(&"[secret key elided]") + .finish() + } +} + +/// A trust anchor (a.k.a. root CA) +/// +/// Traditionally, certificate verification libraries have represented trust anchors as full X.509 +/// root certificates. However, those certificates contain a lot more data than is needed for +/// verifying certificates. The [`TrustAnchor`] representation allows an application to store +/// just the essential elements of trust anchors. +#[derive(Clone, Debug, PartialEq)] +pub struct TrustAnchor<'a> { + /// Value of the `subject` field of the trust anchor + pub subject: Der<'a>, + /// Value of the `subjectPublicKeyInfo` field of the trust anchor + pub subject_public_key_info: Der<'a>, + /// Value of DER-encoded `NameConstraints`, containing name constraints to the trust anchor, if any + pub name_constraints: Option>, +} + +impl TrustAnchor<'_> { + /// Yield a `'static` lifetime of the `TrustAnchor` by allocating owned `Der` variants + #[cfg(feature = "alloc")] + pub fn to_owned(&self) -> TrustAnchor<'static> { + use alloc::borrow::ToOwned; + TrustAnchor { + subject: self.subject.as_ref().to_owned().into(), + subject_public_key_info: self.subject_public_key_info.as_ref().to_owned().into(), + name_constraints: self + .name_constraints + .as_ref() + .map(|nc| nc.as_ref().to_owned().into()), + } + } +} + +/// A Certificate Revocation List; as specified in RFC 5280 +/// +/// Certificate revocation lists are identified in PEM context as `X509 CRL` and when stored in a +/// file usually use a `.crl` extension. For more on PEM files, refer to the crate documentation. +#[derive(Debug, PartialEq)] +pub struct CertificateRevocationListDer<'a>(Der<'a>); + +impl AsRef<[u8]> for CertificateRevocationListDer<'_> { + fn as_ref(&self) -> &[u8] { + self.0.as_ref() + } +} + +impl Deref for CertificateRevocationListDer<'_> { + type Target = [u8]; + + fn deref(&self) -> &Self::Target { + self.as_ref() + } +} + +impl<'a> From<&'a [u8]> for CertificateRevocationListDer<'a> { + fn from(slice: &'a [u8]) -> Self { + Self(Der::from(slice)) + } +} + +#[cfg(feature = "alloc")] +impl<'a> From> for CertificateRevocationListDer<'a> { + fn from(vec: Vec) -> Self { + Self(Der::from(vec)) + } +} + +/// A DER-encoded X.509 certificate; as specified in RFC 5280 +/// +/// Certificates are identified in PEM context as `CERTIFICATE` and when stored in a +/// file usually use a `.pem`, `.cer` or `.crt` extension. For more on PEM files, refer to the +/// crate documentation. +#[derive(Clone, Debug, PartialEq)] +pub struct CertificateDer<'a>(Der<'a>); + +impl AsRef<[u8]> for CertificateDer<'_> { + fn as_ref(&self) -> &[u8] { + self.0.as_ref() + } +} + +impl Deref for CertificateDer<'_> { + type Target = [u8]; + + fn deref(&self) -> &Self::Target { + self.as_ref() + } +} + +impl<'a> From<&'a [u8]> for CertificateDer<'a> { + fn from(slice: &'a [u8]) -> Self { + Self(Der::from(slice)) + } +} + +#[cfg(feature = "alloc")] +impl<'a> From> for CertificateDer<'a> { + fn from(vec: Vec) -> Self { + Self(Der::from(vec)) + } +} + +/// DER-encoded data, either owned or borrowed +/// +/// This wrapper type is used to represent DER-encoded data in a way that is agnostic to whether +/// the data is owned (by a `Vec`) or borrowed (by a `&[u8]`). Support for the owned +/// variant is only available when the `alloc` feature is enabled. +#[derive(Clone, PartialEq)] +pub struct Der<'a>(DerInner<'a>); + +impl<'a> Der<'a> { + /// A const constructor to create a `Der` from a borrowed slice + pub const fn from_slice(der: &'a [u8]) -> Self { + Self(DerInner::Borrowed(der)) + } +} + +impl AsRef<[u8]> for Der<'_> { + fn as_ref(&self) -> &[u8] { + match &self.0 { + #[cfg(feature = "alloc")] + DerInner::Owned(vec) => vec.as_ref(), + DerInner::Borrowed(slice) => slice, + } + } +} + +impl Deref for Der<'_> { + type Target = [u8]; + + fn deref(&self) -> &Self::Target { + self.as_ref() + } +} + +impl<'a> From<&'a [u8]> for Der<'a> { + fn from(slice: &'a [u8]) -> Self { + Self(DerInner::Borrowed(slice)) + } +} + +#[cfg(feature = "alloc")] +impl From> for Der<'static> { + fn from(vec: Vec) -> Self { + Self(DerInner::Owned(vec)) + } +} + +impl fmt::Debug for Der<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("Der").field(&self.as_ref()).finish() + } +} + +#[derive(Clone, PartialEq)] +enum DerInner<'a> { + #[cfg(feature = "alloc")] + Owned(Vec), + Borrowed(&'a [u8]), +} From 7ffc946159c21f41fa01a77ca526a4d18f0b7f3d Mon Sep 17 00:00:00 2001 From: Dirkjan Ochtman Date: Thu, 31 Aug 2023 11:32:22 +0200 Subject: [PATCH 03/13] Rename workflow to match other repos --- .github/workflows/{rust.yml => ci.yml} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .github/workflows/{rust.yml => ci.yml} (100%) diff --git a/.github/workflows/rust.yml b/.github/workflows/ci.yml similarity index 100% rename from .github/workflows/rust.yml rename to .github/workflows/ci.yml From 0d82c1d38599426e8d32fa1f3e78ddc1a368b2ff Mon Sep 17 00:00:00 2001 From: Dirkjan Ochtman Date: Fri, 1 Sep 2023 21:50:57 +0200 Subject: [PATCH 04/13] Derive Clone for CertificateRevocationListDer --- src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index a608db17..756c5600 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -226,7 +226,7 @@ impl TrustAnchor<'_> { /// /// Certificate revocation lists are identified in PEM context as `X509 CRL` and when stored in a /// file usually use a `.crl` extension. For more on PEM files, refer to the crate documentation. -#[derive(Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq)] pub struct CertificateRevocationListDer<'a>(Der<'a>); impl AsRef<[u8]> for CertificateRevocationListDer<'_> { From a67bfade3a6c875255293a6585230aaaacfe1c43 Mon Sep 17 00:00:00 2001 From: Dirkjan Ochtman Date: Fri, 1 Sep 2023 21:51:08 +0200 Subject: [PATCH 05/13] Bump version to 0.1.1 --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 4c7fe8dc..9c783dcb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rustls-pki-types" -version = "0.1.0" +version = "0.1.1" edition = "2021" rust-version = "1.60" license = "MIT OR Apache-2.0" From 7bd05a48156c9fa8f5e9b6943b80c0dbb7490852 Mon Sep 17 00:00:00 2001 From: Joseph Birr-Pixton Date: Wed, 6 Sep 2023 09:24:10 +0100 Subject: [PATCH 06/13] Add `AlgorithmIdentifier` type --- src/lib.rs | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 756c5600..5ed70a2a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -291,6 +291,72 @@ impl<'a> From> for CertificateDer<'a> { } } +/// A DER encoding of the PKIX AlgorithmIdentifier type: +/// +/// ```ASN.1 +/// AlgorithmIdentifier ::= SEQUENCE { +/// algorithm OBJECT IDENTIFIER, +/// parameters ANY DEFINED BY algorithm OPTIONAL } +/// -- contains a value of the type +/// -- registered for use with the +/// -- algorithm object identifier value +/// ``` +/// (from ) +/// +/// The outer sequence encoding is *not included*, so this is the DER encoding +/// of an OID for `algorithm` plus the `parameters` value. +/// +/// For example, this is the `rsaEncryption` algorithm: +/// +/// ``` +/// let rsa_encryption = rustls_pki_types::AlgorithmIdentifier::from_slice( +/// &[ +/// // algorithm: 1.2.840.113549.1.1.1 +/// 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, +/// // parameters: NULL +/// 0x05, 0x00 +/// ] +/// ); +/// ``` +#[derive(Debug, Clone, PartialEq)] +pub struct AlgorithmIdentifier<'a>(Der<'a>); + +impl<'a> AlgorithmIdentifier<'a> { + /// Makes a new `AlgorithmIdentifier` from a static octet slice. + /// + /// This does not validate the contents of the slice. + pub const fn from_slice(bytes: &'a [u8]) -> Self { + Self(Der::from_slice(bytes)) + } +} + +impl AsRef<[u8]> for AlgorithmIdentifier<'_> { + fn as_ref(&self) -> &[u8] { + self.0.as_ref() + } +} + +impl Deref for AlgorithmIdentifier<'_> { + type Target = [u8]; + + fn deref(&self) -> &Self::Target { + self.as_ref() + } +} + +impl<'a> From<&'a [u8]> for AlgorithmIdentifier<'a> { + fn from(slice: &'a [u8]) -> Self { + Self(Der::from(slice)) + } +} + +#[cfg(feature = "alloc")] +impl<'a> From> for AlgorithmIdentifier<'a> { + fn from(vec: Vec) -> Self { + Self(Der::from(vec)) + } +} + /// DER-encoded data, either owned or borrowed /// /// This wrapper type is used to represent DER-encoded data in a way that is agnostic to whether From b2b820247af2500881c89821f637f6a2e284cbae Mon Sep 17 00:00:00 2001 From: Joseph Birr-Pixton Date: Wed, 6 Sep 2023 09:24:28 +0100 Subject: [PATCH 07/13] Add `SignatureVerificationAlgorithm` type --- src/lib.rs | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 5ed70a2a..d25c845d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -291,6 +291,53 @@ impl<'a> From> for CertificateDer<'a> { } } +/// An abstract signature verification algorithm. +/// +/// One of these is needed per supported pair of public key type (identified +/// with `public_key_alg_id()`) and `signatureAlgorithm` (identified with +/// `signature_alg_id()`). Note that both of these `AlgorithmIdentifier`s include +/// the parameters encoding, so separate `SignatureVerificationAlgorithm`s are needed +/// for each possible public key or signature parameters. +pub trait SignatureVerificationAlgorithm: Send + Sync { + /// Verify a signature. + /// + /// `public_key` is the `subjectPublicKey` value from a `SubjectPublicKeyInfo` encoding + /// and is untrusted. The key's `subjectPublicKeyInfo` matches the [`AlgorithmIdentifier`] + /// returned by `public_key_alg_id()`. + /// + /// `message` is the data over which the signature was allegedly computed. + /// It is not hashed; implementations of this trait function must do hashing + /// if that is required by the algorithm they implement. + /// + /// `signature` is the signature allegedly over `message`. + /// + /// Return `Ok(())` only if `signature` is a valid signature on `message`. + /// + /// Return `Err(InvalidSignature)` if the signature is invalid, including if the `public_key` + /// encoding is invalid. There is no need or opportunity to produce errors + /// that are more specific than this. + fn verify_signature( + &self, + public_key: &[u8], + message: &[u8], + signature: &[u8], + ) -> Result<(), InvalidSignature>; + + /// Return the `AlgorithmIdentifier` that must equal a public key's + /// `subjectPublicKeyInfo` value for this `SignatureVerificationAlgorithm` + /// to be used for signature verification. + fn public_key_alg_id(&self) -> AlgorithmIdentifier; + + /// Return the `AlgorithmIdentifier` that must equal the `signatureAlgorithm` value + /// on the data to be verified for this `SignatureVerificationAlgorithm` to be used + /// for signature verification. + fn signature_alg_id(&self) -> AlgorithmIdentifier; +} + +/// A detail-less error when a signature is not valid. +#[derive(Debug, Copy, Clone)] +pub struct InvalidSignature; + /// A DER encoding of the PKIX AlgorithmIdentifier type: /// /// ```ASN.1 From ef9520eeb642545044367ca0b819577be28c4a83 Mon Sep 17 00:00:00 2001 From: Joseph Birr-Pixton Date: Thu, 7 Sep 2023 08:49:14 +0100 Subject: [PATCH 08/13] Bump version to 0.1.2 --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 9c783dcb..80557d30 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rustls-pki-types" -version = "0.1.1" +version = "0.1.2" edition = "2021" rust-version = "1.60" license = "MIT OR Apache-2.0" From 5eb9cdb46c150f6b8e8a36100d3c140b04719b6f Mon Sep 17 00:00:00 2001 From: Joseph Birr-Pixton Date: Thu, 7 Sep 2023 10:39:05 +0100 Subject: [PATCH 09/13] Simplify `AlgorithmIdentifier` type Just store a &'static [u8]. This means the type can become trivially `Copy`. Technically a breaking change for several reasons; eg losing `impl From>`. --- src/lib.rs | 29 ++++++++--------------------- 1 file changed, 8 insertions(+), 21 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index d25c845d..66efc9a6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -365,25 +365,25 @@ pub struct InvalidSignature; /// ] /// ); /// ``` -#[derive(Debug, Clone, PartialEq)] -pub struct AlgorithmIdentifier<'a>(Der<'a>); +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct AlgorithmIdentifier(&'static [u8]); -impl<'a> AlgorithmIdentifier<'a> { +impl AlgorithmIdentifier { /// Makes a new `AlgorithmIdentifier` from a static octet slice. /// /// This does not validate the contents of the slice. - pub const fn from_slice(bytes: &'a [u8]) -> Self { - Self(Der::from_slice(bytes)) + pub const fn from_slice(bytes: &'static [u8]) -> Self { + Self(bytes) } } -impl AsRef<[u8]> for AlgorithmIdentifier<'_> { +impl AsRef<[u8]> for AlgorithmIdentifier { fn as_ref(&self) -> &[u8] { - self.0.as_ref() + self.0 } } -impl Deref for AlgorithmIdentifier<'_> { +impl Deref for AlgorithmIdentifier { type Target = [u8]; fn deref(&self) -> &Self::Target { @@ -391,19 +391,6 @@ impl Deref for AlgorithmIdentifier<'_> { } } -impl<'a> From<&'a [u8]> for AlgorithmIdentifier<'a> { - fn from(slice: &'a [u8]) -> Self { - Self(Der::from(slice)) - } -} - -#[cfg(feature = "alloc")] -impl<'a> From> for AlgorithmIdentifier<'a> { - fn from(vec: Vec) -> Self { - Self(Der::from(vec)) - } -} - /// DER-encoded data, either owned or borrowed /// /// This wrapper type is used to represent DER-encoded data in a way that is agnostic to whether From 0f3121a1ca61e428674fb51deea43f7c5d0c3597 Mon Sep 17 00:00:00 2001 From: Joseph Birr-Pixton Date: Thu, 7 Sep 2023 10:44:19 +0100 Subject: [PATCH 10/13] Bump version to 0.2.0 --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 80557d30..9d3d14ea 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rustls-pki-types" -version = "0.1.2" +version = "0.2.0" edition = "2021" rust-version = "1.60" license = "MIT OR Apache-2.0" From b130ee53ddd8875e7a976dba0082553dd906e8a9 Mon Sep 17 00:00:00 2001 From: Dirkjan Ochtman Date: Tue, 12 Sep 2023 12:15:41 +0200 Subject: [PATCH 11/13] Add UnixTime type --- Cargo.toml | 1 + src/lib.rs | 36 +++++++++++++++++++++++++++++++++++- 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 9d3d14ea..d6b71646 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,7 @@ categories = ["network-programming", "data-structures", "cryptography"] [features] default = ["alloc"] alloc = [] +std = ["alloc"] [package.metadata.docs.rs] all-features = true diff --git a/src/lib.rs b/src/lib.rs index 66efc9a6..058309c3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -26,7 +26,7 @@ //! This crate does not provide any functionality for creating new certificates or keys. However, //! the [rcgen](https://docs.rs/rcgen) crate can be used to create new certificates and keys. -#![no_std] +#![cfg_attr(not(feature = "std"), no_std)] #![warn(unreachable_pub, clippy::use_self)] #![deny(missing_docs)] #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] @@ -38,6 +38,9 @@ extern crate alloc; use alloc::vec::Vec; use core::fmt; use core::ops::Deref; +use core::time::Duration; +#[cfg(feature = "std")] +use std::time::SystemTime; /// A DER-encoded X.509 private key, in one of several formats /// @@ -210,6 +213,7 @@ impl TrustAnchor<'_> { /// Yield a `'static` lifetime of the `TrustAnchor` by allocating owned `Der` variants #[cfg(feature = "alloc")] pub fn to_owned(&self) -> TrustAnchor<'static> { + #[cfg(not(feature = "std"))] use alloc::borrow::ToOwned; TrustAnchor { subject: self.subject.as_ref().to_owned().into(), @@ -391,6 +395,36 @@ impl Deref for AlgorithmIdentifier { } } +/// A timestamp, tracking the number of non-leap seconds since the Unix epoch. +/// +/// The Unix epoch is defined January 1, 1970 00:00:00 UTC. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd)] +pub struct UnixTime(u64); + +impl UnixTime { + /// The current time, as a `UnixTime` + #[cfg(feature = "std")] + pub fn now() -> Self { + Self::since_unix_epoch( + SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH) + .unwrap(), // Safe: this code did not exist before 1970. + ) + } + + /// Convert a `Duration` since the start of 1970 to a `UnixTime` + /// + /// The `duration` must be relative to the Unix epoch. + pub fn since_unix_epoch(duration: Duration) -> Self { + Self(duration.as_secs()) + } + + /// Number of seconds since the Unix epoch + pub fn as_secs(&self) -> u64 { + self.0 + } +} + /// DER-encoded data, either owned or borrowed /// /// This wrapper type is used to represent DER-encoded data in a way that is agnostic to whether From 4d3f58361f1f99dd2aff271d50114479121f3f9e Mon Sep 17 00:00:00 2001 From: Dirkjan Ochtman Date: Tue, 12 Sep 2023 17:00:31 +0200 Subject: [PATCH 12/13] Bump version to 0.2.1 --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index d6b71646..4b333ea4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rustls-pki-types" -version = "0.2.0" +version = "0.2.1" edition = "2021" rust-version = "1.60" license = "MIT OR Apache-2.0" From 294e7a5b20cb6cbfa605e2496aa9262648c376db Mon Sep 17 00:00:00 2001 From: Dirkjan Ochtman Date: Wed, 13 Sep 2023 09:47:49 +0200 Subject: [PATCH 13/13] Move pki-types crate into a workspace --- Cargo.toml | 23 +++------------------- pki-types/Cargo.toml | 20 +++++++++++++++++++ LICENSE-APACHE => pki-types/LICENSE-APACHE | 0 LICENSE-MIT => pki-types/LICENSE-MIT | 0 README.md => pki-types/README.md | 0 {src => pki-types/src}/lib.rs | 0 6 files changed, 23 insertions(+), 20 deletions(-) create mode 100644 pki-types/Cargo.toml rename LICENSE-APACHE => pki-types/LICENSE-APACHE (100%) rename LICENSE-MIT => pki-types/LICENSE-MIT (100%) rename README.md => pki-types/README.md (100%) rename {src => pki-types/src}/lib.rs (100%) diff --git a/Cargo.toml b/Cargo.toml index 4b333ea4..f16e4359 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,20 +1,3 @@ -[package] -name = "rustls-pki-types" -version = "0.2.1" -edition = "2021" -rust-version = "1.60" -license = "MIT OR Apache-2.0" -description = "Shared types for the rustls PKI ecosystem" -documentation = "https://docs.rs/rustls-pki-types" -homepage = "https://github.com/rustls/pki-types" -repository = "https://github.com/rustls/pki-types" -categories = ["network-programming", "data-structures", "cryptography"] - -[features] -default = ["alloc"] -alloc = [] -std = ["alloc"] - -[package.metadata.docs.rs] -all-features = true -rustdoc-args = ["--cfg", "docsrs"] +[workspace] +resolver = "2" +members = ["pki-types"] diff --git a/pki-types/Cargo.toml b/pki-types/Cargo.toml new file mode 100644 index 00000000..4b333ea4 --- /dev/null +++ b/pki-types/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "rustls-pki-types" +version = "0.2.1" +edition = "2021" +rust-version = "1.60" +license = "MIT OR Apache-2.0" +description = "Shared types for the rustls PKI ecosystem" +documentation = "https://docs.rs/rustls-pki-types" +homepage = "https://github.com/rustls/pki-types" +repository = "https://github.com/rustls/pki-types" +categories = ["network-programming", "data-structures", "cryptography"] + +[features] +default = ["alloc"] +alloc = [] +std = ["alloc"] + +[package.metadata.docs.rs] +all-features = true +rustdoc-args = ["--cfg", "docsrs"] diff --git a/LICENSE-APACHE b/pki-types/LICENSE-APACHE similarity index 100% rename from LICENSE-APACHE rename to pki-types/LICENSE-APACHE diff --git a/LICENSE-MIT b/pki-types/LICENSE-MIT similarity index 100% rename from LICENSE-MIT rename to pki-types/LICENSE-MIT diff --git a/README.md b/pki-types/README.md similarity index 100% rename from README.md rename to pki-types/README.md diff --git a/src/lib.rs b/pki-types/src/lib.rs similarity index 100% rename from src/lib.rs rename to pki-types/src/lib.rs