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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
//! Password authentication module.
//!
//! It allows you to:
//!
//! - generate a fingerprint of the password that could be stored;
//! - check a password against the stored fingerprint.
//!
//!
//! ## Standards
//!
//! By default, LibreAuth has security in mind and therefore provides a decent level of security.
//!
//! Sometimes, you may be required to comply with industry or government standards. To ease such
//! requirements, LibreAuth is able to adapt itself to some standards. Please note such modes does
//! not automatically guaranty you compliance, you may have other items to check.
//!
//! ## Storage format
//!
//! The password fingerprint is stored in the [PHC] format which is very close to the modular crypt format (cf. [[1]] and [[2]]).
//!
//! ## Supported identifiers and parameters
//!
//! <table>
//!     <thead>
//!         <tr>
//!             <th>Algorithm</th>
//!             <th>Parameter name</th>
//!             <th>Parameter type</th>
//!             <th>Parameter description</th>
//!             <th>Default value</th>
//!         </tr>
//!     </thead>
//!     <tbody>
//!         <tr>
//!             <td rowspan="7">Global parameters</td>
//!             <td>len-calc</td>
//!             <td>string: bytes | chars</td>
//!             <td>Unicode string length calculation method.</td>
//!             <td>chars</td>
//!         </tr>
//!         <tr>
//!             <td>norm</td>
//!             <td>string: nfd | nfkd | nfc | nfkc | none</td>
//!             <td>Unicode normalization.</td>
//!             <td>nfkc</td>
//!         </tr>
//!         <tr>
//!             <td>pmax</td>
//!             <td>integer</td>
//!             <td>Password maximal length.</td>
//!             <td>128</td>
//!         </tr>
//!         <tr>
//!             <td>pmin</td>
//!             <td>integer</td>
//!             <td>Password minimal length.</td>
//!             <td>8</td>
//!         </tr>
//!         <tr>
//!             <td>ver</td>
//!             <td>integer</td>
//!             <td>The password hashing version.</td>
//!             <td>Sum of the user-defined and internal version numbers.</td>
//!         </tr>
//!         <tr>
//!             <td>xhmac</td>
//!             <td>string: none | before | after</td>
//!             <td>If not none, apply an additional HMAC with an external pepper before or after hashing the password.</td>
//!             <td>none</td>
//!         </tr>
//!         <tr>
//!             <td>xhmac-alg</td>
//!             <td>string: sha1 | sha224 | sha256 | sha384 | sha512 | sha512t224 | sha512t256 | keccak224 | keccak256 | keccak384 | keccak512 | sha3-224 | sha3-256 | sha3-384 | sha3-512</td>
//!             <td>The underlying hash function to use for the HMAC.</td>
//!             <td>sha512</td>
//!         </tr>
//!         <tr>
//!             <td rowspan="4">argon2</td>
//!             <td>lanes</td>
//!             <td>integer</td>
//!             <td>The degree of parallelism by which memory is filled during hash computation.</td>
//!             <td>4</td>
//!         </tr>
//!         <tr>
//!             <td>len</td>
//!             <td>integer</td>
//!             <td>Output length, in bytes.</td>
//!             <td>128</td>
//!         </tr>
//!         <tr>
//!             <td>mem</td>
//!             <td>integer</td>
//!             <td>Memmory cost (2^mem kibbibytes).</td>
//!             <td>12 (4096 KiB)</td>
//!         </tr>
//!         <tr>
//!             <td>passes</td>
//!             <td>integer</td>
//!             <td>The number of block matrix iterations to perform.</td>
//!             <td>3</td>
//!         </tr>
//!         <tr>
//!             <td rowspan="2">pbkdf2</td>
//!             <td>hmac</td>
//!             <td>string: sha1 | sha224 | sha256 | sha384 | sha512 | sha512t224 | sha512t256 | keccak224 | keccak256 | keccak384 | keccak512 | sha3-224 | sha3-256 | sha3-384 | sha3-512</td>
//!             <td>The underlying hash function to use for the HMAC.</td>
//!             <td>sha512</td>
//!         </tr>
//!         <tr>
//!             <td>iter</td>
//!             <td>integer</td>
//!             <td>Number of iterations.</td>
//!             <td>45000</td>
//!         </tr>
//!     </tbody>
//! </table>
//!
//! ## Examples
//! ```rust
//! use libreauth::pass::HashBuilder;
//!
//! const PWD_SCHEME_VERSION: usize = 1;
//!
//! // Hashing a password.
//! let password = "correct horse battery staple";
//! let hasher = HashBuilder::new().version(PWD_SCHEME_VERSION).finalize().unwrap();
//! let stored_password = hasher.hash(password).unwrap();
//! // Store the result in the database.
//!
//! // Checking a password against a previously hashed one.
//! let checker = HashBuilder::from_phc(stored_password.as_str()).unwrap();
//! assert!(!checker.is_valid("bad password"));
//! assert!(checker.is_valid(password));
//! if checker.is_valid(password) && checker.needs_update(Some(PWD_SCHEME_VERSION)) {
//!   // The password hashing scheme has been updated since we stored this
//!   // password. Hence, We should hash it again and update the database.
//! }
//! ```
//!
//! [PHC]: https://github.com/P-H-C/phc-string-format/blob/master/phc-sf-spec.md
//! [1]: https://en.wikipedia.org/wiki/Crypt_(C)#Key_Derivation_Functions_Supported_by_crypt
//! [2]: https://pythonhosted.org/passlib/modular_crypt_format.html

