pqbox 1.0.0

Post-quantum crypto toolkit: hybrid ML-KEM-1024 + P-384 sealed boxes, composite ML-DSA-87 signatures, an opt-in paranoid suite adding Classic McEliece and SLH-DSA, AEAD, KDF, hashing and Argon2id
Documentation
//! Password hashing with Argon2id (`argon2`, RFC 9106), producing PHC strings such as
//! `$argon2id$v=19$m=65536,t=3,p=1$<salt>$<hash>`.

use argon2::password_hash::phc::PasswordHash;
use argon2::{Algorithm, Argon2, PasswordHasher, PasswordVerifier, Version};

use crate::{Error, Result, Rng};

/// Default memory cost: 64 MiB (in KiB).
pub const DEFAULT_M_COST: u32 = 64 * 1024;
/// Default time cost (passes).
pub const DEFAULT_T_COST: u32 = 3;
/// Default parallelism.
pub const DEFAULT_P_COST: u32 = 1;
/// Salt length.
pub const SALT_LEN: usize = 16;
/// The most memory (256 MiB, in KiB) [`verify_password`] and [`hash_password`] agree to spend.
///
/// The costs of a PHC string come from whoever wrote it, so they are capped before any memory is
/// allocated: at the caps, one verification takes about 256 MiB and on the order of a second
/// of CPU (Argon2id cost grows with `m_cost * t_cost`). Use [`verify_password_with_limits`] to
/// accept more expensive hashes on purpose.
pub const MAX_M_COST: u32 = 256 * 1024;
/// The most passes [`verify_password`] and [`hash_password`] agree to run.
pub const MAX_T_COST: u32 = 10;
/// The most lanes [`verify_password`] and [`hash_password`] agree to use.
pub const MAX_P_COST: u32 = 8;

/// Upper bounds on the Argon2id costs a call accepts, checked before anything is allocated.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Limits {
    /// Largest memory cost, in KiB.
    pub max_m_cost: u32,
    /// Largest number of passes.
    pub max_t_cost: u32,
    /// Largest number of lanes.
    pub max_p_cost: u32,
}

impl Limits {
    /// The default limits: [`MAX_M_COST`] (256 MiB), [`MAX_T_COST`] (10) and [`MAX_P_COST`] (8).
    pub const DEFAULT: Self = Self {
        max_m_cost: MAX_M_COST,
        max_t_cost: MAX_T_COST,
        max_p_cost: MAX_P_COST,
    };

    fn allows(self, params: Params) -> bool {
        params.m_cost <= self.max_m_cost && params.t_cost <= self.max_t_cost && params.p_cost <= self.max_p_cost
    }
}

impl Default for Limits {
    fn default() -> Self {
        Self::DEFAULT
    }
}

/// Argon2id cost parameters.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Params {
    /// Memory in KiB.
    pub m_cost: u32,
    /// Passes.
    pub t_cost: u32,
    /// Lanes.
    pub p_cost: u32,
}

impl Default for Params {
    fn default() -> Self {
        Self {
            m_cost: DEFAULT_M_COST,
            t_cost: DEFAULT_T_COST,
            p_cost: DEFAULT_P_COST,
        }
    }
}

impl Params {
    fn argon2(self, limits: Limits) -> Result<Argon2<'static>> {
        if !limits.allows(self) {
            return Err(Error::InvalidParams("Argon2 cost above the limits"));
        }
        let p = argon2::Params::new(self.m_cost, self.t_cost, self.p_cost, Some(32))
            .map_err(|_| Error::InvalidParams("Argon2 parameters out of range"))?;
        Ok(Argon2::new(Algorithm::Argon2id, Version::V0x13, p))
    }
}

/// Hashes `password` with a fresh random salt, returning a PHC string.
///
/// # Errors
/// [`Error::InvalidParams`] when the costs are out of range or above [`Limits::DEFAULT`] (so
/// every hash this function makes passes [`verify_password`]).
pub fn hash_password<R: Rng + ?Sized>(password: &[u8], params: Params, rng: &mut R) -> Result<String> {
    hash_password_with_limits(password, params, Limits::DEFAULT, rng)
}

/// [`hash_password`] with explicit cost limits, for hashes more expensive than the defaults
/// allow. Verify them with [`verify_password_with_limits`] and the same limits.
///
/// # Errors
/// [`Error::InvalidParams`] when the costs are out of range or above `limits`.
pub fn hash_password_with_limits<R: Rng + ?Sized>(
    password: &[u8],
    params: Params,
    limits: Limits,
    rng: &mut R,
) -> Result<String> {
    let salt: [u8; SALT_LEN] = crate::random(rng);
    let hash = params
        .argon2(limits)?
        .hash_password_with_salt(password, &salt)
        .map_err(|_| Error::InvalidParams("Argon2 hashing failed"))?;
    Ok(hash.to_string())
}

/// Checks `password` against an Argon2id PHC string (constant-time comparison inside `argon2`).
///
/// The costs in the string are checked against [`Limits::DEFAULT`] (256 MiB, 10 passes, 8
/// lanes) before any memory is allocated, so a hostile string cannot make a verification cost
/// gigabytes or minutes.
///
/// # Errors
/// [`Error::InvalidPasswordHash`] for a malformed string, another algorithm than Argon2id or
/// costs above the limits; [`Error::PasswordMismatch`] for a wrong password.
pub fn verify_password(password: &[u8], phc: &str) -> Result<()> {
    verify_password_with_limits(password, phc, Limits::DEFAULT)
}

