您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 

1058 行
35 KiB

  1. """passlib.crypto.digest -- crytographic helpers used by the password hashes in passlib
  2. .. versionadded:: 1.7
  3. """
  4. #=============================================================================
  5. # imports
  6. #=============================================================================
  7. from __future__ import division
  8. # core
  9. import hashlib
  10. import logging; log = logging.getLogger(__name__)
  11. try:
  12. # new in py3.4
  13. from hashlib import pbkdf2_hmac as _stdlib_pbkdf2_hmac
  14. if _stdlib_pbkdf2_hmac.__module__ == "hashlib":
  15. # builtin pure-python backends are slightly faster than stdlib's pure python fallback,
  16. # so only using stdlib's version if it's backed by openssl's pbkdf2_hmac()
  17. log.debug("ignoring pure-python hashlib.pbkdf2_hmac()")
  18. _stdlib_pbkdf2_hmac = None
  19. except ImportError:
  20. _stdlib_pbkdf2_hmac = None
  21. import re
  22. import os
  23. from struct import Struct
  24. from warnings import warn
  25. # site
  26. try:
  27. # https://pypi.python.org/pypi/fastpbkdf2/
  28. from fastpbkdf2 import pbkdf2_hmac as _fast_pbkdf2_hmac
  29. except ImportError:
  30. _fast_pbkdf2_hmac = None
  31. # pkg
  32. from passlib import exc
  33. from passlib.utils import join_bytes, to_native_str, join_byte_values, to_bytes, \
  34. SequenceMixin, as_bool
  35. from passlib.utils.compat import irange, int_types, unicode_or_bytes_types, PY3, error_from
  36. from passlib.utils.decor import memoized_property
  37. # local
  38. __all__ = [
  39. # hash utils
  40. "lookup_hash",
  41. "HashInfo",
  42. "norm_hash_name",
  43. # hmac utils
  44. "compile_hmac",
  45. # kdfs
  46. "pbkdf1",
  47. "pbkdf2_hmac",
  48. ]
  49. #=============================================================================
  50. # generic constants
  51. #=============================================================================
  52. #: max 32-bit value
  53. MAX_UINT32 = (1 << 32) - 1
  54. #: max 64-bit value
  55. MAX_UINT64 = (1 << 64) - 1
  56. #=============================================================================
  57. # hash utils
  58. #=============================================================================
  59. #: list of known hash names, used by lookup_hash()'s _norm_hash_name() helper
  60. _known_hash_names = [
  61. # format: (hashlib/ssl name, iana name or standin, other known aliases ...)
  62. #----------------------------------------------------
  63. # hashes with official IANA-assigned names
  64. # (as of 2012-03 - http://www.iana.org/assignments/hash-function-text-names)
  65. #----------------------------------------------------
  66. ("md2", "md2"), # NOTE: openssl dropped md2 support in v1.0.0
  67. ("md5", "md5"),
  68. ("sha1", "sha-1"),
  69. ("sha224", "sha-224", "sha2-224"),
  70. ("sha256", "sha-256", "sha2-256"),
  71. ("sha384", "sha-384", "sha2-384"),
  72. ("sha512", "sha-512", "sha2-512"),
  73. # TODO: add sha3 to this table.
  74. #----------------------------------------------------
  75. # hashlib/ssl-supported hashes without official IANA names,
  76. # (hopefully-) compatible stand-ins have been chosen.
  77. #----------------------------------------------------
  78. ("blake2b", "blake-2b"),
  79. ("blake2s", "blake-2s"),
  80. ("md4", "md4"),
  81. # NOTE: there was an older "ripemd" and "ripemd-128",
  82. # but python 2.7+ resolves "ripemd" -> "ripemd160",
  83. # so treating "ripemd" as alias here.
  84. ("ripemd160", "ripemd-160", "ripemd"),
  85. ]
  86. #: dict mapping hashlib names to hardcoded digest info;
  87. #: so this is available even when hashes aren't present.
  88. _fallback_info = {
  89. # name: (digest_size, block_size)
  90. 'blake2b': (64, 128),
  91. 'blake2s': (32, 64),
  92. 'md4': (16, 64),
  93. 'md5': (16, 64),
  94. 'sha1': (20, 64),
  95. 'sha224': (28, 64),
  96. 'sha256': (32, 64),
  97. 'sha384': (48, 128),
  98. 'sha3_224': (28, 144),
  99. 'sha3_256': (32, 136),
  100. 'sha3_384': (48, 104),
  101. 'sha3_512': (64, 72),
  102. 'sha512': (64, 128),
  103. 'shake128': (16, 168),
  104. 'shake256': (32, 136),
  105. }
  106. def _gen_fallback_info():
  107. """
  108. internal helper used to generate ``_fallback_info`` dict.
  109. currently only run manually to update the above list;
  110. not invoked at runtime.
  111. """
  112. out = {}
  113. for alg in sorted(hashlib.algorithms_available | set(["md4"])):
  114. info = lookup_hash(alg)
  115. out[info.name] = (info.digest_size, info.block_size)
  116. return out
  117. #: cache of hash info instances used by lookup_hash()
  118. _hash_info_cache = {}
  119. def _get_hash_aliases(name):
  120. """
  121. internal helper used by :func:`lookup_hash` --
  122. normalize arbitrary hash name to hashlib format.
  123. if name not recognized, returns dummy record and issues a warning.
  124. :arg name:
  125. unnormalized name
  126. :returns:
  127. tuple with 2+ elements: ``(hashlib_name, iana_name|None, ... 0+ aliases)``.
  128. """
  129. # normalize input
  130. orig = name
  131. if not isinstance(name, str):
  132. name = to_native_str(name, 'utf-8', 'hash name')
  133. name = re.sub("[_ /]", "-", name.strip().lower())
  134. if name.startswith("scram-"): # helper for SCRAM protocol (see passlib.handlers.scram)
  135. name = name[6:]
  136. if name.endswith("-plus"):
  137. name = name[:-5]
  138. # look through standard names and known aliases
  139. def check_table(name):
  140. for row in _known_hash_names:
  141. if name in row:
  142. return row
  143. result = check_table(name)
  144. if result:
  145. return result
  146. # try to clean name up some more
  147. m = re.match(r"(?i)^(?P<name>[a-z]+)-?(?P<rev>\d)?-?(?P<size>\d{3,4})?$", name)
  148. if m:
  149. # roughly follows "SHA2-256" style format, normalize representation,
  150. # and checked table.
  151. iana_name, rev, size = m.group("name", "rev", "size")
  152. if rev:
  153. iana_name += rev
  154. hashlib_name = iana_name
  155. if size:
  156. iana_name += "-" + size
  157. if rev:
  158. hashlib_name += "_"
  159. hashlib_name += size
  160. result = check_table(iana_name)
  161. if result:
  162. return result
  163. # not found in table, but roughly recognize format. use names we built up as fallback.
  164. log.info("normalizing unrecognized hash name %r => %r / %r",
  165. orig, hashlib_name, iana_name)
  166. else:
  167. # just can't make sense of it. return something
  168. iana_name = name
  169. hashlib_name = name.replace("-", "_")
  170. log.warning("normalizing unrecognized hash name and format %r => %r / %r",
  171. orig, hashlib_name, iana_name)
  172. return hashlib_name, iana_name
  173. def _get_hash_const(name):
  174. """
  175. internal helper used by :func:`lookup_hash` --
  176. lookup hash constructor by name
  177. :arg name:
  178. name (normalized to hashlib format, e.g. ``"sha256"``)
  179. :returns:
  180. hash constructor, e.g. ``hashlib.sha256()``;
  181. or None if hash can't be located.
  182. """
  183. # check hashlib.<attr> for an efficient constructor
  184. if not name.startswith("_") and name not in ("new", "algorithms"):
  185. try:
  186. return getattr(hashlib, name)
  187. except AttributeError:
  188. pass
  189. # check hashlib.new() in case SSL supports the digest
  190. new_ssl_hash = hashlib.new
  191. try:
  192. # new() should throw ValueError if alg is unknown
  193. new_ssl_hash(name, b"")
  194. except ValueError:
  195. pass
  196. else:
  197. # create wrapper function
  198. # XXX: is there a faster way to wrap this?
  199. def const(msg=b""):
  200. return new_ssl_hash(name, msg)
  201. const.__name__ = name
  202. const.__module__ = "hashlib"
  203. const.__doc__ = ("wrapper for hashlib.new(%r),\n"
  204. "generated by passlib.crypto.digest.lookup_hash()") % name
  205. return const
  206. # use builtin md4 as fallback when not supported by hashlib
  207. if name == "md4":
  208. from passlib.crypto._md4 import md4
  209. return md4
  210. # XXX: any other modules / registries we should check?
  211. # TODO: add pysha3 support.
  212. return None
  213. def lookup_hash(digest, # *,
  214. return_unknown=False, required=True):
  215. """
  216. Returns a :class:`HashInfo` record containing information about a given hash function.
  217. Can be used to look up a hash constructor by name, normalize hash name representation, etc.
  218. :arg digest:
  219. This can be any of:
  220. * A string containing a :mod:`!hashlib` digest name (e.g. ``"sha256"``),
  221. * A string containing an IANA-assigned hash name,
  222. * A digest constructor function (e.g. ``hashlib.sha256``).
  223. Case is ignored, underscores are converted to hyphens,
  224. and various other cleanups are made.
  225. :param required:
  226. By default (True), this function will throw an :exc:`~passlib.exc.UnknownHashError` if no hash constructor
  227. can be found, or if the hash is not actually available.
  228. If this flag is False, it will instead return a dummy :class:`!HashInfo` record
  229. which will defer throwing the error until it's constructor function is called.
  230. This is mainly used by :func:`norm_hash_name`.
  231. :param return_unknown:
  232. .. deprecated:: 1.7.3
  233. deprecated, and will be removed in passlib 2.0.
  234. this acts like inverse of **required**.
  235. :returns HashInfo:
  236. :class:`HashInfo` instance containing information about specified digest.
  237. Multiple calls resolving to the same hash should always
  238. return the same :class:`!HashInfo` instance.
  239. """
  240. # check for cached entry
  241. cache = _hash_info_cache
  242. try:
  243. return cache[digest]
  244. except (KeyError, TypeError):
  245. # NOTE: TypeError is to catch 'TypeError: unhashable type' (e.g. HashInfo)
  246. pass
  247. # legacy alias
  248. if return_unknown:
  249. required = False
  250. # resolve ``digest`` to ``const`` & ``name_record``
  251. cache_by_name = True
  252. if isinstance(digest, unicode_or_bytes_types):
  253. # normalize name
  254. name_list = _get_hash_aliases(digest)
  255. name = name_list[0]
  256. assert name
  257. # if name wasn't normalized to hashlib format,
  258. # get info for normalized name and reuse it.
  259. if name != digest:
  260. info = lookup_hash(name, required=required)
  261. cache[digest] = info
  262. return info
  263. # else look up constructor
  264. # NOTE: may return None, which is handled by HashInfo constructor
  265. const = _get_hash_const(name)
  266. # if mock fips mode is enabled, replace with dummy constructor
  267. # (to replicate how it would behave on a real fips system).
  268. if const and mock_fips_mode and name not in _fips_algorithms:
  269. def const(source=b""):
  270. raise ValueError("%r disabled for fips by passlib set_mock_fips_mode()" % name)
  271. elif isinstance(digest, HashInfo):
  272. # handle border case where HashInfo is passed in.
  273. return digest
  274. elif callable(digest):
  275. # try to lookup digest based on it's self-reported name
  276. # (which we trust to be the canonical "hashlib" name)
  277. const = digest
  278. name_list = _get_hash_aliases(const().name)
  279. name = name_list[0]
  280. other_const = _get_hash_const(name)
  281. if other_const is None:
  282. # this is probably a third-party digest we don't know about,
  283. # so just pass it on through, and register reverse lookup for it's name.
  284. pass
  285. elif other_const is const:
  286. # if we got back same constructor, this is just a known stdlib constructor,
  287. # which was passed in before we had cached it by name. proceed normally.
  288. pass
  289. else:
  290. # if we got back different object, then ``const`` is something else
  291. # (such as a mock object), in which case we want to skip caching it by name,
  292. # as that would conflict with real hash.
  293. cache_by_name = False
  294. else:
  295. raise exc.ExpectedTypeError(digest, "digest name or constructor", "digest")
  296. # create new instance
  297. info = HashInfo(const=const, names=name_list, required=required)
  298. # populate cache
  299. if const is not None:
  300. cache[const] = info
  301. if cache_by_name:
  302. for name in name_list:
  303. if name: # (skips iana name if it's empty)
  304. assert cache.get(name) in [None, info], "%r already in cache" % name
  305. cache[name] = info
  306. return info
  307. #: UT helper for clearing internal cache
  308. lookup_hash.clear_cache = _hash_info_cache.clear
  309. def norm_hash_name(name, format="hashlib"):
  310. """Normalize hash function name (convenience wrapper for :func:`lookup_hash`).
  311. :arg name:
  312. Original hash function name.
  313. This name can be a Python :mod:`~hashlib` digest name,
  314. a SCRAM mechanism name, IANA assigned hash name, etc.
  315. Case is ignored, and underscores are converted to hyphens.
  316. :param format:
  317. Naming convention to normalize to.
  318. Possible values are:
  319. * ``"hashlib"`` (the default) - normalizes name to be compatible
  320. with Python's :mod:`!hashlib`.
  321. * ``"iana"`` - normalizes name to IANA-assigned hash function name.
  322. For hashes which IANA hasn't assigned a name for, this issues a warning,
  323. and then uses a heuristic to return a "best guess" name.
  324. :returns:
  325. Hash name, returned as native :class:`!str`.
  326. """
  327. info = lookup_hash(name, required=False)
  328. if info.unknown:
  329. warn("norm_hash_name(): " + info.error_text, exc.PasslibRuntimeWarning)
  330. if format == "hashlib":
  331. return info.name
  332. elif format == "iana":
  333. return info.iana_name
  334. else:
  335. raise ValueError("unknown format: %r" % (format,))
  336. class HashInfo(SequenceMixin):
  337. """
  338. Record containing information about a given hash algorithm, as returned :func:`lookup_hash`.
  339. This class exposes the following attributes:
  340. .. autoattribute:: const
  341. .. autoattribute:: digest_size
  342. .. autoattribute:: block_size
  343. .. autoattribute:: name
  344. .. autoattribute:: iana_name
  345. .. autoattribute:: aliases
  346. .. autoattribute:: supported
  347. This object can also be treated a 3-element sequence
  348. containing ``(const, digest_size, block_size)``.
  349. """
  350. #=========================================================================
  351. # instance attrs
  352. #=========================================================================
  353. #: Canonical / hashlib-compatible name (e.g. ``"sha256"``).
  354. name = None
  355. #: IANA assigned name (e.g. ``"sha-256"``), may be ``None`` if unknown.
  356. iana_name = None
  357. #: Tuple of other known aliases (may be empty)
  358. aliases = ()
  359. #: Hash constructor function (e.g. :func:`hashlib.sha256`)
  360. const = None
  361. #: Hash's digest size
  362. digest_size = None
  363. #: Hash's block size
  364. block_size = None
  365. #: set when hash isn't available, will be filled in with string containing error text
  366. #: that const() will raise.
  367. error_text = None
  368. #: set when error_text is due to hash algorithm being completely unknown
  369. #: (not just unavailable on current system)
  370. unknown = False
  371. #=========================================================================
  372. # init
  373. #=========================================================================
  374. def __init__(self, # *,
  375. const, names, required=True):
  376. """
  377. initialize new instance.
  378. :arg const:
  379. hash constructor
  380. :arg names:
  381. list of 2+ names. should be list of ``(name, iana_name, ... 0+ aliases)``.
  382. names must be lower-case. only iana name may be None.
  383. """
  384. # init names
  385. name = self.name = names[0]
  386. self.iana_name = names[1]
  387. self.aliases = names[2:]
  388. def use_stub_const(msg):
  389. """
  390. helper that installs stub constructor which throws specified error <msg>.
  391. """
  392. def const(source=b""):
  393. raise exc.UnknownHashError(msg, name)
  394. if required:
  395. # if caller only wants supported digests returned,
  396. # just throw error immediately...
  397. const()
  398. assert "shouldn't get here"
  399. self.error_text = msg
  400. self.const = const
  401. try:
  402. self.digest_size, self.block_size = _fallback_info[name]
  403. except KeyError:
  404. pass
  405. # handle "constructor not available" case
  406. if const is None:
  407. if names in _known_hash_names:
  408. msg = "unsupported hash: %r" % name
  409. else:
  410. msg = "unknown hash: %r" % name
  411. self.unknown = True
  412. use_stub_const(msg)
  413. # TODO: load in preset digest size info for known hashes.
  414. return
  415. # create hash instance to inspect
  416. try:
  417. hash = const()
  418. except ValueError as err:
  419. # per issue 116, FIPS compliant systems will have a constructor;
  420. # but it will throw a ValueError with this message. As of 1.7.3,
  421. # translating this into DisabledHashError.
  422. # "ValueError: error:060800A3:digital envelope routines:EVP_DigestInit_ex:disabled for fips"
  423. if "disabled for fips" in str(err).lower():
  424. msg = "%r hash disabled for fips" % name
  425. else:
  426. msg = "internal error in %r constructor\n(%s: %s)" % (name, type(err).__name__, err)
  427. use_stub_const(msg)
  428. return
  429. # store stats about hash
  430. self.const = const
  431. self.digest_size = hash.digest_size
  432. self.block_size = hash.block_size
  433. # do sanity check on digest size
  434. if len(hash.digest()) != hash.digest_size:
  435. raise RuntimeError("%r constructor failed sanity check" % self.name)
  436. # do sanity check on name.
  437. if hash.name != self.name:
  438. warn("inconsistent digest name: %r resolved to %r, which reports name as %r" %
  439. (self.name, const, hash.name), exc.PasslibRuntimeWarning)
  440. #=========================================================================
  441. # methods
  442. #=========================================================================
  443. def __repr__(self):
  444. return "<lookup_hash(%r): digest_size=%r block_size=%r)" % \
  445. (self.name, self.digest_size, self.block_size)
  446. def _as_tuple(self):
  447. return self.const, self.digest_size, self.block_size
  448. @memoized_property
  449. def supported(self):
  450. """
  451. whether hash is available for use
  452. (if False, constructor will throw UnknownHashError if called)
  453. """
  454. return self.error_text is None
  455. @memoized_property
  456. def supported_by_fastpbkdf2(self):
  457. """helper to detect if hash is supported by fastpbkdf2()"""
  458. if not _fast_pbkdf2_hmac:
  459. return None
  460. try:
  461. _fast_pbkdf2_hmac(self.name, b"p", b"s", 1)
  462. return True
  463. except ValueError:
  464. # "unsupported hash type"
  465. return False
  466. @memoized_property
  467. def supported_by_hashlib_pbkdf2(self):
  468. """helper to detect if hash is supported by hashlib.pbkdf2_hmac()"""
  469. if not _stdlib_pbkdf2_hmac:
  470. return None
  471. try:
  472. _stdlib_pbkdf2_hmac(self.name, b"p", b"s", 1)
  473. return True
  474. except ValueError:
  475. # "unsupported hash type"
  476. return False
  477. #=========================================================================
  478. # eoc
  479. #=========================================================================
  480. #---------------------------------------------------------------------
  481. # mock fips mode monkeypatch
  482. #---------------------------------------------------------------------
  483. #: flag for detecting if mock fips mode is enabled.
  484. mock_fips_mode = False
  485. #: algorithms allowed under FIPS mode (subset of hashlib.algorithms_available);
  486. #: per https://csrc.nist.gov/Projects/Hash-Functions FIPS 202 list.
  487. _fips_algorithms = set([
  488. # FIPS 180-4 and FIPS 202
  489. 'sha1',
  490. 'sha224',
  491. 'sha256',
  492. 'sha384',
  493. 'sha512',
  494. # 'sha512/224',
  495. # 'sha512/256',
  496. # FIPS 202 only
  497. 'sha3_224',
  498. 'sha3_256',
  499. 'sha3_384',
  500. 'sha3_512',
  501. 'shake_128',
  502. 'shake_256',
  503. ])
  504. def _set_mock_fips_mode(enable=True):
  505. """
  506. UT helper which monkeypatches lookup_hash() internals to replicate FIPS mode.
  507. """
  508. global mock_fips_mode
  509. mock_fips_mode = enable
  510. lookup_hash.clear_cache()
  511. # helper for UTs
  512. if as_bool(os.environ.get("PASSLIB_MOCK_FIPS_MODE")):
  513. _set_mock_fips_mode()
  514. #=============================================================================
  515. # hmac utils
  516. #=============================================================================
  517. #: translation tables used by compile_hmac()
  518. _TRANS_5C = join_byte_values((x ^ 0x5C) for x in irange(256))
  519. _TRANS_36 = join_byte_values((x ^ 0x36) for x in irange(256))
  520. def compile_hmac(digest, key, multipart=False):
  521. """
  522. This function returns an efficient HMAC function, hardcoded with a specific digest & key.
  523. It can be used via ``hmac = compile_hmac(digest, key)``.
  524. :arg digest:
  525. digest name or constructor.
  526. :arg key:
  527. secret key as :class:`!bytes` or :class:`!unicode` (unicode will be encoded using utf-8).
  528. :param multipart:
  529. request a multipart constructor instead (see return description).
  530. :returns:
  531. By default, the returned function has the signature ``hmac(msg) -> digest output``.
  532. However, if ``multipart=True``, the returned function has the signature
  533. ``hmac() -> update, finalize``, where ``update(msg)`` may be called multiple times,
  534. and ``finalize() -> digest_output`` may be repeatedly called at any point to
  535. calculate the HMAC digest so far.
  536. The returned object will also have a ``digest_info`` attribute, containing
  537. a :class:`lookup_hash` instance for the specified digest.
  538. This function exists, and has the weird signature it does, in order to squeeze as
  539. provide as much efficiency as possible, by omitting much of the setup cost
  540. and features of the stdlib :mod:`hmac` module.
  541. """
  542. # all the following was adapted from stdlib's hmac module
  543. # resolve digest (cached)
  544. digest_info = lookup_hash(digest)
  545. const, digest_size, block_size = digest_info
  546. assert block_size >= 16, "block size too small"
  547. # prepare key
  548. if not isinstance(key, bytes):
  549. key = to_bytes(key, param="key")
  550. klen = len(key)
  551. if klen > block_size:
  552. key = const(key).digest()
  553. klen = digest_size
  554. if klen < block_size:
  555. key += b'\x00' * (block_size - klen)
  556. # create pre-initialized hash constructors
  557. _inner_copy = const(key.translate(_TRANS_36)).copy
  558. _outer_copy = const(key.translate(_TRANS_5C)).copy
  559. if multipart:
  560. # create multi-part function
  561. # NOTE: this is slightly slower than the single-shot version,
  562. # and should only be used if needed.
  563. def hmac():
  564. """generated by compile_hmac(multipart=True)"""
  565. inner = _inner_copy()
  566. def finalize():
  567. outer = _outer_copy()
  568. outer.update(inner.digest())
  569. return outer.digest()
  570. return inner.update, finalize
  571. else:
  572. # single-shot function
  573. def hmac(msg):
  574. """generated by compile_hmac()"""
  575. inner = _inner_copy()
  576. inner.update(msg)
  577. outer = _outer_copy()
  578. outer.update(inner.digest())
  579. return outer.digest()
  580. # add info attr
  581. hmac.digest_info = digest_info
  582. return hmac
  583. #=============================================================================
  584. # pbkdf1
  585. #=============================================================================
  586. def pbkdf1(digest, secret, salt, rounds, keylen=None):
  587. """pkcs#5 password-based key derivation v1.5
  588. :arg digest:
  589. digest name or constructor.
  590. :arg secret:
  591. secret to use when generating the key.
  592. may be :class:`!bytes` or :class:`unicode` (encoded using UTF-8).
  593. :arg salt:
  594. salt string to use when generating key.
  595. may be :class:`!bytes` or :class:`unicode` (encoded using UTF-8).
  596. :param rounds:
  597. number of rounds to use to generate key.
  598. :arg keylen:
  599. number of bytes to generate (if omitted / ``None``, uses digest's native size)
  600. :returns:
  601. raw :class:`bytes` of generated key
  602. .. note::
  603. This algorithm has been deprecated, new code should use PBKDF2.
  604. Among other limitations, ``keylen`` cannot be larger
  605. than the digest size of the specified hash.
  606. """
  607. # resolve digest
  608. const, digest_size, block_size = lookup_hash(digest)
  609. # validate secret & salt
  610. secret = to_bytes(secret, param="secret")
  611. salt = to_bytes(salt, param="salt")
  612. # validate rounds
  613. if not isinstance(rounds, int_types):
  614. raise exc.ExpectedTypeError(rounds, "int", "rounds")
  615. if rounds < 1:
  616. raise ValueError("rounds must be at least 1")
  617. # validate keylen
  618. if keylen is None:
  619. keylen = digest_size
  620. elif not isinstance(keylen, int_types):
  621. raise exc.ExpectedTypeError(keylen, "int or None", "keylen")
  622. elif keylen < 0:
  623. raise ValueError("keylen must be at least 0")
  624. elif keylen > digest_size:
  625. raise ValueError("keylength too large for digest: %r > %r" %
  626. (keylen, digest_size))
  627. # main pbkdf1 loop
  628. block = secret + salt
  629. for _ in irange(rounds):
  630. block = const(block).digest()
  631. return block[:keylen]
  632. #=============================================================================
  633. # pbkdf2
  634. #=============================================================================
  635. _pack_uint32 = Struct(">L").pack
  636. def pbkdf2_hmac(digest, secret, salt, rounds, keylen=None):
  637. """pkcs#5 password-based key derivation v2.0 using HMAC + arbitrary digest.
  638. :arg digest:
  639. digest name or constructor.
  640. :arg secret:
  641. passphrase to use to generate key.
  642. may be :class:`!bytes` or :class:`unicode` (encoded using UTF-8).
  643. :arg salt:
  644. salt string to use when generating key.
  645. may be :class:`!bytes` or :class:`unicode` (encoded using UTF-8).
  646. :param rounds:
  647. number of rounds to use to generate key.
  648. :arg keylen:
  649. number of bytes to generate.
  650. if omitted / ``None``, will use digest's native output size.
  651. :returns:
  652. raw bytes of generated key
  653. .. versionchanged:: 1.7
  654. This function will use the first available of the following backends:
  655. * `fastpbk2 <https://pypi.python.org/pypi/fastpbkdf2>`_
  656. * :func:`hashlib.pbkdf2_hmac` (only available in py2 >= 2.7.8, and py3 >= 3.4)
  657. * builtin pure-python backend
  658. See :data:`passlib.crypto.digest.PBKDF2_BACKENDS` to determine
  659. which backend(s) are in use.
  660. """
  661. # validate secret & salt
  662. secret = to_bytes(secret, param="secret")
  663. salt = to_bytes(salt, param="salt")
  664. # resolve digest
  665. digest_info = lookup_hash(digest)
  666. digest_size = digest_info.digest_size
  667. # validate rounds
  668. if not isinstance(rounds, int_types):
  669. raise exc.ExpectedTypeError(rounds, "int", "rounds")
  670. if rounds < 1:
  671. raise ValueError("rounds must be at least 1")
  672. # validate keylen
  673. if keylen is None:
  674. keylen = digest_size
  675. elif not isinstance(keylen, int_types):
  676. raise exc.ExpectedTypeError(keylen, "int or None", "keylen")
  677. elif keylen < 1:
  678. # XXX: could allow keylen=0, but want to be compat w/ stdlib
  679. raise ValueError("keylen must be at least 1")
  680. # find smallest block count s.t. keylen <= block_count * digest_size;
  681. # make sure block count won't overflow (per pbkdf2 spec)
  682. # this corresponds to throwing error if keylen > digest_size * MAX_UINT32
  683. # NOTE: stdlib will throw error at lower bound (keylen > MAX_SINT32)
  684. # NOTE: have do this before other backends checked, since fastpbkdf2 raises wrong error
  685. # (InvocationError, not OverflowError)
  686. block_count = (keylen + digest_size - 1) // digest_size
  687. if block_count > MAX_UINT32:
  688. raise OverflowError("keylen too long for digest")
  689. #
  690. # check for various high-speed backends
  691. #
  692. # ~3x faster than pure-python backend
  693. # NOTE: have to do this after above guards since fastpbkdf2 lacks bounds checks.
  694. if digest_info.supported_by_fastpbkdf2:
  695. return _fast_pbkdf2_hmac(digest_info.name, secret, salt, rounds, keylen)
  696. # ~1.4x faster than pure-python backend
  697. # NOTE: have to do this after fastpbkdf2 since hashlib-ssl is slower,
  698. # will support larger number of hashes.
  699. if digest_info.supported_by_hashlib_pbkdf2:
  700. return _stdlib_pbkdf2_hmac(digest_info.name, secret, salt, rounds, keylen)
  701. #
  702. # otherwise use our own implementation
  703. #
  704. # generated keyed hmac
  705. keyed_hmac = compile_hmac(digest, secret)
  706. # get helper to calculate pbkdf2 inner loop efficiently
  707. calc_block = _get_pbkdf2_looper(digest_size)
  708. # assemble & return result
  709. return join_bytes(
  710. calc_block(keyed_hmac, keyed_hmac(salt + _pack_uint32(i)), rounds)
  711. for i in irange(1, block_count + 1)
  712. )[:keylen]
  713. #-------------------------------------------------------------------------------------
  714. # pick best choice for pure-python helper
  715. # TODO: consider some alternatives, such as C-accelerated xor_bytes helper if available
  716. #-------------------------------------------------------------------------------------
  717. # NOTE: this env var is only present to support the admin/benchmark_pbkdf2 script
  718. _force_backend = os.environ.get("PASSLIB_PBKDF2_BACKEND") or "any"
  719. if PY3 and _force_backend in ["any", "from-bytes"]:
  720. from functools import partial
  721. def _get_pbkdf2_looper(digest_size):
  722. return partial(_pbkdf2_looper, digest_size)
  723. def _pbkdf2_looper(digest_size, keyed_hmac, digest, rounds):
  724. """
  725. py3-only implementation of pbkdf2 inner loop;
  726. uses 'int.from_bytes' + integer XOR
  727. """
  728. from_bytes = int.from_bytes
  729. BIG = "big" # endianess doesn't matter, just has to be consistent
  730. accum = from_bytes(digest, BIG)
  731. for _ in irange(rounds - 1):
  732. digest = keyed_hmac(digest)
  733. accum ^= from_bytes(digest, BIG)
  734. return accum.to_bytes(digest_size, BIG)
  735. _builtin_backend = "from-bytes"
  736. elif _force_backend in ["any", "unpack", "from-bytes"]:
  737. from struct import Struct
  738. from passlib.utils import sys_bits
  739. _have_64_bit = (sys_bits >= 64)
  740. #: cache used by _get_pbkdf2_looper
  741. _looper_cache = {}
  742. def _get_pbkdf2_looper(digest_size):
  743. """
  744. We want a helper function which performs equivalent of the following::
  745. def helper(keyed_hmac, digest, rounds):
  746. accum = digest
  747. for _ in irange(rounds - 1):
  748. digest = keyed_hmac(digest)
  749. accum ^= digest
  750. return accum
  751. However, no efficient way to implement "bytes ^ bytes" in python.
  752. Instead, using approach where we dynamically compile a helper function based
  753. on digest size. Instead of a single `accum` var, this helper breaks the digest
  754. into a series of integers.
  755. It stores these in a series of`accum_<i>` vars, and performs `accum ^= digest`
  756. by unpacking digest and perform xor for each "accum_<i> ^= digest_<i>".
  757. this keeps everything in locals, avoiding excessive list creation, encoding or decoding,
  758. etc.
  759. :param digest_size:
  760. digest size to compile for, in bytes. (must be multiple of 4).
  761. :return:
  762. helper function with call signature outlined above.
  763. """
  764. #
  765. # cache helpers
  766. #
  767. try:
  768. return _looper_cache[digest_size]
  769. except KeyError:
  770. pass
  771. #
  772. # figure out most efficient struct format to unpack digest into list of native ints
  773. #
  774. if _have_64_bit and not digest_size & 0x7:
  775. # digest size multiple of 8, on a 64 bit system -- use array of UINT64
  776. count = (digest_size >> 3)
  777. fmt = "=%dQ" % count
  778. elif not digest_size & 0x3:
  779. if _have_64_bit:
  780. # digest size multiple of 4, on a 64 bit system -- use array of UINT64 + 1 UINT32
  781. count = (digest_size >> 3)
  782. fmt = "=%dQI" % count
  783. count += 1
  784. else:
  785. # digest size multiple of 4, on a 32 bit system -- use array of UINT32
  786. count = (digest_size >> 2)
  787. fmt = "=%dI" % count
  788. else:
  789. # stopping here, cause no known hashes have digest size that isn't multiple of 4 bytes.
  790. # if needed, could go crazy w/ "H" & "B"
  791. raise NotImplementedError("unsupported digest size: %d" % digest_size)
  792. struct = Struct(fmt)
  793. #
  794. # build helper source
  795. #
  796. tdict = dict(
  797. digest_size=digest_size,
  798. accum_vars=", ".join("acc_%d" % i for i in irange(count)),
  799. digest_vars=", ".join("dig_%d" % i for i in irange(count)),
  800. )
  801. # head of function
  802. source = (
  803. "def helper(keyed_hmac, digest, rounds):\n"
  804. " '''pbkdf2 loop helper for digest_size={digest_size}'''\n"
  805. " unpack_digest = struct.unpack\n"
  806. " {accum_vars} = unpack_digest(digest)\n"
  807. " for _ in irange(1, rounds):\n"
  808. " digest = keyed_hmac(digest)\n"
  809. " {digest_vars} = unpack_digest(digest)\n"
  810. ).format(**tdict)
  811. # xor digest
  812. for i in irange(count):
  813. source += " acc_%d ^= dig_%d\n" % (i, i)
  814. # return result
  815. source += " return struct.pack({accum_vars})\n".format(**tdict)
  816. #
  817. # compile helper
  818. #
  819. code = compile(source, "<generated by passlib.crypto.digest._get_pbkdf2_looper()>", "exec")
  820. gdict = dict(irange=irange, struct=struct)
  821. ldict = dict()
  822. eval(code, gdict, ldict)
  823. helper = ldict['helper']
  824. if __debug__:
  825. helper.__source__ = source
  826. #
  827. # store in cache
  828. #
  829. _looper_cache[digest_size] = helper
  830. return helper
  831. _builtin_backend = "unpack"
  832. else:
  833. assert _force_backend in ["any", "hexlify"]
  834. # XXX: older & slower approach that used int(hexlify()),
  835. # keeping it around for a little while just for benchmarking.
  836. from binascii import hexlify as _hexlify
  837. from passlib.utils import int_to_bytes
  838. def _get_pbkdf2_looper(digest_size):
  839. return _pbkdf2_looper
  840. def _pbkdf2_looper(keyed_hmac, digest, rounds):
  841. hexlify = _hexlify
  842. accum = int(hexlify(digest), 16)
  843. for _ in irange(rounds - 1):
  844. digest = keyed_hmac(digest)
  845. accum ^= int(hexlify(digest), 16)
  846. return int_to_bytes(accum, len(digest))
  847. _builtin_backend = "hexlify"
  848. # helper for benchmark script -- disable hashlib, fastpbkdf2 support if builtin requested
  849. if _force_backend == _builtin_backend:
  850. _fast_pbkdf2_hmac = _stdlib_pbkdf2_hmac = None
  851. # expose info about what backends are active
  852. PBKDF2_BACKENDS = [b for b in [
  853. "fastpbkdf2" if _fast_pbkdf2_hmac else None,
  854. "hashlib-ssl" if _stdlib_pbkdf2_hmac else None,
  855. "builtin-" + _builtin_backend
  856. ] if b]
  857. # *very* rough estimate of relative speed (compared to sha256 using 'unpack' backend on 64bit arch)
  858. if "fastpbkdf2" in PBKDF2_BACKENDS:
  859. PBKDF2_SPEED_FACTOR = 3
  860. elif "hashlib-ssl" in PBKDF2_BACKENDS:
  861. PBKDF2_SPEED_FACTOR = 1.4
  862. else:
  863. # remaining backends have *some* difference in performance, but not enough to matter
  864. PBKDF2_SPEED_FACTOR = 1
  865. #=============================================================================
  866. # eof
  867. #=============================================================================