Skip to main content

bitwarden_crypto/safe/
high_entropy_secret.rs

1//! A high-entropy secret is a wrapper around secret bytes that are guaranteed to be high-entropy,
2//! and therefore safe to use as input keying material for a cheap KDF (such as the one used by the
3//! [crate::safe::SecretProtectedKeyEnvelope]).
4//!
5//! Examples of high-entropy secrets are a random URL-fragment secret, a derived key, or random
6//! bytes. They are unlike low-entropy secrets such as PINs or passwords, which can be brute-forced
7//! and therefore require a memory- or compute-hard KDF.
8
9use std::str::FromStr;
10
11use bitwarden_encoding::{B64, FromStrVisitor};
12use bitwarden_sensitive_value::{ExposeSensitive, Sensitive, SensitiveSlice};
13use rand::Rng;
14use serde::{Deserialize, Serialize};
15use thiserror::Error;
16use zeroize::Zeroizing;
17
18/// Minimum accepted secret length in bytes. 16 bytes = 128 bits of headroom for a uniformly
19/// random secret, matching the security level a cheap KDF assumes.
20const MIN_SECRET_LENGTH: usize = 16;
21
22/// A high entropy secret, generated from a CSPRNG or derived from a high-entropy key. This MUST NOT
23/// be:
24/// - An UTF-8 or ASCII string, even if Base64-encoded or hex-encoded high-entropy bytes
25/// - A low-entropy secret
26/// - A static key
27///
28/// Approved sources are:
29/// - A PRF derived from windows-hello biometrics in Bitwarden-Desktop
30/// - A PRF output from a passkey with the hmac-secret extension
31/// - Key-connector-stored bytes
32/// - A high entropy secret generated with `HighEntropySecret::make()`
33pub trait HighEntropySecretSource {
34    /// Returns the secret bytes as a redacted [`SensitiveSlice`].
35    fn provide_high_entropy_bytes(&self) -> SensitiveSlice<'_>;
36}
37
38/// A secret that is guaranteed to be high-entropy, and therefore safe to use as input keying
39/// material for a cheap KDF.
40#[derive(Clone)]
41pub struct HighEntropySecret {
42    secret: Zeroizing<Vec<u8>>,
43}
44
45impl HighEntropySecret {
46    /// Constructs a `HighEntropySecret` from any [`HighEntropySecretSource`], whose implementation
47    /// guarantees the provided bytes are high-entropy.
48    pub fn from<T: HighEntropySecretSource>(secret: T) -> Self {
49        // EXPOSE: This conversion is safe because the `HighEntropySecret` overrides the Debug
50        // implementation to never print the secret bytes.
51        Self::from_internal(secret.provide_high_entropy_bytes().expose_owned())
52    }
53
54    // Creates a new `HighEntropySecret` from the provided bytes, without validation. The caller is
55    // responsible for ensuring that the bytes are high-entropy and not derived from a low-entropy
56    // source!
57    pub(crate) fn from_internal(secret: &[u8]) -> Self {
58        Self {
59            secret: Zeroizing::new(secret.to_vec()),
60        }
61    }
62
63    /// Generates a new high-entropy secret of the desired size, using cryptographically secure
64    /// random bytes. The generated bytes are high-entropy by construction.
65    ///
66    /// `desired_size` should be at least 16 bytes to provide adequate security headroom.
67    pub fn make(desired_size: usize) -> Result<Self, HighEntropySecretError> {
68        if desired_size < MIN_SECRET_LENGTH {
69            return Err(HighEntropySecretError::TooShort);
70        }
71
72        let mut secret = Zeroizing::new(vec![0u8; desired_size]);
73        bitwarden_random::rng().fill_bytes(secret.as_mut_slice());
74        Ok(Self { secret })
75    }
76
77    /// Returns the secret bytes as a redacted [`SensitiveSlice`]. Not public since callers should
78    /// not handle the raw secret material directly.
79    // Consumed by in-crate KDF/envelope code that is not yet wired up on this branch.
80    #[allow(dead_code)]
81    pub(crate) fn as_bytes(&self) -> SensitiveSlice<'_> {
82        Sensitive::from(self.secret.as_slice())
83    }
84}
85
86impl FromStr for HighEntropySecret {
87    type Err = HighEntropySecretError;
88
89    fn from_str(s: &str) -> Result<Self, Self::Err> {
90        let bytes = B64::try_from(s).map_err(|_| HighEntropySecretError::Malformed)?;
91        if bytes.as_bytes().len() < MIN_SECRET_LENGTH {
92            return Err(HighEntropySecretError::TooShort);
93        }
94        Ok(Self::from_internal(bytes.as_bytes()))
95    }
96}
97
98impl From<HighEntropySecret> for String {
99    fn from(val: HighEntropySecret) -> Self {
100        B64::from(val.secret.as_slice()).to_string()
101    }
102}
103
104impl<'de> Deserialize<'de> for HighEntropySecret {
105    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
106    where
107        D: serde::Deserializer<'de>,
108    {
109        deserializer.deserialize_str(FromStrVisitor::new())
110    }
111}
112
113impl Serialize for HighEntropySecret {
114    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
115    where
116        S: serde::Serializer,
117    {
118        serializer.serialize_str(&B64::from(self.secret.as_slice()).to_string())
119    }
120}
121
122// Manually implemented so the secret material is never printed.
123impl std::fmt::Debug for HighEntropySecret {
124    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
125        f.debug_struct("HighEntropySecret").finish()
126    }
127}
128
129/// Errors that can occur when constructing a [`HighEntropySecret`].
130#[derive(Debug, Error)]
131pub enum HighEntropySecretError {
132    /// The provided secret is too short to be used as a high-entropy secret.
133    #[error("Secret is too short")]
134    TooShort,
135    /// The provided string could not be decoded as standardized base64.
136    #[error("Secret is not valid base64")]
137    Malformed,
138}
139
140#[cfg(feature = "wasm")]
141#[wasm_bindgen::prelude::wasm_bindgen(typescript_custom_section)]
142const TS_CUSTOM_TYPES: &'static str = r#"
143export type HighEntropySecret = Tagged<string, "HighEntropySecret">;
144"#;
145
146bitwarden_ffi::impl_wire_string!(
147    HighEntropySecret,
148    parse = |wire: String| wire.parse(),
149    format = |secret: HighEntropySecret| B64::from(secret.secret.as_slice()).to_string(),
150);
151
152#[cfg(test)]
153mod tests {
154    use bitwarden_sensitive_value::ExposeSensitive;
155
156    use super::*;
157
158    #[test]
159    fn test_debug_does_not_leak_secret() {
160        let secret = HighEntropySecret::make(32).unwrap();
161        let debug = format!("{secret:?}");
162        assert_eq!(debug, "HighEntropySecret");
163    }
164
165    #[test]
166    fn test_make_rejects_secret_below_minimum_length() {
167        for size in 0..MIN_SECRET_LENGTH {
168            assert!(
169                matches!(
170                    HighEntropySecret::make(size),
171                    Err(HighEntropySecretError::TooShort)
172                ),
173                "expected size {size} to be rejected as too short"
174            );
175        }
176    }
177
178    #[test]
179    fn test_make_accepts_secret_at_minimum_length() {
180        let secret = HighEntropySecret::make(MIN_SECRET_LENGTH).unwrap();
181        assert_eq!(secret.as_bytes().expose_owned().len(), MIN_SECRET_LENGTH);
182    }
183
184    #[test]
185    fn test_make_produces_secret_of_requested_length() {
186        for size in [16, 32, 64, 128] {
187            let secret = HighEntropySecret::make(size).unwrap();
188            assert_eq!(secret.as_bytes().expose_owned().len(), size);
189        }
190    }
191
192    #[test]
193    fn test_make_produces_distinct_secrets() {
194        let first = HighEntropySecret::make(32).unwrap();
195        let second = HighEntropySecret::make(32).unwrap();
196        // Two independently generated secrets are overwhelmingly unlikely to collide.
197        assert_ne!(
198            first.as_bytes().expose_owned(),
199            second.as_bytes().expose_owned()
200        );
201    }
202
203    #[test]
204    fn test_from_bytes_preserves_secret() {
205        let bytes = vec![7u8; 32];
206        let secret = HighEntropySecret::from_internal(bytes.as_slice());
207        assert_eq!(secret.as_bytes().expose_owned(), bytes.as_slice());
208    }
209
210    #[test]
211    fn test_from_bytes_accepts_secret_at_minimum_length() {
212        let secret = HighEntropySecret::from_internal(vec![1u8; MIN_SECRET_LENGTH].as_slice());
213        assert_eq!(secret.as_bytes().expose_owned().len(), MIN_SECRET_LENGTH);
214    }
215
216    #[test]
217    fn test_clone_preserves_secret_bytes() {
218        let secret = HighEntropySecret::make(32).unwrap();
219        let cloned = secret.clone();
220        assert_eq!(
221            secret.as_bytes().expose_owned(),
222            cloned.as_bytes().expose_owned()
223        );
224    }
225
226    #[test]
227    fn test_base64_round_trip_preserves_bytes() {
228        let secret = HighEntropySecret::make(32).unwrap();
229        let bytes = secret.as_bytes().expose_owned().to_vec();
230        let encoded = String::from(secret);
231        let decoded: HighEntropySecret = encoded.parse().unwrap();
232        assert_eq!(decoded.as_bytes().expose_owned(), bytes.as_slice());
233    }
234
235    #[test]
236    fn test_from_str_rejects_malformed_input() {
237        assert!(matches!(
238            "!!!not-base64!!!".parse::<HighEntropySecret>(),
239            Err(HighEntropySecretError::Malformed)
240        ));
241    }
242
243    #[test]
244    fn test_from_str_rejects_below_minimum_length() {
245        // Any successfully-decoded input shorter than MIN_SECRET_LENGTH bytes must be rejected
246        // so the type's length floor holds regardless of the constructor used.
247        for byte_len in 0..MIN_SECRET_LENGTH {
248            let bytes = vec![0u8; byte_len];
249            let encoded = B64::from(bytes.as_slice()).to_string();
250            assert!(
251                matches!(
252                    encoded.parse::<HighEntropySecret>(),
253                    Err(HighEntropySecretError::TooShort)
254                ),
255                "expected decoded length {byte_len} to be rejected as too short"
256            );
257        }
258    }
259
260    #[test]
261    fn test_from_str_accepts_input_at_minimum_length() {
262        let bytes = vec![7u8; MIN_SECRET_LENGTH];
263        let encoded = B64::from(bytes.as_slice()).to_string();
264        let secret: HighEntropySecret = encoded
265            .parse()
266            .expect("input at minimum length is accepted");
267        assert_eq!(secret.as_bytes().expose_owned().len(), MIN_SECRET_LENGTH);
268    }
269
270    #[test]
271    fn test_serde_json_round_trip_preserves_bytes() {
272        // Locks the serde impls directly. Without this, a regression in `Serialize` /
273        // `Deserialize` would only surface via a downstream crate's integration test.
274        let secret = HighEntropySecret::make(32).unwrap();
275        let bytes = secret.as_bytes().expose_owned().to_vec();
276        let json = serde_json::to_string(&secret).expect("serialize");
277        let round_tripped: HighEntropySecret = serde_json::from_str(&json).expect("deserialize");
278        assert_eq!(round_tripped.as_bytes().expose_owned(), bytes.as_slice());
279    }
280}