/// [`verify_password`] with explicit cost limits: an opt-in for hashes made with costs above
/// [`Limits::DEFAULT`]. Raise the limits only for PHC strings from a trusted source.
///
/// # Errors
/// As [`verify_password`], with `limits` instead of the defaults.
pub fn verify_password_with_limits(password: &[u8], phc: &str, limits: Limits) -> Result<()> {
    let hash = PasswordHash::new(phc).map_err(|_| Error::InvalidPasswordHash)?;
    if hash.algorithm.as_str() != "argon2id" {
        return Err(Error::InvalidPasswordHash);
    }
    let params = argon2::Params::try_from(&hash).map_err(|_| Error::InvalidPasswordHash)?;
    Params {
        m_cost: params.m_cost(),
        t_cost: params.t_cost(),
        p_cost: params.p_cost(),
    }
    .argon2(limits)
    .map_err(|_| Error::InvalidPasswordHash)?;
    Argon2::default().verify_password(password, &hash).map_err(|e| match e {
        argon2::password_hash::Error::PasswordInvalid => Error::PasswordMismatch,
        _ => Error::InvalidPasswordHash,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_util::rng;

    const FAST: Params = Params {
        m_cost: 256,
        t_cost: 1,
        p_cost: 1,
    };

    #[test]
    fn round_trip() {
        let mut rng = rng();
        let phc = hash_password(b"correct horse", FAST, &mut rng).unwrap();
        assert!(phc.starts_with("$argon2id$v=19$m=256,t=1,p=1$"));
        verify_password(b"correct horse", &phc).unwrap();
        assert_eq!(verify_password(b"wrong", &phc), Err(Error::PasswordMismatch));
    }

    #[test]
    fn defaults() {
        assert_eq!(
            Params::default(),
            Params {
                m_cost: 65536,
                t_cost: 3,
                p_cost: 1
            }
        );
    }

    #[test]
    fn rejects_bad_strings() {
        assert_eq!(verify_password(b"x", "nope"), Err(Error::InvalidPasswordHash));
        // Argon2i is refused.
        assert_eq!(
            verify_password(
                b"x",
                "$argon2i$v=19$m=256,t=2,p=1$c29tZXNhbHQ$nf65EOgLrQMR/uIPnA4rEsF5h7TKyQwu9U1bMCHGi/4"
            ),
            Err(Error::InvalidPasswordHash)
        );
        // Memory cost above the cap is refused before any work.
        assert_eq!(
            verify_password(
                b"x",
                "$argon2id$v=19$m=4294967295,t=2,p=1$c29tZXNhbHQ$nf65EOgLrQMR/uIPnA4rEsF5h7TKyQwu9U1bMCHGi/4"
            ),
            Err(Error::InvalidPasswordHash)
        );
        let mut rng = rng();
        assert!(hash_password(b"x", Params { m_cost: 1, ..FAST }, &mut rng).is_err());
    }

    const SALT: &str = "c29tZXNhbHRzb21lc2FsdA";
    const HASH: &str = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";

    fn phc(m: u32, t: u32, p: u32) -> String {
        format!("$argon2id$v=19$m={m},t={t},p={p}${SALT}${HASH}")
    }

    /// Regression: `m=4194304,t=64` (4 GiB, about two minutes of CPU per verification) used to
    /// be accepted. Every cost above the default limits is now refused before any work.
    #[test]
    fn verify_refuses_costs_above_the_default_limits() {
        for (m, t, p) in [
            (4_194_304, 64, 1),
            (4_194_304, 1, 1),
            (MAX_M_COST + 1, 1, 1),
            (1024, MAX_T_COST + 1, 1),
            (1024, 1, MAX_P_COST + 1),
            (u32::MAX, u32::MAX, 1),
        ] {
            let start = std::time::Instant::now();
            assert_eq!(
                verify_password(b"x", &phc(m, t, p)),
                Err(Error::InvalidPasswordHash),
                "m={m} t={t} p={p}"
            );
            assert!(
                start.elapsed() < std::time::Duration::from_millis(50),
                "m={m} t={t} p={p}"
            );
        }
        // Within the limits, the hash is checked (and does not match).
        assert_eq!(
            verify_password(b"x", &phc(1024, MAX_T_COST, MAX_P_COST)),
            Err(Error::PasswordMismatch)
        );
        assert_eq!(Limits::default(), Limits::DEFAULT);
        assert_eq!((MAX_M_COST, MAX_T_COST, MAX_P_COST), (262_144, 10, 8));
    }

    #[test]
    fn limits_can_be_lowered_and_raised_explicitly() {
        let mut rng = rng();
        let tight = Limits {
            max_m_cost: 256,
            max_t_cost: 1,
            max_p_cost: 1,
        };
        let phc_fast = hash_password_with_limits(b"pw", FAST, tight, &mut rng).unwrap();
        verify_password_with_limits(b"pw", &phc_fast, tight).unwrap();
        assert_eq!(
            verify_password_with_limits(b"pw", &phc(264, 1, 1), tight),
            Err(Error::InvalidPasswordHash)
        );

        // A hash above the defaults needs the opt-in on both sides.
        let slow = Params {
            t_cost: MAX_T_COST + 1,
            ..FAST
        };
        assert!(hash_password(b"pw", slow, &mut rng).is_err());
        let raised = Limits {
            max_t_cost: MAX_T_COST + 1,
            ..Limits::DEFAULT
        };
        let phc_slow = hash_password_with_limits(b"pw", slow, raised, &mut rng).unwrap();
        assert_eq!(verify_password(b"pw", &phc_slow), Err(Error::InvalidPasswordHash));
        verify_password_with_limits(b"pw", &phc_slow, raised).unwrap();
        assert_eq!(
            verify_password_with_limits(b"other", &phc_slow, raised),
            Err(Error::PasswordMismatch)
        );
    }
}