Skip to content

Truly independent web browser

LibCrypto+LibWeb: Return derived secrets as SecretBytes

Shannon Boothe91cd3d8eb6e
diff --git a/Libraries/LibCrypto/Rust/src/ec.rs b/Libraries/LibCrypto/Rust/src/ec.rs
index 7d61c7f182b..55aa70575be 100644
--- a/Libraries/LibCrypto/Rust/src/ec.rs
+++ b/Libraries/LibCrypto/Rust/src/ec.rs
@@ -351,7 +351,7 @@ pub fn ec_export_private_scalar(key: &KeyHandle) -> Result<Vec<u8>, CryptoError>
Ok(private_key(key).d_bytes()?.into_vec())
}
-pub fn ec_compute_coordinate(key: &KeyHandle, public_key: &KeyHandle) -> Result<Vec<u8>, CryptoError> {
+pub fn ec_compute_coordinate(key: &KeyHandle, public_key: &KeyHandle) -> Result<SecretBytes, CryptoError> {
let private_key = private_key(key);
let peer = self::public_key(public_key);
if private_key.curve != peer.curve {
diff --git a/Libraries/LibCrypto/Rust/src/key.rs b/Libraries/LibCrypto/Rust/src/key.rs
index 4bac02269cb..9fdbb68289b 100644
--- a/Libraries/LibCrypto/Rust/src/key.rs
+++ b/Libraries/LibCrypto/Rust/src/key.rs
@@ -113,12 +113,8 @@ impl SecretBytes {
Self(bytes)
}
- /// Shortens the bytes to `length`, clearing the ones cut off.
pub(crate) fn truncate(&mut self, length: usize) {
- if length < self.0.len() {
- clear(&mut self.0[length..]);
- self.0.truncate(length);
- }
+ self.0.truncate(length);
}
/// Appends `bytes`, which must fit in the capacity reserved so that no partial copy is left behind by a reallocation.
@@ -127,7 +123,7 @@ impl SecretBytes {
self.0.extend_from_slice(bytes);
}
- pub(crate) fn into_vec(mut self) -> Vec<u8> {
+ pub fn into_vec(mut self) -> Vec<u8> {
core::mem::take(&mut self.0)
}
}
@@ -148,17 +144,14 @@ impl core::ops::DerefMut for SecretBytes {
impl Drop for SecretBytes {
fn drop(&mut self) {
- clear(&mut self.0);
+ clear_allocation(&mut self.0);
}
}
/// Overwrites `bytes` with zeros in a way the compiler does not remove.
pub(crate) fn clear(bytes: &mut [u8]) {
- for byte in bytes.iter_mut() {
- // SAFETY: The pointer comes from a live mutable reference.
- unsafe { core::ptr::write_volatile(byte, 0) };
- }
- core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
+ // SAFETY: The pointer and length come from a live mutable slice.
+ unsafe { sys::OPENSSL_cleanse(bytes.as_mut_ptr().cast(), bytes.len()) };
}
/// Overwrites all of the allocation of `bytes` with zeros, including what lies past its length.
diff --git a/Libraries/LibCrypto/Rust/src/lib.rs b/Libraries/LibCrypto/Rust/src/lib.rs
index b375e368689..5d92b9ecdde 100644
--- a/Libraries/LibCrypto/Rust/src/lib.rs
+++ b/Libraries/LibCrypto/Rust/src/lib.rs
@@ -184,7 +184,7 @@ pub fn hkdf_derive_key(
key: &[u8],
info: &[u8],
length: u32,
-) -> Result<Vec<u8>, CryptoError> {
+) -> Result<SecretBytes, CryptoError> {
let params = [
utf8_parameter(c"digest", kind.name()),
octet_string_parameter(c"key", key),
@@ -192,7 +192,7 @@ pub fn hkdf_derive_key(
octet_string_parameter(c"info", info),
end_parameter(),
];
- let mut derived = vec![0; length as usize];
+ let mut derived = SecretBytes::new(vec![0; length as usize]);
openssl::kdf(c"HKDF", &params, &mut derived)?;
Ok(derived)
}
@@ -203,7 +203,7 @@ pub fn pbkdf2_derive_key(
salt: &[u8],
iterations: u32,
length: u32,
-) -> Result<Vec<u8>, CryptoError> {
+) -> Result<SecretBytes, CryptoError> {
// NB: OpenSSL's PBKDF2 takes the iteration count and the lengths as int.
let fits_in_int = |value: usize| c_int::try_from(value).is_ok();
if ![iterations as usize, password.len(), salt.len(), length as usize]
@@ -224,7 +224,7 @@ pub fn pbkdf2_derive_key(
openssl::int_parameter(c"pkcs5", &mut pkcs5),
end_parameter(),
];
- let mut derived = vec![0; length as usize];
+ let mut derived = SecretBytes::new(vec![0; length as usize]);
openssl::kdf(c"PBKDF2", &params, &mut derived)?;
Ok(derived)
}
@@ -351,14 +351,14 @@ pub fn argon2_validate_parameters(nonce: &[u8]) -> Result<(), CryptoError> {
}
/// Argon2 with inputs that `argon2_validate_parameters()` accepts.
-pub fn argon2_derive_key(kind: Argon2Type, inputs: &Argon2Inputs<'_>) -> Result<Vec<u8>, CryptoError> {
+pub fn argon2_derive_key(kind: Argon2Type, inputs: &Argon2Inputs<'_>) -> Result<SecretBytes, CryptoError> {
let name = match kind {
Argon2Type::Argon2d => c"ARGON2D",
Argon2Type::Argon2i => c"ARGON2I",
Argon2Type::Argon2id => c"ARGON2ID",
};
// NB: OpenSSL takes version 0x13, the only version Web Crypto allows, and one thread when none are given.
- let mut output = vec![0; inputs.tag_length as usize];
+ let mut output = SecretBytes::new(vec![0; inputs.tag_length as usize]);
let (mut passes, mut lanes, mut memory) = (inputs.passes, inputs.parallelism, inputs.memory);
let mut size = c_uint::try_from(output.len()).map_err(|_| CryptoError::Backend)?;
let mut params = vec![
@@ -469,12 +469,12 @@ pub fn aes_ctr_cipher(
_ => remaining.len(),
};
let (segment, rest) = remaining.split_at(segment_length);
- output.extend(aes_ctr_cipher_whole_block_counter(
+ output.extend_from_slice(&SecretBytes::new(aes_ctr_cipher_whole_block_counter(
encrypt,
key,
segment,
&block.to_be_bytes(),
- )?);
+ )?));
remaining = rest;
block &= !mask;
}
@@ -679,7 +679,7 @@ pub fn okp_raw_private_key(key: &KeyHandle) -> Result<SecretBytes, CryptoError>
okp_key(key).key.raw_private_key()
}
-pub fn okp_compute_coordinate(private_key: &KeyHandle, public_key: &KeyHandle) -> Result<Vec<u8>, CryptoError> {
+pub fn okp_compute_coordinate(private_key: &KeyHandle, public_key: &KeyHandle) -> Result<SecretBytes, CryptoError> {
let private_key = okp_key(private_key);
if !matches!(private_key.curve, OkpCurve::X25519 | OkpCurve::X448) {
return Err(CryptoError::Backend);
diff --git a/Libraries/LibCrypto/Rust/src/openssl.rs b/Libraries/LibCrypto/Rust/src/openssl.rs
index 94994e964ad..c4d5a41d244 100644
--- a/Libraries/LibCrypto/Rust/src/openssl.rs
+++ b/Libraries/LibCrypto/Rust/src/openssl.rs
@@ -756,7 +756,7 @@ pub(crate) fn decrypt(key: &Pkey, params: &[Param<'_>], input: &[u8]) -> Result<
}
/// The secret that `key` and the public key `peer` agree on. OpenSSL checks the peer when `validate_peer` is set.
-pub(crate) fn derive(key: &Pkey, peer: &Pkey, validate_peer: bool) -> Result<Vec<u8>, CryptoError> {
+pub(crate) fn derive(key: &Pkey, peer: &Pkey, validate_peer: bool) -> Result<SecretBytes, CryptoError> {
let context = key.context()?;
// SAFETY: The context and peer are live for each call, and the output holds the size the first call gives.
unsafe {
@@ -768,7 +768,7 @@ pub(crate) fn derive(key: &Pkey, peer: &Pkey, validate_peer: bool) -> Result<Vec
))?;
let mut size = 0;
check(sys::EVP_PKEY_derive(context.as_ptr(), ptr::null_mut(), &raw mut size))?;
- let mut secret = vec![0; size];
+ let mut secret = SecretBytes::new(vec![0; size]);
check(sys::EVP_PKEY_derive(
context.as_ptr(),
secret.as_mut_ptr(),
diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs
index 13c3c1f703e..2f537781d6b 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs
@@ -2189,6 +2189,7 @@ impl AlgorithmMethods for HkdfParams {
normalized_algorithm.info.as_slice(),
length / 8,
)
+ .map(SecretBytes::into_vec)
.map(Bytes::new);
// 6. If the key derivation operation fails, then throw an OperationError.
@@ -2273,6 +2274,7 @@ impl AlgorithmMethods for Pbkdf2Params {
iterations,
derived_key_length_bytes,
)
+ .map(SecretBytes::into_vec)
.map(Bytes::new);
// 6. If the key derivation operation fails, then throw an OperationError.
@@ -2507,7 +2509,9 @@ impl AlgorithmMethods for Argon2Params {
tag_length: length.expect("validation requires a length") / 8,
};
- let result = libcrypto_rust::argon2_derive_key(kind, &inputs).map(Bytes::new);
+ let result = libcrypto_rust::argon2_derive_key(kind, &inputs)
+ .map(SecretBytes::into_vec)
+ .map(Bytes::new);
// 10. If the key derivation operation fails, then throw an OperationError.
let result = result.map_err(|detail| {
@@ -8986,12 +8990,14 @@ impl AlgorithmMethods for Ecdh {
// by the [[handle]] internal slot of publicKey as the EC public key.
// 2. Let secret be a byte sequence containing the result of applying the field element to octet string
// conversion defined in Section 6.2 of [RFC6090] to the output of the ECDH primitive.
- libcrypto_rust::ec_compute_coordinate(key.handle(), public_key.handle()).map_err(|detail| {
- Exception::Dom(
- "OperationError",
- libjs_rust::api::utf16_formatted("Failed to compute secret: {}", &[&detail.message()]),
- )
- })?
+ libcrypto_rust::ec_compute_coordinate(key.handle(), public_key.handle())
+ .map_err(|detail| {
+ Exception::Dom(
+ "OperationError",
+ libjs_rust::api::utf16_formatted("Failed to compute secret: {}", &[&detail.message()]),
+ )
+ })?
+ .into_vec()
} else {
// If the namedCurve property of the [[algorithm]] internal slot of key is a value specified
// in an applicable specification that specifies the use of that value with ECDH:
@@ -11007,7 +11013,8 @@ impl AlgorithmMethods for X25519 {
// 7. Let secret be the result of performing the X25519 function specified in [RFC7748] Section 5 with
// key as the X25519 private key k and
// the X25519 public key represented by the [[handle]] internal slot of publicKey as the X25519 public key u.
- let secret = libcrypto_rust::okp_compute_coordinate(key.handle(), public_key.handle());
+ let secret =
+ libcrypto_rust::okp_compute_coordinate(key.handle(), public_key.handle()).map(SecretBytes::into_vec);
let Ok(mut secret) = secret else {
return Err(dom_error("OperationError", b"Failed to compute secret"));
};
@@ -11583,7 +11590,8 @@ impl AlgorithmMethods for X448 {
// 5. Let secret be the result of performing the X448 function specified in [RFC7748] Section 5
// with key as the X448 private key k and the X448 public key represented by the [[handle]]
// internal slot of publicKey as the X448 public key u.
- let secret = libcrypto_rust::okp_compute_coordinate(key.handle(), public_key.handle());
+ let secret =
+ libcrypto_rust::okp_compute_coordinate(key.handle(), public_key.handle()).map(SecretBytes::into_vec);
let Ok(mut secret) = secret else {
return Err(dom_error("OperationError", b"Failed to compute secret"));
};