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
// MIT License

// Copyright (c) 2018-2019 The orion Developers

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

//! Password hashing and verification.
//!
//! # Use case:
//! `orion::pwhash` is suitable for securely storing passwords.
//!
//! An example of this would be needing to store user passwords (from a sign-up
//! at a webstore) in a server database,
//! where a potential disclosure of the data in this database should not result
//! in the user's actual passwords being disclosed as well.
//!
//! # About:
//! - Uses PBKDF2-HMAC-SHA512.
//! - A salt of 64 bytes is automatically generated.
//! - The password hash length is set to 64.
//!
//! The first 64 bytes of the `PasswordHash` returned by `pwhash::hash_password`
//! is the salt used to hash the password and the last 64 bytes is the actual
//! hashed password. When using this function with
//! `pwhash::hash_password_verify()`, then the separation of the salt and the
//! password hash is automatically handled.
//!
//! # Parameters:
//! - `password`: The password to be hashed.
//! - `expected_with_salt`: The expected password hash with the corresponding
//!   salt prepended.
//! - `iterations`: The number of iterations performed by PBKDF2, i.e. the cost
//!   parameter.
//!
//! # Errors:
//! An error will be returned if:
//! - `iterations` is 0.
//! - The `expected_with_salt` is not constructed exactly as in
//!   `pwhash::hash_password`.
//! - The password hash does not match `expected_with_salt`.
//!
//! # Panics:
//! A panic will occur if:
//! - The `OsRng` fails to initialize or read from its source.
//!
//! # Security:
//! - The iteration count should be set as high as feasible. The recommended
//!   minimum is 100000.
//!
//! # Example:
//! ```rust
//! use orion::pwhash;
//!
//! let password = pwhash::Password::from_slice(b"Secret password")?;
//!
//! let hash = pwhash::hash_password(&password, 100000)?;
//! assert!(pwhash::hash_password_verify(&hash, &password, 100000)?);
//! # Ok::<(), orion::errors::UnknownCryptoError>(())
//! ```

pub use crate::hltypes::{Password, PasswordHash, Salt};
use crate::{errors::UnknownCryptoError, hazardous::kdf::pbkdf2};
use zeroize::Zeroize;

#[must_use]
/// Hash a password using PBKDF2-HMAC-SHA512.
pub fn hash_password(
	password: &Password,
	iterations: usize,
) -> Result<PasswordHash, UnknownCryptoError> {
	let mut buffer = [0u8; 128];
	// Cannot panic as this is a valid size.
	let salt = Salt::generate(64).unwrap();

	buffer[..64].copy_from_slice(salt.as_ref());
	pbkdf2::derive_key(
		&pbkdf2::Password::from_slice(password.unprotected_as_bytes())?,
		salt.as_ref(),
		iterations,
		&mut buffer[64..],
	)?;

	let dk = PasswordHash::from_slice(&buffer)?;
	buffer.zeroize();

	Ok(dk)
}

#[must_use]
/// Hash and verify a password using PBKDF2-HMAC-SHA512.
pub fn hash_password_verify(
	expected_with_salt: &PasswordHash,
	password: &Password,
	iterations: usize,
) -> Result<bool, UnknownCryptoError> {
	let mut dk = [0u8; 64];

	let is_good = pbkdf2::verify(
		&expected_with_salt.unprotected_as_bytes()[64..],
		&pbkdf2::Password::from_slice(password.unprotected_as_bytes())?,
		&expected_with_salt.unprotected_as_bytes()[..64],
		iterations,
		&mut dk,
	)?;

	dk.zeroize();

	Ok(is_good)
}

// Testing public functions in the module.
#[cfg(test)]
mod public {
	use super::*;

	mod test_pwhash_and_verify {
		use super::*;

		#[test]
		fn test_pbkdf2_verify() {
			let password = Password::from_slice(&[0u8; 64]).unwrap();

			let pbkdf2_dk = hash_password(&password, 100).unwrap();

			assert_eq!(
				hash_password_verify(&pbkdf2_dk, &password, 100).unwrap(),
				true
			);
		}

		#[test]
		fn test_pbkdf2_verify_err_modified_salt() {
			let password = Password::from_slice(&[0u8; 64]).unwrap();

			let pbkdf2_dk = hash_password(&password, 100).unwrap();
			let mut pwd_mod = pbkdf2_dk.unprotected_as_bytes().to_vec();
			pwd_mod[0..32].copy_from_slice(&[0u8; 32]);
			let modified = PasswordHash::from_slice(&pwd_mod).unwrap();

			assert!(hash_password_verify(&modified, &password, 100).is_err());
		}

		#[test]
		fn test_pbkdf2_verify_err_modified_password() {
			let password = Password::from_slice(&[0u8; 64]).unwrap();

			let pbkdf2_dk = hash_password(&password, 100).unwrap();
			let mut pwd_mod = pbkdf2_dk.unprotected_as_bytes().to_vec();
			pwd_mod[120..128].copy_from_slice(&[0u8; 8]);
			let modified = PasswordHash::from_slice(&pwd_mod).unwrap();

			assert!(hash_password_verify(&modified, &password, 100).is_err());
		}

		#[test]
		fn test_pbkdf2_verify_err_modified_salt_and_password() {
			let password = Password::from_slice(&[0u8; 64]).unwrap();

			let pbkdf2_dk = hash_password(&password, 100).unwrap();
			let mut pwd_mod = pbkdf2_dk.unprotected_as_bytes().to_vec();
			pwd_mod[64..96].copy_from_slice(&[0u8; 32]);
			let modified = PasswordHash::from_slice(&pwd_mod).unwrap();

			assert!(hash_password_verify(&modified, &password, 100).is_err());
		}

		#[test]
		fn test_pbkdf2_zero_iterations() {
			let password = Password::from_slice(&[0u8; 64]).unwrap();

			assert!(hash_password(&password, 0).is_err());
		}
	}

	// Proptests. Only exectued when NOT testing no_std.
	#[cfg(feature = "safe_api")]
	mod proptest {
		use super::*;

		quickcheck! {
			/// Hashing and verifying the same password should always be true.
			fn prop_pwhash_verify(input: Vec<u8>) -> bool {
				let passin = if input.is_empty() {
					vec![1u8; 10]
				} else {
					input
				};

				let pass = Password::from_slice(&passin[..]).unwrap();
				let pass_hash = hash_password(&pass, 100).unwrap();

				if hash_password_verify(&pass_hash, &pass, 100).is_ok() {
					true
				} else {
					false
				}
			}
		}

		quickcheck! {
			/// Hashing and verifying different passwords should always be false.
			fn prop_pwhash_verify_false(input: Vec<u8>) -> bool {
				let passin = if input.is_empty() {
					vec![1u8; 10]
				} else {
					input
				};

				let pass = Password::from_slice(&passin[..]).unwrap();
				let pass_hash = hash_password(&pass, 100).unwrap();
				let bad_pass = Password::generate(32).unwrap();

				if hash_password_verify(&pass_hash, &bad_pass, 100).is_err() {
					true
				} else {
					false
				}
			}
		}
	}
}