Skip to main content

utopia_auth/
phpass.rs

1//! The pieces of phpass (Openwall's Portable PHP password hashing framework 0.5) that
2//! `Utopia\Auth\Hashes\PHPass` implements in PHP: its base64 variant, its blowfish salt and
3//! the MD5 rounds of its portable (`$P$`, phpBB's `$H$`) hashes.
4//!
5//! PHP reads a string offset past the end as `""` with the warning
6//! `Uninitialized string offset N`; these functions read it the same way and report each such
7//! offset to `warn`, in the order PHP raises them.
8
9use md5::{Digest, Md5};
10
11/// The alphabet of phpass's base64 (`PHPass::$itoa64`).
12pub const ITOA64: &[u8; 64] = b"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
13
14/// crypt_blowfish's alphabet, which `gensaltBlowfish()` encodes the salt in.
15const BLOWFISH_ITOA64: &[u8; 64] = b"./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
16
17/// `ord($input[$i])`: 0 for an offset past the end, which is reported.
18fn ord(input: &[u8], i: usize, warn: &mut dyn FnMut(usize)) -> u32 {
19    input.get(i).map_or_else(
20        || {
21            warn(i);
22            0
23        },
24        |b| u32::from(*b),
25    )
26}
27
28/// `$output .= $alphabet[$i]`: nothing for an offset past the end, which is reported.
29fn push(output: &mut Vec<u8>, alphabet: &[u8], i: u32, warn: &mut dyn FnMut(usize)) {
30    let i = i as usize;
31    match alphabet.get(i) {
32        Some(c) => output.push(*c),
33        None => warn(i),
34    }
35}
36
37/// `PHPass::encode64($input, $count)` with `$this->itoa64` as `itoa64`, for `count` of at
38/// least 1 (the method throws below that). Offsets past the end of `input` are reported to
39/// `warn_input`, past the end of `itoa64` to `warn_itoa64`.
40pub fn encode64(
41    itoa64: &[u8],
42    input: &[u8],
43    count: usize,
44    warn_input: &mut dyn FnMut(usize),
45    warn_itoa64: &mut dyn FnMut(usize),
46) -> Vec<u8> {
47    let mut output = Vec::with_capacity(count.div_ceil(3) * 4);
48    let mut i = 0;
49    loop {
50        let mut value = ord(input, i, warn_input);
51        i += 1;
52        push(&mut output, itoa64, value & 0x3F, warn_itoa64);
53        if i < count {
54            value |= ord(input, i, warn_input) << 8;
55        }
56        push(&mut output, itoa64, (value >> 6) & 0x3F, warn_itoa64);
57        let at = i;
58        i += 1;
59        if at >= count {
60            break;
61        }
62        if i < count {
63            value |= ord(input, i, warn_input) << 16;
64        }
65        push(&mut output, itoa64, (value >> 12) & 0x3F, warn_itoa64);
66        let at = i;
67        i += 1;
68        if at >= count {
69            break;
70        }
71        push(&mut output, itoa64, (value >> 18) & 0x3F, warn_itoa64);
72        if i >= count {
73            break;
74        }
75    }
76    output
77}
78
79/// The salt characters `gensaltBlowfish()` appends after `$2a$NN$`: 16 bytes of `input` in
80/// crypt_blowfish's base64 (22 characters). Offsets past the end of `input` are reported.
81pub fn blowfish_salt(input: &[u8], warn: &mut dyn FnMut(usize)) -> Vec<u8> {
82    let mut output = Vec::with_capacity(22);
83    let mut i = 0;
84    loop {
85        let mut c1 = ord(input, i, warn);
86        i += 1;
87        output.push(BLOWFISH_ITOA64[(c1 >> 2) as usize]);
88        c1 = (c1 & 0x03) << 4;
89        if i >= 16 {
90            output.push(BLOWFISH_ITOA64[c1 as usize]);
91            break;
92        }
93        let mut c2 = ord(input, i, warn);
94        i += 1;
95        c1 |= c2 >> 4;
96        output.push(BLOWFISH_ITOA64[c1 as usize]);
97        c1 = (c2 & 0x0F) << 2;
98        c2 = ord(input, i, warn);
99        i += 1;
100        c1 |= c2 >> 6;
101        output.push(BLOWFISH_ITOA64[c1 as usize]);
102        output.push(BLOWFISH_ITOA64[(c2 & 0x3F) as usize]);
103    }
104    output
105}
106
107/// `md5($data, true)`.
108#[must_use]
109pub fn md5_raw(data: &[u8]) -> [u8; 16] {
110    Md5::digest(data).into()
111}
112
113/// The MD5 rounds of a portable hash: `md5($salt . $password, true)`, then `count` times
114/// `md5($hash . $password, true)`.
115#[must_use]
116pub fn md5_rounds(salt: &[u8], password: &[u8], count: u64) -> [u8; 16] {
117    let mut hash: [u8; 16] = Md5::new().chain_update(salt).chain_update(password).finalize().into();
118    for _ in 0..count {
119        hash = Md5::new().chain_update(hash).chain_update(password).finalize().into();
120    }
121    hash
122}
123
124#[cfg(test)]
125mod tests {
126    use super::{ITOA64, blowfish_salt, encode64, md5_rounds};
127
128    fn none(_: usize) {
129        panic!("no offset past the end");
130    }
131
132    /// A portable hash: `$P$` + count character + 8-character salt + `encode64` of the MD5
133    /// rounds, as WordPress stores them (WordPress's `wp_hash_password()` of "password").
134    #[test]
135    fn wordpress_hash() {
136        let setting = b"$P$BkZSVUxvhvrYOqtXfIkMOz2sNVHU8M1";
137        let count_log2 = ITOA64.iter().position(|c| *c == setting[3]).unwrap();
138        let hash = md5_rounds(&setting[4..12], b"password", 1 << count_log2);
139        let mut out = setting[..12].to_vec();
140        out.extend(encode64(ITOA64, &hash, 16, &mut none, &mut none));
141        assert_eq!(out.len(), 34);
142    }
143
144    #[test]
145    fn short_input_reports_offsets() {
146        let mut offsets = Vec::new();
147        let out = encode64(ITOA64, b"ab", 6, &mut |i| offsets.push(i), &mut none);
148        assert_eq!(out.len(), 8);
149        assert_eq!(offsets, vec![2, 3, 4, 5]);
150        let mut offsets = Vec::new();
151        assert_eq!(blowfish_salt(b"", &mut |i| offsets.push(i)).len(), 22);
152        assert_eq!(offsets, (0..16).collect::<Vec<_>>());
153    }
154}