macro_rules! set_normalization {
    ($obj: ident, $attr: ident, $val: ident, $name: expr) => {
        $val.insert(
            $name,
            match $obj.$attr {
                Normalization::Nfd => "nfd".to_string(),
                Normalization::Nfkd => "nfkd".to_string(),
                Normalization::Nfc => "nfc".to_string(),
                Normalization::Nfkc => "nfkc".to_string(),
                Normalization::None => "none".to_string(),
            },
        );
    };
}

pub(crate) mod argon2;
#[cfg(feature = "cbindings")]
mod cbindings;
mod error;
mod hash_builder;
mod hasher;
pub(crate) mod pbkdf2;
mod phc;
pub(crate) mod std_default;
pub(crate) mod std_nist;
#[cfg(test)]
mod tests;

#[cfg(feature = "cbindings")]
pub use self::cbindings::libreauth_pass_hash;
#[cfg(feature = "cbindings")]
pub use self::cbindings::libreauth_pass_init;
#[cfg(feature = "cbindings")]
pub use self::cbindings::libreauth_pass_init_from_phc;
#[cfg(feature = "cbindings")]
pub use self::cbindings::libreauth_pass_init_std;
#[cfg(feature = "cbindings")]
pub use self::cbindings::libreauth_pass_is_valid;
#[cfg(feature = "cbindings")]
pub use self::cbindings::PassCfg;
#[cfg(feature = "cbindings")]
pub use self::cbindings::XHMACType;
pub use self::error::Error;
pub use error::ErrorCode;
pub use hash_builder::HashBuilder;
pub use hasher::Hasher;
use std::collections::HashMap;
use std::fmt;

const INTERNAL_VERSION: usize = 1;
const DEFAULT_USER_VERSION: usize = 0;

/// The recommended length to reserve for password hash storage.
///
/// Most applications will store passwords hash within a database which requires a fixed space.
/// This value represents the size such a fixed reserved space should be. It is intentionally
/// higher than needed in order to accept future improvements.
///
/// ## C interface
/// The C interface refers at this constant as `LIBREAUTH_PASSWORD_STORAGE_LEN`.
pub const PASSWORD_STORAGE_LEN: usize = 512;

/// Algorithms available to hash the password.
///
/// ## C interface
/// The C interface uses an enum of type `libreauth_pass_algo` and the members has been renamed
/// as follows:
/// <table>
///     <thead>
///         <tr>
///             <th>Rust</th>
///             <th>C</th>
///         </tr>
///     </thead>
///     <tbody>
///         <tr>
///             <td>Argon2</td>
///             <td>LIBREAUTH_PASS_ARGON2</td>
///         </tr>
///         <tr>
///             <td>Pbkdf2</td>
///             <td>LIBREAUTH_PASS_PBKDF2</td>
///         </tr>
///     </tbody>
/// </table>
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub enum Algorithm {
    Argon2 = 0,
    Pbkdf2 = 1,
}

