Skip to content

Commit

Permalink
Migrate SPKI parsing from OpenSSL to Rust (#10121)
Browse files Browse the repository at this point in the history
  • Loading branch information
alex committed Jan 21, 2024
1 parent 2c56719 commit 6b4a4de
Show file tree
Hide file tree
Showing 15 changed files with 332 additions and 84 deletions.
3 changes: 3 additions & 0 deletions src/rust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions src/rust/cryptography-key-parsing/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,7 @@ rust-version = "1.63.0"

[dependencies]
asn1 = { version = "0.15.5", default-features = false }
cfg-if = "1"
openssl = "0.10.63"
openssl-sys = "0.9.99"
cryptography-x509 = { path = "../cryptography-x509" }
15 changes: 15 additions & 0 deletions src/rust/cryptography-key-parsing/build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// This file is dual licensed under the terms of the Apache License, Version
// 2.0, and the BSD License. See the LICENSE file in the root of this repository
// for complete details.

use std::env;

fn main() {
if env::var("DEP_OPENSSL_LIBRESSL_VERSION_NUMBER").is_ok() {
println!("cargo:rustc-cfg=CRYPTOGRAPHY_IS_LIBRESSL");
}

if env::var("DEP_OPENSSL_BORINGSSL").is_ok() {
println!("cargo:rustc-cfg=CRYPTOGRAPHY_IS_BORINGSSL");
}
}
5 changes: 5 additions & 0 deletions src/rust/cryptography-key-parsing/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,13 @@
// for complete details.

pub mod rsa;
pub mod spki;

pub enum KeyParsingError {
InvalidKey,
ExplicitCurveUnsupported,
UnsupportedKeyType(asn1::ObjectIdentifier),
UnsupportedEllipticCurve(asn1::ObjectIdentifier),
Parse(asn1::ParseError),
OpenSSL(openssl::error::ErrorStack),
}
Expand Down
2 changes: 1 addition & 1 deletion src/rust/cryptography-key-parsing/src/rsa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ struct Pksc1RsaPublicKey<'a> {
e: asn1::BigUint<'a>,
}

