1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
//! A re-implementation of the `phpbb_check_hash` function (from phpBB 3) in
//! Rust. It allows verifying a salted hash against a password.
//!
//! ## Usage
//!
//! To verify a hash against a password:
//!
//! ```rust
//! use phpbb_pwhash::{check_hash, CheckHashResult};
//!
//! let hash = "$H$9/O41.qQjQNlleivjbckbSNpfS4xgh0";
//! assert_eq!(
//!     check_hash(hash, "pass1234"),
//!     CheckHashResult::Valid
//! );
//! assert_eq!(
//!     check_hash(hash, "pass1235"),
//!     CheckHashResult::Invalid
//! );
//! ```

/// The result type returned by [`check_hash`](crate::check_hash).
#[derive(Debug, PartialEq)]
pub enum CheckHashResult {
    Valid,
    PasswordTooLong,
    InvalidHash(InvalidHash),
    Invalid,
}

/// The error returned if the encoded hash is invalid.
#[derive(Debug, PartialEq)]
pub enum InvalidHash {
    BadLength,
    UnsupportedHashType,
    InvalidRounds,
    InvalidBase64(base64::DecodeError),
}

/// A parsed encoded phpBB3 hash
#[derive(Debug)]
pub struct PhpbbHash<'a> {
    hash_type: &'a str,
    rounds: usize,
    salt: &'a str,
    hashed: &'a str,
}

// Base64 alphabet
static ALPHABET: &str = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

/// Parse a phpBB3 hash.
///
/// A hash for the password "pass1234" can look like this:
///
/// ```text
/// $H$9/O41.qQjQNlleivjbckbSNpfS4xgh0
/// ```
///
/// Details:
///
/// - The first three characters are the hash type, should be '$H$'.
/// - The fourth character encodes the number of hashing rounds, as a power of
///   two. For example, if the value is '9' as above, then (1 << 11) rounds are
///   used (because the offset from the start of the alphabet for '9' is 11).
///   The offset must be between 7 and 30.
/// - Characters 5-13 are the 8-byte salt.
/// - Characters 13 and onwards are the encoded hash.
pub fn parse_hash(salted_hash: &str) -> Result<PhpbbHash, InvalidHash> {
    // Check for unsalted MD5 hashes
    if salted_hash.len() != 34 {
        return Err(InvalidHash::BadLength);
    }

    // Validate prefix
    let hash_type = &salted_hash[0..3];
    if hash_type != "$H$" {
        return Err(InvalidHash::UnsupportedHashType);
    };

    // Determine rounds
    let rounds = match ALPHABET.find(salted_hash.chars().nth(3).unwrap()) {
        None => return Err(InvalidHash::InvalidRounds),
        Some(offset) if offset < 7 || offset > 30 => return Err(InvalidHash::InvalidRounds),
        Some(offset) => 1 << offset,
    };

    // Determine salt and hashed data
    let salt = &salted_hash[4..12];
    let hashed = &salted_hash[12..];

    Ok(PhpbbHash {
        hash_type,
        rounds,
        salt,
        hashed,
    })
}

/// Decoding function.
///
/// Code taken from phpass re-implementation by Joshua Koudys, licensed under
/// the MIT license (https://github.com/clausehound/phpass).
fn decode64(val: &[u8]) -> Result<Vec<u8>, base64::DecodeError> {
    // We pad by 0s, encoded as .
    let len = val.len();
    let bytes = base64::decode_config(
        std::iter::repeat(b'.')
            // Base64 encodes on 3-byte boundaries
            .take(3 - len % 3)
            .chain(val.iter().cloned().rev())
            .collect::<Vec<_>>(),
        base64::CRYPT,
    )?
    .iter()
    // Then those backwards-fed inputs need their outputs reversed.
    .rev()
    .take(16)
    .copied()
    .collect::<Vec<_>>();

    Ok(bytes)
}

/// Validate a password against a phpBB3 salted hash.
pub fn check_hash(salted_hash: &str, password: &str) -> CheckHashResult {
    // Limit password length
    if password.len() > 4096 {
        return CheckHashResult::PasswordTooLong;
    }
    let password_bytes = password.as_bytes();
    let password_bytes_len = password_bytes.len();

    // Parse salted hash
    let parsed = match parse_hash(salted_hash) {
        Ok(p) => p,
        Err(e) => return CheckHashResult::InvalidHash(e),
    };

    // Decode hash
    let decoded_hashed = match decode64(parsed.hashed.as_bytes()) {
        Ok(d) => d,
        Err(e) => return CheckHashResult::InvalidHash(InvalidHash::InvalidBase64(e)),
    };

    // Initial hash
    let mut buf: Vec<u8> = Vec::with_capacity(8 + password_bytes_len);
    buf.extend_from_slice(parsed.salt.as_bytes());
    buf.extend_from_slice(password.as_bytes());
    let mut hash = md5::compute(&buf);

    // Some additional rounds of hashing
    // (Yeah, this re-allocates a buffer for every round, could be improved.)
    for _ in 0..parsed.rounds {
        let mut buf: Vec<u8> = Vec::with_capacity(16 /* md5 */ + password_bytes_len);
        buf.extend_from_slice(&hash.0);
        buf.extend_from_slice(password_bytes);
        hash = md5::compute(&buf);
    }

    if hash.0.as_ref() == decoded_hashed {
        CheckHashResult::Valid
    } else {
        CheckHashResult::Invalid
    }
}

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

    #[derive(Debug)]
    struct TestCase {
        encoded_hash: &'static str,
        password: &'static str,
        result: CheckHashResult,
    }

    #[test]
    fn test_validation() {
        let test_cases = [
            TestCase {
                encoded_hash: "$H$9/O41.qQjQNlleivjbckbSNpfS4xgh0",
                password: "pass1234",
                result: CheckHashResult::Valid,
            },
            TestCase {
                encoded_hash: "$H$9PoEptdBNUJZuamBBKOr/KPdi1ZmSw1",
                password: "pass1234",
                result: CheckHashResult::Valid,
            },
            TestCase {
                encoded_hash: "$H$94VS2e40wcTQ38TK2P2yBc0TnmMfLC1",
                password: "pass1234",
                result: CheckHashResult::Valid,
            },
            TestCase {
                encoded_hash: "$H$9/O41.qQjQNlleivjbckbSNpfS4xgh0",
                password: "pass1235",
                result: CheckHashResult::Invalid,
            },
            TestCase {
                encoded_hash: "$H$9/O41.qQjQNlleivjbckbSNpfS4xgh012",
                password: "pass1234",
                result: CheckHashResult::InvalidHash(InvalidHash::BadLength),
            },
            TestCase {
                encoded_hash: "$X$9/O41.qQjQNlleivjbckbSNpfS4xgh0",
                password: "pass1234",
                result: CheckHashResult::InvalidHash(InvalidHash::UnsupportedHashType),
            },
            TestCase {
                encoded_hash: "$H$1/O41.qQjQNlleivjbckbSNpfS4xgh0",
                password: "pass1234",
                result: CheckHashResult::InvalidHash(InvalidHash::InvalidRounds),
            },
        ];
        for case in &test_cases {
            let result = check_hash(case.encoded_hash, case.password);
            assert_eq!(result, case.result, "{:?}", case);
        }
    }
}