mz_auth/
hash.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10// Clippy misreads some doc comments as HTML tags, so we disable the lint
11#![allow(rustdoc::invalid_html_tags)]
12
13use std::fmt::Display;
14use std::num::NonZeroU32;
15
16use base64::prelude::*;
17use itertools::Itertools;
18
19use crate::password::Password;
20
21/// The default iteration count as suggested by
22/// <https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html>
23const DEFAULT_ITERATIONS: NonZeroU32 = NonZeroU32::new(600_000).unwrap();
24
25/// The default salt size, which isn't currently configurable.
26const DEFAULT_SALT_SIZE: usize = 32;
27
28const SHA256_OUTPUT_LEN: usize = 32;
29
30/// The options for hashing a password
31#[derive(Debug, PartialEq)]
32pub struct HashOpts {
33    /// The number of iterations to use for PBKDF2
34    pub iterations: NonZeroU32,
35    /// The salt to use for PBKDF2. It is up to the caller to
36    /// ensure that however the salt is generated, it is cryptographically
37    /// secure.
38    pub salt: [u8; DEFAULT_SALT_SIZE],
39}
40
41pub struct PasswordHash {
42    /// The salt used for hashing
43    pub salt: [u8; DEFAULT_SALT_SIZE],
44    /// The number of iterations used for hashing
45    pub iterations: NonZeroU32,
46    /// The hash of the password.
47    /// This is the result of PBKDF2 with SHA256
48    pub hash: [u8; SHA256_OUTPUT_LEN],
49}
50
51#[derive(Debug)]
52pub enum VerifyError {
53    MalformedHash,
54    InvalidPassword,
55    Hash(HashError),
56}
57
58#[derive(Debug)]
59pub enum HashError {
60    Openssl(openssl::error::ErrorStack),
61}
62
63impl Display for HashError {
64    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65        match self {
66            HashError::Openssl(e) => write!(f, "OpenSSL error: {}", e),
67        }
68    }
69}
70
71/// Hashes a password using PBKDF2 with SHA256
72/// and a random salt.
73pub fn hash_password(password: &Password) -> Result<PasswordHash, HashError> {
74    let mut salt = [0u8; DEFAULT_SALT_SIZE];
75    openssl::rand::rand_bytes(&mut salt).map_err(HashError::Openssl)?;
76
77    let hash = hash_password_inner(
78        &HashOpts {
79            iterations: DEFAULT_ITERATIONS,
80            salt,
81        },
82        password.to_string().as_bytes(),
83    )?;
84
85    Ok(PasswordHash {
86        salt,
87        iterations: DEFAULT_ITERATIONS,
88        hash,
89    })
90}
91
92pub fn generate_nonce(client_nonce: &str) -> Result<String, HashError> {
93    let mut nonce = [0u8; 24];
94    openssl::rand::rand_bytes(&mut nonce).map_err(HashError::Openssl)?;
95    let nonce = BASE64_STANDARD.encode(&nonce);
96    let new_nonce = format!("{}{}", client_nonce, nonce);
97    Ok(new_nonce)
98}
99
100/// Hashes a password using PBKDF2 with SHA256
101/// and the given options.
102pub fn hash_password_with_opts(
103    opts: &HashOpts,
104    password: &Password,
105) -> Result<PasswordHash, HashError> {
106    let hash = hash_password_inner(opts, password.to_string().as_bytes())?;
107
108    Ok(PasswordHash {
109        salt: opts.salt,
110        iterations: opts.iterations,
111        hash,
112    })
113}
114
115/// Hashes a password using PBKDF2 with SHA256,
116/// and returns it in the SCRAM-SHA-256 format.
117/// The format is SCRAM-SHA-256$<iterations>:<salt>$<client_key>:<server_key>
118pub fn scram256_hash(password: &Password) -> Result<String, HashError> {
119    let hashed_password = hash_password(password)?;
120    Ok(scram256_hash_inner(hashed_password).to_string())
121}
122
123fn constant_time_compare(a: &[u8], b: &[u8]) -> bool {
124    if a.len() != b.len() {
125        return false;
126    }
127    openssl::memcmp::eq(a, b)
128}
129
130/// Verifies a password against a SCRAM-SHA-256 hash.
131pub fn scram256_verify(password: &Password, hashed_password: &str) -> Result<(), VerifyError> {
132    let opts = scram256_parse_opts(hashed_password)?;
133    let hashed = hash_password_with_opts(&opts, password).map_err(VerifyError::Hash)?;
134    let scram = scram256_hash_inner(hashed);
135    if constant_time_compare(hashed_password.as_bytes(), scram.to_string().as_bytes()) {
136        Ok(())
137    } else {
138        Err(VerifyError::InvalidPassword)
139    }
140}
141
142pub fn sasl_verify(
143    hashed_password: &str,
144    proof: &str,
145    auth_message: &str,
146) -> Result<String, VerifyError> {
147    // Parse SCRAM hash: SCRAM-SHA-256$<iterations>:<salt>$<client_key>:<server_key>
148    let parts: Vec<&str> = hashed_password.split('$').collect();
149    if parts.len() != 3 {
150        return Err(VerifyError::MalformedHash);
151    }
152    let auth_info = parts[1].split(':').collect::<Vec<&str>>();
153    if auth_info.len() != 2 {
154        return Err(VerifyError::MalformedHash);
155    }
156    let auth_value = parts[2].split(':').collect::<Vec<&str>>();
157    if auth_value.len() != 2 {
158        return Err(VerifyError::MalformedHash);
159    }
160
161    let client_key = BASE64_STANDARD
162        .decode(auth_value[0])
163        .map_err(|_| VerifyError::MalformedHash)?;
164    let server_key = BASE64_STANDARD
165        .decode(auth_value[1])
166        .map_err(|_| VerifyError::MalformedHash)?;
167
168    // Compute stored key
169    let stored_key = openssl::sha::sha256(&client_key);
170
171    // Compute client signature: HMAC(stored_key, auth_message)
172    let client_signature = generate_signature(&stored_key, auth_message)?;
173
174    // Compute expected client proof: client_key XOR client_signature
175    let expected_client_proof: Vec<u8> = client_key
176        .iter()
177        .zip_eq(client_signature.iter())
178        .map(|(a, b)| a ^ b)
179        .collect();
180
181    // Decode provided proof
182    let provided_client_proof = BASE64_STANDARD
183        .decode(proof)
184        .map_err(|_| VerifyError::InvalidPassword)?;
185
186    if constant_time_compare(&expected_client_proof, &provided_client_proof) {
187        // Compute server verifier: HMAC(server_key, auth_message)
188        let verifier = generate_signature(&server_key, auth_message)?;
189        let verifier = BASE64_STANDARD.encode(&verifier);
190        Ok(verifier)
191    } else {
192        Err(VerifyError::InvalidPassword)
193    }
194}
195
196fn generate_signature(key: &[u8], message: &str) -> Result<Vec<u8>, VerifyError> {
197    let signing_key =
198        openssl::pkey::PKey::hmac(key).map_err(|e| VerifyError::Hash(HashError::Openssl(e)))?;
199    let mut signer =
200        openssl::sign::Signer::new(openssl::hash::MessageDigest::sha256(), &signing_key)
201            .map_err(|e| VerifyError::Hash(HashError::Openssl(e)))?;
202    signer
203        .update(message.as_bytes())
204        .map_err(|e| VerifyError::Hash(HashError::Openssl(e)))?;
205    let signature = signer
206        .sign_to_vec()
207        .map_err(|e| VerifyError::Hash(HashError::Openssl(e)))?;
208    Ok(signature)
209}
210
211// Generate a mock challenge based on the username and client nonce
212// We do this so that we can present a deterministic challenge even for
213// nonexistent users, to avoid user enumeration attacks.
214pub fn mock_sasl_challenge(username: &str, mock_nonce: &str) -> HashOpts {
215    let mut buf = Vec::with_capacity(username.len() + mock_nonce.len());
216    buf.extend_from_slice(username.as_bytes());
217    buf.extend_from_slice(mock_nonce.as_bytes());
218    let digest = openssl::sha::sha256(&buf);
219
220    HashOpts {
221        iterations: DEFAULT_ITERATIONS,
222        salt: digest,
223    }
224}
225
226/// Parses a SCRAM-SHA-256 hash and returns the options used to create it.
227pub fn scram256_parse_opts(hashed_password: &str) -> Result<HashOpts, VerifyError> {
228    let parts: Vec<&str> = hashed_password.split('$').collect();
229    if parts.len() != 3 {
230        return Err(VerifyError::MalformedHash);
231    }
232    let scheme = parts[0];
233    if scheme != "SCRAM-SHA-256" {
234        return Err(VerifyError::MalformedHash);
235    }
236    let auth_info = parts[1].split(':').collect::<Vec<&str>>();
237    if auth_info.len() != 2 {
238        return Err(VerifyError::MalformedHash);
239    }
240    let auth_value = parts[2].split(':').collect::<Vec<&str>>();
241    if auth_value.len() != 2 {
242        return Err(VerifyError::MalformedHash);
243    }
244
245    let iterations = auth_info[0]
246        .parse::<u32>()
247        .map_err(|_| VerifyError::MalformedHash)?;
248
249    let salt = BASE64_STANDARD
250        .decode(auth_info[1])
251        .map_err(|_| VerifyError::MalformedHash)?;
252
253    let salt = salt.try_into().map_err(|_| VerifyError::MalformedHash)?;
254
255    Ok(HashOpts {
256        iterations: NonZeroU32::new(iterations).ok_or(VerifyError::MalformedHash)?,
257        salt,
258    })
259}
260
261/// The SCRAM-SHA-256 hash
262struct ScramSha256Hash {
263    /// The number of iterations used for hashing
264    iterations: NonZeroU32,
265    /// The salt used for hashing
266    salt: [u8; 32],
267    /// The server key
268    server_key: [u8; SHA256_OUTPUT_LEN],
269    /// The client key
270    client_key: [u8; SHA256_OUTPUT_LEN],
271}
272
273impl Display for ScramSha256Hash {
274    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
275        write!(
276            f,
277            "SCRAM-SHA-256${}:{}${}:{}",
278            self.iterations,
279            BASE64_STANDARD.encode(&self.salt),
280            BASE64_STANDARD.encode(&self.client_key),
281            BASE64_STANDARD.encode(&self.server_key)
282        )
283    }
284}
285
286fn scram256_hash_inner(hashed_password: PasswordHash) -> ScramSha256Hash {
287    let signing_key = openssl::pkey::PKey::hmac(&hashed_password.hash).unwrap();
288    let mut signer =
289        openssl::sign::Signer::new(openssl::hash::MessageDigest::sha256(), &signing_key).unwrap();
290    signer.update(b"Client Key").unwrap();
291    let client_key = signer.sign_to_vec().unwrap();
292    let mut signer =
293        openssl::sign::Signer::new(openssl::hash::MessageDigest::sha256(), &signing_key).unwrap();
294    signer.update(b"Server Key").unwrap();
295    let server_key = signer.sign_to_vec().unwrap();
296
297    ScramSha256Hash {
298        iterations: hashed_password.iterations,
299        salt: hashed_password.salt,
300        server_key: server_key.try_into().unwrap(),
301        client_key: client_key.try_into().unwrap(),
302    }
303}
304
305fn hash_password_inner(
306    opts: &HashOpts,
307    password: &[u8],
308) -> Result<[u8; SHA256_OUTPUT_LEN], HashError> {
309    let mut salted_password = [0u8; SHA256_OUTPUT_LEN];
310    openssl::pkcs5::pbkdf2_hmac(
311        password,
312        &opts.salt,
313        opts.iterations.get().try_into().unwrap(),
314        openssl::hash::MessageDigest::sha256(),
315        &mut salted_password,
316    )
317    .map_err(HashError::Openssl)?;
318    Ok(salted_password)
319}
320
321#[cfg(test)]
322mod tests {
323    use itertools::Itertools;
324
325    use super::*;
326
327    #[mz_ore::test]
328    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `OPENSSL_init_ssl` on OS `linux`
329    fn test_hash_password() {
330        let password = "password".to_string();
331        let hashed_password = hash_password(&password.into()).expect("Failed to hash password");
332        assert_eq!(hashed_password.iterations, DEFAULT_ITERATIONS);
333        assert_eq!(hashed_password.salt.len(), DEFAULT_SALT_SIZE);
334        assert_eq!(hashed_password.hash.len(), SHA256_OUTPUT_LEN);
335    }
336
337    #[mz_ore::test]
338    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `OPENSSL_init_ssl` on OS `linux`
339    fn test_scram256_hash() {
340        let password = "password".into();
341        let scram_hash = scram256_hash(&password).expect("Failed to hash password");
342
343        let res = scram256_verify(&password, &scram_hash);
344        assert!(res.is_ok());
345        let res = scram256_verify(&"wrong_password".into(), &scram_hash);
346        assert!(res.is_err());
347    }
348
349    #[mz_ore::test]
350    fn test_scram256_parse_opts() {
351        let salt = "9bkIQQjQ7f1OwPsXZGC/YfIkbZsOMDXK0cxxvPBaSfM=";
352        let hashed_password = format!("SCRAM-SHA-256$600000:{}$client-key:server-key", salt);
353        let opts = scram256_parse_opts(&hashed_password);
354
355        assert!(opts.is_ok());
356        let opts = opts.unwrap();
357        assert_eq!(opts.iterations, DEFAULT_ITERATIONS);
358        assert_eq!(opts.salt.len(), DEFAULT_SALT_SIZE);
359        let decoded_salt = BASE64_STANDARD.decode(salt).expect("Failed to decode salt");
360        assert_eq!(opts.salt, decoded_salt.as_ref());
361    }
362
363    #[mz_ore::test]
364    #[cfg_attr(miri, ignore)]
365    fn test_mock_sasl_challenge() {
366        let username = "alice";
367        let mock = "cnonce";
368        let opts1 = mock_sasl_challenge(username, mock);
369        let opts2 = mock_sasl_challenge(username, mock);
370        assert_eq!(opts1, opts2);
371    }
372
373    #[mz_ore::test]
374    #[cfg_attr(miri, ignore)]
375    fn test_sasl_verify_success() {
376        let password: Password = "password".into();
377        let hashed_password = scram256_hash(&password).expect("hash password");
378        let auth_message = "n=user,r=clientnonce,s=somesalt"; // arbitrary auth message
379
380        // Parse client_key and server_key from the SCRAM hash
381        // Format: SCRAM-SHA-256$<iterations>:<salt>$<client_key>:<server_key>
382        let parts: Vec<&str> = hashed_password.split('$').collect();
383        assert_eq!(parts.len(), 3);
384        let key_parts: Vec<&str> = parts[2].split(':').collect();
385        assert_eq!(key_parts.len(), 2);
386        let client_key = BASE64_STANDARD
387            .decode(key_parts[0])
388            .expect("decode client key");
389        let server_key = BASE64_STANDARD
390            .decode(key_parts[1])
391            .expect("decode server key");
392
393        // stored_key = SHA256(client_key)
394        let stored_key = openssl::sha::sha256(&client_key);
395        // client_signature = HMAC(stored_key, auth_message)
396        let client_signature =
397            generate_signature(&stored_key, auth_message).expect("client signature");
398        // client_proof = client_key XOR client_signature
399        let client_proof: Vec<u8> = client_key
400            .iter()
401            .zip_eq(client_signature.iter())
402            .map(|(a, b)| a ^ b)
403            .collect();
404        let client_proof_b64 = BASE64_STANDARD.encode(&client_proof);
405
406        let verifier = sasl_verify(&hashed_password, &client_proof_b64, auth_message)
407            .expect("sasl_verify should succeed");
408
409        // Expected verifier: HMAC(server_key, auth_message)
410        let expected_verifier = BASE64_STANDARD
411            .encode(&generate_signature(&server_key, auth_message).expect("server verifier"));
412        assert_eq!(verifier, expected_verifier);
413    }
414
415    #[mz_ore::test]
416    #[cfg_attr(miri, ignore)]
417    fn test_sasl_verify_invalid_proof() {
418        let password: Password = "password".into();
419        let hashed_password = scram256_hash(&password).expect("hash password");
420        let auth_message = "n=user,r=clientnonce,s=somesalt";
421        // Provide an obviously invalid base64 proof (different size / random)
422        let bad_proof = BASE64_STANDARD.encode([0u8; 32]);
423        let res = sasl_verify(&hashed_password, &bad_proof, auth_message);
424        assert!(matches!(res, Err(VerifyError::InvalidPassword)));
425    }
426
427    #[mz_ore::test]
428    fn test_sasl_verify_malformed_hash() {
429        let malformed_hash = "NOT-SCRAM$bad"; // clearly malformed (wrong parts count)
430        let auth_message = "n=user,r=clientnonce,s=somesalt";
431        let bad_proof = BASE64_STANDARD.encode([0u8; 32]);
432        let res = sasl_verify(malformed_hash, &bad_proof, auth_message);
433        assert!(matches!(res, Err(VerifyError::MalformedHash)));
434    }
435}