pub fn parse_pkcs1_rsa_public_key(
pub fn parse_pkcs1_public_key(
data: &[u8],
) -> KeyParsingResult<openssl::pkey::PKey<openssl::pkey::Public>> {
let k = asn1::parse_single::<Pksc1RsaPublicKey>(data)?;
Expand Down
142 changes: 142 additions & 0 deletions src/rust/cryptography-key-parsing/src/spki.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
// This file is dual licensed under the terms of the Apache License, Version
// 2.0, and the BSD License. See the LICENSE file in the root of this repository
// for complete details.

use cryptography_x509::common::{AlgorithmParameters, EcParameters, SubjectPublicKeyInfo};

use crate::{KeyParsingError, KeyParsingResult};

pub fn parse_public_key(
data: &[u8],
) -> KeyParsingResult<openssl::pkey::PKey<openssl::pkey::Public>> {
let k = asn1::parse_single::<SubjectPublicKeyInfo>(data)?;

match k.algorithm.params {
AlgorithmParameters::Ec(ec_params) => match ec_params {
EcParameters::NamedCurve(curve_oid) => {
let curve_nid = match curve_oid {
cryptography_x509::oid::EC_SECP192R1 => openssl::nid::Nid::X9_62_PRIME192V1,
cryptography_x509::oid::EC_SECP224R1 => openssl::nid::Nid::SECP224R1,
cryptography_x509::oid::EC_SECP256R1 => openssl::nid::Nid::X9_62_PRIME256V1,
cryptography_x509::oid::EC_SECP384R1 => openssl::nid::Nid::SECP384R1,
cryptography_x509::oid::EC_SECP521R1 => openssl::nid::Nid::SECP521R1,

cryptography_x509::oid::EC_SECP256K1 => openssl::nid::Nid::SECP256K1,

cryptography_x509::oid::EC_SECT233R1 => openssl::nid::Nid::SECT233R1,
cryptography_x509::oid::EC_SECT283R1 => openssl::nid::Nid::SECT283R1,
cryptography_x509::oid::EC_SECT409R1 => openssl::nid::Nid::SECT409R1,
cryptography_x509::oid::EC_SECT571R1 => openssl::nid::Nid::SECT571R1,

cryptography_x509::oid::EC_SECT163R2 => openssl::nid::Nid::SECT163R2,

cryptography_x509::oid::EC_SECT163K1 => openssl::nid::Nid::SECT163K1,
cryptography_x509::oid::EC_SECT233K1 => openssl::nid::Nid::SECT233K1,
cryptography_x509::oid::EC_SECT283K1 => openssl::nid::Nid::SECT283K1,
cryptography_x509::oid::EC_SECT409K1 => openssl::nid::Nid::SECT409K1,
cryptography_x509::oid::EC_SECT571K1 => openssl::nid::Nid::SECT571K1,

#[cfg(not(CRYPTOGRAPHY_IS_BORINGSSL))]
cryptography_x509::oid::EC_BRAINPOOLP256R1 => {
openssl::nid::Nid::BRAINPOOL_P256R1
}
#[cfg(not(CRYPTOGRAPHY_IS_BORINGSSL))]
cryptography_x509::oid::EC_BRAINPOOLP384R1 => {
openssl::nid::Nid::BRAINPOOL_P384R1
}
#[cfg(not(CRYPTOGRAPHY_IS_BORINGSSL))]
cryptography_x509::oid::EC_BRAINPOOLP512R1 => {
openssl::nid::Nid::BRAINPOOL_P512R1
}

_ => return Err(KeyParsingError::UnsupportedEllipticCurve(curve_oid)),
};

let group = openssl::ec::EcGroup::from_curve_name(curve_nid)
.map_err(|_| KeyParsingError::UnsupportedEllipticCurve(curve_oid))?;
let mut bn_ctx = openssl::bn::BigNumContext::new()?;
let ec_point = openssl::ec::EcPoint::from_bytes(
&group,
k.subject_public_key.as_bytes(),
&mut bn_ctx,
)
.map_err(|_| KeyParsingError::InvalidKey)?;
let ec_key = openssl::ec::EcKey::from_public_key(&group, &ec_point)?;
Ok(openssl::pkey::PKey::from_ec_key(ec_key)?)
}
EcParameters::ImplicitCurve(_) | EcParameters::SpecifiedCurve(_) => {
Err(KeyParsingError::ExplicitCurveUnsupported)
}
},
AlgorithmParameters::Ed25519 => Ok(openssl::pkey::PKey::public_key_from_raw_bytes(
k.subject_public_key.as_bytes(),
openssl::pkey::Id::ED25519,
)?),
#[cfg(all(not(CRYPTOGRAPHY_IS_LIBRESSL), not(CRYPTOGRAPHY_IS_BORINGSSL)))]
AlgorithmParameters::Ed448 => Ok(openssl::pkey::PKey::public_key_from_raw_bytes(
k.subject_public_key.as_bytes(),
openssl::pkey::Id::ED448,
)?),
AlgorithmParameters::X25519 => Ok(openssl::pkey::PKey::public_key_from_raw_bytes(
k.subject_public_key.as_bytes(),
openssl::pkey::Id::X25519,
)?),
#[cfg(all(not(CRYPTOGRAPHY_IS_LIBRESSL), not(CRYPTOGRAPHY_IS_BORINGSSL)))]
AlgorithmParameters::X448 => Ok(openssl::pkey::PKey::public_key_from_raw_bytes(
k.subject_public_key.as_bytes(),
openssl::pkey::Id::X448,
)?),
AlgorithmParameters::Rsa(_) | AlgorithmParameters::RsaPss(_) => {
// RSA-PSS keys are treated the same as bare RSA keys.
crate::rsa::parse_pkcs1_public_key(k.subject_public_key.as_bytes())
}
AlgorithmParameters::Dsa(dsa_params) => {
let p = openssl::bn::BigNum::from_slice(dsa_params.p.as_bytes())?;
let q = openssl::bn::BigNum::from_slice(dsa_params.q.as_bytes())?;
let g = openssl::bn::BigNum::from_slice(dsa_params.g.as_bytes())?;

let pub_key_int =
asn1::parse_single::<asn1::BigUint<'_>>(k.subject_public_key.as_bytes())?;
let pub_key = openssl::bn::BigNum::from_slice(pub_key_int.as_bytes())?;

let dsa = openssl::dsa::Dsa::from_public_components(p, q, g, pub_key)?;
Ok(openssl::pkey::PKey::from_dsa(dsa)?)
}
#[cfg(not(CRYPTOGRAPHY_IS_BORINGSSL))]
AlgorithmParameters::Dh(dh_params) => {
let p = openssl::bn::BigNum::from_slice(dh_params.p.as_bytes())?;
let q = openssl::bn::BigNum::from_slice(dh_params.q.as_bytes())?;
let g = openssl::bn::BigNum::from_slice(dh_params.g.as_bytes())?;
let dh = openssl::dh::Dh::from_pqg(p, Some(q), g)?;

let pub_key_int =
asn1::parse_single::<asn1::BigUint<'_>>(k.subject_public_key.as_bytes())?;
let pub_key = openssl::bn::BigNum::from_slice(pub_key_int.as_bytes())?;
let dh = dh.set_public_key(pub_key)?;

cfg_if::cfg_if! {
if #[cfg(CRYPTOGRAPHY_IS_LIBRESSL)] {
Ok(openssl::pkey::PKey::from_dh(dh)?)
} else {
Ok(openssl::pkey::PKey::from_dhx(dh)?)
}
}
}
#[cfg(not(CRYPTOGRAPHY_IS_BORINGSSL))]
AlgorithmParameters::DhKeyAgreement(dh_params) => {
let p = openssl::bn::BigNum::from_slice(dh_params.p.as_bytes())?;
let g = openssl::bn::BigNum::from_slice(dh_params.g.as_bytes())?;
let dh = openssl::dh::Dh::from_pqg(p, None, g)?;

let pub_key_int =
asn1::parse_single::<asn1::BigUint<'_>>(k.subject_public_key.as_bytes())?;
let pub_key = openssl::bn::BigNum::from_slice(pub_key_int.as_bytes())?;
let dh = dh.set_public_key(pub_key)?;

Ok(openssl::pkey::PKey::from_dh(dh)?)
}
_ => Err(KeyParsingError::UnsupportedKeyType(
k.algorithm.oid().clone(),
)),
}
}
59 changes: 59 additions & 0 deletions src/rust/cryptography-x509/src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@ pub enum AlgorithmParameters<'a> {
#[defined_by(oid::ED448_OID)]
Ed448,

#[defined_by(oid::X25519_OID)]
X25519,
#[defined_by(oid::X448_OID)]
X448,

// These encodings are only used in SPKI AlgorithmIdentifiers.
#[defined_by(oid::EC_OID)]
Ec(EcParameters<'a>),
Expand Down Expand Up @@ -103,6 +108,9 @@ pub enum AlgorithmParameters<'a> {
#[defined_by(oid::RSASSA_PSS_OID)]
RsaPss(Option<Box<RsaPssParameters<'a>>>),

#[defined_by(oid::DSA_OID)]
Dsa(DssParams<'a>),

#[defined_by(oid::DSA_WITH_SHA224_OID)]
DsaWithSha224(Option<asn1::Null>),
#[defined_by(oid::DSA_WITH_SHA256_OID)]
Expand All @@ -112,6 +120,11 @@ pub enum AlgorithmParameters<'a> {
#[defined_by(oid::DSA_WITH_SHA512_OID)]
DsaWithSha512(Option<asn1::Null>),

#[defined_by(oid::DH_OID)]
Dh(DHXParams<'a>),
#[defined_by(oid::DH_KEY_AGREEMENT_OID)]
DhKeyAgreement(BasicDHParams<'a>),

#[default]
Other(asn1::ObjectIdentifier, Option<asn1::Tlv<'a>>),
}
Expand Down Expand Up @@ -235,6 +248,38 @@ pub struct DHParams<'a> {
pub g: asn1::BigUint<'a>,
pub q: Option<asn1::BigUint<'a>>,
}

// From PKCS#3 Section 9
// DHParameter ::= SEQUENCE {
// prime INTEGER, -- p
// base INTEGER, -- g
// privateValueLength INTEGER OPTIONAL
// }
#[derive(asn1::Asn1Read, asn1::Asn1Write, Clone, PartialEq, Eq, Debug, Hash)]
pub struct BasicDHParams<'a> {
pub p: asn1::BigUint<'a>,
pub g: asn1::BigUint<'a>,
pub private_value_length: Option<u32>,
}

// From https://www.rfc-editor.org/rfc/rfc3279#section-2.3.3
// DomainParameters ::= SEQUENCE {
// p INTEGER, -- odd prime, p=jq +1
// g INTEGER, -- generator, g
// q INTEGER, -- factor of p-1
// j INTEGER OPTIONAL, -- subgroup factor
// validationParms ValidationParms OPTIONAL
// }
#[derive(asn1::Asn1Read, asn1::Asn1Write, Clone, PartialEq, Eq, Debug, Hash)]
pub struct DHXParams<'a> {
pub p: asn1::BigUint<'a>,
pub g: asn1::BigUint<'a>,
pub q: asn1::BigUint<'a>,
pub j: Option<asn1::BigUint<'a>>,
// No support for this, so don't bother filling out the fields.
pub validation_params: Option<asn1::Sequence<'a>>,
}

// RSA-PSS ASN.1 default hash algorithm
pub const PSS_SHA1_HASH_ALG: AlgorithmIdentifier<'_> = AlgorithmIdentifier {
oid: asn1::DefinedByMarker::marker(),
Expand Down Expand Up @@ -327,6 +372,20 @@ pub struct RsaPssParameters<'a> {
pub _trailer_field: u8,
}

// https://datatracker.ietf.org/doc/html/rfc3279#section-2.3.2
//
// Dss-Parms ::= SEQUENCE {
// p INTEGER,
// q INTEGER,
// g INTEGER
// }
#[derive(asn1::Asn1Read, asn1::Asn1Write, Hash, Clone, PartialEq, Eq, Debug)]
pub struct DssParams<'a> {
pub p: asn1::BigUint<'a>,
pub q: asn1::BigUint<'a>,
pub g: asn1::BigUint<'a>,
}

/// A VisibleString ASN.1 element whose contents is not validated as meeting the
/// requirements (visible characters of IA5), and instead is only known to be
/// valid UTF-8.
Expand Down
30 changes: 30 additions & 0 deletions src/rust/cryptography-x509/src/oid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,32 @@ pub const ACCEPTABLE_RESPONSES_OID: asn1::ObjectIdentifier =

// Public key identifiers
pub const EC_OID: asn1::ObjectIdentifier = asn1::oid!(1, 2, 840, 10045, 2, 1);

pub const EC_SECP192R1: asn1::ObjectIdentifier = asn1::oid!(1, 2, 840, 10045, 3, 1, 1);
pub const EC_SECP224R1: asn1::ObjectIdentifier = asn1::oid!(1, 3, 132, 0, 33);
pub const EC_SECP256R1: asn1::ObjectIdentifier = asn1::oid!(1, 2, 840, 10045, 3, 1, 7);
pub const EC_SECP384R1: asn1::ObjectIdentifier = asn1::oid!(1, 3, 132, 0, 34);
pub const EC_SECP521R1: asn1::ObjectIdentifier = asn1::oid!(1, 3, 132, 0, 35);

pub const EC_SECP256K1: asn1::ObjectIdentifier = asn1::oid!(1, 3, 132, 0, 10);

pub const EC_SECT233R1: asn1::ObjectIdentifier = asn1::oid!(1, 3, 132, 0, 27);
pub const EC_SECT283R1: asn1::ObjectIdentifier = asn1::oid!(1, 3, 132, 0, 17);
pub const EC_SECT409R1: asn1::ObjectIdentifier = asn1::oid!(1, 3, 132, 0, 37);
pub const EC_SECT571R1: asn1::ObjectIdentifier = asn1::oid!(1, 3, 132, 0, 39);

pub const EC_SECT163R2: asn1::ObjectIdentifier = asn1::oid!(1, 3, 132, 0, 15);

pub const EC_SECT163K1: asn1::ObjectIdentifier = asn1::oid!(1, 3, 132, 0, 1);
pub const EC_SECT233K1: asn1::ObjectIdentifier = asn1::oid!(1, 3, 132, 0, 26);
pub const EC_SECT283K1: asn1::ObjectIdentifier = asn1::oid!(1, 3, 132, 0, 16);
pub const EC_SECT409K1: asn1::ObjectIdentifier = asn1::oid!(1, 3, 132, 0, 36);
pub const EC_SECT571K1: asn1::ObjectIdentifier = asn1::oid!(1, 3, 132, 0, 38);

pub const EC_BRAINPOOLP256R1: asn1::ObjectIdentifier = asn1::oid!(1, 3, 36, 3, 3, 2, 8, 1, 1, 7);
pub const EC_BRAINPOOLP384R1: asn1::ObjectIdentifier = asn1::oid!(1, 3, 36, 3, 3, 2, 8, 1, 1, 11);
pub const EC_BRAINPOOLP512R1: asn1::ObjectIdentifier = asn1::oid!(1, 3, 36, 3, 3, 2, 8, 1, 1, 13);

pub const RSA_OID: asn1::ObjectIdentifier = asn1::oid!(1, 2, 840, 113549, 1, 1, 1);

// Signing methods
Expand Down Expand Up @@ -81,11 +104,18 @@ pub const RSA_WITH_SHA3_384_OID: asn1::ObjectIdentifier =
pub const RSA_WITH_SHA3_512_OID: asn1::ObjectIdentifier =
asn1::oid!(2, 16, 840, 1, 101, 3, 4, 3, 16);

pub const DSA_OID: asn1::ObjectIdentifier = asn1::oid!(1, 2, 840, 10040, 4, 1);
pub const DSA_WITH_SHA224_OID: asn1::ObjectIdentifier = asn1::oid!(2, 16, 840, 1, 101, 3, 4, 3, 1);
pub const DSA_WITH_SHA256_OID: asn1::ObjectIdentifier = asn1::oid!(2, 16, 840, 1, 101, 3, 4, 3, 2);
pub const DSA_WITH_SHA384_OID: asn1::ObjectIdentifier = asn1::oid!(2, 16, 840, 1, 101, 3, 4, 3, 3);
pub const DSA_WITH_SHA512_OID: asn1::ObjectIdentifier = asn1::oid!(2, 16, 840, 1, 101, 3, 4, 3, 4);

pub const DH_OID: asn1::ObjectIdentifier = asn1::oid!(1, 2, 840, 10046, 2, 1);
pub const DH_KEY_AGREEMENT_OID: asn1::ObjectIdentifier = asn1::oid!(1, 2, 840, 113549, 1, 3, 1);

pub const X25519_OID: asn1::ObjectIdentifier = asn1::oid!(1, 3, 101, 110);
pub const X448_OID: asn1::ObjectIdentifier = asn1::oid!(1, 3, 101, 111);

pub const ED25519_OID: asn1::ObjectIdentifier = asn1::oid!(1, 3, 101, 112);
pub const ED448_OID: asn1::ObjectIdentifier = asn1::oid!(1, 3, 101, 113);

Expand Down

0 comments on commit 6b4a4de

Please sign in to comment.