Skip to content

Truly independent web browser

LibCrypto: Tie OpenSSL parameters to what they point at

Shannon Boothce2a24da9549
diff --git a/Libraries/LibCrypto/Rust/src/ec.rs b/Libraries/LibCrypto/Rust/src/ec.rs
index df725ccbbe2..b089e82cfe3 100644
--- a/Libraries/LibCrypto/Rust/src/ec.rs
+++ b/Libraries/LibCrypto/Rust/src/ec.rs
@@ -110,12 +110,12 @@ impl EcPublicKey {
};
let curve = EcCurve::from_scalar_size(scalar_size)?;
let invalid = |_| CryptoError::Invalid("Invalid EC public key");
- let mut params = [
+ let params = [
utf8_parameter(c"group", curve.name()),
octet_string_parameter(c"pub", data),
end_parameter(),
];
- let key = Pkey::from_data(c"EC", sys::EVP_PKEY_PUBLIC_KEY, params.as_mut_ptr()).map_err(invalid)?;
+ let key = Pkey::from_data(c"EC", sys::EVP_PKEY_PUBLIC_KEY, &params).map_err(invalid)?;
if !openssl::check_key(&key, false, false).map_err(invalid)?.public {
return Err(invalid(CryptoError::Backend));
}
@@ -150,7 +150,7 @@ impl EcPublicKey {
impl EcPrivateKey {
fn generate(curve: EcCurve) -> Result<Self, CryptoError> {
let params = [utf8_parameter(c"group", curve.name()), end_parameter()];
- let key = Pkey::generate(c"EC", Some(params.as_ptr()))?;
+ let key = Pkey::generate(c"EC", &params)?;
let (x, y) = coordinates(&key, curve)?;
let public_key = EcPublicKey::from_coordinates(&x, &y)?;
Ok(Self { key, curve, public_key })
@@ -172,7 +172,7 @@ impl EcPrivateKey {
builder.push_number(c"priv", d, true)?;
builder.push_octets(c"pub", &point)?;
let params = builder.build()?;
- let key = Pkey::from_data(c"EC", sys::EVP_PKEY_KEYPAIR, params.as_ptr())?;
+ let key = Pkey::from_data(c"EC", sys::EVP_PKEY_KEYPAIR, &params)?;
let public_key = match public_key {
Some(public_key) => public_key,
None => EcPublicKey::from_octets(&point)?,
diff --git a/Libraries/LibCrypto/Rust/src/lib.rs b/Libraries/LibCrypto/Rust/src/lib.rs
index 1e574fdb5b6..0a510005cc0 100644
--- a/Libraries/LibCrypto/Rust/src/lib.rs
+++ b/Libraries/LibCrypto/Rust/src/lib.rs
@@ -641,7 +641,7 @@ fn okp_key(key: &KeyHandle) -> &OkpKey {
pub fn okp_generate_key_pair(curve: OkpCurve) -> Result<KeyPair, CryptoError> {
let private_key = OkpKey {
curve,
- key: Pkey::generate(curve.name(), None)?,
+ key: Pkey::generate(curve.name(), &[end_parameter()])?,
};
Ok(KeyPair {
public_key: KeyHandle(Key::OkpPublic(private_key.public_key()?)),
diff --git a/Libraries/LibCrypto/Rust/src/ml.rs b/Libraries/LibCrypto/Rust/src/ml.rs
index 98823c8de4f..db9fcb0b28d 100644
--- a/Libraries/LibCrypto/Rust/src/ml.rs
+++ b/Libraries/LibCrypto/Rust/src/ml.rs
@@ -167,8 +167,8 @@ impl MlPrivateKey {
/// The private key of `parameter_set` that `seed` makes.
// NB: The seed parameter points at the caller's buffer, and the key clears its own copy.
fn private_key_from_seed(parameter_set: ParameterSet, seed: &[u8]) -> Result<Pkey, CryptoError> {
- let mut params = [openssl::octet_string_parameter(c"seed", seed), openssl::end_parameter()];
- Pkey::from_data(parameter_set.name(), sys::EVP_PKEY_KEYPAIR, params.as_mut_ptr())
+ let params = [openssl::octet_string_parameter(c"seed", seed), openssl::end_parameter()];
+ Pkey::from_data(parameter_set.name(), sys::EVP_PKEY_KEYPAIR, &params)
}
fn private_key(key: &KeyHandle) -> &MlPrivateKey {
diff --git a/Libraries/LibCrypto/Rust/src/openssl.rs b/Libraries/LibCrypto/Rust/src/openssl.rs
index 6145403d084..5bbdc836225 100644
--- a/Libraries/LibCrypto/Rust/src/openssl.rs
+++ b/Libraries/LibCrypto/Rust/src/openssl.rs
@@ -117,29 +117,85 @@ impl Clone for Pkey {
}
}
-pub(crate) fn octet_string_parameter(name: &CStr, bytes: &[u8]) -> sys::OSSL_PARAM {
- // SAFETY: Constructing a parameter only records the pointer and length, which the caller keeps alive.
- unsafe { sys::OSSL_PARAM_construct_octet_string(name.as_ptr(), bytes.as_ptr().cast_mut().cast(), bytes.len()) }
+/// An OSSL_PARAM, which points at a static name and at a value that lives for `'a`.
+#[derive(Clone, Copy)]
+#[repr(transparent)]
+pub(crate) struct Param<'a> {
+ raw: sys::OSSL_PARAM,
+ value: PhantomData<&'a ()>,
}
-pub(crate) fn utf8_parameter(name: &CStr, value: &'static CStr) -> sys::OSSL_PARAM {
- // SAFETY: Constructing a parameter only records the pointer, a static string, and its length.
- unsafe { sys::OSSL_PARAM_construct_utf8_string(name.as_ptr(), value.as_ptr().cast_mut(), value.count_bytes()) }
+impl Param<'_> {
+ fn new(raw: sys::OSSL_PARAM) -> Self {
+ Self {
+ raw,
+ value: PhantomData,
+ }
+ }
+}
+
+/// A list of parameters for OpenSSL, which reads them up to the end marker.
+///
+/// # Safety
+///
+/// `as_params_ptr()` must give parameters that end with the end marker, and whose names and values live as long as the
+/// list does.
+pub(crate) unsafe trait Params {
+ fn as_params_ptr(&self) -> *const sys::OSSL_PARAM;
+}
+
+// SAFETY: The parameters borrow their values, and the end marker is checked for.
+unsafe impl Params for [Param<'_>] {
+ fn as_params_ptr(&self) -> *const sys::OSSL_PARAM {
+ assert!(
+ self.last().is_some_and(|param| param.raw.is_end()),
+ "The parameters end with the end marker"
+ );
+ <[Param<'_>]>::as_ptr(self).cast()
+ }
}
-pub(crate) fn uint_parameter(name: &CStr, value: &mut c_uint) -> sys::OSSL_PARAM {
- // SAFETY: Constructing a parameter only records the pointer, which the caller keeps alive.
- unsafe { sys::OSSL_PARAM_construct_uint(name.as_ptr(), value) }
+// SAFETY: See the slice's implementation.
+unsafe impl<const N: usize> Params for [Param<'_>; N] {
+ fn as_params_ptr(&self) -> *const sys::OSSL_PARAM {
+ self.as_slice().as_params_ptr()
+ }
+}
+
+// SAFETY: OpenSSL builds the array with the end marker, and the array owns the parameters' values.
+unsafe impl Params for ParamArray {
+ fn as_params_ptr(&self) -> *const sys::OSSL_PARAM {
+ self.as_ptr()
+ }
}
-pub(crate) fn int_parameter(name: &CStr, value: &mut c_int) -> sys::OSSL_PARAM {
- // SAFETY: Constructing a parameter only records the pointer, which the caller keeps alive.
- unsafe { sys::OSSL_PARAM_construct_int(name.as_ptr(), value) }
+pub(crate) fn octet_string_parameter<'a>(name: &'static CStr, bytes: &'a [u8]) -> Param<'a> {
+ // SAFETY: Constructing a parameter only records the pointers and length, which the parameter borrows.
+ Param::new(unsafe {
+ sys::OSSL_PARAM_construct_octet_string(name.as_ptr(), bytes.as_ptr().cast_mut().cast(), bytes.len())
+ })
+}
+
+pub(crate) fn utf8_parameter(name: &'static CStr, value: &'static CStr) -> Param<'static> {
+ // SAFETY: Constructing a parameter only records the pointers, to static strings, and the value's length.
+ Param::new(unsafe {
+ sys::OSSL_PARAM_construct_utf8_string(name.as_ptr(), value.as_ptr().cast_mut(), value.count_bytes())
+ })
}
-pub(crate) fn end_parameter() -> sys::OSSL_PARAM {
+pub(crate) fn uint_parameter<'a>(name: &'static CStr, value: &'a mut c_uint) -> Param<'a> {
+ // SAFETY: Constructing a parameter only records the pointers, which the parameter borrows.
+ Param::new(unsafe { sys::OSSL_PARAM_construct_uint(name.as_ptr(), value) })
+}
+
+pub(crate) fn int_parameter<'a>(name: &'static CStr, value: &'a mut c_int) -> Param<'a> {
+ // SAFETY: Constructing a parameter only records the pointers, which the parameter borrows.
+ Param::new(unsafe { sys::OSSL_PARAM_construct_int(name.as_ptr(), value) })
+}
+
+pub(crate) fn end_parameter() -> Param<'static> {
// SAFETY: Constructing the end marker takes no pointers.
- unsafe { sys::OSSL_PARAM_construct_end() }
+ Param::new(unsafe { sys::OSSL_PARAM_construct_end() })
}
/// Parameters that hold big numbers, which an OSSL_PARAM_BLD builds.
@@ -262,29 +318,39 @@ impl Pkey {
}
/// The key of the algorithm `name` that `params` describe, with the parts that `selection` names.
- pub(crate) fn from_data(name: &CStr, selection: c_int, params: *mut sys::OSSL_PARAM) -> Result<Self, CryptoError> {
+ pub(crate) fn from_data(
+ name: &CStr,
+ selection: c_int,
+ params: &(impl Params + ?Sized),
+ ) -> Result<Self, CryptoError> {
// SAFETY: The name is live; a non-null result is owned.
let context =
PkeyContext::new(unsafe { sys::EVP_PKEY_CTX_new_from_name(ptr::null_mut(), name.as_ptr(), ptr::null()) })?;
// SAFETY: The context is live.
check(unsafe { sys::EVP_PKEY_fromdata_init(context.as_ptr()) })?;
let mut key = ptr::null_mut();
- // SAFETY: The context and the caller's parameters are live; a non-null result is owned.
- check(unsafe { sys::EVP_PKEY_fromdata(context.as_ptr(), &raw mut key, selection, params) })?;
+ // SAFETY: The context and the parameters are live, and OpenSSL only reads the parameters; a non-null result is
+ // owned.
+ check(unsafe {
+ sys::EVP_PKEY_fromdata(
+ context.as_ptr(),
+ &raw mut key,
+ selection,
+ params.as_params_ptr().cast_mut(),
+ )
+ })?;
Self::new(key)
}
- /// A new key of the algorithm `name`, with the generation parameters `params`, which end with the end marker.
- pub(crate) fn generate(name: &CStr, params: Option<*const sys::OSSL_PARAM>) -> Result<Self, CryptoError> {
+ /// A new key of the algorithm `name`, with the generation parameters `params`.
+ pub(crate) fn generate(name: &CStr, params: &(impl Params + ?Sized)) -> Result<Self, CryptoError> {
// SAFETY: The name is live; a non-null result is owned.
let context =
PkeyContext::new(unsafe { sys::EVP_PKEY_CTX_new_from_name(ptr::null_mut(), name.as_ptr(), ptr::null()) })?;
// SAFETY: The context is live.
check(unsafe { sys::EVP_PKEY_keygen_init(context.as_ptr()) })?;
- if let Some(params) = params {
- // SAFETY: The context and the caller's parameters are live.
- check(unsafe { sys::EVP_PKEY_CTX_set_params(context.as_ptr(), params) })?;
- }
+ // SAFETY: The context and the parameters are live.
+ check(unsafe { sys::EVP_PKEY_CTX_set_params(context.as_ptr(), params.as_params_ptr()) })?;
let mut key = ptr::null_mut();
// SAFETY: The context is live; a non-null result is owned.
check(unsafe { sys::EVP_PKEY_generate(context.as_ptr(), &raw mut key) })?;
@@ -424,7 +490,7 @@ pub(crate) fn check_key(key: &Pkey, private: bool, pairwise: bool) -> Result<Key
pub(crate) fn digest_sign(
key: &Pkey,
digest_name: Option<&CStr>,
- params: &[sys::OSSL_PARAM],
+ params: &[Param<'_>],
message: &[u8],
) -> Result<Vec<u8>, CryptoError> {
// SAFETY: Making a context takes no arguments.
@@ -438,7 +504,7 @@ pub(crate) fn digest_sign(
ptr::null_mut(),
ptr::null(),
key.as_ptr(),
- params.as_ptr(),
+ params.as_params_ptr(),
)
})?;
let mut size = 0;
@@ -471,7 +537,7 @@ pub(crate) fn digest_sign(
pub(crate) fn digest_verify(
key: &Pkey,
digest_name: Option<&CStr>,
- params: &[sys::OSSL_PARAM],
+ params: &[Param<'_>],
message: &[u8],
signature: &[u8],
) -> Result<bool, CryptoError> {
@@ -486,7 +552,7 @@ pub(crate) fn digest_verify(
ptr::null_mut(),
ptr::null(),
key.as_ptr(),
- params.as_ptr(),
+ params.as_params_ptr(),
)
})?;
// SAFETY: The context and both buffers are live for the call.
@@ -568,7 +634,7 @@ pub(crate) fn sign_message(
check(sys::EVP_PKEY_sign_message_init(
key_context.as_ptr(),
signature_algorithm.as_ptr(),
- params.as_ptr(),
+ params.as_params_ptr(),
))?;
let mut size = 0;
check(sys::EVP_PKEY_sign(
@@ -609,7 +675,7 @@ pub(crate) fn verify_message(
check(sys::EVP_PKEY_verify_message_init(
key_context.as_ptr(),
signature_algorithm.as_ptr(),
- params.as_ptr(),
+ params.as_params_ptr(),
))?;
check_bool(sys::EVP_PKEY_verify(
key_context.as_ptr(),
@@ -621,11 +687,11 @@ pub(crate) fn verify_message(
}
}
-pub(crate) fn context_string_parameters(context: &[u8]) -> [sys::OSSL_PARAM; 2] {
+pub(crate) fn context_string_parameters(context: &[u8]) -> [Param<'_>; 2] {
[octet_string_parameter(c"context-string", context), end_parameter()]
}
-fn optional_context_string_parameters(context: &[u8]) -> [sys::OSSL_PARAM; 2] {
+fn optional_context_string_parameters(context: &[u8]) -> [Param<'_>; 2] {
if context.is_empty() {
[end_parameter(), end_parameter()]
} else {
@@ -634,10 +700,10 @@ fn optional_context_string_parameters(context: &[u8]) -> [sys::OSSL_PARAM; 2] {
}
/// Encrypts `input` with `key`, with the parameters `params`, which end with the end marker.
-pub(crate) fn encrypt(key: &Pkey, params: &[sys::OSSL_PARAM], input: &[u8]) -> Result<Vec<u8>, CryptoError> {
+pub(crate) fn encrypt(key: &Pkey, params: &[Param<'_>], input: &[u8]) -> Result<Vec<u8>, CryptoError> {
let context = key.context()?;
// SAFETY: The context and parameters are live.
- check(unsafe { sys::EVP_PKEY_encrypt_init_ex(context.as_ptr(), params.as_ptr()) })?;
+ check(unsafe { sys::EVP_PKEY_encrypt_init_ex(context.as_ptr(), params.as_params_ptr()) })?;
let mut size = 0;
// SAFETY: A null output asks for its size.
check(unsafe {
@@ -665,10 +731,10 @@ pub(crate) fn encrypt(key: &Pkey, params: &[sys::OSSL_PARAM], input: &[u8]) -> R
}
/// Decrypts `input` with `key`, with the parameters `params`, which end with the end marker.
-pub(crate) fn decrypt(key: &Pkey, params: &[sys::OSSL_PARAM], input: &[u8]) -> Result<Vec<u8>, CryptoError> {
+pub(crate) fn decrypt(key: &Pkey, params: &[Param<'_>], input: &[u8]) -> Result<Vec<u8>, CryptoError> {
let context = key.context()?;
// SAFETY: The context and parameters are live.
- check(unsafe { sys::EVP_PKEY_decrypt_init_ex(context.as_ptr(), params.as_ptr()) })?;
+ check(unsafe { sys::EVP_PKEY_decrypt_init_ex(context.as_ptr(), params.as_params_ptr()) })?;
let mut size = 0;
// SAFETY: A null output asks for its size.
check(unsafe {
@@ -927,7 +993,7 @@ pub(crate) fn mac(
key: &[u8],
message: &[u8],
output_size: usize,
- params: &[sys::OSSL_PARAM],
+ params: &[Param<'_>],
) -> Result<Vec<u8>, CryptoError> {
// SAFETY: The name is live; a non-null result is owned.
let mac = Mac::new(unsafe { sys::EVP_MAC_fetch(ptr::null_mut(), name.as_ptr(), ptr::null()) })?;
@@ -939,7 +1005,7 @@ pub(crate) fn mac(
context.as_ptr(),
key.as_ptr(),
key.len(),
- params.as_ptr(),
+ params.as_params_ptr(),
))?;
check(sys::EVP_MAC_update(context.as_ptr(), message.as_ptr(), message.len()))?;
let mut output = vec![0; output_size];
@@ -961,13 +1027,20 @@ pub(crate) fn mac(
/// end marker.
// NB: The parameters point at the caller's buffers, so OpenSSL copies secrets only into the KDF context, which clears
// them.
-pub(crate) fn kdf(name: &CStr, params: &[sys::OSSL_PARAM], output: &mut [u8]) -> Result<(), CryptoError> {
+pub(crate) fn kdf(name: &CStr, params: &[Param<'_>], output: &mut [u8]) -> Result<(), CryptoError> {
// SAFETY: The name is live; a non-null result is owned.
let kdf = Kdf::new(unsafe { sys::EVP_KDF_fetch(ptr::null_mut(), name.as_ptr(), ptr::null()) })?;
// SAFETY: The KDF is live; a non-null result is owned.
let context = KdfContext::new(unsafe { sys::EVP_KDF_CTX_new(kdf.as_ptr()) })?;
// SAFETY: The context, parameters and output are live, and the output holds its length.
- check(unsafe { sys::EVP_KDF_derive(context.as_ptr(), output.as_mut_ptr(), output.len(), params.as_ptr()) })
+ check(unsafe {
+ sys::EVP_KDF_derive(
+ context.as_ptr(),
+ output.as_mut_ptr(),
+ output.len(),
+ params.as_params_ptr(),
+ )
+ })
}
pub(crate) fn fill_with_random(bytes: &mut [u8]) -> Result<(), CryptoError> {
diff --git a/Libraries/LibCrypto/Rust/src/rsa.rs b/Libraries/LibCrypto/Rust/src/rsa.rs
index 37a5fad575d..2b8d218430b 100644
--- a/Libraries/LibCrypto/Rust/src/rsa.rs
+++ b/Libraries/LibCrypto/Rust/src/rsa.rs
@@ -12,7 +12,7 @@ use core::ffi::{CStr, c_int};
use crate::key::{HandleTag, Key, KeyDecodeError, KeyHandle, KeyPair, SecretBytes, StoredKey};
use crate::openssl::{
- self, BigNum, ParamBuilder, Pkey, end_parameter, int_parameter, octet_string_parameter, utf8_parameter,
+ self, BigNum, Param, ParamBuilder, Pkey, end_parameter, int_parameter, octet_string_parameter, utf8_parameter,
};
use crate::{CryptoError, KeyAlgorithm, RsaJwkInteger, ShaHashKind, der, sys};
@@ -67,7 +67,7 @@ impl RsaPublicKey {
builder.push_number(c"e", public_exponent, false)?;
let params = builder.build()?;
Ok(Self {
- key: Pkey::from_data(c"RSA", sys::EVP_PKEY_PUBLIC_KEY, params.as_ptr())?,
+ key: Pkey::from_data(c"RSA", sys::EVP_PKEY_PUBLIC_KEY, &params)?,
})
}
@@ -104,7 +104,7 @@ impl RsaPrivateKey {
}
let params = builder.build()?;
Ok(Self {
- key: Pkey::from_data(c"RSA", sys::EVP_PKEY_KEYPAIR, params.as_ptr())?,
+ key: Pkey::from_data(c"RSA", sys::EVP_PKEY_KEYPAIR, &params)?,
has_crt_components: crt_components.is_some(),
})
}
@@ -180,7 +180,7 @@ pub fn rsa_generate_key_pair(modulus_length: u32, exponent: &[u8]) -> Result<Key
builder.push_uint(c"bits", modulus_length)?;
builder.push_number(c"e", exponent, false)?;
let params = builder.build()?;
- let private_key = RsaPrivateKey::from_key(Pkey::generate(c"RSA", Some(params.as_ptr()))?);
+ let private_key = RsaPrivateKey::from_key(Pkey::generate(c"RSA", &params)?);
let public_key = private_key.public_key()?;
Ok(KeyPair {
public_key: KeyHandle(Key::RsaPublic(public_key)),
@@ -324,7 +324,7 @@ impl RsaSignaturePadding {
}
/// The signature parameters of the padding, which point at `salt_length`.
-fn signature_parameters(hash_kind: ShaHashKind, salt_length: Option<&mut c_int>) -> Vec<sys::OSSL_PARAM> {
+fn signature_parameters(hash_kind: ShaHashKind, salt_length: Option<&mut c_int>) -> Vec<Param<'_>> {
match salt_length {
Some(salt_length) => vec![
utf8_parameter(c"pad-mode", c"pss"),
diff --git a/Libraries/LibCrypto/Rust/src/sys.rs b/Libraries/LibCrypto/Rust/src/sys.rs
index 6a9f416d0db..a334e65bb82 100644
--- a/Libraries/LibCrypto/Rust/src/sys.rs
+++ b/Libraries/LibCrypto/Rust/src/sys.rs
@@ -56,6 +56,12 @@ pub(crate) struct OSSL_PARAM {
return_size: usize,
}
+impl OSSL_PARAM {
+ pub(crate) fn is_end(&self) -> bool {
+ self.key.is_null()
+ }
+}
+
pub(crate) const EVP_PKEY_PUBLIC_KEY: c_int = 0x86;
pub(crate) const EVP_PKEY_KEYPAIR: c_int = 0x87;