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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
use std::str;
use crate::crypto_utils;

/// Possible errors during a hash creation.
#[derive(PartialEq, Debug)]
pub enum HasherError {
    /// Algorithm not recognizable.
    UnknownAlgorithm,
    /// Hash string is corrupted.
    BadHash,
    /// Hash string is empty.
    EmptyHash,
    /// Number of iterations is not a positive integer.
    InvalidIterations,
    /// Argon2 salt should be Base64 encoded.
    InvalidArgon2Salt,
}

/// Hasher abstraction, providing methods to encode and verify hashes.
pub trait Hasher {
    /// Verifies a password against an encoded hash.
    fn verify(&self, password: &str, encoded: &str) -> Result<bool, HasherError>;
    /// Generates an encoded hash for a given password and salt.
    fn encode(&self, password: &str, salt: &str, iterations: u32) -> String;
}

// List of Hashers:

/// Hasher that uses the PBKDF2 key-derivation function with the SHA256 hashing algorithm.
#[cfg(feature="with_pbkdf2")]
pub struct PBKDF2Hasher;

#[cfg(feature="with_pbkdf2")]
impl Hasher for PBKDF2Hasher {
    fn verify(&self, password: &str, encoded: &str) -> Result<bool, HasherError> {
        let mut encoded_part = encoded.split('$').skip(1);
        let iterations = encoded_part.next().ok_or(HasherError::BadHash)?
            .parse::<u32>().map_err(|_| HasherError::InvalidIterations)?;
        let salt = encoded_part.next().ok_or(HasherError::BadHash)?;
        let hash = encoded_part.next().ok_or(HasherError::BadHash)?;
        Ok(crypto_utils::safe_eq(hash, crypto_utils::hash_pbkdf2_sha256(password, salt, iterations)))
    }

    fn encode(&self, password: &str, salt: &str, iterations: u32) -> String {
        let hash = crypto_utils::hash_pbkdf2_sha256(password, salt, iterations);
        format!("{}${}${}${}", "pbkdf2_sha256", iterations, salt, hash)
    }
}

/// Hasher that uses the PBKDF2 key-derivation function with the SHA1 hashing algorithm.
#[cfg(feature="with_pbkdf2")]
pub struct PBKDF2SHA1Hasher;

#[cfg(feature="with_pbkdf2")]
impl Hasher for PBKDF2SHA1Hasher {
    fn verify(&self, password: &str, encoded: &str) -> Result<bool, HasherError> {
        let mut encoded_part = encoded.split('$').skip(1);
        let iterations = encoded_part.next().ok_or(HasherError::BadHash)?
            .parse::<u32>().map_err(|_| HasherError::InvalidIterations)?;
        let salt = encoded_part.next().ok_or(HasherError::BadHash)?;
        let hash = encoded_part.next().ok_or(HasherError::BadHash)?;
        Ok(crypto_utils::safe_eq(hash, crypto_utils::hash_pbkdf2_sha1(password, salt, iterations)))
    }

    fn encode(&self, password: &str, salt: &str, iterations: u32) -> String {
        let hash = crypto_utils::hash_pbkdf2_sha1(password, salt, iterations);
        format!("{}${}${}${}", "pbkdf2_sha1", iterations, salt, hash)
    }
}

/// Hasher that uses the Argon2 function (new in Django 1.10).
#[cfg(feature="with_argon2")]
pub struct Argon2Hasher;

#[cfg(feature="with_argon2")]
const OLD_ARGON2_VERSION: u32 = 0x10;
#[cfg(feature="with_argon2")]
const NEW_ARGON2_VERSION: u32 = 0x13;

