Skip to main content

devolutions_crypto/
utils.rs

1//! Module for utils that does not use any of the Devolutions custom data types.
2
3use base64::{
4    Engine as _, alphabet,
5    engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig},
6};
7use hmac::Hmac;
8use pbkdf2::pbkdf2;
9use rand::TryRng;
10use sha2::Sha256;
11use subtle::ConstantTimeEq as _;
12use zeroize::Zeroizing;
13
14use crate::online_ciphertext::OnlineCiphertextHeader;
15
16use super::Argon2Parameters;
17use super::DataType;
18use super::Error;
19use super::Header;
20use super::Result;
21
22/// Returns a random key of the specified length. Can also be used
23///  whenever you need a random byte array, like for a salt.
24/// # Arguments
25///  * `length` - Length of the desired key.
26/// # Example
27/// ```
28/// use devolutions_crypto::utils::generate_key;
29///
30/// let key = generate_key(32).expect("generate key shouldn't fail");;
31/// assert_eq!(32, key.len());
32/// ```
33pub fn generate_key(length: usize) -> Result<Vec<u8>> {
34    let mut key = vec![0u8; length];
35    rand::rngs::SysRng
36        .try_fill_bytes(&mut key)
37        .map_err(|_| Error::RandomError)?;
38    Ok(key)
39}
40
41/// Fills a fixed-size buffer directly from the operating system's CSPRNG.
42///
43/// Used for private key generation: drawing the bytes straight from the OS
44/// avoids any intermediate userspace CSPRNG state that could be used to
45/// reconstruct the key. The buffer is zeroized on drop.
46pub(crate) fn random_bytes<const N: usize>() -> Result<Zeroizing<[u8; N]>> {
47    let mut bytes = Zeroizing::new([0u8; N]);
48    rand::rngs::SysRng
49        .try_fill_bytes(bytes.as_mut_slice())
50        .map_err(|_| Error::RandomError)?;
51    Ok(bytes)
52}
53
54/// Derives a password or key into a new one using PBKDF2.
55/// # Arguments
56///  * `key` - The key or password to derive.
57///  * `salt` - The cryptographic salt to be used to add randomness. Can be empty. Recommended size is 16 bytes.
58///  * `iterations` - The number of time the key will be derived. A higher number is slower but harder to brute-force.
59///    600,000 iterations are recommended for a password.
60///  * `length` - Length of the desired key.
61/// # Example
62/// ```
63/// use devolutions_crypto::utils::{derive_key_pbkdf2, generate_key};
64/// let key = b"this is a secret password";
65/// let salt = generate_key(16).expect("generate key shouldn't fail");;
66/// let iterations = 600000;
67/// let length = 32;
68///
69/// let new_key = derive_key_pbkdf2(key, &salt, iterations, length);
70///
71/// assert_eq!(32, new_key.len());
72/// ```
73pub fn derive_key_pbkdf2(key: &[u8], salt: &[u8], iterations: u32, length: usize) -> Vec<u8> {
74    let mut new_key = vec![0u8; length];
75    pbkdf2::<Hmac<Sha256>>(key, salt, iterations, &mut new_key)
76        .expect("HMAC-SHA256 accepts keys of any length, so this cannot fail");
77    new_key
78}
79
80/// Derives a password or key into a new one using Argon2.
81/// # Arguments
82///  * `key` - The key or password to derive.
83///  * `parameters` - The `Argon2Parameters` to use.
84/// # Example
85/// ```
86/// use devolutions_crypto::utils::{derive_key_argon2, generate_key};
87/// use devolutions_crypto::Argon2Parameters;
88/// let key = b"this is a secret password";
89/// let parameters = Argon2Parameters::default();
90///
91/// let new_key = derive_key_argon2(key, &parameters).expect("default parameters should not fail");
92///
93/// assert_eq!(32, new_key.len());
94/// ```
95pub fn derive_key_argon2(key: &[u8], parameters: &Argon2Parameters) -> Result<Vec<u8>> {
96    parameters.compute(key)
97}
98
99/// Only validate the header to make sure it is valid. Used to quickly determine if the data comes from the library.
100/// # Arguments
101///  * `data` - The data to verify.
102///  * `data_type` - The type of the data.
103/// # Returns
104/// `true` if the header is valid, `false` if it is not.
105/// # Example
106/// ```
107/// use devolutions_crypto::DataType;
108/// use devolutions_crypto::ciphertext::{encrypt, CiphertextVersion};
109/// use devolutions_crypto::utils::{generate_key, validate_header};
110///
111/// let key = generate_key(32).expect("generate key shouldn't fail");
112/// let ciphertext: Vec<u8> = encrypt(b"test", &key, CiphertextVersion::Latest)
113///     .expect("encryption shouldn't fail")
114///     .into();
115///
116/// assert!(validate_header(&ciphertext, DataType::Ciphertext));
117/// assert!(!validate_header(&ciphertext, DataType::PasswordHash));
118/// assert!(!validate_header(&key, DataType::Ciphertext));
119/// ```
120pub fn validate_header(data: &[u8], data_type: DataType) -> bool {
121    use super::ciphertext::Ciphertext;
122    use super::derive_encrypt::KdfEncryptedData;
123    use super::key::{PrivateKey, PublicKey};
124    use super::password_hash::PasswordHash;
125    use super::secret_sharing::Share;
126    use super::signature::Signature;
127    use super::signing_key::{SigningKeyPair, SigningPublicKey};
128
129    if data.len() < Header::len() {
130        return false;
131    }
132
133    match data_type {
134        DataType::None => false,
135        DataType::Ciphertext => Header::<Ciphertext>::try_from(&data[0..Header::len()]).is_ok(),
136        DataType::PasswordHash => Header::<PasswordHash>::try_from(&data[0..Header::len()]).is_ok(),
137        DataType::Key => {
138            Header::<PrivateKey>::try_from(&data[0..Header::len()]).is_ok()
139                || Header::<PublicKey>::try_from(&data[0..Header::len()]).is_ok()
140        }
141        DataType::SigningKey => {
142            Header::<SigningKeyPair>::try_from(&data[0..Header::len()]).is_ok()
143                || Header::<SigningPublicKey>::try_from(&data[0..Header::len()]).is_ok()
144        }
145        DataType::Share => Header::<Share>::try_from(&data[0..Header::len()]).is_ok(),
146        DataType::Signature => Header::<Signature>::try_from(&data[0..Header::len()]).is_ok(),
147        DataType::OnlineCiphertext => {
148            Header::<OnlineCiphertextHeader>::try_from(&data[0..Header::len()]).is_ok()
149        }
150        DataType::KeyDerivation => {
151            use super::key_derivation::DerivationParameters;
152            Header::<DerivationParameters>::try_from(&data[0..Header::len()]).is_ok()
153        }
154        DataType::KdfEncryptedData => {
155            Header::<KdfEncryptedData>::try_from(&data[0..Header::len()]).is_ok()
156        }
157    }
158}
159
160/// Temporarly binded here for a specific use case, don't rely on this.
161///
162/// Copied and modified from:
163/// <https://github.com/RustCrypto/password-hashing/blob/master/scrypt/src/simple.rs>
164/// Because rand is outdated, I cannot use the crate directly
165pub fn scrypt_simple(password: &[u8], salt: &[u8], log_n: u8, r: u32, p: u32) -> String {
166    use byteorder::{ByteOrder, LittleEndian};
167
168    let params = scrypt::Params::new(log_n, r, p).expect("params should be valid");
169
170    // 256-bit derived key
171    let mut dk = [0u8; 32];
172
173    scrypt::scrypt(password, salt, &params, &mut dk)
174        .expect("32 bytes always satisfy output length requirements");
175
176    // usually 128 bytes is enough
177    let mut result = String::with_capacity(128);
178    result.push_str("$rscrypt$");
179    if r < 256 && p < 256 {
180        result.push_str("0$");
181        let mut tmp = [0u8; 3];
182        tmp[0] = log_n;
183        tmp[1] = r as u8;
184        tmp[2] = p as u8;
185        result.push_str(&DEVO_BASE64.encode(tmp));
186    } else {
187        result.push_str("1$");
188        let mut tmp = [0u8; 9];
189        tmp[0] = log_n;
190        LittleEndian::write_u32(&mut tmp[1..5], r);
191        LittleEndian::write_u32(&mut tmp[5..9], p);
192        result.push_str(&DEVO_BASE64.encode(tmp));
193    }
194    result.push('$');
195    result.push_str(&DEVO_BASE64.encode(salt));
196    result.push('$');
197    result.push_str(&DEVO_BASE64.encode(dk));
198    result.push('$');
199
200    result
201}
202
203pub fn base64_encode(data: &[u8]) -> String {
204    DEVO_BASE64.encode(data)
205}
206
207pub fn base64_encode_url(data: &[u8]) -> String {
208    DEVO_BASE64_URLSAFE_NOPAD.encode(data)
209}
210
211pub fn base64_decode(data: &str) -> Result<Vec<u8>> {
212    match DEVO_BASE64.decode(data) {
213        Ok(d) => Ok(d),
214        _ => Err(Error::InvalidData),
215    }
216}
217
218pub fn base64_decode_url(data: &str) -> Result<Vec<u8>> {
219    match DEVO_BASE64_URLSAFE_NOPAD.decode(data) {
220        Ok(d) => Ok(d),
221        _ => Err(Error::InvalidData),
222    }
223}
224
225pub fn constant_time_equals(x: &[u8], y: &[u8]) -> bool {
226    x.ct_eq(y).into()
227}
228
229const BASE64_CONFIG: GeneralPurposeConfig = GeneralPurposeConfig::new()
230    .with_encode_padding(true)
231    .with_decode_padding_mode(DecodePaddingMode::Indifferent)
232    .with_decode_allow_trailing_bits(true);
233
234const BASE64_CONFIG_NO_PAD: GeneralPurposeConfig = GeneralPurposeConfig::new()
235    .with_encode_padding(false)
236    .with_decode_padding_mode(DecodePaddingMode::Indifferent)
237    .with_decode_allow_trailing_bits(true);
238
239const DEVO_BASE64: GeneralPurpose = GeneralPurpose::new(&alphabet::STANDARD, BASE64_CONFIG);
240const DEVO_BASE64_URLSAFE_NOPAD: GeneralPurpose =
241    GeneralPurpose::new(&alphabet::URL_SAFE, BASE64_CONFIG_NO_PAD);
242
243#[test]
244fn test_constant_time_equals() {
245    let x: [u8; 3] = [0, 1, 2];
246    let y: [u8; 3] = [4, 5, 6];
247    let z: [u8; 4] = [0, 1, 2, 3];
248
249    assert!(constant_time_equals(&x, &x));
250    assert!(!constant_time_equals(&x, &y));
251    assert!(!constant_time_equals(&x, &z));
252    assert!(!constant_time_equals(&y, &x));
253    assert!(constant_time_equals(&y, &y));
254    assert!(!constant_time_equals(&y, &z));
255    assert!(!constant_time_equals(&z, &x));
256    assert!(!constant_time_equals(&z, &y));
257    assert!(constant_time_equals(&z, &z));
258}
259
260#[test]
261fn test_generate_key() {
262    let size = 32;
263    let key = generate_key(size).unwrap();
264
265    assert_eq!(size, key.len());
266    assert_ne!(vec![0u8; size], key);
267}
268
269#[test]
270fn test_derive_key_pbkdf2() {
271    let salt = b"salt";
272    let key = b"key";
273    let iterations = 100;
274    let size = 32;
275
276    let derived = derive_key_pbkdf2(key, salt, iterations, size);
277
278    assert_eq!(size, derived.len());
279    assert_ne!(vec![0u8; size], derived);
280}
281
282#[test]
283fn test_validate_header() {
284    use base64::engine::general_purpose::STANDARD;
285
286    let valid_ciphertext = STANDARD.decode("DQwCAAAAAQA=").unwrap();
287    let valid_password_hash = STANDARD.decode("DQwDAAAAAQA=").unwrap();
288    let valid_share = STANDARD.decode("DQwEAAAAAQA=").unwrap();
289    let valid_private_key = STANDARD.decode("DQwBAAEAAQA=").unwrap();
290    let valid_public_key = STANDARD.decode("DQwBAAEAAQA=").unwrap();
291
292    assert!(validate_header(&valid_ciphertext, DataType::Ciphertext));
293    assert!(validate_header(
294        &valid_password_hash,
295        DataType::PasswordHash
296    ));
297    assert!(validate_header(&valid_share, DataType::Share));
298    assert!(validate_header(&valid_private_key, DataType::Key));
299    assert!(validate_header(&valid_public_key, DataType::Key));
300
301    assert!(!validate_header(&valid_ciphertext, DataType::PasswordHash));
302
303    let invalid_signature = STANDARD.decode("DAwBAAEAAQA=").unwrap();
304    let invalid_type = STANDARD.decode("DQwIAAEAAQA=").unwrap();
305    let invalid_subtype = STANDARD.decode("DQwBAAgAAQA=").unwrap();
306    let invalid_version = STANDARD.decode("DQwBAAEACAA=").unwrap();
307
308    assert!(!validate_header(&invalid_signature, DataType::Key));
309    assert!(!validate_header(&invalid_type, DataType::Key));
310    assert!(!validate_header(&invalid_subtype, DataType::Key));
311    assert!(!validate_header(&invalid_version, DataType::Key));
312
313    let not_long_enough = STANDARD.decode("DQwBAAEAAQ==").unwrap();
314
315    assert!(!validate_header(&not_long_enough, DataType::Key));
316}
317
318#[test]
319fn test_scrypt_simple() {
320    // Regression vector: locks the scrypt output and the `$rscrypt$` format so any
321    // future scrypt crate bump that changes the derived bytes is caught. This value
322    // was verified byte-identical against scrypt 0.11 (the pre-bump version).
323    let hash = scrypt_simple(b"password", b"devolutions-salt", 8, 8, 1);
324
325    assert_eq!(
326        hash,
327        "$rscrypt$0$CAgB$ZGV2b2x1dGlvbnMtc2FsdA==$hIK4WZ1ct+CgcxYxMoi+lkk5RztS/EJBxxm0zmsNVY0=$"
328    );
329}