/// Available methods to calculate the length of a UTF-8 string.
///
/// ## C interface
/// The C interface uses an enum of type `libreauth_pass_len_calc` and the members has been renamed
/// as follows:
/// <table>
///     <thead>
///         <tr>
///             <th>Rust</th>
///             <th>C</th>
///         </tr>
///     </thead>
///     <tbody>
///         <tr>
///             <td>Bytes</td>
///             <td>LIBREAUTH_PASS_BYTES</td>
///         </tr>
///         <tr>
///             <td>Characters</td>
///             <td>LIBREAUTH_PASS_CHARACTERS</td>
///         </tr>
///     </tbody>
/// </table>
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LengthCalculationMethod {
    Bytes = 0,
    Characters = 1,
}

/// Available string normalization methods.
///
/// ## C interface
/// The C interface uses an enum of type `libreauth_pass_normalization` and the members has been renamed
/// as follows:
/// <table>
///     <thead>
///         <tr>
///             <th>Rust</th>
///             <th>C</th>
///         </tr>
///     </thead>
///     <tbody>
///         <tr>
///             <td>Nfd</td>
///             <td>LIBREAUTH_PASS_NFD</td>
///         </tr>
///         <tr>
///             <td>Nfkd</td>
///             <td>LIBREAUTH_PASS_NFKD</td>
///         </tr>
///         <tr>
///             <td>Nfc</td>
///             <td>LIBREAUTH_PASS_NFC</td>
///         </tr>
///         <tr>
///             <td>Nfkc</td>
///             <td>LIBREAUTH_PASS_NFKC</td>
///         </tr>
///         <tr>
///             <td>None</td>
///             <td>LIBREAUTH_PASS_NO_NORMALIZATION</td>
///         </tr>
///     </tbody>
/// </table>
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub enum Normalization {
    Nfd = 1,
    Nfkd = 2,
    Nfc = 3,
    Nfkc = 4,
    None = 0,
}

/// Defines whether or not LibreAuth should comply with recommendations from a specific standard.
///
/// ## C interface
/// The C interface uses an enum of type `libreauth_pass_standard` and the members has been renamed
/// as follows:
/// <table>
///     <thead>
///         <tr>
///             <th>Rust</th>
///             <th>C</th>
///         </tr>
///     </thead>
///     <tbody>
///         <tr>
///             <td>NoStandard</td>
///             <td>LIBREAUTH_PASS_NOSTANDARD</td>
///         </tr>
///         <tr>
///             <td>Nist80063b</td>
///             <td>LIBREAUTH_PASS_NIST80063B</td>
///         </tr>
///     </tbody>
/// </table>
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub enum PasswordStorageStandard {
    /// Default mode of operation, safe.
    NoStandard = 0,
    /// Comply with the [NIST Special Publication 800-63B](https://pages.nist.gov/800-63-3/sp800-63b.html).
    Nist80063b = 1,
}

#[derive(Clone, Eq, PartialEq, Debug)]
#[allow(clippy::upper_case_acronyms)]
pub(crate) enum XHMAC {
    Before(Vec<u8>),
    After(Vec<u8>),
    None,
}

impl fmt::Display for XHMAC {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            XHMAC::Before(_) => "before",
            XHMAC::After(_) => "after",
            XHMAC::None => "none",
        };
        write!(f, "{}", s)
    }
}

impl XHMAC {
    pub(crate) fn is_none(&self) -> bool {
        matches!(*self, XHMAC::None)
    }

    pub(crate) fn is_some(&self) -> bool {
        !self.is_none()
    }
}

trait HashingFunction {
    fn get_id(&self) -> String;
    fn get_parameters(&self) -> HashMap<String, String>;
    fn set_parameter(&mut self, name: &str, value: &str) -> Result<(), Error>;
    fn get_salt(&self) -> Option<Vec<u8>>;
    fn set_salt(&mut self, salt: Vec<u8>) -> Result<(), Error>;
    fn set_salt_len(&mut self, salt_len: usize) -> Result<(), Error>;
    fn set_normalization(&mut self, norm: Normalization) -> Result<(), Error>;
    fn hash(&self, input: &[u8]) -> Vec<u8>;
}

struct HashedDuo {
    raw: Vec<u8>,
    formated: String,
}