#[cfg(feature="with_argon2")]
impl Hasher for Argon2Hasher {
    fn verify(&self, password: &str, encoded: &str) -> Result<bool, HasherError> {
        let encoded_part: Vec<&str> = encoded.split('$').collect();
        let version = match encoded_part.len() {
            6 => NEW_ARGON2_VERSION,
            5 => OLD_ARGON2_VERSION,
            _ => return Err(HasherError::BadHash),
        };
        let segment_shift = 6 - encoded_part.len();
        let settings = encoded_part[3 - segment_shift];
        let salt = encoded_part[4 - segment_shift];
        let string_hash = encoded_part[5 - segment_shift].replace('+', "-");
        let hash = string_hash.as_str();
        let settings_part: Vec<&str> = settings.split(',').collect();
        let memory_cost: u32 = settings_part[0].split('=').collect::<Vec<&str>>()[1].parse::<u32>().unwrap();
        let time_cost: u32 = settings_part[1].split('=').collect::<Vec<&str>>()[1].parse::<u32>().unwrap();
        let parallelism: u32 = settings_part[2].split('=').collect::<Vec<&str>>()[1].parse::<u32>().unwrap();

        // Django's implementation expects a Base64-encoded salt, if it is not, return an error:
        match base64::decode_config(salt, base64::URL_SAFE_NO_PAD) {
            Ok(_) => {},
            Err(_) => return Err(HasherError::InvalidArgon2Salt)
        };

        // Argon2 has a flexible hash length:
        let hash_length = match base64::decode_config(hash, base64::URL_SAFE_NO_PAD) {
            Ok(value) => value.len() as u32,
            Err(_) => return Ok(false)
        };

        Ok(crypto_utils::safe_eq(hash, crypto_utils::hash_argon2(password, salt, time_cost, memory_cost, parallelism, version, hash_length)))
    }

    fn encode(&self, password: &str, salt: &str, _: u32) -> String {
        // "Profile 1": Settings used in Django 1.10: This may change in the
        // future, if so, use the "iterations" parameter as a profile input,
        // and match against it:
        let memory_cost: u32 = 512;  // "kib" in Argon2's lingo.
        let time_cost: u32 = 2;  // "passes" in Argon2's lingo.
        let parallelism: u32 = 2;  // "lanes" in Argon2's lingo.
        let version: u32 = NEW_ARGON2_VERSION;
        let hash_length: u32 = 16;
        let hash = crypto_utils::hash_argon2(password, salt, time_cost, memory_cost, parallelism, version, hash_length);
        format!("argon2$argon2i$v=19$m={},t={},p={}${}${}", memory_cost, time_cost, parallelism, salt, hash)
    }

}

/// Hasher that uses the bcrypt key-derivation function with the password padded with SHA256.
#[cfg(feature="with_bcrypt")]
pub struct BCryptSHA256Hasher;

#[cfg(feature="with_bcrypt")]
impl Hasher for BCryptSHA256Hasher {
    fn verify(&self, password: &str, encoded: &str) -> Result<bool, HasherError> {
        let bcrypt_encoded_part: Vec<&str> = encoded.splitn(2, '$').collect();
        let hash = bcrypt_encoded_part[1];
        let hashed_password = crypto_utils::hash_sha256(password);
        match bcrypt::verify(&hashed_password, hash) {
            Ok(valid) => Ok(valid),
            Err(_) => Ok(false)
        }
    }

    fn encode(&self, password: &str, _: &str, iterations: u32) -> String {
        let hashed_password = crypto_utils::hash_sha256(password);
        let hash = bcrypt::hash(&hashed_password, iterations).unwrap();
        format!("{}${}", "bcrypt_sha256", hash)
    }
}

/// Hasher that uses the bcrypt key-derivation function without password padding.
#[cfg(feature="with_bcrypt")]
pub struct BCryptHasher;

#[cfg(feature="with_bcrypt")]
impl Hasher for BCryptHasher {
    fn verify(&self, password: &str, encoded: &str) -> Result<bool, HasherError> {
        let bcrypt_encoded_part: Vec<&str> = encoded.splitn(2, '$').collect();
        let hash = bcrypt_encoded_part[1];
        match bcrypt::verify(password, hash) {
            Ok(valid) => Ok(valid),
            Err(_) => Ok(false)
        }
    }

