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