diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-05-04 12:41:41 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-05-04 12:41:41 +0000 |
commit | 10ee2acdd26a7f1298c6f6d6b7af9b469fe29b87 (patch) | |
tree | bdffd5d80c26cf4a7a518281a204be1ace85b4c1 /vendor/spki/src | |
parent | Releasing progress-linux version 1.70.0+dfsg1-9~progress7.99u1. (diff) | |
download | rustc-10ee2acdd26a7f1298c6f6d6b7af9b469fe29b87.tar.xz rustc-10ee2acdd26a7f1298c6f6d6b7af9b469fe29b87.zip |
Merging upstream version 1.70.0+dfsg2.
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'vendor/spki/src')
-rw-r--r-- | vendor/spki/src/algorithm.rs | 132 | ||||
-rw-r--r-- | vendor/spki/src/error.rs | 68 | ||||
-rw-r--r-- | vendor/spki/src/fingerprint.rs | 43 | ||||
-rw-r--r-- | vendor/spki/src/lib.rs | 55 | ||||
-rw-r--r-- | vendor/spki/src/spki.rs | 141 | ||||
-rw-r--r-- | vendor/spki/src/traits.rs | 94 |
6 files changed, 533 insertions, 0 deletions
diff --git a/vendor/spki/src/algorithm.rs b/vendor/spki/src/algorithm.rs new file mode 100644 index 000000000..2a8b6c7f9 --- /dev/null +++ b/vendor/spki/src/algorithm.rs @@ -0,0 +1,132 @@ +//! X.509 `AlgorithmIdentifier` + +use crate::{Error, Result}; +use core::cmp::Ordering; +use der::asn1::{AnyRef, ObjectIdentifier}; +use der::{Decode, DecodeValue, DerOrd, Encode, Header, Reader, Sequence, ValueOrd}; + +/// X.509 `AlgorithmIdentifier` as defined in [RFC 5280 Section 4.1.1.2]. +/// +/// ```text +/// AlgorithmIdentifier ::= SEQUENCE { +/// algorithm OBJECT IDENTIFIER, +/// parameters ANY DEFINED BY algorithm OPTIONAL } +/// ``` +/// +/// [RFC 5280 Section 4.1.1.2]: https://tools.ietf.org/html/rfc5280#section-4.1.1.2 +#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)] +pub struct AlgorithmIdentifier<'a> { + /// Algorithm OID, i.e. the `algorithm` field in the `AlgorithmIdentifier` + /// ASN.1 schema. + pub oid: ObjectIdentifier, + + /// Algorithm `parameters`. + pub parameters: Option<AnyRef<'a>>, +} + +impl<'a> AlgorithmIdentifier<'a> { + /// Assert the `algorithm` OID is an expected value. + pub fn assert_algorithm_oid(&self, expected_oid: ObjectIdentifier) -> Result<ObjectIdentifier> { + if self.oid == expected_oid { + Ok(expected_oid) + } else { + Err(Error::OidUnknown { oid: expected_oid }) + } + } + + /// Assert `parameters` is an OID and has the expected value. + pub fn assert_parameters_oid( + &self, + expected_oid: ObjectIdentifier, + ) -> Result<ObjectIdentifier> { + let actual_oid = self.parameters_oid()?; + + if actual_oid == expected_oid { + Ok(actual_oid) + } else { + Err(Error::OidUnknown { oid: expected_oid }) + } + } + + /// Assert the values of the `algorithm` and `parameters` OIDs. + pub fn assert_oids( + &self, + algorithm: ObjectIdentifier, + parameters: ObjectIdentifier, + ) -> Result<()> { + self.assert_algorithm_oid(algorithm)?; + self.assert_parameters_oid(parameters)?; + Ok(()) + } + + /// Get the `parameters` field as an [`AnyRef`]. + /// + /// Returns an error if `parameters` are `None`. + pub fn parameters_any(&self) -> Result<AnyRef<'a>> { + self.parameters.ok_or(Error::AlgorithmParametersMissing) + } + + /// Get the `parameters` field as an [`ObjectIdentifier`]. + /// + /// Returns an error if it is absent or not an OID. + pub fn parameters_oid(&self) -> Result<ObjectIdentifier> { + Ok(ObjectIdentifier::try_from(self.parameters_any()?)?) + } + + /// Convert to a pair of [`ObjectIdentifier`]s. + /// + /// This method is helpful for decomposing in match statements. Note in + /// particular that `NULL` parameters are treated the same as missing + /// parameters. + /// + /// Returns an error if parameters are present but not an OID. + pub fn oids(&self) -> der::Result<(ObjectIdentifier, Option<ObjectIdentifier>)> { + Ok(( + self.oid, + match self.parameters { + None => None, + Some(p) => match p { + AnyRef::NULL => None, + _ => Some(p.oid()?), + }, + }, + )) + } +} + +impl<'a> DecodeValue<'a> for AlgorithmIdentifier<'a> { + fn decode_value<R: Reader<'a>>(reader: &mut R, header: Header) -> der::Result<Self> { + reader.read_nested(header.length, |reader| { + Ok(Self { + oid: reader.decode()?, + parameters: reader.decode()?, + }) + }) + } +} + +impl<'a> Sequence<'a> for AlgorithmIdentifier<'a> { + fn fields<F, T>(&self, f: F) -> der::Result<T> + where + F: FnOnce(&[&dyn Encode]) -> der::Result<T>, + { + f(&[&self.oid, &self.parameters]) + } +} + +impl<'a> TryFrom<&'a [u8]> for AlgorithmIdentifier<'a> { + type Error = Error; + + fn try_from(bytes: &'a [u8]) -> Result<Self> { + Ok(Self::from_der(bytes)?) + } +} + +impl ValueOrd for AlgorithmIdentifier<'_> { + fn value_cmp(&self, other: &Self) -> der::Result<Ordering> { + match self.oid.der_cmp(&other.oid)? { + Ordering::Equal => self.parameters.der_cmp(&other.parameters), + other => Ok(other), + } + } +} diff --git a/vendor/spki/src/error.rs b/vendor/spki/src/error.rs new file mode 100644 index 000000000..9d05990f3 --- /dev/null +++ b/vendor/spki/src/error.rs @@ -0,0 +1,68 @@ +//! Error types + +use core::fmt; +use der::asn1::ObjectIdentifier; + +/// Result type with `spki` crate's [`Error`] type. +pub type Result<T> = core::result::Result<T, Error>; + +#[cfg(feature = "pem")] +use der::pem; + +/// Error type +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum Error { + /// Algorithm parameters are missing. + AlgorithmParametersMissing, + + /// ASN.1 DER-related errors. + Asn1(der::Error), + + /// Malformed cryptographic key contained in a SPKI document. + /// + /// This is intended for relaying errors related to the raw data contained + /// in [`SubjectPublicKeyInfo::subject_public_key`][`crate::SubjectPublicKeyInfo::subject_public_key`]. + KeyMalformed, + + /// Unknown algorithm OID. + OidUnknown { + /// Unrecognized OID value found in e.g. a SPKI `AlgorithmIdentifier`. + oid: ObjectIdentifier, + }, +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::AlgorithmParametersMissing => { + f.write_str("AlgorithmIdentifier parameters missing") + } + Error::Asn1(err) => write!(f, "ASN.1 error: {}", err), + Error::KeyMalformed => f.write_str("SPKI cryptographic key data malformed"), + Error::OidUnknown { oid } => { + write!(f, "unknown/unsupported algorithm OID: {}", oid) + } + } + } +} + +impl From<der::Error> for Error { + fn from(err: der::Error) -> Error { + if let der::ErrorKind::OidUnknown { oid } = err.kind() { + Error::OidUnknown { oid } + } else { + Error::Asn1(err) + } + } +} + +#[cfg(feature = "pem")] +impl From<pem::Error> for Error { + fn from(err: pem::Error) -> Error { + der::Error::from(err).into() + } +} + +#[cfg(feature = "std")] +impl std::error::Error for Error {} diff --git a/vendor/spki/src/fingerprint.rs b/vendor/spki/src/fingerprint.rs new file mode 100644 index 000000000..6a3901fb1 --- /dev/null +++ b/vendor/spki/src/fingerprint.rs @@ -0,0 +1,43 @@ +//! SPKI fingerprint support. + +use der::Writer; +use sha2::{Digest, Sha256}; + +/// Size of a SHA-256 SPKI fingerprint in bytes. +pub(crate) const SIZE: usize = 32; + +/// Raw bytes of a SPKI fingerprint i.e. SHA-256 digest of +/// `SubjectPublicKeyInfo`'s DER encoding. +/// +/// See [RFC7469 § 2.1.1] for more information. +/// +/// [RFC7469 § 2.1.1]: https://datatracker.ietf.org/doc/html/rfc7469#section-2.1.1 +#[cfg_attr(docsrs, doc(cfg(feature = "fingerprint")))] +pub type FingerprintBytes = [u8; SIZE]; + +/// Writer newtype which accepts DER being serialized on-the-fly and computes a +/// hash of the contents. +#[derive(Clone, Default)] +pub(crate) struct Builder { + /// In-progress digest being computed from streaming DER. + digest: Sha256, +} + +impl Builder { + /// Create a new fingerprint builder. + pub fn new() -> Self { + Self::default() + } + + /// Finish computing a fingerprint, returning the computed digest. + pub fn finish(self) -> FingerprintBytes { + self.digest.finalize().into() + } +} + +impl Writer for Builder { + fn write(&mut self, der_bytes: &[u8]) -> der::Result<()> { + self.digest.update(der_bytes); + Ok(()) + } +} diff --git a/vendor/spki/src/lib.rs b/vendor/spki/src/lib.rs new file mode 100644 index 000000000..f46675674 --- /dev/null +++ b/vendor/spki/src/lib.rs @@ -0,0 +1,55 @@ +#![no_std] +#![cfg_attr(docsrs, feature(doc_cfg))] +#![doc = include_str!("../README.md")] +#![doc( + html_logo_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg", + html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg" +)] +#![forbid(unsafe_code, clippy::unwrap_used)] +#![warn(missing_docs, rust_2018_idioms, unused_qualifications)] + +//! # Usage +//! The following example demonstrates how to use an OID as the `parameters` +//! of an [`AlgorithmIdentifier`]. +//! +//! Borrow the [`ObjectIdentifier`] first then use [`der::AnyRef::from`] or `.into()`: +//! +//! ``` +//! use spki::{AlgorithmIdentifier, ObjectIdentifier, der::AnyRef}; +//! +//! let alg_oid = "1.2.840.10045.2.1".parse::<ObjectIdentifier>().unwrap(); +//! let params_oid = "1.2.840.10045.3.1.7".parse::<ObjectIdentifier>().unwrap(); +//! +//! let alg_id = AlgorithmIdentifier { +//! oid: alg_oid, +//! parameters: Some(AnyRef::from(¶ms_oid)) +//! }; +//! ``` + +#[cfg(feature = "alloc")] +#[allow(unused_extern_crates)] +extern crate alloc; +#[cfg(feature = "std")] +extern crate std; + +mod algorithm; +mod error; +mod spki; +mod traits; + +#[cfg(feature = "fingerprint")] +mod fingerprint; + +pub use crate::{ + algorithm::AlgorithmIdentifier, + error::{Error, Result}, + spki::SubjectPublicKeyInfo, + traits::DecodePublicKey, +}; +pub use der::{self, asn1::ObjectIdentifier}; + +#[cfg(feature = "alloc")] +pub use {crate::traits::EncodePublicKey, der::Document}; + +#[cfg(feature = "fingerprint")] +pub use crate::fingerprint::FingerprintBytes; diff --git a/vendor/spki/src/spki.rs b/vendor/spki/src/spki.rs new file mode 100644 index 000000000..9058e49c7 --- /dev/null +++ b/vendor/spki/src/spki.rs @@ -0,0 +1,141 @@ +//! X.509 `SubjectPublicKeyInfo` + +use crate::{AlgorithmIdentifier, Error, Result}; +use core::cmp::Ordering; +use der::{ + asn1::BitStringRef, Decode, DecodeValue, DerOrd, Encode, Header, Reader, Sequence, ValueOrd, +}; + +#[cfg(feature = "alloc")] +use der::Document; + +#[cfg(feature = "fingerprint")] +use crate::{fingerprint, FingerprintBytes}; + +#[cfg(all(feature = "alloc", feature = "fingerprint"))] +use { + alloc::string::String, + base64ct::{Base64, Encoding}, +}; + +#[cfg(feature = "pem")] +use der::pem::PemLabel; + +/// X.509 `SubjectPublicKeyInfo` (SPKI) as defined in [RFC 5280 § 4.1.2.7]. +/// +/// ASN.1 structure containing an [`AlgorithmIdentifier`] and public key +/// data in an algorithm specific format. +/// +/// ```text +/// SubjectPublicKeyInfo ::= SEQUENCE { +/// algorithm AlgorithmIdentifier, +/// subjectPublicKey BIT STRING } +/// ``` +/// +/// [RFC 5280 § 4.1.2.7]: https://tools.ietf.org/html/rfc5280#section-4.1.2.7 +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub struct SubjectPublicKeyInfo<'a> { + /// X.509 [`AlgorithmIdentifier`] for the public key type + pub algorithm: AlgorithmIdentifier<'a>, + + /// Public key data + pub subject_public_key: &'a [u8], +} + +impl<'a> SubjectPublicKeyInfo<'a> { + /// Calculate the SHA-256 fingerprint of this [`SubjectPublicKeyInfo`] and + /// encode it as a Base64 string. + /// + /// See [RFC7469 § 2.1.1] for more information. + /// + /// [RFC7469 § 2.1.1]: https://datatracker.ietf.org/doc/html/rfc7469#section-2.1.1 + #[cfg(all(feature = "fingerprint", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(all(feature = "fingerprint", feature = "alloc"))))] + pub fn fingerprint_base64(&self) -> Result<String> { + Ok(Base64::encode_string(&self.fingerprint_bytes()?)) + } + + /// Calculate the SHA-256 fingerprint of this [`SubjectPublicKeyInfo`] as + /// a raw byte array. + /// + /// See [RFC7469 § 2.1.1] for more information. + /// + /// [RFC7469 § 2.1.1]: https://datatracker.ietf.org/doc/html/rfc7469#section-2.1.1 + #[cfg(feature = "fingerprint")] + #[cfg_attr(docsrs, doc(cfg(feature = "fingerprint")))] + pub fn fingerprint_bytes(&self) -> Result<FingerprintBytes> { + let mut builder = fingerprint::Builder::new(); + self.encode(&mut builder)?; + Ok(builder.finish()) + } + + /// Get a [`BitString`] representing the `subject_public_key` + fn bitstring(&self) -> der::Result<BitStringRef<'a>> { + BitStringRef::from_bytes(self.subject_public_key) + } +} + +impl<'a> DecodeValue<'a> for SubjectPublicKeyInfo<'a> { + fn decode_value<R: Reader<'a>>(reader: &mut R, header: Header) -> der::Result<Self> { + reader.read_nested(header.length, |reader| { + Ok(Self { + algorithm: reader.decode()?, + subject_public_key: BitStringRef::decode(reader)? + .as_bytes() + .ok_or_else(|| der::Tag::BitString.value_error())?, + }) + }) + } +} + +impl<'a> Sequence<'a> for SubjectPublicKeyInfo<'a> { + fn fields<F, T>(&self, f: F) -> der::Result<T> + where + F: FnOnce(&[&dyn Encode]) -> der::Result<T>, + { + f(&[&self.algorithm, &self.bitstring()?]) + } +} + +impl<'a> TryFrom<&'a [u8]> for SubjectPublicKeyInfo<'a> { + type Error = Error; + + fn try_from(bytes: &'a [u8]) -> Result<Self> { + Ok(Self::from_der(bytes)?) + } +} + +impl ValueOrd for SubjectPublicKeyInfo<'_> { + fn value_cmp(&self, other: &Self) -> der::Result<Ordering> { + match self.algorithm.der_cmp(&other.algorithm)? { + Ordering::Equal => self.bitstring()?.der_cmp(&other.bitstring()?), + other => Ok(other), + } + } +} + +#[cfg(feature = "alloc")] +#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))] +impl TryFrom<SubjectPublicKeyInfo<'_>> for Document { + type Error = Error; + + fn try_from(spki: SubjectPublicKeyInfo<'_>) -> Result<Document> { + Self::try_from(&spki) + } +} + +#[cfg(feature = "alloc")] +#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))] +impl TryFrom<&SubjectPublicKeyInfo<'_>> for Document { + type Error = Error; + + fn try_from(spki: &SubjectPublicKeyInfo<'_>) -> Result<Document> { + Ok(Self::encode_msg(spki)?) + } +} + +#[cfg(feature = "pem")] +#[cfg_attr(docsrs, doc(cfg(feature = "pem")))] +impl PemLabel for SubjectPublicKeyInfo<'_> { + const PEM_LABEL: &'static str = "PUBLIC KEY"; +} diff --git a/vendor/spki/src/traits.rs b/vendor/spki/src/traits.rs new file mode 100644 index 000000000..c16e3974d --- /dev/null +++ b/vendor/spki/src/traits.rs @@ -0,0 +1,94 @@ +//! Traits for encoding/decoding SPKI public keys. + +use crate::{Error, Result, SubjectPublicKeyInfo}; + +#[cfg(feature = "alloc")] +use der::Document; + +#[cfg(feature = "pem")] +use { + alloc::string::String, + der::pem::{LineEnding, PemLabel}, +}; + +#[cfg(feature = "std")] +use std::path::Path; + +/// Parse a public key object from an encoded SPKI document. +pub trait DecodePublicKey: + for<'a> TryFrom<SubjectPublicKeyInfo<'a>, Error = Error> + Sized +{ + /// Deserialize object from ASN.1 DER-encoded [`SubjectPublicKeyInfo`] + /// (binary format). + fn from_public_key_der(bytes: &[u8]) -> Result<Self> { + Self::try_from(SubjectPublicKeyInfo::try_from(bytes)?) + } + + /// Deserialize PEM-encoded [`SubjectPublicKeyInfo`]. + /// + /// Keys in this format begin with the following delimiter: + /// + /// ```text + /// -----BEGIN PUBLIC KEY----- + /// ``` + #[cfg(feature = "pem")] + #[cfg_attr(docsrs, doc(cfg(feature = "pem")))] + fn from_public_key_pem(s: &str) -> Result<Self> { + let (label, doc) = Document::from_pem(s)?; + SubjectPublicKeyInfo::validate_pem_label(label)?; + Self::from_public_key_der(doc.as_bytes()) + } + + /// Load public key object from an ASN.1 DER-encoded file on the local + /// filesystem (binary format). + #[cfg(feature = "std")] + #[cfg_attr(docsrs, doc(cfg(feature = "std")))] + fn read_public_key_der_file(path: impl AsRef<Path>) -> Result<Self> { + let doc = Document::read_der_file(path)?; + Self::from_public_key_der(doc.as_bytes()) + } + + /// Load public key object from a PEM-encoded file on the local filesystem. + #[cfg(all(feature = "pem", feature = "std"))] + #[cfg_attr(docsrs, doc(cfg(all(feature = "pem", feature = "std"))))] + fn read_public_key_pem_file(path: impl AsRef<Path>) -> Result<Self> { + let (label, doc) = Document::read_pem_file(path)?; + SubjectPublicKeyInfo::validate_pem_label(&label)?; + Self::from_public_key_der(doc.as_bytes()) + } +} + +/// Serialize a public key object to a SPKI-encoded document. +#[cfg(feature = "alloc")] +#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))] +pub trait EncodePublicKey { + /// Serialize a [`Document`] containing a SPKI-encoded public key. + fn to_public_key_der(&self) -> Result<Document>; + + /// Serialize this public key as PEM-encoded SPKI with the given [`LineEnding`]. + #[cfg(feature = "pem")] + #[cfg_attr(docsrs, doc(cfg(feature = "pem")))] + fn to_public_key_pem(&self, line_ending: LineEnding) -> Result<String> { + let doc = self.to_public_key_der()?; + Ok(doc.to_pem(SubjectPublicKeyInfo::PEM_LABEL, line_ending)?) + } + + /// Write ASN.1 DER-encoded public key to the given path + #[cfg(feature = "std")] + #[cfg_attr(docsrs, doc(cfg(feature = "std")))] + fn write_public_key_der_file(&self, path: impl AsRef<Path>) -> Result<()> { + Ok(self.to_public_key_der()?.write_der_file(path)?) + } + + /// Write ASN.1 DER-encoded public key to the given path + #[cfg(all(feature = "pem", feature = "std"))] + #[cfg_attr(docsrs, doc(cfg(all(feature = "pem", feature = "std"))))] + fn write_public_key_pem_file( + &self, + path: impl AsRef<Path>, + line_ending: LineEnding, + ) -> Result<()> { + let doc = self.to_public_key_der()?; + Ok(doc.write_pem_file(path, SubjectPublicKeyInfo::PEM_LABEL, line_ending)?) + } +} |