Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 

1244 lignes
52 KiB

  1. """passlib.bcrypt -- implementation of OpenBSD's BCrypt algorithm.
  2. TODO:
  3. * support 2x and altered-2a hashes?
  4. http://www.openwall.com/lists/oss-security/2011/06/27/9
  5. * deal with lack of PY3-compatibile c-ext implementation
  6. """
  7. #=============================================================================
  8. # imports
  9. #=============================================================================
  10. from __future__ import with_statement, absolute_import
  11. # core
  12. from base64 import b64encode
  13. from hashlib import sha256
  14. import os
  15. import re
  16. import logging; log = logging.getLogger(__name__)
  17. from warnings import warn
  18. # site
  19. _bcrypt = None # dynamically imported by _load_backend_bcrypt()
  20. _pybcrypt = None # dynamically imported by _load_backend_pybcrypt()
  21. _bcryptor = None # dynamically imported by _load_backend_bcryptor()
  22. # pkg
  23. _builtin_bcrypt = None # dynamically imported by _load_backend_builtin()
  24. from passlib.crypto.digest import compile_hmac
  25. from passlib.exc import PasslibHashWarning, PasslibSecurityWarning, PasslibSecurityError
  26. from passlib.utils import safe_crypt, repeat_string, to_bytes, parse_version, \
  27. rng, getrandstr, test_crypt, to_unicode, \
  28. utf8_truncate, utf8_repeat_string, crypt_accepts_bytes
  29. from passlib.utils.binary import bcrypt64
  30. from passlib.utils.compat import get_unbound_method_function
  31. from passlib.utils.compat import u, uascii_to_str, unicode, str_to_uascii, PY3, error_from
  32. import passlib.utils.handlers as uh
  33. # local
  34. __all__ = [
  35. "bcrypt",
  36. ]
  37. #=============================================================================
  38. # support funcs & constants
  39. #=============================================================================
  40. IDENT_2 = u("$2$")
  41. IDENT_2A = u("$2a$")
  42. IDENT_2X = u("$2x$")
  43. IDENT_2Y = u("$2y$")
  44. IDENT_2B = u("$2b$")
  45. _BNULL = b'\x00'
  46. # reference hash of "test", used in various self-checks
  47. TEST_HASH_2A = "$2a$04$5BJqKfqMQvV7nS.yUguNcueVirQqDBGaLXSqj.rs.pZPlNR0UX/HK"
  48. def _detect_pybcrypt():
  49. """
  50. internal helper which tries to distinguish pybcrypt vs bcrypt.
  51. :returns:
  52. True if cext-based py-bcrypt,
  53. False if ffi-based bcrypt,
  54. None if 'bcrypt' module not found.
  55. .. versionchanged:: 1.6.3
  56. Now assuming bcrypt installed, unless py-bcrypt explicitly detected.
  57. Previous releases assumed py-bcrypt by default.
  58. Making this change since py-bcrypt is (apparently) unmaintained and static,
  59. whereas bcrypt is being actively maintained, and it's internal structure may shift.
  60. """
  61. # NOTE: this is also used by the unittests.
  62. # check for module.
  63. try:
  64. import bcrypt
  65. except ImportError:
  66. # XXX: this is ignoring case where py-bcrypt's "bcrypt._bcrypt" C Ext fails to import;
  67. # would need to inspect actual ImportError message to catch that.
  68. return None
  69. # py-bcrypt has a "._bcrypt.__version__" attribute (confirmed for v0.1 - 0.4),
  70. # which bcrypt lacks (confirmed for v1.0 - 2.0)
  71. # "._bcrypt" alone isn't sufficient, since bcrypt 2.0 now has that attribute.
  72. try:
  73. from bcrypt._bcrypt import __version__
  74. except ImportError:
  75. return False
  76. return True
  77. #=============================================================================
  78. # backend mixins
  79. #=============================================================================
  80. class _BcryptCommon(uh.SubclassBackendMixin, uh.TruncateMixin, uh.HasManyIdents,
  81. uh.HasRounds, uh.HasSalt, uh.GenericHandler):
  82. """
  83. Base class which implements brunt of BCrypt code.
  84. This is then subclassed by the various backends,
  85. to override w/ backend-specific methods.
  86. When a backend is loaded, the bases of the 'bcrypt' class proper
  87. are modified to prepend the correct backend-specific subclass.
  88. """
  89. #===================================================================
  90. # class attrs
  91. #===================================================================
  92. #--------------------
  93. # PasswordHash
  94. #--------------------
  95. name = "bcrypt"
  96. setting_kwds = ("salt", "rounds", "ident", "truncate_error")
  97. #--------------------
  98. # GenericHandler
  99. #--------------------
  100. checksum_size = 31
  101. checksum_chars = bcrypt64.charmap
  102. #--------------------
  103. # HasManyIdents
  104. #--------------------
  105. default_ident = IDENT_2B
  106. ident_values = (IDENT_2, IDENT_2A, IDENT_2X, IDENT_2Y, IDENT_2B)
  107. ident_aliases = {u("2"): IDENT_2, u("2a"): IDENT_2A, u("2y"): IDENT_2Y,
  108. u("2b"): IDENT_2B}
  109. #--------------------
  110. # HasSalt
  111. #--------------------
  112. min_salt_size = max_salt_size = 22
  113. salt_chars = bcrypt64.charmap
  114. # NOTE: 22nd salt char must be in restricted set of ``final_salt_chars``, not full set above.
  115. final_salt_chars = ".Oeu" # bcrypt64._padinfo2[1]
  116. #--------------------
  117. # HasRounds
  118. #--------------------
  119. default_rounds = 12 # current passlib default
  120. min_rounds = 4 # minimum from bcrypt specification
  121. max_rounds = 31 # 32-bit integer limit (since real_rounds=1<<rounds)
  122. rounds_cost = "log2"
  123. #--------------------
  124. # TruncateMixin
  125. #--------------------
  126. truncate_size = 72
  127. #--------------------
  128. # custom
  129. #--------------------
  130. # backend workaround detection flags
  131. # NOTE: these are only set on the backend mixin classes
  132. _workrounds_initialized = False
  133. _has_2a_wraparound_bug = False
  134. _lacks_20_support = False
  135. _lacks_2y_support = False
  136. _lacks_2b_support = False
  137. _fallback_ident = IDENT_2A
  138. _require_valid_utf8_bytes = False
  139. #===================================================================
  140. # formatting
  141. #===================================================================
  142. @classmethod
  143. def from_string(cls, hash):
  144. ident, tail = cls._parse_ident(hash)
  145. if ident == IDENT_2X:
  146. raise ValueError("crypt_blowfish's buggy '2x' hashes are not "
  147. "currently supported")
  148. rounds_str, data = tail.split(u("$"))
  149. rounds = int(rounds_str)
  150. if rounds_str != u('%02d') % (rounds,):
  151. raise uh.exc.MalformedHashError(cls, "malformed cost field")
  152. salt, chk = data[:22], data[22:]
  153. return cls(
  154. rounds=rounds,
  155. salt=salt,
  156. checksum=chk or None,
  157. ident=ident,
  158. )
  159. def to_string(self):
  160. hash = u("%s%02d$%s%s") % (self.ident, self.rounds, self.salt, self.checksum)
  161. return uascii_to_str(hash)
  162. # NOTE: this should be kept separate from to_string()
  163. # so that bcrypt_sha256() can still use it, while overriding to_string()
  164. def _get_config(self, ident):
  165. """internal helper to prepare config string for backends"""
  166. config = u("%s%02d$%s") % (ident, self.rounds, self.salt)
  167. return uascii_to_str(config)
  168. #===================================================================
  169. # migration
  170. #===================================================================
  171. @classmethod
  172. def needs_update(cls, hash, **kwds):
  173. # NOTE: can't convert this to use _calc_needs_update() helper,
  174. # since _norm_hash() will correct salt padding before we can read it here.
  175. # check for incorrect padding bits (passlib issue 25)
  176. if isinstance(hash, bytes):
  177. hash = hash.decode("ascii")
  178. if hash.startswith(IDENT_2A) and hash[28] not in cls.final_salt_chars:
  179. return True
  180. # TODO: try to detect incorrect 8bit/wraparound hashes using kwds.get("secret")
  181. # hand off to base implementation, so HasRounds can check rounds value.
  182. return super(_BcryptCommon, cls).needs_update(hash, **kwds)
  183. #===================================================================
  184. # specialized salt generation - fixes passlib issue 25
  185. #===================================================================
  186. @classmethod
  187. def normhash(cls, hash):
  188. """helper to normalize hash, correcting any bcrypt padding bits"""
  189. if cls.identify(hash):
  190. return cls.from_string(hash).to_string()
  191. else:
  192. return hash
  193. @classmethod
  194. def _generate_salt(cls):
  195. # generate random salt as normal,
  196. # but repair last char so the padding bits always decode to zero.
  197. salt = super(_BcryptCommon, cls)._generate_salt()
  198. return bcrypt64.repair_unused(salt)
  199. @classmethod
  200. def _norm_salt(cls, salt, **kwds):
  201. salt = super(_BcryptCommon, cls)._norm_salt(salt, **kwds)
  202. assert salt is not None, "HasSalt didn't generate new salt!"
  203. changed, salt = bcrypt64.check_repair_unused(salt)
  204. if changed:
  205. # FIXME: if salt was provided by user, this message won't be
  206. # correct. not sure if we want to throw error, or use different warning.
  207. warn(
  208. "encountered a bcrypt salt with incorrectly set padding bits; "
  209. "you may want to use bcrypt.normhash() "
  210. "to fix this; this will be an error under Passlib 2.0",
  211. PasslibHashWarning)
  212. return salt
  213. def _norm_checksum(self, checksum, relaxed=False):
  214. checksum = super(_BcryptCommon, self)._norm_checksum(checksum, relaxed=relaxed)
  215. changed, checksum = bcrypt64.check_repair_unused(checksum)
  216. if changed:
  217. warn(
  218. "encountered a bcrypt hash with incorrectly set padding bits; "
  219. "you may want to use bcrypt.normhash() "
  220. "to fix this; this will be an error under Passlib 2.0",
  221. PasslibHashWarning)
  222. return checksum
  223. #===================================================================
  224. # backend configuration
  225. # NOTE: backends are defined in terms of mixin classes,
  226. # which are dynamically inserted into the bases of the 'bcrypt' class
  227. # via the machinery in 'SubclassBackendMixin'.
  228. # this lets us load in a backend-specific implementation
  229. # of _calc_checksum() and similar methods.
  230. #===================================================================
  231. # NOTE: backend config is located down in <bcrypt> class
  232. # NOTE: set_backend() will execute the ._load_backend_mixin()
  233. # of the matching mixin class, which will handle backend detection
  234. # appended to HasManyBackends' "no backends available" error message
  235. _no_backend_suggestion = " -- recommend you install one (e.g. 'pip install bcrypt')"
  236. @classmethod
  237. def _finalize_backend_mixin(mixin_cls, backend, dryrun):
  238. """
  239. helper called by from backend mixin classes' _load_backend_mixin() --
  240. invoked after backend imports have been loaded, and performs
  241. feature detection & testing common to all backends.
  242. """
  243. #----------------------------------------------------------------
  244. # setup helpers
  245. #----------------------------------------------------------------
  246. assert mixin_cls is bcrypt._backend_mixin_map[backend], \
  247. "_configure_workarounds() invoked from wrong class"
  248. if mixin_cls._workrounds_initialized:
  249. return True
  250. verify = mixin_cls.verify
  251. err_types = (ValueError, uh.exc.MissingBackendError)
  252. if _bcryptor:
  253. err_types += (_bcryptor.engine.SaltError,)
  254. def safe_verify(secret, hash):
  255. """verify() wrapper which traps 'unknown identifier' errors"""
  256. try:
  257. return verify(secret, hash)
  258. except err_types:
  259. # backends without support for given ident will throw various
  260. # errors about unrecognized version:
  261. # os_crypt -- internal code below throws
  262. # - PasswordValueError if there's encoding issue w/ password.
  263. # - InternalBackendError if crypt fails for unknown reason
  264. # (trapped below so we can debug it)
  265. # pybcrypt, bcrypt -- raises ValueError
  266. # bcryptor -- raises bcryptor.engine.SaltError
  267. return NotImplemented
  268. except uh.exc.InternalBackendError:
  269. # _calc_checksum() code may also throw CryptBackendError
  270. # if correct hash isn't returned (e.g. 2y hash converted to 2b,
  271. # such as happens with bcrypt 3.0.0)
  272. log.debug("trapped unexpected response from %r backend: verify(%r, %r):",
  273. backend, secret, hash, exc_info=True)
  274. return NotImplemented
  275. def assert_lacks_8bit_bug(ident):
  276. """
  277. helper to check for cryptblowfish 8bit bug (fixed in 2y/2b);
  278. even though it's not known to be present in any of passlib's backends.
  279. this is treated as FATAL, because it can easily result in seriously malformed hashes,
  280. and we can't correct for it ourselves.
  281. test cases from <http://cvsweb.openwall.com/cgi/cvsweb.cgi/Owl/packages/glibc/crypt_blowfish/wrapper.c.diff?r1=1.9;r2=1.10>
  282. reference hash is the incorrectly generated $2x$ hash taken from above url
  283. """
  284. # NOTE: passlib 1.7.2 and earlier used the commented-out LATIN-1 test vector to detect
  285. # this bug; but python3's crypt.crypt() only supports unicode inputs (and
  286. # always encodes them as UTF8 before passing to crypt); so passlib 1.7.3
  287. # switched to the UTF8-compatible test vector below. This one's bug_hash value
  288. # ("$2x$...rcAS") was drawn from the same openwall source (above); and the correct
  289. # hash ("$2a$...X6eu") was generated by passing the raw bytes to python2's
  290. # crypt.crypt() using OpenBSD 6.7 (hash confirmed as same for $2a$ & $2b$).
  291. # LATIN-1 test vector
  292. # secret = b"\xA3"
  293. # bug_hash = ident.encode("ascii") + b"05$/OK.fbVrR/bpIqNJ5ianF.CE5elHaaO4EbggVDjb8P19RukzXSM3e"
  294. # correct_hash = ident.encode("ascii") + b"05$/OK.fbVrR/bpIqNJ5ianF.Sa7shbm4.OzKpvFnX1pQLmQW96oUlCq"
  295. # UTF-8 test vector
  296. secret = b"\xd1\x91" # aka "\u0451"
  297. bug_hash = ident.encode("ascii") + b"05$6bNw2HLQYeqHYyBfLMsv/OiwqTymGIGzFsA4hOTWebfehXHNprcAS"
  298. correct_hash = ident.encode("ascii") + b"05$6bNw2HLQYeqHYyBfLMsv/OUcZd0LKP39b87nBw3.S2tVZSqiQX6eu"
  299. if verify(secret, bug_hash):
  300. # NOTE: this only EVER be observed in (broken) 2a and (backward-compat) 2x hashes
  301. # generated by crypt_blowfish library. 2y/2b hashes should not have the bug
  302. # (but we check w/ them anyways).
  303. raise PasslibSecurityError(
  304. "passlib.hash.bcrypt: Your installation of the %r backend is vulnerable to "
  305. "the crypt_blowfish 8-bit bug (CVE-2011-2483) under %r hashes, "
  306. "and should be upgraded or replaced with another backend" % (backend, ident))
  307. # it doesn't have wraparound bug, but make sure it *does* verify against the correct
  308. # hash, or we're in some weird third case!
  309. if not verify(secret, correct_hash):
  310. raise RuntimeError("%s backend failed to verify %s 8bit hash" % (backend, ident))
  311. def detect_wrap_bug(ident):
  312. """
  313. check for bsd wraparound bug (fixed in 2b)
  314. this is treated as a warning, because it's rare in the field,
  315. and pybcrypt (as of 2015-7-21) is unpatched, but some people may be stuck with it.
  316. test cases from <http://www.openwall.com/lists/oss-security/2012/01/02/4>
  317. NOTE: reference hash is of password "0"*72
  318. NOTE: if in future we need to deliberately create hashes which have this bug,
  319. can use something like 'hashpw(repeat_string(secret[:((1+secret) % 256) or 1]), 72)'
  320. """
  321. # check if it exhibits wraparound bug
  322. secret = (b"0123456789"*26)[:255]
  323. bug_hash = ident.encode("ascii") + b"04$R1lJ2gkNaoPGdafE.H.16.nVyh2niHsGJhayOHLMiXlI45o8/DU.6"
  324. if verify(secret, bug_hash):
  325. return True
  326. # if it doesn't have wraparound bug, make sure it *does* handle things
  327. # correctly -- or we're in some weird third case.
  328. correct_hash = ident.encode("ascii") + b"04$R1lJ2gkNaoPGdafE.H.16.1MKHPvmKwryeulRe225LKProWYwt9Oi"
  329. if not verify(secret, correct_hash):
  330. raise RuntimeError("%s backend failed to verify %s wraparound hash" % (backend, ident))
  331. return False
  332. def assert_lacks_wrap_bug(ident):
  333. if not detect_wrap_bug(ident):
  334. return
  335. # should only see in 2a, later idents should NEVER exhibit this bug:
  336. # * 2y implementations should have been free of it
  337. # * 2b was what (supposedly) fixed it
  338. raise RuntimeError("%s backend unexpectedly has wraparound bug for %s" % (backend, ident))
  339. #----------------------------------------------------------------
  340. # check for old 20 support
  341. #----------------------------------------------------------------
  342. test_hash_20 = b"$2$04$5BJqKfqMQvV7nS.yUguNcuRfMMOXK0xPWavM7pOzjEi5ze5T1k8/S"
  343. result = safe_verify("test", test_hash_20)
  344. if result is NotImplemented:
  345. mixin_cls._lacks_20_support = True
  346. log.debug("%r backend lacks $2$ support, enabling workaround", backend)
  347. elif not result:
  348. raise RuntimeError("%s incorrectly rejected $2$ hash" % backend)
  349. #----------------------------------------------------------------
  350. # check for 2a support
  351. #----------------------------------------------------------------
  352. result = safe_verify("test", TEST_HASH_2A)
  353. if result is NotImplemented:
  354. # 2a support is required, and should always be present
  355. raise RuntimeError("%s lacks support for $2a$ hashes" % backend)
  356. elif not result:
  357. raise RuntimeError("%s incorrectly rejected $2a$ hash" % backend)
  358. else:
  359. assert_lacks_8bit_bug(IDENT_2A)
  360. if detect_wrap_bug(IDENT_2A):
  361. if backend == "os_crypt":
  362. # don't make this a warning for os crypt (e.g. openbsd);
  363. # they'll have proper 2b implementation which will be used for new hashes.
  364. # so even if we didn't have a workaround, this bug wouldn't be a concern.
  365. log.debug("%r backend has $2a$ bsd wraparound bug, enabling workaround", backend)
  366. else:
  367. # installed library has the bug -- want to let users know,
  368. # so they can upgrade it to something better (e.g. bcrypt cffi library)
  369. warn("passlib.hash.bcrypt: Your installation of the %r backend is vulnerable to "
  370. "the bsd wraparound bug, "
  371. "and should be upgraded or replaced with another backend "
  372. "(enabling workaround for now)." % backend,
  373. uh.exc.PasslibSecurityWarning)
  374. mixin_cls._has_2a_wraparound_bug = True
  375. #----------------------------------------------------------------
  376. # check for 2y support
  377. #----------------------------------------------------------------
  378. test_hash_2y = TEST_HASH_2A.replace("2a", "2y")
  379. result = safe_verify("test", test_hash_2y)
  380. if result is NotImplemented:
  381. mixin_cls._lacks_2y_support = True
  382. log.debug("%r backend lacks $2y$ support, enabling workaround", backend)
  383. elif not result:
  384. raise RuntimeError("%s incorrectly rejected $2y$ hash" % backend)
  385. else:
  386. # NOTE: Not using this as fallback candidate,
  387. # lacks wide enough support across implementations.
  388. assert_lacks_8bit_bug(IDENT_2Y)
  389. assert_lacks_wrap_bug(IDENT_2Y)
  390. #----------------------------------------------------------------
  391. # TODO: check for 2x support
  392. #----------------------------------------------------------------
  393. #----------------------------------------------------------------
  394. # check for 2b support
  395. #----------------------------------------------------------------
  396. test_hash_2b = TEST_HASH_2A.replace("2a", "2b")
  397. result = safe_verify("test", test_hash_2b)
  398. if result is NotImplemented:
  399. mixin_cls._lacks_2b_support = True
  400. log.debug("%r backend lacks $2b$ support, enabling workaround", backend)
  401. elif not result:
  402. raise RuntimeError("%s incorrectly rejected $2b$ hash" % backend)
  403. else:
  404. mixin_cls._fallback_ident = IDENT_2B
  405. assert_lacks_8bit_bug(IDENT_2B)
  406. assert_lacks_wrap_bug(IDENT_2B)
  407. # set flag so we don't have to run this again
  408. mixin_cls._workrounds_initialized = True
  409. return True
  410. #===================================================================
  411. # digest calculation
  412. #===================================================================
  413. # _calc_checksum() defined by backends
  414. def _prepare_digest_args(self, secret):
  415. """
  416. common helper for backends to implement _calc_checksum().
  417. takes in secret, returns (secret, ident) pair,
  418. """
  419. return self._norm_digest_args(secret, self.ident, new=self.use_defaults)
  420. @classmethod
  421. def _norm_digest_args(cls, secret, ident, new=False):
  422. # make sure secret is unicode
  423. require_valid_utf8_bytes = cls._require_valid_utf8_bytes
  424. if isinstance(secret, unicode):
  425. secret = secret.encode("utf-8")
  426. elif require_valid_utf8_bytes:
  427. # if backend requires utf8 bytes (os_crypt);
  428. # make sure input actually is utf8, or don't bother enabling utf-8 specific helpers.
  429. try:
  430. secret.decode("utf-8")
  431. except UnicodeDecodeError:
  432. # XXX: could just throw PasswordValueError here, backend will just do that
  433. # when _calc_digest() is actually called.
  434. require_valid_utf8_bytes = False
  435. # check max secret size
  436. uh.validate_secret(secret)
  437. # check for truncation (during .hash() calls only)
  438. if new:
  439. cls._check_truncate_policy(secret)
  440. # NOTE: especially important to forbid NULLs for bcrypt, since many
  441. # backends (bcryptor, bcrypt) happily accept them, and then
  442. # silently truncate the password at first NULL they encounter!
  443. if _BNULL in secret:
  444. raise uh.exc.NullPasswordError(cls)
  445. # TODO: figure out way to skip these tests when not needed...
  446. # protect from wraparound bug by truncating secret before handing it to the backend.
  447. # bcrypt only uses first 72 bytes anyways.
  448. # NOTE: not needed for 2y/2b, but might use 2a as fallback for them.
  449. if cls._has_2a_wraparound_bug and len(secret) >= 255:
  450. if require_valid_utf8_bytes:
  451. # backend requires valid utf8 bytes, so truncate secret to nearest valid segment.
  452. # want to do this in constant time to not give away info about secret.
  453. # NOTE: this only works because bcrypt will ignore everything past
  454. # secret[71], so padding to include a full utf8 sequence
  455. # won't break anything about the final output.
  456. secret = utf8_truncate(secret, 72)
  457. else:
  458. secret = secret[:72]
  459. # special case handling for variants (ordered most common first)
  460. if ident == IDENT_2A:
  461. # nothing needs to be done.
  462. pass
  463. elif ident == IDENT_2B:
  464. if cls._lacks_2b_support:
  465. # handle $2b$ hash format even if backend is too old.
  466. # have it generate a 2A/2Y digest, then return it as a 2B hash.
  467. # 2a-only backend could potentially exhibit wraparound bug --
  468. # but we work around that issue above.
  469. ident = cls._fallback_ident
  470. elif ident == IDENT_2Y:
  471. if cls._lacks_2y_support:
  472. # handle $2y$ hash format (not supported by BSDs, being phased out on others)
  473. # have it generate a 2A/2B digest, then return it as a 2Y hash.
  474. ident = cls._fallback_ident
  475. elif ident == IDENT_2:
  476. if cls._lacks_20_support:
  477. # handle legacy $2$ format (not supported by most backends except BSD os_crypt)
  478. # we can fake $2$ behavior using the 2A/2Y/2B algorithm
  479. # by repeating the password until it's at least 72 chars in length.
  480. if secret:
  481. if require_valid_utf8_bytes:
  482. # NOTE: this only works because bcrypt will ignore everything past
  483. # secret[71], so padding to include a full utf8 sequence
  484. # won't break anything about the final output.
  485. secret = utf8_repeat_string(secret, 72)
  486. else:
  487. secret = repeat_string(secret, 72)
  488. ident = cls._fallback_ident
  489. elif ident == IDENT_2X:
  490. # NOTE: shouldn't get here.
  491. # XXX: could check if backend does actually offer 'support'
  492. raise RuntimeError("$2x$ hashes not currently supported by passlib")
  493. else:
  494. raise AssertionError("unexpected ident value: %r" % ident)
  495. return secret, ident
  496. #-----------------------------------------------------------------------
  497. # stub backend
  498. #-----------------------------------------------------------------------
  499. class _NoBackend(_BcryptCommon):
  500. """
  501. mixin used before any backend has been loaded.
  502. contains stubs that force loading of one of the available backends.
  503. """
  504. #===================================================================
  505. # digest calculation
  506. #===================================================================
  507. def _calc_checksum(self, secret):
  508. self._stub_requires_backend()
  509. # NOTE: have to use super() here so that we don't recursively
  510. # call subclass's wrapped _calc_checksum, e.g. bcrypt_sha256._calc_checksum
  511. return super(bcrypt, self)._calc_checksum(secret)
  512. #===================================================================
  513. # eoc
  514. #===================================================================
  515. #-----------------------------------------------------------------------
  516. # bcrypt backend
  517. #-----------------------------------------------------------------------
  518. class _BcryptBackend(_BcryptCommon):
  519. """
  520. backend which uses 'bcrypt' package
  521. """
  522. @classmethod
  523. def _load_backend_mixin(mixin_cls, name, dryrun):
  524. # try to import bcrypt
  525. global _bcrypt
  526. if _detect_pybcrypt():
  527. # pybcrypt was installed instead
  528. return False
  529. try:
  530. import bcrypt as _bcrypt
  531. except ImportError: # pragma: no cover
  532. return False
  533. try:
  534. version = _bcrypt.__about__.__version__
  535. except:
  536. log.warning("(trapped) error reading bcrypt version", exc_info=True)
  537. version = '<unknown>'
  538. log.debug("detected 'bcrypt' backend, version %r", version)
  539. return mixin_cls._finalize_backend_mixin(name, dryrun)
  540. # # TODO: would like to implementing verify() directly,
  541. # # to skip need for parsing hash strings.
  542. # # below method has a few edge cases where it chokes though.
  543. # @classmethod
  544. # def verify(cls, secret, hash):
  545. # if isinstance(hash, unicode):
  546. # hash = hash.encode("ascii")
  547. # ident = hash[:hash.index(b"$", 1)+1].decode("ascii")
  548. # if ident not in cls.ident_values:
  549. # raise uh.exc.InvalidHashError(cls)
  550. # secret, eff_ident = cls._norm_digest_args(secret, ident)
  551. # if eff_ident != ident:
  552. # # lacks support for original ident, replace w/ new one.
  553. # hash = eff_ident.encode("ascii") + hash[len(ident):]
  554. # result = _bcrypt.hashpw(secret, hash)
  555. # assert result.startswith(eff_ident)
  556. # return consteq(result, hash)
  557. def _calc_checksum(self, secret):
  558. # bcrypt behavior:
  559. # secret must be bytes
  560. # config must be ascii bytes
  561. # returns ascii bytes
  562. secret, ident = self._prepare_digest_args(secret)
  563. config = self._get_config(ident)
  564. if isinstance(config, unicode):
  565. config = config.encode("ascii")
  566. hash = _bcrypt.hashpw(secret, config)
  567. assert isinstance(hash, bytes)
  568. if not hash.startswith(config) or len(hash) != len(config)+31:
  569. raise uh.exc.CryptBackendError(self, config, hash, source="`bcrypt` package")
  570. return hash[-31:].decode("ascii")
  571. #-----------------------------------------------------------------------
  572. # bcryptor backend
  573. #-----------------------------------------------------------------------
  574. class _BcryptorBackend(_BcryptCommon):
  575. """
  576. backend which uses 'bcryptor' package
  577. """
  578. @classmethod
  579. def _load_backend_mixin(mixin_cls, name, dryrun):
  580. # try to import bcryptor
  581. global _bcryptor
  582. try:
  583. import bcryptor as _bcryptor
  584. except ImportError: # pragma: no cover
  585. return False
  586. # deprecated as of 1.7.2
  587. if not dryrun:
  588. warn("Support for `bcryptor` is deprecated, and will be removed in Passlib 1.8; "
  589. "Please use `pip install bcrypt` instead", DeprecationWarning)
  590. return mixin_cls._finalize_backend_mixin(name, dryrun)
  591. def _calc_checksum(self, secret):
  592. # bcryptor behavior:
  593. # py2: unicode secret/hash encoded as ascii bytes before use,
  594. # bytes taken as-is; returns ascii bytes.
  595. # py3: not supported
  596. secret, ident = self._prepare_digest_args(secret)
  597. config = self._get_config(ident)
  598. hash = _bcryptor.engine.Engine(False).hash_key(secret, config)
  599. if not hash.startswith(config) or len(hash) != len(config) + 31:
  600. raise uh.exc.CryptBackendError(self, config, hash, source="bcryptor library")
  601. return str_to_uascii(hash[-31:])
  602. #-----------------------------------------------------------------------
  603. # pybcrypt backend
  604. #-----------------------------------------------------------------------
  605. class _PyBcryptBackend(_BcryptCommon):
  606. """
  607. backend which uses 'pybcrypt' package
  608. """
  609. #: classwide thread lock used for pybcrypt < 0.3
  610. _calc_lock = None
  611. @classmethod
  612. def _load_backend_mixin(mixin_cls, name, dryrun):
  613. # try to import pybcrypt
  614. global _pybcrypt
  615. if not _detect_pybcrypt():
  616. # not installed, or bcrypt installed instead
  617. return False
  618. try:
  619. import bcrypt as _pybcrypt
  620. except ImportError: # pragma: no cover
  621. # XXX: should we raise AssertionError here? (if get here, _detect_pybcrypt() is broken)
  622. return False
  623. # deprecated as of 1.7.2
  624. if not dryrun:
  625. warn("Support for `py-bcrypt` is deprecated, and will be removed in Passlib 1.8; "
  626. "Please use `pip install bcrypt` instead", DeprecationWarning)
  627. # determine pybcrypt version
  628. try:
  629. version = _pybcrypt._bcrypt.__version__
  630. except:
  631. log.warning("(trapped) error reading pybcrypt version", exc_info=True)
  632. version = "<unknown>"
  633. log.debug("detected 'pybcrypt' backend, version %r", version)
  634. # return calc function based on version
  635. vinfo = parse_version(version) or (0, 0)
  636. if vinfo < (0, 3):
  637. warn("py-bcrypt %s has a major security vulnerability, "
  638. "you should upgrade to py-bcrypt 0.3 immediately."
  639. % version, uh.exc.PasslibSecurityWarning)
  640. if mixin_cls._calc_lock is None:
  641. import threading
  642. mixin_cls._calc_lock = threading.Lock()
  643. mixin_cls._calc_checksum = get_unbound_method_function(mixin_cls._calc_checksum_threadsafe)
  644. return mixin_cls._finalize_backend_mixin(name, dryrun)
  645. def _calc_checksum_threadsafe(self, secret):
  646. # as workaround for pybcrypt < 0.3's concurrency issue,
  647. # we wrap everything in a thread lock. as long as bcrypt is only
  648. # used through passlib, this should be safe.
  649. with self._calc_lock:
  650. return self._calc_checksum_raw(secret)
  651. def _calc_checksum_raw(self, secret):
  652. # py-bcrypt behavior:
  653. # py2: unicode secret/hash encoded as ascii bytes before use,
  654. # bytes taken as-is; returns ascii bytes.
  655. # py3: unicode secret encoded as utf-8 bytes,
  656. # hash encoded as ascii bytes, returns ascii unicode.
  657. secret, ident = self._prepare_digest_args(secret)
  658. config = self._get_config(ident)
  659. hash = _pybcrypt.hashpw(secret, config)
  660. if not hash.startswith(config) or len(hash) != len(config) + 31:
  661. raise uh.exc.CryptBackendError(self, config, hash, source="pybcrypt library")
  662. return str_to_uascii(hash[-31:])
  663. _calc_checksum = _calc_checksum_raw
  664. #-----------------------------------------------------------------------
  665. # os crypt backend
  666. #-----------------------------------------------------------------------
  667. class _OsCryptBackend(_BcryptCommon):
  668. """
  669. backend which uses :func:`crypt.crypt`
  670. """
  671. #: set flag to ensure _prepare_digest_args() doesn't create invalid utf8 string
  672. #: when truncating bytes.
  673. _require_valid_utf8_bytes = not crypt_accepts_bytes
  674. @classmethod
  675. def _load_backend_mixin(mixin_cls, name, dryrun):
  676. if not test_crypt("test", TEST_HASH_2A):
  677. return False
  678. return mixin_cls._finalize_backend_mixin(name, dryrun)
  679. def _calc_checksum(self, secret):
  680. #
  681. # run secret through crypt.crypt().
  682. # if everything goes right, we'll get back a properly formed bcrypt hash.
  683. #
  684. secret, ident = self._prepare_digest_args(secret)
  685. config = self._get_config(ident)
  686. hash = safe_crypt(secret, config)
  687. if hash is not None:
  688. if not hash.startswith(config) or len(hash) != len(config) + 31:
  689. raise uh.exc.CryptBackendError(self, config, hash)
  690. return hash[-31:]
  691. #
  692. # Check if this failed due to non-UTF8 bytes
  693. # In detail: under py3, crypt.crypt() requires unicode inputs, which are then encoded to
  694. # utf8 before passing them to os crypt() call. this is done according to the "s" format
  695. # specifier for PyArg_ParseTuple (https://docs.python.org/3/c-api/arg.html).
  696. # There appears no way to get around that to pass raw bytes; so we just throw error here
  697. # to let user know they need to use another backend if they want raw bytes support.
  698. #
  699. # XXX: maybe just let safe_crypt() throw UnicodeDecodeError under passlib 2.0,
  700. # and then catch it above? maybe have safe_crypt ALWAYS throw error
  701. # instead of returning None? (would save re-detecting what went wrong)
  702. # XXX: isn't secret ALWAYS bytes at this point?
  703. #
  704. if PY3 and isinstance(secret, bytes):
  705. try:
  706. secret.decode("utf-8")
  707. except UnicodeDecodeError:
  708. raise error_from(uh.exc.PasswordValueError(
  709. "python3 crypt.crypt() ony supports bytes passwords using UTF8; "
  710. "passlib recommends running `pip install bcrypt` for general bcrypt support.",
  711. ), None)
  712. #
  713. # else crypt() call failed for unknown reason.
  714. #
  715. # NOTE: getting here should be considered a bug in passlib --
  716. # if os_crypt backend detection said there's support,
  717. # and we've already checked all known reasons above;
  718. # want them to file bug so we can figure out what happened.
  719. # in the meantime, users can avoid this by installing bcrypt-cffi backend;
  720. # which won't have this (or utf8) edgecases.
  721. #
  722. # XXX: throw something more specific, like an "InternalBackendError"?
  723. # NOTE: if do change this error, need to update test_81_crypt_fallback() expectations
  724. # about what will be thrown; as well as safe_verify() above.
  725. #
  726. debug_only_repr = uh.exc.debug_only_repr
  727. raise uh.exc.InternalBackendError(
  728. "crypt.crypt() failed for unknown reason; "
  729. "passlib recommends running `pip install bcrypt` for general bcrypt support."
  730. # for debugging UTs --
  731. "(config=%s, secret=%s)" % (debug_only_repr(config), debug_only_repr(secret)),
  732. )
  733. #-----------------------------------------------------------------------
  734. # builtin backend
  735. #-----------------------------------------------------------------------
  736. class _BuiltinBackend(_BcryptCommon):
  737. """
  738. backend which uses passlib's pure-python implementation
  739. """
  740. @classmethod
  741. def _load_backend_mixin(mixin_cls, name, dryrun):
  742. from passlib.utils import as_bool
  743. if not as_bool(os.environ.get("PASSLIB_BUILTIN_BCRYPT")):
  744. log.debug("bcrypt 'builtin' backend not enabled via $PASSLIB_BUILTIN_BCRYPT")
  745. return False
  746. global _builtin_bcrypt
  747. from passlib.crypto._blowfish import raw_bcrypt as _builtin_bcrypt
  748. return mixin_cls._finalize_backend_mixin(name, dryrun)
  749. def _calc_checksum(self, secret):
  750. secret, ident = self._prepare_digest_args(secret)
  751. chk = _builtin_bcrypt(secret, ident[1:-1],
  752. self.salt.encode("ascii"), self.rounds)
  753. return chk.decode("ascii")
  754. #=============================================================================
  755. # handler
  756. #=============================================================================
  757. class bcrypt(_NoBackend, _BcryptCommon):
  758. """This class implements the BCrypt password hash, and follows the :ref:`password-hash-api`.
  759. It supports a fixed-length salt, and a variable number of rounds.
  760. The :meth:`~passlib.ifc.PasswordHash.using` method accepts the following optional keywords:
  761. :type salt: str
  762. :param salt:
  763. Optional salt string.
  764. If not specified, one will be autogenerated (this is recommended).
  765. If specified, it must be 22 characters, drawn from the regexp range ``[./0-9A-Za-z]``.
  766. :type rounds: int
  767. :param rounds:
  768. Optional number of rounds to use.
  769. Defaults to 12, must be between 4 and 31, inclusive.
  770. This value is logarithmic, the actual number of iterations used will be :samp:`2**{rounds}`
  771. -- increasing the rounds by +1 will double the amount of time taken.
  772. :type ident: str
  773. :param ident:
  774. Specifies which version of the BCrypt algorithm will be used when creating a new hash.
  775. Typically this option is not needed, as the default (``"2b"``) is usually the correct choice.
  776. If specified, it must be one of the following:
  777. * ``"2"`` - the first revision of BCrypt, which suffers from a minor security flaw and is generally not used anymore.
  778. * ``"2a"`` - some implementations suffered from rare security flaws, replaced by 2b.
  779. * ``"2y"`` - format specific to the *crypt_blowfish* BCrypt implementation,
  780. identical to ``"2b"`` in all but name.
  781. * ``"2b"`` - latest revision of the official BCrypt algorithm, current default.
  782. :param bool truncate_error:
  783. By default, BCrypt will silently truncate passwords larger than 72 bytes.
  784. Setting ``truncate_error=True`` will cause :meth:`~passlib.ifc.PasswordHash.hash`
  785. to raise a :exc:`~passlib.exc.PasswordTruncateError` instead.
  786. .. versionadded:: 1.7
  787. :type relaxed: bool
  788. :param relaxed:
  789. By default, providing an invalid value for one of the other
  790. keywords will result in a :exc:`ValueError`. If ``relaxed=True``,
  791. and the error can be corrected, a :exc:`~passlib.exc.PasslibHashWarning`
  792. will be issued instead. Correctable errors include ``rounds``
  793. that are too small or too large, and ``salt`` strings that are too long.
  794. .. versionadded:: 1.6
  795. .. versionchanged:: 1.6
  796. This class now supports ``"2y"`` hashes, and recognizes
  797. (but does not support) the broken ``"2x"`` hashes.
  798. (see the :ref:`crypt_blowfish bug <crypt-blowfish-bug>`
  799. for details).
  800. .. versionchanged:: 1.6
  801. Added a pure-python backend.
  802. .. versionchanged:: 1.6.3
  803. Added support for ``"2b"`` variant.
  804. .. versionchanged:: 1.7
  805. Now defaults to ``"2b"`` variant.
  806. """
  807. #=============================================================================
  808. # backend
  809. #=============================================================================
  810. # NOTE: the brunt of the bcrypt class is implemented in _BcryptCommon.
  811. # there are then subclass for each backend (e.g. _PyBcryptBackend),
  812. # these are dynamically prepended to this class's bases
  813. # in order to load the appropriate backend.
  814. #: list of potential backends
  815. backends = ("bcrypt", "pybcrypt", "bcryptor", "os_crypt", "builtin")
  816. #: flag that this class's bases should be modified by SubclassBackendMixin
  817. _backend_mixin_target = True
  818. #: map of backend -> mixin class, used by _get_backend_loader()
  819. _backend_mixin_map = {
  820. None: _NoBackend,
  821. "bcrypt": _BcryptBackend,
  822. "pybcrypt": _PyBcryptBackend,
  823. "bcryptor": _BcryptorBackend,
  824. "os_crypt": _OsCryptBackend,
  825. "builtin": _BuiltinBackend,
  826. }
  827. #=============================================================================
  828. # eoc
  829. #=============================================================================
  830. #=============================================================================
  831. # variants
  832. #=============================================================================
  833. _UDOLLAR = u("$")
  834. # XXX: it might be better to have all the bcrypt variants share a common base class,
  835. # and have the (django_)bcrypt_sha256 wrappers just proxy bcrypt instead of subclassing it.
  836. class _wrapped_bcrypt(bcrypt):
  837. """
  838. abstracts out some bits bcrypt_sha256 & django_bcrypt_sha256 share.
  839. - bypass backend-loading wrappers for hash() etc
  840. - disable truncation support, sha256 wrappers don't need it.
  841. """
  842. setting_kwds = tuple(elem for elem in bcrypt.setting_kwds if elem not in ["truncate_error"])
  843. truncate_size = None
  844. # XXX: these will be needed if any bcrypt backends directly implement this...
  845. # @classmethod
  846. # def hash(cls, secret, **kwds):
  847. # # bypass bcrypt backend overriding this method
  848. # # XXX: would wrapping bcrypt make this easier than subclassing it?
  849. # return super(_BcryptCommon, cls).hash(secret, **kwds)
  850. #
  851. # @classmethod
  852. # def verify(cls, secret, hash):
  853. # # bypass bcrypt backend overriding this method
  854. # return super(_BcryptCommon, cls).verify(secret, hash)
  855. #
  856. # @classmethod
  857. # def genhash(cls, secret, hash):
  858. # # bypass bcrypt backend overriding this method
  859. # return super(_BcryptCommon, cls).genhash(secret, hash)
  860. @classmethod
  861. def _check_truncate_policy(cls, secret):
  862. # disable check performed by bcrypt(), since this doesn't truncate passwords.
  863. pass
  864. #=============================================================================
  865. # bcrypt sha256 wrapper
  866. #=============================================================================
  867. class bcrypt_sha256(_wrapped_bcrypt):
  868. """
  869. This class implements a composition of BCrypt + HMAC_SHA256,
  870. and follows the :ref:`password-hash-api`.
  871. It supports a fixed-length salt, and a variable number of rounds.
  872. The :meth:`~passlib.ifc.PasswordHash.hash` and :meth:`~passlib.ifc.PasswordHash.genconfig` methods accept
  873. all the same optional keywords as the base :class:`bcrypt` hash.
  874. .. versionadded:: 1.6.2
  875. .. versionchanged:: 1.7
  876. Now defaults to ``"2b"`` bcrypt variant; though supports older hashes
  877. generated using the ``"2a"`` bcrypt variant.
  878. .. versionchanged:: 1.7.3
  879. For increased security, updated to use HMAC-SHA256 instead of plain SHA256.
  880. Now only supports the ``"2b"`` bcrypt variant. Hash format updated to "v=2".
  881. """
  882. #===================================================================
  883. # class attrs
  884. #===================================================================
  885. #--------------------
  886. # PasswordHash
  887. #--------------------
  888. name = "bcrypt_sha256"
  889. #--------------------
  890. # GenericHandler
  891. #--------------------
  892. # this is locked at 2b for now (with 2a allowed only for legacy v1 format)
  893. ident_values = (IDENT_2A, IDENT_2B)
  894. # clone bcrypt's ident aliases so they can be used here as well...
  895. ident_aliases = (lambda ident_values: dict(item for item in bcrypt.ident_aliases.items()
  896. if item[1] in ident_values))(ident_values)
  897. default_ident = IDENT_2B
  898. #--------------------
  899. # class specific
  900. #--------------------
  901. _supported_versions = set([1, 2])
  902. #===================================================================
  903. # instance attrs
  904. #===================================================================
  905. #: wrapper version.
  906. #: v1 -- used prior to passlib 1.7.3; performs ``bcrypt(sha256(secret), salt, cost)``
  907. #: v2 -- new in passlib 1.7.3; performs `bcrypt(sha256_hmac(salt, secret), salt, cost)``
  908. version = 2
  909. #===================================================================
  910. # configuration
  911. #===================================================================
  912. @classmethod
  913. def using(cls, version=None, **kwds):
  914. subcls = super(bcrypt_sha256, cls).using(**kwds)
  915. if version is not None:
  916. subcls.version = subcls._norm_version(version)
  917. ident = subcls.default_ident
  918. if subcls.version > 1 and ident != IDENT_2B:
  919. raise ValueError("bcrypt %r hashes not allowed for version %r" %
  920. (ident, subcls.version))
  921. return subcls
  922. #===================================================================
  923. # formatting
  924. #===================================================================
  925. # sample hash:
  926. # $bcrypt-sha256$2a,6$/3OeRpbOf8/l6nPPRdZPp.$nRiyYqPobEZGdNRBWihQhiFDh1ws1tu
  927. # $bcrypt-sha256$ -- prefix/identifier
  928. # 2a -- bcrypt variant
  929. # , -- field separator
  930. # 6 -- bcrypt work factor
  931. # $ -- section separator
  932. # /3OeRpbOf8/l6nPPRdZPp. -- salt
  933. # $ -- section separator
  934. # nRiyYqPobEZGdNRBWihQhiFDh1ws1tu -- digest
  935. # XXX: we can't use .ident attr due to bcrypt code using it.
  936. # working around that via prefix.
  937. prefix = u('$bcrypt-sha256$')
  938. #: current version 2 hash format
  939. _v2_hash_re = re.compile(r"""(?x)
  940. ^
  941. [$]bcrypt-sha256[$]
  942. v=(?P<version>\d+),
  943. t=(?P<type>2b),
  944. r=(?P<rounds>\d{1,2})
  945. [$](?P<salt>[^$]{22})
  946. (?:[$](?P<digest>[^$]{31}))?
  947. $
  948. """)
  949. #: old version 1 hash format
  950. _v1_hash_re = re.compile(r"""(?x)
  951. ^
  952. [$]bcrypt-sha256[$]
  953. (?P<type>2[ab]),
  954. (?P<rounds>\d{1,2})
  955. [$](?P<salt>[^$]{22})
  956. (?:[$](?P<digest>[^$]{31}))?
  957. $
  958. """)
  959. @classmethod
  960. def identify(cls, hash):
  961. hash = uh.to_unicode_for_identify(hash)
  962. if not hash:
  963. return False
  964. return hash.startswith(cls.prefix)
  965. @classmethod
  966. def from_string(cls, hash):
  967. hash = to_unicode(hash, "ascii", "hash")
  968. if not hash.startswith(cls.prefix):
  969. raise uh.exc.InvalidHashError(cls)
  970. m = cls._v2_hash_re.match(hash)
  971. if m:
  972. version = int(m.group("version"))
  973. if version < 2:
  974. raise uh.exc.MalformedHashError(cls)
  975. else:
  976. m = cls._v1_hash_re.match(hash)
  977. if m:
  978. version = 1
  979. else:
  980. raise uh.exc.MalformedHashError(cls)
  981. rounds = m.group("rounds")
  982. if rounds.startswith(uh._UZERO) and rounds != uh._UZERO:
  983. raise uh.exc.ZeroPaddedRoundsError(cls)
  984. return cls(
  985. version=version,
  986. ident=m.group("type"),
  987. rounds=int(rounds),
  988. salt=m.group("salt"),
  989. checksum=m.group("digest"),
  990. )
  991. _v2_template = u("$bcrypt-sha256$v=2,t=%s,r=%d$%s$%s")
  992. _v1_template = u("$bcrypt-sha256$%s,%d$%s$%s")
  993. def to_string(self):
  994. if self.version == 1:
  995. template = self._v1_template
  996. else:
  997. template = self._v2_template
  998. hash = template % (self.ident.strip(_UDOLLAR), self.rounds, self.salt, self.checksum)
  999. return uascii_to_str(hash)
  1000. #===================================================================
  1001. # init
  1002. #===================================================================
  1003. def __init__(self, version=None, **kwds):
  1004. if version is not None:
  1005. self.version = self._norm_version(version)
  1006. super(bcrypt_sha256, self).__init__(**kwds)
  1007. #===================================================================
  1008. # version
  1009. #===================================================================
  1010. @classmethod
  1011. def _norm_version(cls, version):
  1012. if version not in cls._supported_versions:
  1013. raise ValueError("%s: unknown or unsupported version: %r" % (cls.name, version))
  1014. return version
  1015. #===================================================================
  1016. # checksum
  1017. #===================================================================
  1018. def _calc_checksum(self, secret):
  1019. # NOTE: can't use digest directly, since bcrypt stops at first NULL.
  1020. # NOTE: bcrypt doesn't fully mix entropy for bytes 55-72 of password
  1021. # (XXX: citation needed), so we don't want key to be > 55 bytes.
  1022. # thus, have to use base64 (44 bytes) rather than hex (64 bytes).
  1023. # XXX: it's later come out that 55-72 may be ok, so later revision of bcrypt_sha256
  1024. # may switch to hex encoding, since it's simpler to implement elsewhere.
  1025. if isinstance(secret, unicode):
  1026. secret = secret.encode("utf-8")
  1027. if self.version == 1:
  1028. # version 1 -- old version just ran secret through sha256(),
  1029. # though this could be vulnerable to a breach attach
  1030. # (c.f. issue 114); which is why v2 switched to hmac wrapper.
  1031. digest = sha256(secret).digest()
  1032. else:
  1033. # version 2 -- running secret through HMAC keyed off salt.
  1034. # this prevents known secret -> sha256 password tables from being
  1035. # used to test against a bcrypt_sha256 hash.
  1036. # keying off salt (instead of constant string) should minimize chances of this
  1037. # colliding with existing table of hmac digest lookups as well.
  1038. # NOTE: salt in this case is the "bcrypt64"-encoded value, not the raw salt bytes,
  1039. # to make things easier for parallel implementations of this hash --
  1040. # saving them the trouble of implementing a "bcrypt64" decoder.
  1041. salt = self.salt
  1042. if salt[-1] not in self.final_salt_chars:
  1043. # forbidding salts with padding bits set, because bcrypt implementations
  1044. # won't consistently hash them the same. since we control this format,
  1045. # just prevent these from even getting used.
  1046. raise ValueError("invalid salt string")
  1047. digest = compile_hmac("sha256", salt.encode("ascii"))(secret)
  1048. # NOTE: output of b64encode() uses "+/" altchars, "=" padding chars,
  1049. # and no leading/trailing whitespace.
  1050. key = b64encode(digest)
  1051. # hand result off to normal bcrypt algorithm
  1052. return super(bcrypt_sha256, self)._calc_checksum(key)
  1053. #===================================================================
  1054. # other
  1055. #===================================================================
  1056. def _calc_needs_update(self, **kwds):
  1057. if self.version < type(self).version:
  1058. return True
  1059. return super(bcrypt_sha256, self)._calc_needs_update(**kwds)
  1060. #===================================================================
  1061. # eoc
  1062. #===================================================================
  1063. #=============================================================================
  1064. # eof
  1065. #=============================================================================