    fn encode(&self, password: &str, _: &str, iterations: u32) -> String {
        let hash = bcrypt::hash(password, iterations).unwrap();
        format!("{}${}", "bcrypt", hash)
    }
}

/// Hasher that uses the SHA1 hashing function over the salted password.
#[cfg(feature="with_legacy")]
pub struct SHA1Hasher;

#[cfg(feature="with_legacy")]
impl Hasher for SHA1Hasher {
    fn verify(&self, password: &str, encoded: &str) -> Result<bool, HasherError> {
        let mut encoded_part = encoded.split('$').skip(1);
        let salt = encoded_part.next().ok_or(HasherError::BadHash)?;
        let hash = encoded_part.next().ok_or(HasherError::BadHash)?;
        Ok(crypto_utils::safe_eq(hash, crypto_utils::hash_sha1(password, salt)))
    }

    fn encode(&self, password: &str, salt: &str, _: u32) -> String {
        let hash = crypto_utils::hash_sha1(password, salt);
        format!("{}${}${}", "sha1", salt, hash)
    }
}

/// Hasher that uses the MD5 hashing function over the salted password.
#[cfg(feature="with_legacy")]
pub struct MD5Hasher;

#[cfg(feature="with_legacy")]
impl Hasher for MD5Hasher {
    fn verify(&self, password: &str, encoded: &str) -> Result<bool, HasherError> {
        let mut encoded_part = encoded.split('$').skip(1);
        let salt = encoded_part.next().ok_or(HasherError::BadHash)?;
        let hash = encoded_part.next().ok_or(HasherError::BadHash)?;
        Ok(crypto_utils::safe_eq(hash, crypto_utils::hash_md5(password, salt)))
    }

    fn encode(&self, password: &str, salt: &str, _: u32) -> String {
        let hash = crypto_utils::hash_md5(password, salt);
        format!("{}${}${}", "md5", salt, hash)
    }
}

/// Hasher that uses the SHA1 hashing function with no salting.
#[cfg(feature="with_legacy")]
pub struct UnsaltedSHA1Hasher;

#[cfg(feature="with_legacy")]
impl Hasher for UnsaltedSHA1Hasher {
    fn verify(&self, password: &str, encoded: &str) -> Result<bool, HasherError> {
        let mut encoded_part = encoded.split('$').skip(2);
        let hash = encoded_part.next().ok_or(HasherError::BadHash)?;
        Ok(crypto_utils::safe_eq(hash, crypto_utils::hash_sha1(password, "")))
    }

    fn encode(&self, password: &str, _: &str, _: u32) -> String {
        let hash = crypto_utils::hash_sha1(password, "");
        format!("{}$${}", "sha1", hash)
    }
}

/// Hasher that uses the MD5 hashing function with no salting.
#[cfg(feature="with_legacy")]
pub struct UnsaltedMD5Hasher;

#[cfg(feature="with_legacy")]
impl Hasher for UnsaltedMD5Hasher {
    fn verify(&self, password: &str, encoded: &str) -> Result<bool, HasherError> {
        Ok(crypto_utils::safe_eq(encoded, crypto_utils::hash_md5(password, "")))
    }

    fn encode(&self, password: &str, _: &str, _: u32) -> String {
        crypto_utils::hash_md5(password, "").to_string()
    }
}

/// Hasher that uses the UNIX's crypt(3) hash function.
#[cfg(feature="with_legacy")]
pub struct CryptHasher;

#[cfg(feature="with_legacy")]
impl Hasher for CryptHasher {
    fn verify(&self, password: &str, encoded: &str) -> Result<bool, HasherError> {
        let mut encoded_part = encoded.split('$').skip(2);
        let hash = encoded_part.next().ok_or(HasherError::BadHash)?;
        Ok(crypto_utils::safe_eq(hash, crypto_utils::hash_unix_crypt(password, hash)))
    }

    fn encode(&self, password: &str, salt: &str, _: u32) -> String {
        let hash = crypto_utils::hash_unix_crypt(password, salt);
        format!("{}$${}", "crypt", hash)
    }
}