Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Update rng helpers (#2468)

Leendert de Borst35af3018dc11
diff --git a/core/rust/src/common/rng.rs b/core/rust/src/common/rng.rs
index e83f94484..3e5f25f32 100644
--- a/core/rust/src/common/rng.rs
+++ b/core/rust/src/common/rng.rs
@@ -8,6 +8,20 @@ pub(crate) fn fill_random(dest: &mut [u8]) {
getrandom::fill(dest).expect("the OS CSPRNG is unavailable");
}
+/// `len` fresh bytes from the operating system's CSPRNG.
+pub(crate) fn random_bytes(len: usize) -> Vec<u8> {
+ let mut bytes = vec![0u8; len];
+ fill_random(&mut bytes);
+ bytes
+}
+
+/// A fixed-size array of fresh bytes from the operating system's CSPRNG.
+pub(crate) fn random_array<const N: usize>() -> [u8; N] {
+ let mut bytes = [0u8; N];
+ fill_random(&mut bytes);
+ bytes
+}
+
/// Build the RNG used for generation.
///
/// If `seed` is a valid 64-character hex string (32 bytes), the RNG is deterministically
diff --git a/core/rust/src/crypto/pin.rs b/core/rust/src/crypto/pin.rs
index a4cb3055b..eb4dcda1a 100644
--- a/core/rust/src/crypto/pin.rs
+++ b/core/rust/src/crypto/pin.rs
@@ -4,7 +4,7 @@ use serde::Serialize;
use zeroize::Zeroizing;
use crate::common::error::{VaultError, VaultResult};
-use crate::common::rng::fill_random;
+use crate::common::rng::random_bytes;
use crate::crypto::aes_gcm::{symmetric_decrypt_with_raw_key, symmetric_encrypt_with_raw_key};
use crate::crypto::argon2::argon2_derive_key_bytes_from_settings;
@@ -32,9 +32,7 @@ pub struct PinFailure {
/// A fresh random salt for a new PIN wrap.
pub fn pin_generate_salt() -> Vec<u8> {
- let mut salt = vec![0u8; PIN_SALT_LENGTH];
- fill_random(&mut salt);
- salt
+ random_bytes(PIN_SALT_LENGTH)
}
/// Encrypt `secret` with a key derived from the PIN and salt. Returns `IV | ciphertext | tag`.
diff --git a/core/rust/src/crypto/srp.rs b/core/rust/src/crypto/srp.rs
index 597f00ea8..380f39878 100644
--- a/core/rust/src/crypto/srp.rs
+++ b/core/rust/src/crypto/srp.rs
@@ -1,8 +1,9 @@
-//! SRP (Secure Remote Password) protocol implementation.
+//! SRP-6a (Secure Remote Password), client side only; the server side lives in the .NET API.
//!
//! Uses RustCrypto `srp` crate for most operations, except certain places
//! where the format must stay compatible with the `SecureRemotePassword` .NET package
//! used by the API server and the `secure-remote-password` library used in the JS test suite.
+//! The tests module carries a server side of the handshake to test the client-server flow locally.
use num_bigint::BigUint;
use serde::{Deserialize, Serialize};
@@ -10,13 +11,12 @@ use sha2::{Digest, Sha256};
use std::fmt;
use srp::client::SrpClient;
use srp::groups::G_2048;
-use srp::server::SrpServer;
use srp::utils::{compute_k, compute_u};
use subtle::ConstantTimeEq;
use thiserror::Error;
use crate::common::encoding::{hex_decode, hex_encode_upper as bytes_to_hex};
-use crate::common::rng::fill_random;
+use crate::common::rng::random_bytes;
/// Byte length of the 2048-bit group modulus N; all padded values use this size.
const N_BYTES: usize = 256;
@@ -72,13 +72,6 @@ fn hex_to_bytes(hex: &str) -> Result<Vec<u8>, SrpError> {
hex_decode(hex).ok_or_else(|| SrpError::InvalidHex(format!("malformed hex string of length {}", hex.len())))
}
-/// Generate cryptographically secure random bytes.
-fn generate_random_bytes(len: usize) -> Vec<u8> {
- let mut bytes = vec![0u8; len];
- fill_random(&mut bytes);
- bytes
-}
-
/// Left-pad bytes with zeros to a specific length.
fn pad_to_length(bytes: Vec<u8>, target_len: usize) -> Vec<u8> {
if bytes.len() >= target_len {
@@ -97,7 +90,7 @@ fn to_padded_bytes(value: &BigUint) -> Vec<u8> {
/// A random 32-byte SRP salt as an uppercase hex string.
pub fn srp_generate_salt() -> String {
- bytes_to_hex(&generate_random_bytes(32))
+ bytes_to_hex(&random_bytes(32))
}
/// The SRP private key `x = H(salt | H(identity | ":" | password_hash))` as uppercase hex, from hex inputs.
@@ -129,7 +122,7 @@ pub fn srp_derive_verifier(private_key: &str) -> Result<String, SrpError> {
pub fn srp_generate_ephemeral() -> SrpEphemeral {
let client = SrpClient::<Sha256>::new(&G_2048);
- let a = generate_random_bytes(64);
+ let a = random_bytes(64);
let a_pub = client.compute_public_ephemeral(&a);
SrpEphemeral { public: bytes_to_hex(&pad_to_length(a_pub, N_BYTES)), secret: bytes_to_hex(&a) }
@@ -181,70 +174,6 @@ pub fn srp_verify_session(client_public: &str, client_proof: &str, session_key:
Ok(expected_m2.ct_eq(&server_m2_bytes).unwrap_u8() == 1)
}
-// Server side of the handshake.
-
-/// A server ephemeral pair: `B = k*v + g^b mod N` for a random 64-byte secret `b`, from the hex verifier.
-pub fn srp_generate_ephemeral_server(verifier: &str) -> Result<SrpEphemeral, SrpError> {
- let v_bytes = hex_to_bytes(verifier)?;
-
- let server = SrpServer::<Sha256>::new(&G_2048);
-
- let b = generate_random_bytes(64);
- let b_pub = server.compute_public_ephemeral(&b, &v_bytes);
-
- Ok(SrpEphemeral { public: bytes_to_hex(&pad_to_length(b_pub, N_BYTES)), secret: bytes_to_hex(&b) })
-}
-
-/// The server session (key `K` and proof `M2`) once the client's proof `M1` verifies; `None` when it does not.
-pub fn srp_derive_session_server(
- server_secret: &str,
- client_public: &str,
- salt: &str,
- identity: &str,
- verifier: &str,
- client_proof: &str,
-) -> Result<Option<SrpSession>, SrpError> {
- let identity = identity.to_lowercase();
- let b = BigUint::from_bytes_be(&hex_to_bytes(server_secret)?);
- let a_pub = BigUint::from_bytes_be(&hex_to_bytes(client_public)?);
- let salt_bytes = hex_to_bytes(salt)?;
- let v = BigUint::from_bytes_be(&hex_to_bytes(verifier)?);
- let client_m1 = hex_to_bytes(client_proof)?;
-
- // Safeguard against malicious A (A mod N must not be 0)
- if &a_pub % &G_2048.n == BigUint::default() {
- return Err(SrpError::InvalidParameter("client public ephemeral is invalid".to_string()));
- }
-
- let server = SrpServer::<Sha256>::new(&G_2048);
- let k = compute_k::<Sha256>(&G_2048);
-
- // B = k*v + g^b mod N
- let b_pub = server.compute_b_pub(&b, &k, &v);
-
- let a_pub_bytes = to_padded_bytes(&a_pub);
- let b_pub_bytes = to_padded_bytes(&b_pub);
-
- let u = compute_u::<Sha256>(&a_pub_bytes, &b_pub_bytes);
- if u == BigUint::default() {
- return Err(SrpError::InvalidParameter("scrambling parameter u is zero".to_string()));
- }
-
- // S = (A * v^u)^b mod N
- let s = server.compute_premaster_secret(&a_pub, &v, &u, &b);
-
- let key = derive_session_key(&s);
- let expected_m1 = compute_m1(&a_pub_bytes, &b_pub_bytes, &salt_bytes, &identity, &key);
-
- if expected_m1.ct_eq(&client_m1).unwrap_u8() != 1 {
- return Ok(None);
- }
-
- let m2 = compute_m2(&a_pub_bytes, &expected_m1, &key);
-
- Ok(Some(SrpSession { proof: bytes_to_hex(&m2), key: bytes_to_hex(&key) }))
-}
-
/*
* Wire format primitives that deviate from the `srp` crate on purpose: the SecureRemotePassword (.NET/JS) format hashes
* the padded premaster secret into K and uses the RFC 2945 M1, while the crate uses raw S and M1 = H(A|B|S).
@@ -287,6 +216,71 @@ fn compute_m2(a_pub: &[u8], m1: &[u8], key: &[u8]) -> Vec<u8> {
#[cfg(test)]
mod tests {
use super::*;
+ use srp::server::SrpServer;
+
+ // Server side of the handshake: lets the tests run a full client/server flow.
+
+ /// A server ephemeral pair: `B = k*v + g^b mod N` for a random 64-byte secret `b`, from the hex verifier.
+ fn srp_generate_ephemeral_server(verifier: &str) -> Result<SrpEphemeral, SrpError> {
+ let v_bytes = hex_to_bytes(verifier)?;
+
+ let server = SrpServer::<Sha256>::new(&G_2048);
+
+ let b = random_bytes(64);
+ let b_pub = server.compute_public_ephemeral(&b, &v_bytes);
+
+ Ok(SrpEphemeral { public: bytes_to_hex(&pad_to_length(b_pub, N_BYTES)), secret: bytes_to_hex(&b) })
+ }
+
+ /// The server session (key `K` and proof `M2`) once the client's proof `M1` verifies; `None` when it does not.
+ fn srp_derive_session_server(
+ server_secret: &str,
+ client_public: &str,
+ salt: &str,
+ identity: &str,
+ verifier: &str,
+ client_proof: &str,
+ ) -> Result<Option<SrpSession>, SrpError> {
+ let identity = identity.to_lowercase();
+ let b = BigUint::from_bytes_be(&hex_to_bytes(server_secret)?);
+ let a_pub = BigUint::from_bytes_be(&hex_to_bytes(client_public)?);
+ let salt_bytes = hex_to_bytes(salt)?;
+ let v = BigUint::from_bytes_be(&hex_to_bytes(verifier)?);
+ let client_m1 = hex_to_bytes(client_proof)?;
+
+ // Safeguard against malicious A (A mod N must not be 0)
+ if &a_pub % &G_2048.n == BigUint::default() {
+ return Err(SrpError::InvalidParameter("client public ephemeral is invalid".to_string()));
+ }
+
+ let server = SrpServer::<Sha256>::new(&G_2048);
+ let k = compute_k::<Sha256>(&G_2048);
+
+ // B = k*v + g^b mod N
+ let b_pub = server.compute_b_pub(&b, &k, &v);
+
+ let a_pub_bytes = to_padded_bytes(&a_pub);
+ let b_pub_bytes = to_padded_bytes(&b_pub);
+
+ let u = compute_u::<Sha256>(&a_pub_bytes, &b_pub_bytes);
+ if u == BigUint::default() {
+ return Err(SrpError::InvalidParameter("scrambling parameter u is zero".to_string()));
+ }
+
+ // S = (A * v^u)^b mod N
+ let s = server.compute_premaster_secret(&a_pub, &v, &u, &b);
+
+ let key = derive_session_key(&s);
+ let expected_m1 = compute_m1(&a_pub_bytes, &b_pub_bytes, &salt_bytes, &identity, &key);
+
+ if expected_m1.ct_eq(&client_m1).unwrap_u8() != 1 {
+ return Ok(None);
+ }
+
+ let m2 = compute_m2(&a_pub_bytes, &expected_m1, &key);
+
+ Ok(Some(SrpSession { proof: bytes_to_hex(&m2), key: bytes_to_hex(&key) }))
+ }
/// Test with fixed values for deterministic verification.
#[test]
diff --git a/core/rust/src/passkey/mod.rs b/core/rust/src/passkey/mod.rs
index 13375c82f..7d26d0dc8 100644
--- a/core/rust/src/passkey/mod.rs
+++ b/core/rust/src/passkey/mod.rs
@@ -107,11 +107,7 @@ pub fn create_passkey(
};
let attestation_object = cbor::map(&[(cbor::text("fmt"), cbor::text(fmt)), (cbor::text("attStmt"), statement), (cbor::text("authData"), cbor::bytes(&authenticator_data))]);
- let prf_secret = enable_prf.then(|| {
- let mut secret = vec![0u8; 32];
- crate::common::rng::fill_random(&mut secret);
- secret
- });
+ let prf_secret = enable_prf.then(|| crate::common::rng::random_bytes(32));
let prf_results = prf(prf_secret.as_deref(), prf_inputs);
Ok(PasskeyCreation { attestation_object, authenticator_data, public_key_jwk: key.public_key_jwk, public_key_spki: key.public_key_spki, private_key_jwk: key.private_key_jwk, prf_secret, prf_results })
diff --git a/core/rust/src/sqlite_host/mod.rs b/core/rust/src/sqlite_host/mod.rs
index 38f7ce7e8..6a3f3b4d1 100644
--- a/core/rust/src/sqlite_host/mod.rs
+++ b/core/rust/src/sqlite_host/mod.rs
@@ -268,8 +268,7 @@ mod tests {
use crate::common::encoding::base64_encode;
fn adversarial() -> Vec<Vec<u8>> {
- let mut large = vec![0u8; 1024 * 1024];
- crate::common::rng::fill_random(&mut large);
+ let large = crate::common::rng::random_bytes(1024 * 1024);
vec![vec![], vec![0x00], vec![0xFF], vec![0x00, 0xFF], vec![0xC3, 0x28, 0xA0], vec![0xED, 0xA0, 0x80, 0xF8], b"QUJD".to_vec(), (0u8..=255).collect(), large]
}
diff --git a/core/rust/src/vault_codec/mod.rs b/core/rust/src/vault_codec/mod.rs
index 2d54eac90..00618ddbb 100644
--- a/core/rust/src/vault_codec/mod.rs
+++ b/core/rust/src/vault_codec/mod.rs
@@ -55,9 +55,7 @@ pub fn logo_content_hash(bytes: &[u8]) -> String {
/// Generate a fresh 32-byte per-manifest blob-hashing salt as a lowercase hex string.
pub fn generate_manifest_salt() -> String {
- let mut bytes = [0u8; 32];
- crate::common::rng::fill_random(&mut bytes);
- hex_encode_lower(&bytes)
+ hex_encode_lower(&crate::common::rng::random_array::<32>())
}
/// Wrap a payload JSON string in an integrity envelope (`{ schemaVersion, contentHash, payload }`)
diff --git a/core/rust/src/vault_items/mod.rs b/core/rust/src/vault_items/mod.rs
index f0d03eb74..7898c87b2 100644
--- a/core/rust/src/vault_items/mod.rs
+++ b/core/rust/src/vault_items/mod.rs
@@ -151,9 +151,7 @@ fn blob(row: &Row<'_>, column: &str) -> rusqlite::Result<Option<Vec<u8>>> {
/// A new lowercase v4 id.
fn new_id() -> String {
- let mut bytes = [0u8; 16];
- crate::common::rng::fill_random(&mut bytes);
- crate::common::encoding::uuid_from_bytes(bytes, 4)
+ crate::common::encoding::uuid_from_bytes(crate::common::rng::random_array(), 4)
}
/// The vault error for a failed statement.
diff --git a/core/rust/src/vault_sync/db.rs b/core/rust/src/vault_sync/db.rs
index 60b33345d..a615a6bd9 100644
--- a/core/rust/src/vault_sync/db.rs
+++ b/core/rust/src/vault_sync/db.rs
@@ -222,9 +222,7 @@ fn bind_value(value: &Value, blobs: &HashMap<String, Vec<u8>>) -> Value {
/// A random lowercase UUID v4.
pub(crate) fn new_id() -> String {
- let mut bytes = [0u8; 16];
- crate::common::rng::fill_random(&mut bytes);
- uuid_from_bytes(bytes, 4)
+ uuid_from_bytes(crate::common::rng::random_array(), 4)
}
const GET_ACTIVE_PUBLIC_KEY_FOR_MANIFEST: &str = "SELECT x.PublicKey FROM EncryptionKeys x WHERE x.ManifestId = ? AND x.IsPrimary = 1 AND x.IsDeleted = 0 LIMIT 1";