Skip to main content

kanidm_lib_crypto/
lib.rs

1#![deny(warnings)]
2#![warn(unused_extern_crates)]
3#![deny(clippy::todo)]
4#![deny(clippy::unimplemented)]
5#![deny(clippy::unwrap_used)]
6#![deny(clippy::expect_used)]
7#![deny(clippy::panic)]
8#![deny(clippy::await_holding_lock)]
9#![deny(clippy::needless_pass_by_value)]
10#![deny(clippy::trivially_copy_pass_by_ref)]
11#![deny(clippy::unreachable)]
12
13use base64::{
14    alphabet,
15    engine::{general_purpose, GeneralPurpose},
16    Engine,
17};
18use base64urlsafedata::Base64UrlSafeData;
19use crypto_glue::{
20    argon2::{Algorithm, Argon2, Params, PasswordHash, Version},
21    pbkdf2::pbkdf2_hmac,
22    s256::Sha256,
23    s512::Sha512,
24    sha1::Sha1,
25    traits::Digest,
26};
27use kanidm_hsm_crypto::{provider::TpmHmacS256, structures::HmacS256Key};
28use md4::Md4;
29use rand::RngExt;
30use serde::{Deserialize, Serialize};
31use std::{
32    fmt,
33    fmt::Display,
34    num::ParseIntError,
35    time::{Duration, Instant},
36};
37use tracing::{debug, error, warn};
38
39mod crypt_md5;
40
41pub use sha2;
42
43// Per https://pages.nist.gov/800-63-4/sp800-63b.html max length should be 64. This is
44// measured in GRAPHEMES, not bytes.
45pub const PW_MAX_LENGTH_NIST: u32 = 128;
46
47// Single factor passwords have a greater minimum length requirement per nist.
48pub const PW_SFA_MIN_LENGTH_NIST: u32 = 15;
49// When used with MFA, the MIN length can be relaxed. Per NIST 8 is acceptable, but we
50// have used 10 for this value.
51pub const PW_MFA_MIN_LENGTH: u32 = 10;
52
53// Since we added a max length constraint later, we should continue to allow long
54// passwords to be validated. NOTE this is BYTES not GRAPHEMES.
55pub const PW_MAX_LENGTH_CHECK: usize = PW_MAX_LENGTH_NIST as usize * 4;
56
57// NIST 800-63.b salt should be 112 bits -> 14  8u8.
58const PBKDF2_SALT_LEN: usize = 24;
59
60pub const PBKDF2_MIN_NIST_SALT_LEN: usize = 14;
61
62// Min number of rounds for a pbkdf2
63pub const PBKDF2_MIN_NIST_COST: u32 = 10_000;
64// Default rounds - owasp recommend 600_000 rounds.
65pub const PBKDF2_DEFAULT_COST: u32 = 600_000;
66
67// 32 * u8 -> 256 bits of out.
68const PBKDF2_KEY_LEN: usize = 32;
69const PBKDF2_MIN_NIST_KEY_LEN: usize = 32;
70const PBKDF2_SHA1_MIN_KEY_LEN: usize = 19;
71
72const DS_SHA1_HASH_LEN: usize = 20;
73const DS_SHA256_HASH_LEN: usize = 32;
74const DS_SHA512_HASH_LEN: usize = 64;
75
76// Taken from the argon2 library and rfc 9106
77const ARGON2_VERSION: u32 = 19;
78const ARGON2_SALT_LEN: usize = 16;
79// 32 * u8 -> 256 bits of out.
80const ARGON2_KEY_LEN: usize = 32;
81// Default amount of ram we sacrifice per thread
82const ARGON2_MIN_RAM_KIB: u32 = 8 * 1024;
83const ARGON2_MAX_RAM_KIB: u32 = 64 * 1024;
84// Amount of ram to subtract when we do a T cost iter. This
85// is because t=2 m=32 == t=3 m=20. So we just step down a little
86// to keep the value about the same.
87const ARGON2_TCOST_RAM_ITER_KIB: u32 = 12 * 1024;
88const ARGON2_MIN_T_COST: u32 = 2;
89const ARGON2_MAX_T_COST: u32 = 16;
90const ARGON2_MAX_P_COST: u32 = 1;
91
92#[derive(Clone, Debug)]
93pub enum CryptoError {
94    Hsm,
95    HsmContextMissing,
96    OpenSSL(u64),
97    Md4Disabled,
98    Argon2,
99    Argon2Version,
100    Argon2Parameters,
101    Crypt,
102    InvalidServerName,
103}
104
105#[derive(Serialize, Deserialize, PartialEq, Eq, Clone)]
106#[allow(non_camel_case_types)]
107pub enum DbPasswordV1 {
108    TPM_ARGON2ID {
109        m: u32,
110        t: u32,
111        p: u32,
112        v: u32,
113        s: Base64UrlSafeData,
114        k: Base64UrlSafeData,
115    },
116    ARGON2ID {
117        m: u32,
118        t: u32,
119        p: u32,
120        v: u32,
121        s: Base64UrlSafeData,
122        k: Base64UrlSafeData,
123    },
124    PBKDF2(u32, Vec<u8>, Vec<u8>),
125    PBKDF2_SHA1(u32, Vec<u8>, Vec<u8>),
126    PBKDF2_SHA512(u32, Vec<u8>, Vec<u8>),
127    SHA1(Vec<u8>),
128    SSHA1(Vec<u8>, Vec<u8>),
129    SHA256(Vec<u8>),
130    SSHA256(Vec<u8>, Vec<u8>),
131    SHA512(Vec<u8>),
132    SSHA512(Vec<u8>, Vec<u8>),
133    NT_MD4(Vec<u8>),
134    CRYPT_MD5 {
135        s: Base64UrlSafeData,
136        h: Base64UrlSafeData,
137    },
138    CRYPT_SHA256 {
139        h: String,
140    },
141    CRYPT_SHA512 {
142        h: String,
143    },
144}
145
146impl fmt::Debug for DbPasswordV1 {
147    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
148        match self {
149            DbPasswordV1::TPM_ARGON2ID { .. } => write!(f, "TPM_ARGON2ID"),
150            DbPasswordV1::ARGON2ID { .. } => write!(f, "ARGON2ID"),
151            DbPasswordV1::PBKDF2(_, _, _) => write!(f, "PBKDF2"),
152            DbPasswordV1::PBKDF2_SHA1(_, _, _) => write!(f, "PBKDF2_SHA1"),
153            DbPasswordV1::PBKDF2_SHA512(_, _, _) => write!(f, "PBKDF2_SHA512"),
154            DbPasswordV1::SHA1(_) => write!(f, "SHA1"),
155            DbPasswordV1::SSHA1(_, _) => write!(f, "SSHA1"),
156            DbPasswordV1::SHA256(_) => write!(f, "SHA256"),
157            DbPasswordV1::SSHA256(_, _) => write!(f, "SSHA256"),
158            DbPasswordV1::SHA512(_) => write!(f, "SHA512"),
159            DbPasswordV1::SSHA512(_, _) => write!(f, "SSHA512"),
160            DbPasswordV1::NT_MD4(_) => write!(f, "NT_MD4"),
161            DbPasswordV1::CRYPT_MD5 { .. } => write!(f, "CRYPT_MD5"),
162            DbPasswordV1::CRYPT_SHA256 { .. } => write!(f, "CRYPT_SHA256"),
163            DbPasswordV1::CRYPT_SHA512 { .. } => write!(f, "CRYPT_SHA512"),
164        }
165    }
166}
167
168#[derive(Debug)]
169pub struct CryptoPolicy {
170    pub(crate) pbkdf2_cost: u32,
171    // https://docs.rs/argon2/0.5.0/argon2/struct.Params.html
172    // defaults to 19mb memory, 2 iterations and 1 thread, with a 32byte output.
173    pub(crate) argon2id_params: Params,
174}
175
176impl CryptoPolicy {
177    pub fn minimum() -> Self {
178        CryptoPolicy {
179            pbkdf2_cost: PBKDF2_MIN_NIST_COST,
180            argon2id_params: Params::default(),
181        }
182    }
183
184    pub fn danger_test_minimum() -> Self {
185        CryptoPolicy {
186            pbkdf2_cost: 1000,
187            argon2id_params: Params::new(
188                Params::MIN_M_COST,
189                Params::MIN_T_COST,
190                Params::MIN_P_COST,
191                None,
192            )
193            .unwrap_or_default(),
194        }
195    }
196
197    pub fn time_target(target_time: Duration) -> Self {
198        // Argon2id has multiple parameters. These all are about *exchanges* that you can
199        // request in how the computation is performed.
200        //
201        // rfc9106 explains that there are two algorithms stacked here. Argon2i has defences
202        // against side-channel timing. Argon2d provides defences for time-memory tradeoffs.
203        //
204        // We can see how this impacts timings from sources like:
205        // https://www.twelve21.io/how-to-choose-the-right-parameters-for-argon2/
206        //
207        // M =  256 MB, T =    2, d = 8, Time = 0.732 s
208        // M =  128 MB, T =    6, d = 8, Time = 0.99 s
209        // M =   64 MB, T =   12, d = 8, Time = 0.968 s
210        // M =   32 MB, T =   24, d = 8, Time = 0.896 s
211        // M =   16 MB, T =   49, d = 8, Time = 0.973 s
212        // M =    8 MB, T =   96, d = 8, Time = 0.991 s
213        // M =    4 MB, T =  190, d = 8, Time = 0.977 s
214        // M =    2 MB, T =  271, d = 8, Time = 0.973 s
215        // M =    1 MB, T =  639, d = 8, Time = 0.991 s
216        //
217        // As we can see, the time taken stays constant, but as ram decreases the amount of
218        // CPU work required goes up. In our case, our primary threat is from GPU hashcat
219        // cracking. GPU's tend to have many fast cores but very little amounts of fast ram
220        // for those cores. So we want to have as much ram as *possible* up to a limit, and
221        // then we want to increase iterations.
222        //
223        // This way a GPU has to expend further GPU time to compensate for the less ram.
224        //
225        // We also need to balance this against the fact we are a database, and we do have
226        // caches. We also don't want to over-use RAM, especially because in the worst case
227        // every thread will be operating in argon2id at the same time. That means
228        // thread x ram will be used. If we had 8 threads at 64mb of ram, that would require
229        // 512mb of ram alone just for hashing. This becomes worse as core counts scale, with
230        // 24 core xeons easily reaching 1.5GB in these cases.
231
232        let mut m_cost = ARGON2_MIN_RAM_KIB;
233        let mut t_cost = ARGON2_MIN_T_COST;
234        let p_cost = ARGON2_MAX_P_COST;
235
236        // Raise memory usage until an acceptable ram amount is reached.
237        loop {
238            let params = if let Ok(p) = Params::new(m_cost, t_cost, p_cost, None) {
239                p
240            } else {
241                // Unable to proceed.
242                error!(
243                    ?m_cost,
244                    ?t_cost,
245                    ?p_cost,
246                    "Parameters were not valid for argon2"
247                );
248                break;
249            };
250
251            if let Some(ubt) = Password::bench_argon2id(params) {
252                debug!("{}ns - t_cost {} m_cost {}", ubt.as_nanos(), t_cost, m_cost);
253                // Parameter adjustment
254                if ubt < target_time {
255                    let m_mult = target_time
256                        .as_nanos()
257                        .checked_div(ubt.as_nanos())
258                        .unwrap_or(1);
259                    if m_cost < ARGON2_MAX_RAM_KIB {
260                        // Help narrow in quicker.
261                        let m_adjust = if m_mult >= 2 {
262                            // Far away, multiply up
263                            m_cost * u32::try_from(m_mult).unwrap_or(2)
264                        } else {
265                            // Close! Increase in a small step
266                            m_cost + 1024
267                        };
268
269                        m_cost = if m_adjust > ARGON2_MAX_RAM_KIB {
270                            ARGON2_MAX_RAM_KIB
271                        } else {
272                            m_adjust
273                        };
274                        continue;
275                    } else if t_cost < ARGON2_MAX_T_COST {
276                        // Help narrow in quicker.
277                        if m_mult >= 2 {
278                            // Far away, multiply T next
279                            let t_adjust = t_cost * u32::try_from(m_mult).unwrap_or(2);
280                            t_cost = t_adjust.clamp(ARGON2_MIN_T_COST, ARGON2_MAX_T_COST);
281                        } else {
282                            // t=2 with m = 32MB is about the same as t=3 m=20MB, so we want to start with ram
283                            // higher on these iterations. About 12MB appears to be one iteration. We use 8MB
284                            // here though, just to give a little window under that for adjustment.
285                            //
286                            // Similar, once we hit t=4 we just need to have max ram.
287                            t_cost += 1;
288                            // Halve the ram cost.
289                            let m_adjust = m_cost
290                                .checked_sub(ARGON2_TCOST_RAM_ITER_KIB)
291                                .unwrap_or(ARGON2_MIN_RAM_KIB);
292
293                            // Clamp the value
294                            m_cost = m_adjust.clamp(ARGON2_MIN_RAM_KIB, ARGON2_MAX_RAM_KIB);
295                        }
296                        continue;
297                    } else {
298                        // Unable to proceed, parameters are maxed out.
299                        warn!("Argon2 parameters have hit their maximums - this may be a bug!");
300                        break;
301                    }
302                } else {
303                    // Found the target time.
304                    break;
305                }
306            } else {
307                error!("Unable to perform bench of argon2id, stopping benchmark");
308                break;
309            }
310        }
311
312        let argon2id_params = Params::new(m_cost, t_cost, p_cost, None)
313            // fallback
314            .unwrap_or_default();
315
316        let p = CryptoPolicy {
317            pbkdf2_cost: PBKDF2_DEFAULT_COST,
318            argon2id_params,
319        };
320        debug!(argon2id_m = %p.argon2id_params.m_cost(), argon2id_p = %p.argon2id_params.p_cost(), argon2id_t = %p.argon2id_params.t_cost(), );
321        p
322    }
323}
324
325// Why PBKDF2? Rust's bcrypt has a number of hardcodings like max pw len of 72
326// I don't really feel like adding in so many restrictions, so I'll use
327// pbkdf2 in openssl because it doesn't have the same limits.
328#[derive(Clone, Debug, PartialEq)]
329#[allow(non_camel_case_types)]
330enum Kdf {
331    TPM_ARGON2ID {
332        m_cost: u32,
333        t_cost: u32,
334        p_cost: u32,
335        version: u32,
336        salt: Vec<u8>,
337        key: Vec<u8>,
338    },
339    //
340    ARGON2ID {
341        m_cost: u32,
342        t_cost: u32,
343        p_cost: u32,
344        version: u32,
345        salt: Vec<u8>,
346        key: Vec<u8>,
347    },
348    //     cost, salt,   hash
349    PBKDF2(u32, Vec<u8>, Vec<u8>),
350
351    // Imported types, will upgrade to the above.
352    //         cost,   salt,    hash
353    PBKDF2_SHA1(u32, Vec<u8>, Vec<u8>),
354    //           cost,   salt,    hash
355    PBKDF2_SHA512(u32, Vec<u8>, Vec<u8>),
356    //      salt     hash
357    SHA1(Vec<u8>),
358    SSHA1(Vec<u8>, Vec<u8>),
359    SHA256(Vec<u8>),
360    SSHA256(Vec<u8>, Vec<u8>),
361    SHA512(Vec<u8>),
362    SSHA512(Vec<u8>, Vec<u8>),
363    //     hash
364    NT_MD4(Vec<u8>),
365    CRYPT_MD5 {
366        s: Vec<u8>,
367        h: Vec<u8>,
368    },
369    CRYPT_SHA256 {
370        h: String,
371    },
372    CRYPT_SHA512 {
373        h: String,
374    },
375}
376
377#[derive(Debug, Clone, PartialEq)]
378pub enum PasswordError {
379    Base64Decoding,
380    InvalidFormat,
381    InvalidKeyLength,
382    InvalidLength,
383    InvalidSaltLength,
384    // We guess what it is, but don't know how to handle it
385    UnsupportedAlgorithm(String),
386    // No idea how to decode this password
387    NoDecoderFound(String),
388    ParsingFailed,
389}
390
391impl Display for PasswordError {
392    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
393        match self {
394            PasswordError::Base64Decoding => write!(f, "Base64 decoding failed"),
395            PasswordError::InvalidFormat => write!(f, "Invalid password format"),
396            PasswordError::InvalidKeyLength => write!(f, "Invalid key length for password"),
397            PasswordError::InvalidLength => write!(f, "Invalid length for password"),
398            PasswordError::InvalidSaltLength => write!(f, "Invalid salt length for password"),
399            PasswordError::UnsupportedAlgorithm(alg) => {
400                write!(f, "Unsupported algorithm: {alg}")
401            }
402            PasswordError::NoDecoderFound(hint) => {
403                write!(f, "No decoder found for password in this format - input started with '{hint}' - please report it upstream")
404            }
405            PasswordError::ParsingFailed => write!(f, "Parsing of password failed"),
406        }
407    }
408}
409
410impl From<ParseIntError> for PasswordError {
411    fn from(_err: ParseIntError) -> Self {
412        PasswordError::ParsingFailed
413    }
414}
415
416impl From<base64::DecodeError> for PasswordError {
417    fn from(_err: base64::DecodeError) -> Self {
418        PasswordError::Base64Decoding
419    }
420}
421
422#[derive(Clone, Debug, PartialEq)]
423pub struct Password {
424    material: Kdf,
425}
426
427impl TryFrom<DbPasswordV1> for Password {
428    type Error = ();
429
430    fn try_from(value: DbPasswordV1) -> Result<Self, Self::Error> {
431        match value {
432            DbPasswordV1::TPM_ARGON2ID { m, t, p, v, s, k } => Ok(Password {
433                material: Kdf::TPM_ARGON2ID {
434                    m_cost: m,
435                    t_cost: t,
436                    p_cost: p,
437                    version: v,
438                    salt: s.into(),
439                    key: k.into(),
440                },
441            }),
442            DbPasswordV1::ARGON2ID { m, t, p, v, s, k } => Ok(Password {
443                material: Kdf::ARGON2ID {
444                    m_cost: m,
445                    t_cost: t,
446                    p_cost: p,
447                    version: v,
448                    salt: s.into(),
449                    key: k.into(),
450                },
451            }),
452            DbPasswordV1::PBKDF2(c, s, h) => Ok(Password {
453                material: Kdf::PBKDF2(c, s, h),
454            }),
455            DbPasswordV1::PBKDF2_SHA1(c, s, h) => Ok(Password {
456                material: Kdf::PBKDF2_SHA1(c, s, h),
457            }),
458            DbPasswordV1::PBKDF2_SHA512(c, s, h) => Ok(Password {
459                material: Kdf::PBKDF2_SHA512(c, s, h),
460            }),
461            DbPasswordV1::SHA1(h) => Ok(Password {
462                material: Kdf::SHA1(h),
463            }),
464            DbPasswordV1::SSHA1(s, h) => Ok(Password {
465                material: Kdf::SSHA1(s, h),
466            }),
467            DbPasswordV1::SHA256(h) => Ok(Password {
468                material: Kdf::SHA256(h),
469            }),
470            DbPasswordV1::SSHA256(s, h) => Ok(Password {
471                material: Kdf::SSHA256(s, h),
472            }),
473            DbPasswordV1::SHA512(h) => Ok(Password {
474                material: Kdf::SHA512(h),
475            }),
476            DbPasswordV1::SSHA512(s, h) => Ok(Password {
477                material: Kdf::SSHA512(s, h),
478            }),
479            DbPasswordV1::NT_MD4(h) => Ok(Password {
480                material: Kdf::NT_MD4(h),
481            }),
482            DbPasswordV1::CRYPT_MD5 { s, h } => Ok(Password {
483                material: Kdf::CRYPT_MD5 {
484                    s: s.into(),
485                    h: h.into(),
486                },
487            }),
488            DbPasswordV1::CRYPT_SHA256 { h } => Ok(Password {
489                material: Kdf::CRYPT_SHA256 { h },
490            }),
491            DbPasswordV1::CRYPT_SHA512 { h } => Ok(Password {
492                material: Kdf::CRYPT_SHA256 { h },
493            }),
494        }
495    }
496}
497
498// OpenLDAP based their PBKDF2 implementation on passlib from python, that uses a
499// non-standard base64 altchar set and padding that is not supported by
500// anything else in the world. To manage this, we only ever encode to base64 with
501// no pad but we have to remap ab64 to b64. This function allows b64 standard with
502// padding to pass, and remaps ab64 to b64 standard with padding.
503macro_rules! ab64_to_b64 {
504    ($ab64:expr) => {{
505        let mut s = $ab64.replace(".", "+");
506        match s.len() & 3 {
507            0 => {
508                // Do nothing
509            }
510            1 => {
511                // One is invalid, do nothing, we'll error in base64
512            }
513            2 => s.push_str("=="),
514            3 => s.push_str("="),
515            _ => unreachable!(),
516        }
517        s
518    }};
519}
520
521/// Django passwords look like `algo$salt$hash`
522fn parse_django_password(value: &str) -> Result<Password, PasswordError> {
523    let django_pbkdf: Vec<&str> = value.split('$').collect();
524    if django_pbkdf.len() != 4 {
525        return Err(PasswordError::InvalidLength);
526    }
527    // let _algo = django_pbkdf[0];
528    let cost = django_pbkdf[1];
529    let salt = django_pbkdf[2];
530    let hash = django_pbkdf[3];
531    let c = cost.parse::<u32>()?;
532    let s: Vec<_> = salt.as_bytes().to_vec();
533    let h = general_purpose::STANDARD.decode(hash)?;
534    if h.len() < PBKDF2_MIN_NIST_KEY_LEN {
535        Err(PasswordError::InvalidLength)
536    } else {
537        Ok(Password {
538            material: Kdf::PBKDF2(c, s, h),
539        })
540    }
541}
542
543fn parse_ipanthash(hash_value: &str) -> Result<Password, PasswordError> {
544    // Great work.
545    let h = base64::engine::general_purpose::URL_SAFE_NO_PAD
546        .decode(hash_value)
547        .or_else(|_| base64::engine::general_purpose::URL_SAFE.decode(hash_value))?;
548
549    Ok(Password {
550        material: Kdf::NT_MD4(h),
551    })
552}
553
554fn parse_sambantpassword(hash_value: &str) -> Result<Password, PasswordError> {
555    let h = hex::decode(hash_value).map_err(|_| PasswordError::ParsingFailed)?;
556    Ok(Password {
557        material: Kdf::NT_MD4(h),
558    })
559}
560
561fn parse_crypt(hash_value: &str) -> Result<Password, PasswordError> {
562    if let Some(crypt_md5_phc) = hash_value.strip_prefix("$1$") {
563        let (salt, hash) = crypt_md5_phc
564            .split_once('$')
565            .ok_or(PasswordError::ParsingFailed)?;
566
567        // These are a hash64 format, so leave them as bytes, don't try
568        // to decode.
569        let s = salt.as_bytes().to_vec();
570        let h = hash.as_bytes().to_vec();
571
572        Ok(Password {
573            material: Kdf::CRYPT_MD5 { s, h },
574        })
575    } else if hash_value.starts_with("$5$") {
576        Ok(Password {
577            material: Kdf::CRYPT_SHA256 {
578                h: hash_value.to_string(),
579            },
580        })
581    } else if hash_value.starts_with("$6$") {
582        Ok(Password {
583            material: Kdf::CRYPT_SHA512 {
584                h: hash_value.to_string(),
585            },
586        })
587    } else {
588        Err(PasswordError::UnsupportedAlgorithm("crypt".to_string()))
589    }
590}
591
592fn parse_pbkdf2(hash_format: &str, hash_value: &str) -> Result<Password, PasswordError> {
593    let ol_pbkdf: Vec<&str> = hash_value.split('$').collect();
594    if ol_pbkdf.len() != 3 {
595        warn!("oldap pbkdf2 found but invalid number of elements?");
596        return Err(PasswordError::InvalidLength);
597    }
598
599    let cost = ol_pbkdf[0];
600    let salt = ol_pbkdf[1];
601    let hash = ol_pbkdf[2];
602
603    let c: u32 = cost.parse()?;
604
605    let s = ab64_to_b64!(salt);
606    let base64_decoder_config =
607        general_purpose::GeneralPurposeConfig::new().with_decode_allow_trailing_bits(true);
608    let base64_decoder = GeneralPurpose::new(&alphabet::STANDARD, base64_decoder_config);
609    let s = base64_decoder.decode(s).inspect_err(|e| {
610        error!(?e, "Invalid base64 in oldap pbkdf2-sha1");
611    })?;
612
613    let h = ab64_to_b64!(hash);
614    let h = base64_decoder.decode(h).inspect_err(|e| {
615        error!(?e, "Invalid base64 in oldap pbkdf2-sha1");
616    })?;
617
618    match hash_format {
619        // This is just sha1 in a trenchcoat.
620        "pbkdf2" | "pbkdf2-sha1" => {
621            if h.len() < PBKDF2_SHA1_MIN_KEY_LEN {
622                Err(PasswordError::InvalidKeyLength)
623            } else {
624                Ok(Password {
625                    material: Kdf::PBKDF2_SHA1(c, s, h),
626                })
627            }
628        }
629        "pbkdf2-sha256" => {
630            if h.len() < PBKDF2_MIN_NIST_KEY_LEN {
631                Err(PasswordError::InvalidKeyLength)
632            } else {
633                Ok(Password {
634                    material: Kdf::PBKDF2(c, s, h),
635                })
636            }
637        }
638        "pbkdf2-sha512" => {
639            if h.len() < PBKDF2_MIN_NIST_KEY_LEN {
640                Err(PasswordError::InvalidKeyLength)
641            } else {
642                Ok(Password {
643                    material: Kdf::PBKDF2_SHA512(c, s, h),
644                })
645            }
646        }
647        _ => Err(PasswordError::UnsupportedAlgorithm(hash_format.to_string())),
648    }
649}
650
651fn parse_argon(hash_value: &str) -> Result<Password, PasswordError> {
652    match PasswordHash::try_from(hash_value) {
653        Ok(PasswordHash {
654            algorithm,
655            version,
656            params,
657            salt,
658            hash,
659        }) => {
660            if algorithm.as_str() != "argon2id" {
661                error!(alg = %algorithm.as_str(), "Only argon2id is supported");
662                return Err(PasswordError::UnsupportedAlgorithm(algorithm.to_string()));
663            }
664
665            let version = version.unwrap_or(ARGON2_VERSION);
666            let version: Version = version.try_into().map_err(|_| {
667                error!("Failed to convert {} to valid argon2id version", version);
668                PasswordError::ParsingFailed
669            })?;
670
671            let m_cost = params.get_decimal("m").ok_or_else(|| {
672                error!("Failed to access m_cost parameter");
673                PasswordError::ParsingFailed
674            })?;
675
676            let t_cost = params.get_decimal("t").ok_or_else(|| {
677                error!("Failed to access t_cost parameter");
678                PasswordError::ParsingFailed
679            })?;
680
681            let p_cost = params.get_decimal("p").ok_or_else(|| {
682                error!("Failed to access p_cost parameter");
683                PasswordError::ParsingFailed
684            })?;
685
686            let salt = salt
687                .and_then(|s| {
688                    let mut salt_arr = [0u8; 64];
689                    s.decode_b64(&mut salt_arr)
690                        .ok()
691                        .map(|salt_bytes| salt_bytes.to_owned())
692                })
693                .ok_or_else(|| {
694                    error!("Failed to access salt");
695                    PasswordError::ParsingFailed
696                })?;
697
698            let key = hash.map(|h| h.as_bytes().into()).ok_or_else(|| {
699                error!("Failed to access key");
700                PasswordError::ParsingFailed
701            })?;
702
703            Ok(Password {
704                material: Kdf::ARGON2ID {
705                    m_cost,
706                    t_cost,
707                    p_cost,
708                    version: version as u32,
709                    salt,
710                    key,
711                },
712            })
713        }
714        Err(e) => {
715            error!(?e, "Invalid argon2 PHC string");
716            Err(PasswordError::ParsingFailed)
717        }
718    }
719}
720
721impl TryFrom<&str> for Password {
722    type Error = PasswordError;
723
724    // As we may add more algos, we keep the match algo single for later.
725
726    fn try_from(value: &str) -> Result<Self, Self::Error> {
727        if value.starts_with("pbkdf2_sha256$") {
728            parse_django_password(value)
729        } else if let Some(hash_value) = value.strip_prefix("ipaNTHash: ") {
730            parse_ipanthash(hash_value)
731        } else if let Some(hash_value) = value.strip_prefix("sambaNTPassword: ") {
732            parse_sambantpassword(hash_value)
733        } else if value.starts_with("{") {
734            // Test 389ds/openldap formats. Shout outs openldap which sometimes makes these
735            // lowercase, so we're making them all lowercase!
736
737            // turn {hash_format}hash_value into hash_format and hash_value (and lowercase hash_format)
738            let (hash_format, hash_value) = match value.split_once('}') {
739                Some((format, value)) => (
740                    format.strip_prefix('{').unwrap_or(format).to_lowercase(),
741                    value,
742                ),
743                None => {
744                    return Err(PasswordError::InvalidFormat);
745                }
746            };
747
748            match hash_format.as_str() {
749                // Test for OpenLDAP formats
750                "pbkdf2" | "pbkdf2-sha1" | "pbkdf2-sha256" | "pbkdf2-sha512" => {
751                    parse_pbkdf2(&hash_format, hash_value)
752                }
753
754                // This is the binary version of 389-ds pbkdf2 which we do not support.
755                "pbkdf2_sha256" => Err(PasswordError::InvalidFormat),
756
757                "argon2" => parse_argon(hash_value),
758                "crypt" => parse_crypt(hash_value),
759                "sha" => {
760                    let h = general_purpose::STANDARD.decode(hash_value)?;
761                    if h.len() != DS_SHA1_HASH_LEN {
762                        return Err(PasswordError::InvalidSaltLength);
763                    }
764                    Ok(Password {
765                        material: Kdf::SHA1(h.to_vec()),
766                    })
767                }
768                "ssha" => {
769                    let sh = general_purpose::STANDARD.decode(hash_value)?;
770                    let (h, s) = sh
771                        .split_at_checked(DS_SHA1_HASH_LEN)
772                        .ok_or(PasswordError::InvalidLength)?;
773
774                    Ok(Password {
775                        material: Kdf::SSHA1(s.to_vec(), h.to_vec()),
776                    })
777                }
778                "sha256" => {
779                    let h = general_purpose::STANDARD.decode(hash_value)?;
780                    if h.len() != DS_SHA256_HASH_LEN {
781                        return Err(PasswordError::InvalidSaltLength);
782                    }
783                    Ok(Password {
784                        material: Kdf::SHA256(h.to_vec()),
785                    })
786                }
787                "ssha256" => {
788                    let sh = general_purpose::STANDARD.decode(hash_value)?;
789                    let (h, s) = sh
790                        .split_at_checked(DS_SHA256_HASH_LEN)
791                        .ok_or(PasswordError::InvalidLength)?;
792                    Ok(Password {
793                        material: Kdf::SSHA256(s.to_vec(), h.to_vec()),
794                    })
795                }
796                "sha512" => {
797                    let h = general_purpose::STANDARD.decode(hash_value)?;
798                    if h.len() != DS_SHA512_HASH_LEN {
799                        return Err(PasswordError::InvalidSaltLength);
800                    }
801                    Ok(Password {
802                        material: Kdf::SHA512(h.to_vec()),
803                    })
804                }
805                "ssha512" => {
806                    let sh = general_purpose::STANDARD.decode(hash_value)?;
807                    if sh.len() <= DS_SHA512_HASH_LEN {
808                        return Err(PasswordError::InvalidSaltLength);
809                    }
810                    let (h, s) = sh
811                        .split_at_checked(DS_SHA512_HASH_LEN)
812                        .ok_or(PasswordError::InvalidLength)?;
813                    Ok(Password {
814                        material: Kdf::SSHA512(s.to_vec(), h.to_vec()),
815                    })
816                }
817                _ => Err(PasswordError::NoDecoderFound(hash_format)),
818            }
819        } else {
820            Err(PasswordError::NoDecoderFound(
821                value.chars().take(5).collect(),
822            ))
823        }
824    }
825}
826
827impl Password {
828    fn bench_argon2id(params: Params) -> Option<Duration> {
829        let mut rng = rand::rng();
830        let salt: Vec<u8> = (0..ARGON2_SALT_LEN).map(|_| rng.random()).collect();
831        let input: Vec<u8> = (0..ARGON2_SALT_LEN).map(|_| rng.random()).collect();
832        let mut key: Vec<u8> = (0..ARGON2_KEY_LEN).map(|_| 0).collect();
833
834        let argon = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
835
836        let start = Instant::now();
837        argon
838            .hash_password_into(input.as_slice(), salt.as_slice(), key.as_mut_slice())
839            .ok()?;
840        let end = Instant::now();
841
842        end.checked_duration_since(start)
843    }
844
845    pub fn new_pbkdf2(policy: &CryptoPolicy, cleartext: &str) -> Result<Self, CryptoError> {
846        let pbkdf2_cost = policy.pbkdf2_cost;
847        let mut rng = rand::rng();
848        let salt: Vec<u8> = (0..PBKDF2_SALT_LEN).map(|_| rng.random()).collect();
849        let mut key: Vec<u8> = (0..PBKDF2_KEY_LEN).map(|_| 0).collect();
850
851        pbkdf2_hmac::<Sha256>(
852            cleartext.as_bytes(),
853            salt.as_slice(),
854            pbkdf2_cost,
855            key.as_mut_slice(),
856        );
857
858        // Turn key to a vec.
859        Ok(Password {
860            material: Kdf::PBKDF2(pbkdf2_cost, salt, key),
861        })
862    }
863
864    pub fn new_argon2id(policy: &CryptoPolicy, cleartext: &str) -> Result<Self, CryptoError> {
865        let version = Version::V0x13;
866
867        let argon = Argon2::new(Algorithm::Argon2id, version, policy.argon2id_params.clone());
868
869        let mut rng = rand::rng();
870        let salt: Vec<u8> = (0..ARGON2_SALT_LEN).map(|_| rng.random()).collect();
871        let mut key: Vec<u8> = (0..ARGON2_KEY_LEN).map(|_| 0).collect();
872
873        argon
874            .hash_password_into(cleartext.as_bytes(), salt.as_slice(), key.as_mut_slice())
875            .map(|()| Kdf::ARGON2ID {
876                m_cost: policy.argon2id_params.m_cost(),
877                t_cost: policy.argon2id_params.t_cost(),
878                p_cost: policy.argon2id_params.p_cost(),
879                version: version as u32,
880                salt,
881                key,
882            })
883            .map_err(|_| CryptoError::Argon2)
884            .map(|material| Password { material })
885    }
886
887    pub fn new_argon2id_hsm(
888        policy: &CryptoPolicy,
889        cleartext: &str,
890        hsm: &mut dyn TpmHmacS256,
891        hmac_key: &HmacS256Key,
892    ) -> Result<Self, CryptoError> {
893        let version = Version::V0x13;
894
895        let argon = Argon2::new(Algorithm::Argon2id, version, policy.argon2id_params.clone());
896
897        let mut rng = rand::rng();
898        let salt: Vec<u8> = (0..ARGON2_SALT_LEN).map(|_| rng.random()).collect();
899        let mut check_key: Vec<u8> = (0..ARGON2_KEY_LEN).map(|_| 0).collect();
900
901        argon
902            .hash_password_into(
903                cleartext.as_bytes(),
904                salt.as_slice(),
905                check_key.as_mut_slice(),
906            )
907            .map_err(|_| CryptoError::Argon2)
908            .and_then(|()| {
909                hsm.hmac_s256(hmac_key, &check_key)
910                    .map_err(|err| {
911                        error!(?err, "hsm error");
912                        CryptoError::Hsm
913                    })
914                    .map(|hmac_output| hmac_output.into_bytes().to_vec())
915            })
916            .map(|key| Kdf::TPM_ARGON2ID {
917                m_cost: policy.argon2id_params.m_cost(),
918                t_cost: policy.argon2id_params.t_cost(),
919                p_cost: policy.argon2id_params.p_cost(),
920                version: version as u32,
921                salt,
922                key,
923            })
924            .map(|material| Password { material })
925    }
926
927    #[inline]
928    pub fn new(policy: &CryptoPolicy, cleartext: &str) -> Result<Self, CryptoError> {
929        Self::new_argon2id(policy, cleartext)
930    }
931
932    pub fn verify(&self, cleartext: &str) -> Result<bool, CryptoError> {
933        self.verify_ctx(cleartext, None)
934    }
935
936    pub fn verify_ctx(
937        &self,
938        cleartext: &str,
939        hsm: Option<(&mut dyn TpmHmacS256, &HmacS256Key)>,
940    ) -> Result<bool, CryptoError> {
941        if cleartext.len() > PW_MAX_LENGTH_CHECK {
942            error!("Cleartext input exceeds safe KDF length {PW_MAX_LENGTH_CHECK}, refusing to proceed.");
943            return Ok(false);
944        }
945
946        match (&self.material, hsm) {
947            (
948                Kdf::TPM_ARGON2ID {
949                    m_cost,
950                    t_cost,
951                    p_cost,
952                    version,
953                    salt,
954                    key,
955                },
956                Some((hsm, hmac_key)),
957            ) => {
958                let version: Version = (*version).try_into().map_err(|_| {
959                    error!("Failed to convert {} to valid argon2id version", version);
960                    CryptoError::Argon2Version
961                })?;
962
963                let key_len = key.len();
964
965                let params =
966                    Params::new(*m_cost, *t_cost, *p_cost, Some(key_len)).map_err(|e| {
967                        error!(err = ?e, "invalid argon2id parameters");
968                        CryptoError::Argon2Parameters
969                    })?;
970
971                let argon = Argon2::new(Algorithm::Argon2id, version, params);
972                let mut check_key: Vec<u8> = (0..key_len).map(|_| 0).collect();
973
974                argon
975                    .hash_password_into(
976                        cleartext.as_bytes(),
977                        salt.as_slice(),
978                        check_key.as_mut_slice(),
979                    )
980                    .map_err(|e| {
981                        error!(err = ?e, "unable to perform argon2id hash");
982                        CryptoError::Argon2
983                    })
984                    .and_then(|()| {
985                        hsm.hmac_s256(hmac_key, &check_key).map_err(|err| {
986                            error!(?err, "hsm error");
987                            CryptoError::Hsm
988                        })
989                    })
990                    .map(|hmac_key| {
991                        // Actually compare the outputs.
992                        hmac_key.into_bytes().as_slice() == key
993                    })
994            }
995            (Kdf::TPM_ARGON2ID { .. }, None) => {
996                error!("Unable to validate password - not hsm context available");
997                Err(CryptoError::HsmContextMissing)
998            }
999            (
1000                Kdf::ARGON2ID {
1001                    m_cost,
1002                    t_cost,
1003                    p_cost,
1004                    version,
1005                    salt,
1006                    key,
1007                },
1008                _,
1009            ) => {
1010                let version: Version = (*version).try_into().map_err(|_| {
1011                    error!("Failed to convert {} to valid argon2id version", version);
1012                    CryptoError::Argon2Version
1013                })?;
1014
1015                let key_len = key.len();
1016
1017                let params =
1018                    Params::new(*m_cost, *t_cost, *p_cost, Some(key_len)).map_err(|e| {
1019                        error!(err = ?e, "invalid argon2id parameters");
1020                        CryptoError::Argon2Parameters
1021                    })?;
1022
1023                let argon = Argon2::new(Algorithm::Argon2id, version, params);
1024                let mut check_key: Vec<u8> = (0..key_len).map(|_| 0).collect();
1025
1026                argon
1027                    .hash_password_into(
1028                        cleartext.as_bytes(),
1029                        salt.as_slice(),
1030                        check_key.as_mut_slice(),
1031                    )
1032                    .map_err(|e| {
1033                        error!(err = ?e, "unable to perform argon2id hash");
1034                        CryptoError::Argon2
1035                    })
1036                    .map(|()| {
1037                        // Actually compare the outputs.
1038                        &check_key == key
1039                    })
1040            }
1041            (Kdf::PBKDF2(cost, salt, key), _) => {
1042                // We have to get the number of bits to derive from our stored hash
1043                // as some imported hash types may have variable lengths
1044                let key_len = key.len();
1045                debug_assert!(key_len >= PBKDF2_MIN_NIST_KEY_LEN);
1046                let mut chal_key: Vec<u8> = (0..key_len).map(|_| 0).collect();
1047
1048                pbkdf2_hmac::<Sha256>(
1049                    cleartext.as_bytes(),
1050                    salt.as_slice(),
1051                    *cost,
1052                    chal_key.as_mut_slice(),
1053                );
1054
1055                // Actually compare the outputs.
1056                Ok(&chal_key == key)
1057            }
1058            (Kdf::PBKDF2_SHA1(cost, salt, key), _) => {
1059                let key_len = key.len();
1060                debug_assert!(key_len >= PBKDF2_SHA1_MIN_KEY_LEN);
1061                let mut chal_key: Vec<u8> = (0..key_len).map(|_| 0).collect();
1062
1063                pbkdf2_hmac::<Sha1>(
1064                    cleartext.as_bytes(),
1065                    salt.as_slice(),
1066                    *cost,
1067                    chal_key.as_mut_slice(),
1068                );
1069
1070                // Actually compare the outputs.
1071                Ok(&chal_key == key)
1072            }
1073            (Kdf::PBKDF2_SHA512(cost, salt, key), _) => {
1074                let key_len = key.len();
1075                debug_assert!(key_len >= PBKDF2_MIN_NIST_KEY_LEN);
1076                let mut chal_key: Vec<u8> = (0..key_len).map(|_| 0).collect();
1077
1078                pbkdf2_hmac::<Sha512>(
1079                    cleartext.as_bytes(),
1080                    salt.as_slice(),
1081                    *cost,
1082                    chal_key.as_mut_slice(),
1083                );
1084
1085                // Actually compare the outputs.
1086                Ok(&chal_key == key)
1087            }
1088            (Kdf::SHA1(key), _) => {
1089                let mut hasher = Sha1::new();
1090                hasher.update(cleartext.as_bytes());
1091                let r = hasher.finalize();
1092                Ok(key == &(r.to_vec()))
1093            }
1094            (Kdf::SSHA1(salt, key), _) => {
1095                let mut hasher = Sha1::new();
1096                hasher.update(cleartext.as_bytes());
1097                hasher.update(salt);
1098                let r = hasher.finalize();
1099                Ok(key == &(r.to_vec()))
1100            }
1101            (Kdf::SHA256(key), _) => {
1102                let mut hasher = Sha256::new();
1103                hasher.update(cleartext.as_bytes());
1104                let r = hasher.finalize();
1105                Ok(key == &(r.to_vec()))
1106            }
1107            (Kdf::SSHA256(salt, key), _) => {
1108                let mut hasher = Sha256::new();
1109                hasher.update(cleartext.as_bytes());
1110                hasher.update(salt);
1111                let r = hasher.finalize();
1112                Ok(key == &(r.to_vec()))
1113            }
1114            (Kdf::SHA512(key), _) => {
1115                let mut hasher = Sha512::new();
1116                hasher.update(cleartext.as_bytes());
1117                let r = hasher.finalize();
1118                Ok(key == &(r.to_vec()))
1119            }
1120            (Kdf::SSHA512(salt, key), _) => {
1121                let mut hasher = Sha512::new();
1122                hasher.update(cleartext.as_bytes());
1123                hasher.update(salt);
1124                let r = hasher.finalize();
1125                Ok(key == &(r.to_vec()))
1126            }
1127            (Kdf::NT_MD4(key), _) => {
1128                // We need to get the cleartext to utf16le for reasons.
1129                let clear_utf16le: Vec<u8> = cleartext
1130                    .encode_utf16()
1131                    .map(|c| c.to_le_bytes())
1132                    .flat_map(|i| i.into_iter())
1133                    .collect();
1134
1135                let mut hasher = Md4::new();
1136                hasher.update(&clear_utf16le);
1137                let chal_key = hasher.finalize();
1138
1139                Ok(chal_key.as_slice() == key)
1140            }
1141            (Kdf::CRYPT_MD5 { s, h }, _) => {
1142                let chal_key = crypt_md5::do_md5_crypt(cleartext.as_bytes(), s);
1143                Ok(chal_key == *h)
1144            }
1145            (Kdf::CRYPT_SHA256 { h }, _) => {
1146                let is_valid = sha_crypt::sha256_check(cleartext, h.as_str()).is_ok();
1147
1148                Ok(is_valid)
1149            }
1150            (Kdf::CRYPT_SHA512 { h }, _) => {
1151                let is_valid = sha_crypt::sha512_check(cleartext, h.as_str()).is_ok();
1152
1153                Ok(is_valid)
1154            }
1155        }
1156    }
1157
1158    pub fn to_dbpasswordv1(&self) -> DbPasswordV1 {
1159        match &self.material {
1160            Kdf::TPM_ARGON2ID {
1161                m_cost,
1162                t_cost,
1163                p_cost,
1164                version,
1165                salt,
1166                key,
1167            } => DbPasswordV1::TPM_ARGON2ID {
1168                m: *m_cost,
1169                t: *t_cost,
1170                p: *p_cost,
1171                v: *version,
1172                s: salt.clone().into(),
1173                k: key.clone().into(),
1174            },
1175            Kdf::ARGON2ID {
1176                m_cost,
1177                t_cost,
1178                p_cost,
1179                version,
1180                salt,
1181                key,
1182            } => DbPasswordV1::ARGON2ID {
1183                m: *m_cost,
1184                t: *t_cost,
1185                p: *p_cost,
1186                v: *version,
1187                s: salt.clone().into(),
1188                k: key.clone().into(),
1189            },
1190            Kdf::PBKDF2(cost, salt, hash) => {
1191                DbPasswordV1::PBKDF2(*cost, salt.clone(), hash.clone())
1192            }
1193            Kdf::PBKDF2_SHA1(cost, salt, hash) => {
1194                DbPasswordV1::PBKDF2_SHA1(*cost, salt.clone(), hash.clone())
1195            }
1196            Kdf::PBKDF2_SHA512(cost, salt, hash) => {
1197                DbPasswordV1::PBKDF2_SHA512(*cost, salt.clone(), hash.clone())
1198            }
1199            Kdf::SHA1(hash) => DbPasswordV1::SHA1(hash.clone()),
1200            Kdf::SSHA1(salt, hash) => DbPasswordV1::SSHA1(salt.clone(), hash.clone()),
1201            Kdf::SHA256(hash) => DbPasswordV1::SHA256(hash.clone()),
1202            Kdf::SSHA256(salt, hash) => DbPasswordV1::SSHA256(salt.clone(), hash.clone()),
1203            Kdf::SHA512(hash) => DbPasswordV1::SHA512(hash.clone()),
1204            Kdf::SSHA512(salt, hash) => DbPasswordV1::SSHA512(salt.clone(), hash.clone()),
1205            Kdf::NT_MD4(hash) => DbPasswordV1::NT_MD4(hash.clone()),
1206            Kdf::CRYPT_MD5 { s, h } => DbPasswordV1::CRYPT_MD5 {
1207                s: s.clone().into(),
1208                h: h.clone().into(),
1209            },
1210            Kdf::CRYPT_SHA256 { h } => DbPasswordV1::CRYPT_SHA256 { h: h.clone() },
1211            Kdf::CRYPT_SHA512 { h } => DbPasswordV1::CRYPT_SHA512 { h: h.clone() },
1212        }
1213    }
1214
1215    pub fn requires_upgrade(&self) -> bool {
1216        match &self.material {
1217            Kdf::ARGON2ID {
1218                m_cost,
1219                t_cost,
1220                p_cost,
1221                version,
1222                salt,
1223                key,
1224            } => {
1225                *version < ARGON2_VERSION ||
1226                salt.len() < ARGON2_SALT_LEN ||
1227                key.len() < ARGON2_KEY_LEN ||
1228                // Can't multi-thread
1229                *p_cost > ARGON2_MAX_P_COST ||
1230                // Likely too long on cpu time.
1231                *t_cost > ARGON2_MAX_T_COST ||
1232                // Too much ram
1233                *m_cost > ARGON2_MAX_RAM_KIB
1234            }
1235            // Only used in unixd today
1236            Kdf::TPM_ARGON2ID { .. } => false,
1237            // All now upgraded to argon2id
1238            Kdf::PBKDF2(_, _, _)
1239            | Kdf::PBKDF2_SHA512(_, _, _)
1240            | Kdf::PBKDF2_SHA1(_, _, _)
1241            | Kdf::SHA1(_)
1242            | Kdf::SSHA1(_, _)
1243            | Kdf::SHA256(_)
1244            | Kdf::SSHA256(_, _)
1245            | Kdf::SHA512(_)
1246            | Kdf::SSHA512(_, _)
1247            | Kdf::NT_MD4(_)
1248            | Kdf::CRYPT_MD5 { .. }
1249            | Kdf::CRYPT_SHA256 { .. }
1250            | Kdf::CRYPT_SHA512 { .. } => true,
1251        }
1252    }
1253}
1254
1255#[cfg(test)]
1256mod tests {
1257    use kanidm_hsm_crypto::{
1258        provider::{SoftTpm, TpmHmacS256},
1259        AuthValue,
1260    };
1261    use std::convert::TryFrom;
1262
1263    use crate::*;
1264
1265    #[test]
1266    fn test_credential_simple() {
1267        let p = CryptoPolicy::minimum();
1268        let c = Password::new(&p, "password").unwrap();
1269        assert!(c.verify("password").unwrap());
1270        assert!(!c.verify("password1").unwrap());
1271        assert!(!c.verify("Password1").unwrap());
1272        assert!(!c.verify("It Works!").unwrap());
1273        assert!(!c.verify("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").unwrap());
1274    }
1275
1276    #[test]
1277    fn test_password_pbkdf2() {
1278        let p = CryptoPolicy::minimum();
1279        let c = Password::new_pbkdf2(&p, "password").unwrap();
1280        assert!(c.verify("password").unwrap());
1281        assert!(!c.verify("password1").unwrap());
1282        assert!(!c.verify("Password1").unwrap());
1283    }
1284
1285    #[test]
1286    fn test_password_argon2id() {
1287        let p = CryptoPolicy::minimum();
1288        let c = Password::new_argon2id(&p, "password").unwrap();
1289        assert!(c.verify("password").unwrap());
1290        assert!(!c.verify("password1").unwrap());
1291        assert!(!c.verify("Password1").unwrap());
1292    }
1293
1294    #[test]
1295    fn test_password_from_invalid() {
1296        assert!(Password::try_from("password").is_err())
1297    }
1298
1299    #[test]
1300    fn test_password_from_django_pbkdf2_sha256() {
1301        let im_pw = "pbkdf2_sha256$36000$xIEozuZVAoYm$uW1b35DUKyhvQAf1mBqMvoBDcqSD06juzyO/nmyV0+w=";
1302        let password = "eicieY7ahchaoCh0eeTa";
1303        let r = Password::try_from(im_pw).expect("Failed to parse");
1304        assert!(r.verify(password).unwrap_or(false));
1305    }
1306
1307    #[test]
1308    fn test_password_from_ds_sha1() {
1309        let im_pw = "{SHA}W6ph5Mm5Pz8GgiULbPgzG37mj9g=";
1310        let _r = Password::try_from(im_pw).expect("Failed to parse");
1311
1312        let im_pw = "{sha}W6ph5Mm5Pz8GgiULbPgzG37mj9g=";
1313        let password = "password";
1314        let r = Password::try_from(im_pw).expect("Failed to parse");
1315
1316        // Known weak, require upgrade.
1317        assert!(r.requires_upgrade());
1318        assert!(r.verify(password).unwrap_or(false));
1319    }
1320
1321    #[test]
1322    fn test_password_from_ds_ssha1() {
1323        let im_pw = "{SSHA}EyzbBiP4u4zxOrLpKTORI/RX3HC6TCTJtnVOCQ==";
1324        let _r = Password::try_from(im_pw).expect("Failed to parse");
1325
1326        let im_pw = "{ssha}EyzbBiP4u4zxOrLpKTORI/RX3HC6TCTJtnVOCQ==";
1327        let password = "password";
1328        let r = Password::try_from(im_pw).expect("Failed to parse");
1329
1330        // Known weak, require upgrade.
1331        assert!(r.requires_upgrade());
1332        assert!(r.verify(password).unwrap_or(false));
1333    }
1334
1335    #[test]
1336    fn test_password_from_ds_sha256() {
1337        let im_pw = "{SHA256}XohImNooBHFR0OVvjcYpJ3NgPQ1qq73WKhHvch0VQtg=";
1338        let _r = Password::try_from(im_pw).expect("Failed to parse");
1339
1340        let im_pw = "{sha256}XohImNooBHFR0OVvjcYpJ3NgPQ1qq73WKhHvch0VQtg=";
1341        let password = "password";
1342        let r = Password::try_from(im_pw).expect("Failed to parse");
1343
1344        // Known weak, require upgrade.
1345        assert!(r.requires_upgrade());
1346        assert!(r.verify(password).unwrap_or(false));
1347    }
1348
1349    #[test]
1350    fn test_password_from_ds_ssha256() {
1351        let im_pw = "{SSHA256}luYWfFJOZgxySTsJXHgIaCYww4yMpu6yest69j/wO5n5OycuHFV/GQ==";
1352        let _r = Password::try_from(im_pw).expect("Failed to parse");
1353
1354        let im_pw = "{ssha256}luYWfFJOZgxySTsJXHgIaCYww4yMpu6yest69j/wO5n5OycuHFV/GQ==";
1355        let password = "password";
1356        let r = Password::try_from(im_pw).expect("Failed to parse");
1357
1358        // Known weak, require upgrade.
1359        assert!(r.requires_upgrade());
1360        assert!(r.verify(password).unwrap_or(false));
1361    }
1362
1363    #[test]
1364    fn test_password_from_ds_sha512() {
1365        let im_pw = "{SHA512}sQnzu7wkTrgkQZF+0G1hi5AI3Qmzvv0bXgc5THBqi7mAsdd4Xll27ASbRt9fEyavWi6m0QP9B8lThf+rDKy8hg==";
1366        let _r = Password::try_from(im_pw).expect("Failed to parse");
1367
1368        let im_pw = "{sha512}sQnzu7wkTrgkQZF+0G1hi5AI3Qmzvv0bXgc5THBqi7mAsdd4Xll27ASbRt9fEyavWi6m0QP9B8lThf+rDKy8hg==";
1369        let password = "password";
1370        let r = Password::try_from(im_pw).expect("Failed to parse");
1371
1372        // Known weak, require upgrade.
1373        assert!(r.requires_upgrade());
1374        assert!(r.verify(password).unwrap_or(false));
1375    }
1376
1377    #[test]
1378    fn test_password_from_ds_ssha512() {
1379        let im_pw = "{SSHA512}JwrSUHkI7FTAfHRVR6KoFlSN0E3dmaQWARjZ+/UsShYlENOqDtFVU77HJLLrY2MuSp0jve52+pwtdVl2QUAHukQ0XUf5LDtM";
1380        let _r = Password::try_from(im_pw).expect("Failed to parse");
1381
1382        let im_pw = "{ssha512}JwrSUHkI7FTAfHRVR6KoFlSN0E3dmaQWARjZ+/UsShYlENOqDtFVU77HJLLrY2MuSp0jve52+pwtdVl2QUAHukQ0XUf5LDtM";
1383        let password = "password";
1384        let r = Password::try_from(im_pw).expect("Failed to parse");
1385
1386        // Known weak, require upgrade.
1387        assert!(r.requires_upgrade());
1388        assert!(r.verify(password).unwrap_or(false));
1389    }
1390
1391    // Can be generated with:
1392    // slappasswd -s password -o module-load=/usr/lib64/openldap/pw-argon2.so -h {ARGON2}
1393
1394    #[test]
1395    fn test_password_from_openldap_pkbdf2() {
1396        let im_pw = "{PBKDF2}10000$IlfapjA351LuDSwYC0IQ8Q$saHqQTuYnjJN/tmAndT.8mJt.6w";
1397        let password = "password";
1398        let r = Password::try_from(im_pw).expect("Failed to parse");
1399        assert!(r.requires_upgrade());
1400        assert!(r.verify(password).unwrap_or(false));
1401    }
1402
1403    #[test]
1404    fn test_password_from_openldap_pkbdf2_sha1() {
1405        let im_pw = "{PBKDF2-SHA1}10000$ZBEH6B07rgQpJSikyvMU2w$TAA03a5IYkz1QlPsbJKvUsTqNV";
1406        let password = "password";
1407        let r = Password::try_from(im_pw).expect("Failed to parse");
1408        assert!(r.requires_upgrade());
1409        assert!(r.verify(password).unwrap_or(false));
1410    }
1411
1412    #[test]
1413    fn test_password_from_openldap_pkbdf2_sha256() {
1414        let im_pw = "{PBKDF2-SHA256}10000$henZGfPWw79Cs8ORDeVNrQ$1dTJy73v6n3bnTmTZFghxHXHLsAzKaAy8SksDfZBPIw";
1415        let password = "password";
1416        let r = Password::try_from(im_pw).expect("Failed to parse");
1417        assert!(r.requires_upgrade());
1418        assert!(r.verify(password).unwrap_or(false));
1419    }
1420
1421    #[test]
1422    fn test_password_from_openldap_pkbdf2_sha512() {
1423        let im_pw = "{PBKDF2-SHA512}10000$Je1Uw19Bfv5lArzZ6V3EPw$g4T/1sqBUYWl9o93MVnyQ/8zKGSkPbKaXXsT8WmysXQJhWy8MRP2JFudSL.N9RklQYgDPxPjnfum/F2f/TrppA";
1424        let password = "password";
1425        let r = Password::try_from(im_pw).expect("Failed to parse");
1426        assert!(r.requires_upgrade());
1427        assert!(r.verify(password).unwrap_or(false));
1428    }
1429
1430    // Not supported in openssl, may need an external crate.
1431    #[test]
1432    fn test_password_from_openldap_argon2() {
1433        sketching::test_init();
1434        let im_pw = "{ARGON2}$argon2id$v=19$m=65536,t=2,p=1$IyTQMsvzB2JHDiWx8fq7Ew$VhYOA7AL0kbRXI5g2kOyyp8St1epkNj7WZyUY4pAIQQ";
1435        let password = "password";
1436        let r = Password::try_from(im_pw).expect("Failed to parse");
1437        assert!(!r.requires_upgrade());
1438        assert!(r.verify(password).unwrap_or(false));
1439    }
1440
1441    /*
1442     * wbrown - 20221104 - I tried to programmatically enable the legacy provider, but
1443     * it consistently "did nothing at all", meaning we have to rely on users to enable
1444     * this for this test.
1445     */
1446
1447    #[test]
1448    fn test_password_from_ipa_nt_hash() {
1449        sketching::test_init();
1450        // Base64 no pad
1451        let im_pw = "ipaNTHash: iEb36u6PsRetBr3YMLdYbA";
1452        let password = "password";
1453        let r = Password::try_from(im_pw).expect("Failed to parse");
1454        assert!(r.requires_upgrade());
1455
1456        assert!(r.verify(password).expect("Failed to hash"));
1457        let im_pw = "ipaNTHash: pS43DjQLcUYhaNF_cd_Vhw==";
1458        Password::try_from(im_pw).expect("Failed to parse");
1459    }
1460
1461    #[test]
1462    fn test_password_from_samba_nt_hash() {
1463        sketching::test_init();
1464        // Base64 no pad
1465        let im_pw = "sambaNTPassword: 8846F7EAEE8FB117AD06BDD830B7586C";
1466        let password = "password";
1467        let r = Password::try_from(im_pw).expect("Failed to parse");
1468        assert!(r.requires_upgrade());
1469        assert!(r.verify(password).expect("Failed to hash"));
1470    }
1471
1472    #[test]
1473    fn test_password_from_crypt_md5() {
1474        sketching::test_init();
1475        let im_pw = "{crypt}$1$zaRIAsoe$7887GzjDTrst0XbDPpF5m.";
1476        let password = "password";
1477        let r = Password::try_from(im_pw).expect("Failed to parse");
1478
1479        assert!(r.requires_upgrade());
1480        assert!(r.verify(password).unwrap_or(false));
1481    }
1482
1483    #[test]
1484    fn test_password_from_crypt_sha256() {
1485        sketching::test_init();
1486        let im_pw = "{crypt}$5$3UzV7Sut8EHCUxlN$41V.jtMQmFAOucqI4ImFV43r.bRLjPlN.hyfoCdmGE2";
1487        let password = "password";
1488        let r = Password::try_from(im_pw).expect("Failed to parse");
1489
1490        assert!(r.requires_upgrade());
1491        assert!(r.verify(password).unwrap_or(false));
1492    }
1493
1494    #[test]
1495    fn test_password_from_crypt_sha512() {
1496        sketching::test_init();
1497        let im_pw = "{crypt}$6$aXn8azL8DXUyuMvj$9aJJC/KEUwygIpf2MTqjQa.f0MEXNg2cGFc62Fet8XpuDVDedM05CweAlxW6GWxnmHqp14CRf6zU7OQoE/bCu0";
1498        let password = "password";
1499        let r = Password::try_from(im_pw).expect("Failed to parse");
1500
1501        assert!(r.requires_upgrade());
1502        assert!(r.verify(password).unwrap_or(false));
1503    }
1504
1505    #[test]
1506    fn test_password_argon2id_hsm_bind() {
1507        sketching::test_init();
1508
1509        let mut hsm: Box<dyn TpmHmacS256> = Box::new(SoftTpm::default());
1510
1511        let auth_value = AuthValue::ephemeral().unwrap();
1512
1513        let loadable_machine_key = hsm.root_storage_key_create(&auth_value).unwrap();
1514        let machine_key = hsm
1515            .root_storage_key_load(&auth_value, &loadable_machine_key)
1516            .unwrap();
1517
1518        let loadable_hmac_key = hsm.hmac_s256_create(&machine_key).unwrap();
1519        let key = hsm
1520            .hmac_s256_load(&machine_key, &loadable_hmac_key)
1521            .unwrap();
1522
1523        let ctx: &mut dyn TpmHmacS256 = &mut *hsm;
1524
1525        let p = CryptoPolicy::minimum();
1526        let c = Password::new_argon2id_hsm(&p, "password", ctx, &key).unwrap();
1527
1528        assert!(matches!(
1529            c.verify("password"),
1530            Err(CryptoError::HsmContextMissing)
1531        ));
1532
1533        // Assert it fails without the hmac
1534        let dup = match &c.material {
1535            Kdf::TPM_ARGON2ID {
1536                m_cost,
1537                t_cost,
1538                p_cost,
1539                version,
1540                salt,
1541                key,
1542            } => Password {
1543                material: Kdf::ARGON2ID {
1544                    m_cost: *m_cost,
1545                    t_cost: *t_cost,
1546                    p_cost: *p_cost,
1547                    version: *version,
1548                    salt: salt.clone(),
1549                    key: key.clone(),
1550                },
1551            },
1552            #[allow(clippy::unreachable)]
1553            _ => unreachable!(),
1554        };
1555
1556        assert!(!dup.verify("password").unwrap());
1557
1558        assert!(c.verify_ctx("password", Some((ctx, &key))).unwrap());
1559        assert!(!c.verify_ctx("password1", Some((ctx, &key))).unwrap());
1560        assert!(!c.verify_ctx("Password1", Some((ctx, &key))).unwrap());
1561    }
1562}