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
//! Standard *BSD hash. // // Copyright (c) 2016 Ivan Nejgebauer <inejge@gmail.com> // // Licensed under the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>. This file may not be copied, // modified, or distributed except according to the terms of this // license. //! //! Bcrypt is a hashing algorithm based on the Blowfish stream cipher, //! originally developed for OpenBSD and since adopted on other BSD //! variants and other systems. It has a large salt, variable number //! of rounds, and no known weaknesses. //! //! # Examples //! //! To hash a password with a randomly generated salt, default cost, //! and default output variant (__2b__): //! //! ``` //! use pwhash::bcrypt; //! //! let hash = bcrypt::hash("password").unwrap(); //! ``` //! //! To use a different variant (__2y__), while letting the program //! pick the salt and use the default cost: //! //! ``` //! use pwhash::bcrypt::{self, BcryptSetup, BcryptVariant}; //! //! let hash = bcrypt::hash_with(BcryptSetup { //! variant: Some(BcryptVariant::V2y), //! ..Default::default() }, //! "password").unwrap(); //! ``` //! //! # Parameters //! //! * __Password length__: up to 72 characters. Longer passwords are //! truncated to the maximum length. //! //! * __Salt length__: 16 random bytes, encoded as 22 Base64 characters. //! //! * __Cost__: logarithmic value between 4 and 31, inclusive. Increasing //! the value by 1 doubles the amount of work. The default is 8. //! //! # Hash Format //! //! The format of the hash is //! **`$`**_`{variant}`_**`$`**_`{cost}`_**`$`**_`{salt}{checksum}`_, where: //! //! * _`{variant}`_ is one of **2a**, **2b**, or **2y**. The default is **2b**. //! The actual computation is the same for all three variants; the choice //! exists in order to retain compatibility with other software. See //! [`BcryptVariant`](enum.BcryptVariant.html) for details. //! //! * _`{cost}`_ is a two-digit decimal cost value between 4 and 31. Values //! below 10 have a leading zero. //! //! * _`{salt}`_ is a 22-character Base64 encoding of the 16 bytes of salt. The //! salt must be exactly this long. //! //! * _`{checksum}`_ is a 31-character Base64 encoding of the computed hash. use super::{Result, HashSetup, consteq}; use enc_dec::{bcrypt_hash64_encode,bcrypt_hash64_decode}; use error::Error; use random; use parse::{self, HashIterator}; use std::{iter, fmt}; use std::cmp::min; use std::default::Default; use crypto::bcrypt::bcrypt; const MAX_PASS_LEN: usize = 72; const DEFAULT_VARIANT: BcryptVariant = BcryptVariant::V2b; const ENC_SALT_LEN: usize = 22; /// Minimum cost. pub const MIN_COST: u32 = 4; /// Maximum cost. pub const MAX_COST: u32 = 31; /// Default cost. pub const DEFAULT_COST: u32 = 8; /// Identifiers of algorithm variants which can be produced. /// /// Bcrypt has a long history of use, during which a number bugs were found /// and fixed in the widely-used implementations. Some bugs were serious /// enough to warrant a change in the minor version number of the algorithm /// identifier. /// /// There are two major bcrypt implementations: OpenBSD (the original, used in /// all *BSDs) and Openwall. A short history of variants is as follows: /// /// * **2** is the original OpenBSD version, which was very quickly replaced by /// /// * **2a**, which fixed a bug that caused passwords with repeated strings to /// produce the same hash as those with a single string ("abab" hashed the same /// as "ab".) This was the most widely used version, until /// /// * **2y**, produced by Openwall, which fixed a sign-extension bug that /// caused certain passwords with high-bit-set characters to produce weak keys. /// OpenBSD didn't have this bug, and their logic can transparently handle the /// **2y** hashes. The Openwall fix also introduced /// /// * **2x**, meant for unambiguously identifying pre-fix **2a** hashes as /// those produced by the buggy algorithm. OpenBSD doesn't treat **2x** hashes /// specially, which means that it won't be able to verify buggy hashes. Some /// time later, a wraparound bug was found in OpenBSD, leading to /// /// * **2b**, which fixed the bug. As the problem involved unrealistically long /// passwords, the bug was, fortunately, mostly theoretical. This variant is the /// current default in most implementations. /// /// This crate has a single bcrypt algorithm implementation which is equivalent /// to the **2b** variant. It accepts **2a** and **2y** on input, and can /// generate both on output, but doesn't treat them specially in any way. pub enum BcryptVariant { /// Second OpenBSD variant, fixed repeated string hashing. V2a, /// Third OpenBSD variant, fixed a wraparound bug. V2b, /// Openwall variant, fixed a sign extension bug. V2y, } impl fmt::Display for BcryptVariant { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", match *self { BcryptVariant::V2a => "2a", BcryptVariant::V2b => "2b", BcryptVariant::V2y => "2y", }) } } /// Setup struct for bcrypt. /// /// In addition to custom salt and cost values, a bcrypt hash can use different /// algorithm variant identifiers. pub struct BcryptSetup<'a> { /// Custom salt. pub salt: Option<&'a str>, /// Custom cost. pub cost: Option<u32>, /// Algorithm variant. pub variant: Option<BcryptVariant>, } /// A trait for converting a type into a `BcryptSetup` struct. pub trait IntoBcryptSetup<'a> { /// The conversion function. fn into_bcrypt_setup(self) -> Result<BcryptSetup<'a>>; } const MAGIC_LEN: usize = 4; impl<'a> IntoBcryptSetup<'a> for &'a str { fn into_bcrypt_setup(self) -> Result<BcryptSetup<'a>> { let mut hs = parse::HashSlice::new(self); let variant = match hs.take(MAGIC_LEN).unwrap_or("X") { "$2a$" => BcryptVariant::V2a, "$2b$" => BcryptVariant::V2b, "$2y$" => BcryptVariant::V2y, _ => return Err(Error::InvalidHashString), }; let cost = if let Some(cost_str) = hs.take_until(b'$') { if cost_str.len() != 2 { return Err(Error::InvalidHashString); } let cost = cost_str.parse::<u32>().map_err(|_e| Error::InvalidRounds)?; if cost < 10 && !cost_str.starts_with('0') { return Err(Error::InvalidHashString); } cost } else { return Err(Error::InvalidHashString); }; let salt = if let Some(salt) = hs.take(ENC_SALT_LEN) { salt } else { return Err(Error::InvalidHashString); }; Ok(BcryptSetup { salt: Some(salt), cost: Some(cost), variant: Some(variant) }) } } impl<'a> IntoBcryptSetup<'a> for HashSetup<'a> { fn into_bcrypt_setup(self) -> Result<BcryptSetup<'a>> { Ok(BcryptSetup { salt: self.salt, cost: self.rounds, variant: Some(DEFAULT_VARIANT) }) } } impl<'a> IntoBcryptSetup<'a> for BcryptSetup<'a> { fn into_bcrypt_setup(self) -> Result<BcryptSetup<'a>> { Ok(self) } } impl<'a> Default for BcryptSetup<'a> { fn default() -> Self { BcryptSetup { salt: None, cost: Some(DEFAULT_COST), variant: Some(DEFAULT_VARIANT) } } } fn do_bcrypt(pass: &[u8], salt: &[u8], cost: u32, variant: BcryptVariant) -> Result<String> { let mut upd_pass = pass.iter().map(|b| *b).chain(iter::repeat(0u8)).take(min(pass.len() + 1, MAX_PASS_LEN)).collect::<Vec<_>>(); let mut output = [0u8; 24]; bcrypt(cost, &salt, &upd_pass[..], &mut output); for b in &mut upd_pass { *b = 0u8; } Ok(format!("${}${:02}${}{}", variant, cost, bcrypt_hash64_encode(&salt), bcrypt_hash64_encode(&output[..23]))) } /// Hash a password with a randomly generated salt, default cost, /// and default variant. /// /// An error is returned if the system random number generator cannot /// be opened. pub fn hash<B: AsRef<[u8]>>(pass: B) -> Result<String> { let mut salt_buf = [0u8; 16]; random::gen_salt_bytes(&mut salt_buf)?; do_bcrypt(pass.as_ref(), &salt_buf, DEFAULT_COST, DEFAULT_VARIANT) } /// Hash a password with user-provided parameters. /// /// Bcrypt has its own setup struct because of the additional variant /// field. An ordinary `HashSetup` can be converted into `BcryptSetup`, which /// will set the variant to default. The `Default` trait is implemented for /// `BcryptSetup`, which makes it easier to initialize just the desired /// fields (see the module-level example.) pub fn hash_with<'a, IBS, B>(param: IBS, pass: B) -> Result<String> where IBS: IntoBcryptSetup<'a>, B: AsRef<[u8]> { let bs = param.into_bcrypt_setup()?; let cost = if let Some(c) = bs.cost { if c < MIN_COST || c > MAX_COST { return Err(Error::InvalidRounds); } c } else { DEFAULT_COST }; let variant = if let Some(v) = bs.variant { v } else { DEFAULT_VARIANT }; let mut salt_buf = [0u8; 16]; if bs.salt.is_some() { bcrypt_hash64_decode(bs.salt.unwrap(), &mut salt_buf)?; } else { random::gen_salt_bytes(&mut salt_buf)?; } do_bcrypt(pass.as_ref(), &salt_buf, cost, variant) } /// Verify that the hash corresponds to a password. pub fn verify<B: AsRef<[u8]>>(pass: B, hash: &str) -> bool { consteq(hash, hash_with(hash, pass)) } #[cfg(test)] mod tests { use super::{BcryptSetup, BcryptVariant}; #[test] fn variant() { assert_eq!("$2y$05$bvIG6Nmid91Mu9RcmmWZfO5HJIMCT8riNW0hEp8f6/FuA2/mHZFpe", super::hash_with(BcryptSetup { salt: Some("bvIG6Nmid91Mu9RcmmWZfO"), cost: Some(5), variant: Some(BcryptVariant::V2y) }, "password").unwrap()); } }