Skip to content

Commit

Permalink
Migrate SPKI parsing from OpenSSL to Rust
Browse files Browse the repository at this point in the history
  • Loading branch information
alex committed Jan 4, 2024
1 parent 0e44ccf commit 9a78475
Show file tree
Hide file tree
Showing 15 changed files with 285 additions and 80 deletions.
12 changes: 6 additions & 6 deletions src/rust/Cargo.lock

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

4 changes: 4 additions & 0 deletions src/rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,7 @@ members = [
"cryptography-x509",
"cryptography-x509-verification",
]

[patch.crates-io]
openssl = { git = "https://github.com/sfackler/rust-openssl" }
openssl-sys = { git = "https://github.com/sfackler/rust-openssl" }
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.62"
openssl-sys = "0.9.98"
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
132 changes: 132 additions & 0 deletions src/rust/cryptography-key-parsing/src/spki.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
// 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_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_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(any(CRYPTOGRAPHY_IS_LIBRESSL, CRYPTOGRAPHY_IS_BORINGSSL)))]
cryptography_x509::oid::EC_BRAINPOOLP256R1 => {
openssl::nid::Nid::BRAINPOOL_P256R1
}
#[cfg(not(any(CRYPTOGRAPHY_IS_LIBRESSL, CRYPTOGRAPHY_IS_BORINGSSL)))]
cryptography_x509::oid::EC_BRAINPOOLP384R1 => {
openssl::nid::Nid::BRAINPOOL_P384R1
}
#[cfg(not(any(CRYPTOGRAPHY_IS_LIBRESSL, 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::UnsupportedKeyType(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) | AlgorithmParameters::DhKeyAgreement(dh_params) => {
let p = openssl::bn::BigNum::from_slice(dh_params.p.as_bytes())?;
let q = dh_params
.q
.as_ref()
.map(|v| openssl::bn::BigNum::from_slice(v.as_bytes()))
.transpose()?;
let g = openssl::bn::BigNum::from_slice(dh_params.g.as_bytes())?;
let dh = openssl::dh::Dh::from_pqg(p, 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 {
if dh_params.q.is_some() {
Ok(openssl::pkey::PKey::from_dhx(dh)?)
} else {
Ok(openssl::pkey::PKey::from_dh(dh)?)
}
}
}
}
_ => Err(KeyParsingError::UnsupportedKeyType(
k.algorithm.oid().clone(),
)),
}
}
22 changes: 21 additions & 1 deletion 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(DssParms<'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(DHParams<'a>),
#[defined_by(oid::DH_KEY_AGREEMENT_OID)]
DhKeyAgreement(DHParams<'a>),

#[default]
Other(asn1::ObjectIdentifier, Option<asn1::Tlv<'a>>),
}
Expand Down Expand Up @@ -229,7 +242,7 @@ pub struct DssSignature<'a> {
pub s: asn1::BigUint<'a>,
}

#[derive(asn1::Asn1Read, asn1::Asn1Write)]
#[derive(asn1::Asn1Read, asn1::Asn1Write, Clone, Hash, PartialEq, Eq, Debug)]
pub struct DHParams<'a> {
pub p: asn1::BigUint<'a>,
pub g: asn1::BigUint<'a>,
Expand Down Expand Up @@ -327,6 +340,13 @@ pub struct RsaPssParameters<'a> {
pub _trailer_field: u8,
}

#[derive(asn1::Asn1Read, asn1::Asn1Write, Hash, Clone, PartialEq, Eq, Debug)]
pub struct DssParms<'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
25 changes: 25 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,27 @@ 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_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_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 +99,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
26 changes: 21 additions & 5 deletions src/rust/src/backend/dh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,23 @@ pub(crate) fn public_key_from_pkey(
}
}

#[cfg(not(CRYPTOGRAPHY_IS_BORINGSSL))]
fn pkey_from_dh<T: openssl::pkey::HasParams>(
dh: openssl::dh::Dh<T>,
) -> CryptographyResult<openssl::pkey::PKey<T>> {
cfg_if::cfg_if! {
if #[cfg(CRYPTOGRAPHY_IS_LIBRESSL)] {
Ok(openssl::pkey::PKey::from_dh(dh)?)
} else {
if dh.prime_q().is_some() {
Ok(openssl::pkey::PKey::from_dhx(dh)?)
} else {
Ok(openssl::pkey::PKey::from_dh(dh)?)
}
}
}
}

#[pyo3::prelude::pyfunction]
fn from_der_parameters(
data: &[u8],
Expand Down Expand Up @@ -186,8 +203,7 @@ impl DHPrivateKey {
let orig_dh = self.pkey.dh().unwrap();
let dh = clone_dh(&orig_dh)?;

let pkey =
openssl::pkey::PKey::from_dh(dh.set_public_key(orig_dh.public_key().to_owned()?)?)?;
let pkey = pkey_from_dh(dh.set_public_key(orig_dh.public_key().to_owned()?)?)?;

Ok(DHPublicKey { pkey })
}
Expand Down Expand Up @@ -295,7 +311,7 @@ impl DHParameters {
fn generate_private_key(&self) -> CryptographyResult<DHPrivateKey> {
let dh = clone_dh(&self.dh)?.generate_key()?;
Ok(DHPrivateKey {
pkey: openssl::pkey::PKey::from_dh(dh)?,
pkey: pkey_from_dh(dh)?,
})
}

Expand Down Expand Up @@ -407,7 +423,7 @@ impl DHPrivateNumbers {
));
}

let pkey = openssl::pkey::PKey::from_dh(dh)?;
let pkey = pkey_from_dh(dh)?;
Ok(DHPrivateKey { pkey })
}

Expand Down Expand Up @@ -449,7 +465,7 @@ impl DHPublicNumbers {

let pub_key = utils::py_int_to_bn(py, self.y.as_ref(py))?;

let pkey = openssl::pkey::PKey::from_dh(dh.set_public_key(pub_key)?)?;
let pkey = pkey_from_dh(dh.set_public_key(pub_key)?)?;

Ok(DHPublicKey { pkey })
}
Expand Down
Loading

0 comments on commit 9a78475

Please sign in to comment.