diff options
| author | Eli Collins <elic@assurancetechnologies.com> | 2013-12-28 11:02:12 -0500 |
|---|---|---|
| committer | Eli Collins <elic@assurancetechnologies.com> | 2013-12-28 11:02:12 -0500 |
| commit | 127f9f098bcb7f5239097ade4c36c7e71c47b16a (patch) | |
| tree | 79462f3de06bae24413dc5fa57bcb7a77398935c | |
| parent | 7f14a72163cc51272905c9736e145af0f9824ebf (diff) | |
| parent | 378b92f5ef5212a7d76d2c58deb0f368c4f11a12 (diff) | |
| download | passlib-127f9f098bcb7f5239097ade4c36c7e71c47b16a.tar.gz | |
Merge with stable
57 files changed, 2400 insertions, 476 deletions
@@ -4,6 +4,9 @@ Release History =============== +**1.7** (NOT YET RELEASED) +========================== + .. warning:: **Passlib 1.7 will drop support for Python 2.5,** and require Python 2.6 or newer, @@ -16,6 +19,49 @@ Release History Passlib 1.7's :mod:`passlib.ext.django` extension will drop support for Django 1.3 and earlier, and require Django 1.4 or newer. +Major Changes +------------- +* New :mod:`passlib.pwd` module added to aid in password generation + and strength measurement (with contributions from Thomas Waldmann). + +* The :func:`~passlib.utils.pbkdf2.pbkdf2` function and all PBKDF2-based + hashes have been sped up by ~20% compared to Passlib 1.6. + +* Passlib will now detect and work around the fatal concurrency bug + in py-bcrypt 0.2 and earlier (a :exc:`~passlib.exc.PasslibSecurityWarning` + will also be issued). Nevertheless, users are *strongly* encouraged + to upgrade to py-bcrypt 0.3 or another bcrypt library if you are using + the :doc:`bcrypt </lib/passlib.hash.bcrypt>` hash. + +Minor Changes +------------- +* The shared :class:`!PasswordHash` unittests now check all hash handlers for + basic thread-safety (motivated by the pybcrypt 0.2 concurrency bug). + +* The internal support module :mod:`passlib.utils.pbkdf2` has gained + to new helpers: :func:`~passlib.utils.pbkdf2.get_hash_info` + and :func:`~passlib.utils.pbkdf2.get_keyed_prf`. + +Deprecations +------------ +* The :func:`~passlib.utils.generate_secret` function has been deprecated + in favor of the new :mod:`passlib.pwd` module, and will be removed + in Passlib 2.0. + +* :class:`passlib.utils.handlers.HasManyBackends` internal API change + + Applications implementing a custom handler with multiple backends + should now provide :samp:`_load_backend_{name}` classmethod for each backend. + This is simpler, more flexible, and more explicit than the + previous (1.6 and earlier) API, which required a :samp:`_has_backend_{name}` + class property and a :samp:`_calc_checksum_{name}` method. Support + for the older API is deprecated, and will it be removed in Passlib 2.0. + +Todo +---- + +* Thread safety audit and tests for CryptContext, HasManyBackends, and lazy-init subclasses. + **1.6.2** (2013-12-26) ====================== diff --git a/admin/benchmarks.py b/admin/benchmarks.py index 1491336..1a01951 100644 --- a/admin/benchmarks.py +++ b/admin/benchmarks.py @@ -17,8 +17,6 @@ sys.path.insert(0, os.curdir) # core from binascii import hexlify import logging; log = logging.getLogger(__name__) -import os -import warnings # site # pkg try: @@ -26,7 +24,7 @@ try: except ImportError: PasslibConfigWarning = None import passlib.utils.handlers as uh -from passlib.utils.compat import u, print_, unicode, next_method_attr +from passlib.utils.compat import u, print_, unicode # local #============================================================================= @@ -270,6 +268,16 @@ def test_phpass(): handler.verify(OTHER, hash) return helper +@benchmark.constructor() +def test_sha1_crypt(): + from passlib.hash import sha1_crypt as handler + kwds = dict(salt='.'*8, rounds=10000) + def helper(): + hash = handler.encrypt(SECRET, **kwds) + handler.verify(SECRET, hash) + handler.verify(OTHER, hash) + return helper + #============================================================================= # crypto utils #============================================================================= @@ -277,16 +285,30 @@ def test_phpass(): def test_pbkdf2_sha1(): from passlib.utils.pbkdf2 import pbkdf2 def helper(): - result = hexlify(pbkdf2("abracadabra", "open sesasme", 40960, 20, "hmac-sha1")) - assert result == 'ad317ed77bce584c90932b609e37e3736e6297bf', result + result = hexlify(pbkdf2("abracadabra", "open sesame", 10240, 20, "hmac-sha1")) + assert result == 'e45ce658e79b16107a418ad4634836f5f0601ad1', result return helper @benchmark.constructor() def test_pbkdf2_sha256(): from passlib.utils.pbkdf2 import pbkdf2 def helper(): - result = hexlify(pbkdf2("abracadabra", "open sesasme", 10240, 32, "hmac-sha256")) - assert result == '21d1ac0d474aaec49feb4f2172a266223e43edcf1052643dd27d82ebd5fa10c6', result + result = hexlify(pbkdf2("abracadabra", "open sesame", 10240, 32, "hmac-sha256")) + assert result == 'fadef97054306c93c55213cd57111d6c0791735dcdde8ac32f9f934b49c5af1e', result + return helper + +#============================================================================= +# entropy estimates +#============================================================================= +@benchmark.constructor() +def test_average_entropy(): + from passlib.pwd import _average_entropy + testc = "abcdef"*100000 + def helper(): + _average_entropy(testc) + _average_entropy(testc, True) + _average_entropy(iter(testc)) + _average_entropy(iter(testc), True) return helper #============================================================================= diff --git a/choose_rounds.py b/choose_rounds.py new file mode 100644 index 0000000..d9967fc --- /dev/null +++ b/choose_rounds.py @@ -0,0 +1,166 @@ +"""cli helper for selecting appropriate <rounds> value for a given hash""" +#============================================================================= +# imports +#============================================================================= +from __future__ import division +# core +import math +import logging; log = logging.getLogger(__name__) +import sys +# site +# pkg +from passlib.registry import get_crypt_handler +from passlib.utils import tick +# local +__all__ = [ + "main", +] + +#============================================================================= +# main +#============================================================================= +_usage = "usage: python choose_rounds.py <hash_name> [<target_milliseconds>]\n" + +def main(*args): + #--------------------------------------------------------------- + # parse args + #--------------------------------------------------------------- + args = list(args) + def print_error(msg): + print "error: %s\n" % msg + + # parse hasher + if args: + name = args.pop(0) + if name == "-h" or name == "--help": + print _usage + return 1 + try: + hasher = get_crypt_handler(name) + except KeyError: + print_error("unknown hash %r" % name) + return 1 + if 'rounds' not in hasher.setting_kwds: + print_error("%s does not support variable rounds" % name) + return 1 + else: + print_error("hash name not specified") + print _usage + return 1 + + # parse target time + if args: + try: + target = int(args.pop(0))*.001 + if target <= 0: + raise ValueError + except ValueError: + print_error("target time must be integer milliseconds > 0") + return 1 + else: + target = .350 + + #--------------------------------------------------------------- + # setup some helper functions + #--------------------------------------------------------------- + if hasher.rounds_cost == "log2": + # time cost varies logarithmically with rounds parameter, + # so speed = (2**rounds) / elapsed + def rounds_to_cost(rounds): + return 2 ** rounds + def cost_to_rounds(cost): + return math.log(cost, 2) + else: + # time cost varies linearly with rounds parameter, + # so speed = rounds / elapsed + assert hasher.rounds_cost == "linear" + rounds_to_cost = cost_to_rounds = lambda value: value + + def clamp_rounds(rounds): + """convert float rounds to int value, clamped to hasher's limits""" + if hasher.max_rounds and rounds > hasher.max_rounds: + rounds = hasher.max_rounds + rounds = int(rounds) + if getattr(hasher, "_avoid_even_rounds", False): + rounds |= 1 + return max(hasher.min_rounds, rounds) + + def average(seq): + if not hasattr(seq, "__length__"): + seq = tuple(seq) + return sum(seq) / len(seq) + + def estimate_speed(rounds): + """estimate speed using specified # of rounds""" + # time a single verify() call + secret = "S0m3-S3Kr1T" + hash = hasher.encrypt(secret, rounds=rounds) + def helper(): + start = tick() + hasher.verify(secret, hash) + return tick() - start + # try to get average time over a few samples + # XXX: way too much variability between sampling runs, + # would like to improve this bit + elapsed = min(average(helper() for _ in range(4)) for _ in range(4)) + return rounds_to_cost(rounds) / elapsed + + #--------------------------------------------------------------- + # get rough estimate of speed using fraction of default_rounds + # (so we don't take crazy long amounts of time on slow systems) + #--------------------------------------------------------------- + rounds = clamp_rounds(cost_to_rounds(.5 * rounds_to_cost(hasher.default_rounds))) + speed = estimate_speed(rounds) + + #--------------------------------------------------------------- + # re-do estimate using previous result, + # to get more accurate sample using a larger number of rounds. + #--------------------------------------------------------------- + for _ in range(2): + rounds = clamp_rounds(cost_to_rounds(speed * target)) + speed = estimate_speed(rounds) + + #--------------------------------------------------------------- + # using final estimate, calc desired number of rounds for target time + #--------------------------------------------------------------- + if hasattr(hasher, "backends"): + name = "%s (using %s backend)" % (name, hasher.get_backend()) + print "hash............: %s" % name + if speed < 1000: + speedstr = "%.2f" % speed + else: + speedstr = int(speed) + print "speed...........: %s iterations/second" % speedstr + print "target time.....: %d ms" % (target*1000,) + rounds = cost_to_rounds(speed * target) + if hasher.rounds_cost == "log2": + # for log2 rounds parameter, target time will usually fall + # somewhere between two integer values, which will have large gulf + # between them. if target is within <tolerance> percent of + # one of two ends, report it, otherwise list both and let user decide. + tolerance = .05 + lower = clamp_rounds(rounds) + upper = clamp_rounds(math.ceil(rounds)) + lower_elapsed = rounds_to_cost(lower) / speed + upper_elapsed = rounds_to_cost(upper) / speed + if (target-lower_elapsed)/target < tolerance: + print "target rounds...: %d" % lower + elif (upper_elapsed-target)/target < tolerance: + print "target rounds...: %d" % upper + else: + print "target rounds...: %d (%dms -- %dms faster than requested)" % \ + (lower, lower_elapsed*1000, (target - lower_elapsed) * 1000) + print "target rounds...: %d (%dms -- %dms slower than requested)" % \ + (upper, upper_elapsed*1000, (upper_elapsed - target) * 1000) + else: + # for linear rounds parameter, just use nearest integer value + rounds = clamp_rounds(round(rounds)) + print "target rounds...: %d" % (rounds,) + print + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) + +#============================================================================= +# eof +#============================================================================= diff --git a/docs/contents.rst b/docs/contents.rst index 099c5f8..700735f 100644 --- a/docs/contents.rst +++ b/docs/contents.rst @@ -20,6 +20,7 @@ Table Of Contents lib/passlib.apache lib/passlib.ext.django + lib/passlib.pwd lib/passlib.exc lib/passlib.registry diff --git a/docs/index.rst b/docs/index.rst index 270fcba..97be1fc 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -85,6 +85,9 @@ Application Helpers :mod:`passlib.ext.django` Django plugin which monkeypatches support for (almost) any hash in Passlib. + :mod:`passlib.pwd` + Password generation helpers. + .. Support Modules --------------- diff --git a/docs/lib/passlib.context.rst b/docs/lib/passlib.context.rst index 6df24ba..6d40067 100644 --- a/docs/lib/passlib.context.rst +++ b/docs/lib/passlib.context.rst @@ -458,8 +458,8 @@ if any invalid-but-correctable values are encountered :class:`~passlib.hash.sha256_crypt` 's minimum of 1000). .. versionchanged:: 1.6 - Previous releases issued a generic :exc:`UserWarning` instead - of the more specific :exc:`PasslibConfigWarning`. + Previous releases used Python's builtin :exc:`UserWarning` instead + of the more specific :exc:`!passlib.exc.PasslibConfigWarning`. Other Helpers ============= diff --git a/docs/lib/passlib.hash.rst b/docs/lib/passlib.hash.rst index c4d7574..8fbea1d 100644 --- a/docs/lib/passlib.hash.rst +++ b/docs/lib/passlib.hash.rst @@ -123,7 +123,6 @@ they can be used compatibly along side other modular crypt format hashes. :maxdepth: 1 passlib.hash.apr_md5_crypt - passlib.hash.bcrypt_sha256 passlib.hash.phpass passlib.hash.pbkdf2_digest passlib.hash.cta_pbkdf2_sha1 diff --git a/docs/lib/passlib.pwd.rst b/docs/lib/passlib.pwd.rst new file mode 100644 index 0000000..48441df --- /dev/null +++ b/docs/lib/passlib.pwd.rst @@ -0,0 +1,48 @@ +.. module:: passlib.pwd + :synopsis: password generation helpers + +================================================= +:mod:`passlib.pwd` -- password generation helpers +================================================= + +.. versionadded:: 1.7 + +.. todo:: + This module is still a work in progress, it's API may change + before release. See module source for detailed todo list. + +Generation +========== +.. warning:: + + Before using these routines, be sure your system's RNG state is safe, + and that you use a sufficiently high ``entropy`` value for + the intended purpose. + +.. autofunction:: generate(size=None, entropy=None, count=None, preset=None, charset=None, wordset=None, spaces=True) + +.. rst-class:: html-toggle + +Generator Backends +------------------ +The following classes are used by the :func:`generate` function behind the scenes, +to perform word- and phrase- generation. They are useful for folks who want +a little more information about the password generation process, and/or +want to use a preconfigured generator. + +.. autoclass:: SecretGenerator +.. autoclass:: WordGenerator +.. autoclass:: PhraseGenerator + +Analysis +======== +.. warning:: + + *Disclaimer:* + There can be no accurate estimate of the quality of a password, + because it depends on too many conditions that are unknowable from just + looking at the password. This code attempts to rule out the worst passwords, + and identify potentially-weak passwords, but should be used only as a guide. + +.. autofunction:: strength +.. autofunction:: classify diff --git a/docs/lib/passlib.utils.pbkdf2.rst b/docs/lib/passlib.utils.pbkdf2.rst index f8eb89f..7fa9f98 100644 --- a/docs/lib/passlib.utils.pbkdf2.rst +++ b/docs/lib/passlib.utils.pbkdf2.rst @@ -26,7 +26,10 @@ PKCS#5 Key Derivation Functions Helper Functions ================ .. autofunction:: norm_hash_name +.. autofunction:: get_hash_info + .. autofunction:: get_prf +.. autofunction:: get_keyed_prf .. given how this module is expanding in scope, diff --git a/docs/password_hash_api.rst b/docs/password_hash_api.rst index 69e0d5c..c9d6191 100644 --- a/docs/password_hash_api.rst +++ b/docs/password_hash_api.rst @@ -630,7 +630,7 @@ and the following attributes should be defined: The maximum number of rounds the scheme allows. Specifying a value beyond this will result in a :exc:`ValueError`. - Will be a positive integer, or ``None`` (indicating + This will be either a positive integer, or ``None`` (indicating the algorithm has no effective upper limit). .. attribute:: PasswordHash.min_rounds @@ -720,8 +720,8 @@ and the following attributes should be defined: Choosing the right rounds value =============================== -For hash algorithms which support a variable time-cost, -Passlib's default ``rounds`` choices attempt to be secure enough for +For hash algorithms with a variable time-cost, +Passlib's :attr:`~PasswordHash.default_rounds` values attempt to be secure enough for the average [#avgsys]_ system. But the "right" value for a given hash is dependant on the server, its cpu, its expected load, and its users. Since larger values mean increased work for an attacker, @@ -733,8 +733,8 @@ take upwards of 250ms - 400ms before users start getting annoyed. For superuser accounts, it should take as much time as the admin can stand (usually ~4x more delay than a regular account). -Passlib's ``default_rounds`` values are retuned periodically -by taking a rough estimate of what an "average" system is capable of, +Passlib's :attr:`!default_rounds` values are retuned periodically, +starting with a rough estimate of what an "average" system is capable of, and then setting all :samp:`{hash}.default_rounds` values to take ~300ms on such a system. However, some older algorithms (e.g. :class:`~passlib.hash.bsdi_crypt`) are weak enough that a tradeoff must be made, choosing "secure but intolerably slow" over "fast but unacceptably insecure". diff --git a/passlib/__init__.py b/passlib/__init__.py index aeea1fc..3e435c2 100644 --- a/passlib/__init__.py +++ b/passlib/__init__.py @@ -1,3 +1,3 @@ """passlib - suite of password hashing & generation routinges""" -__version__ = '1.6.2' +__version__ = '1.7.dev0' diff --git a/passlib/_data/beale.wordset.z b/passlib/_data/beale.wordset.z Binary files differnew file mode 100644 index 0000000..f94b381 --- /dev/null +++ b/passlib/_data/beale.wordset.z diff --git a/passlib/_data/diceware.wordset.z b/passlib/_data/diceware.wordset.z Binary files differnew file mode 100644 index 0000000..675e792 --- /dev/null +++ b/passlib/_data/diceware.wordset.z diff --git a/passlib/_data/electrum.wordset.z b/passlib/_data/electrum.wordset.z Binary files differnew file mode 100644 index 0000000..f22575a --- /dev/null +++ b/passlib/_data/electrum.wordset.z diff --git a/passlib/_setup/stamp.py b/passlib/_setup/stamp.py index 8a68658..d5e559f 100644 --- a/passlib/_setup/stamp.py +++ b/passlib/_setup/stamp.py @@ -6,7 +6,6 @@ from __future__ import with_statement # core import os import re -import time from distutils.dist import Distribution # pkg # local diff --git a/passlib/apache.py b/passlib/apache.py index ad39704..4b5654c 100644 --- a/passlib/apache.py +++ b/passlib/apache.py @@ -5,19 +5,17 @@ #============================================================================= from __future__ import with_statement # core -from hashlib import md5 import logging; log = logging.getLogger(__name__) import os -import sys from warnings import warn # site # pkg from passlib.context import CryptContext from passlib.exc import ExpectedStringError from passlib.hash import htdigest -from passlib.utils import consteq, render_bytes, to_bytes, deprecated_method, is_ascii_codec -from passlib.utils.compat import b, bytes, join_bytes, str_to_bascii, u, \ - unicode, BytesIO, iteritems, imap, PY3 +from passlib.utils import render_bytes, to_bytes, deprecated_method, is_ascii_codec +from passlib.utils.compat import b, bytes, join_bytes, unicode, BytesIO, \ + iteritems, PY3 # local __all__ = [ 'HtpasswdFile', diff --git a/passlib/context.py b/passlib/context.py index e489f7d..e581eb9 100644 --- a/passlib/context.py +++ b/passlib/context.py @@ -4,14 +4,8 @@ #============================================================================= from __future__ import with_statement # core -from functools import update_wrapper -import inspect -import re -import hashlib from math import log as logb, ceil import logging; log = logging.getLogger(__name__) -import os -import re from time import sleep from warnings import warn # site diff --git a/passlib/handlers/bcrypt.py b/passlib/handlers/bcrypt.py index 5158fcd..f1e166f 100644 --- a/passlib/handlers/bcrypt.py +++ b/passlib/handlers/bcrypt.py @@ -19,18 +19,14 @@ import re import logging; log = logging.getLogger(__name__) from warnings import warn # site -try: - import bcrypt as _bcrypt -except ImportError: # pragma: no cover - _bcrypt = None -try: - from bcryptor.engine import Engine as bcryptor_engine -except ImportError: # pragma: no cover - bcryptor_engine = None +_bcrypt = None # dynamically imported by _load_backend_bcrypt() +_pybcrypt = None # dynamically imported by _load_backend_pybcrypt() +_bcryptor_engine = None # dynamically imported by _load_backend_bcryptor() # pkg +_builtin_bcrypt = None # dynamically imported by _load_backend_builtin() from passlib.exc import PasslibHashWarning -from passlib.utils import bcrypt64, safe_crypt, repeat_string, to_bytes, \ - classproperty, rng, getrandstr, test_crypt, to_unicode +from passlib.utils import bcrypt64, safe_crypt, repeat_string, to_bytes, parse_version, \ + rng, getrandstr, test_crypt, to_unicode from passlib.utils.compat import bytes, b, u, uascii_to_str, unicode, str_to_uascii import passlib.utils.handlers as uh @@ -42,13 +38,6 @@ __all__ = [ #============================================================================= # support funcs & constants #============================================================================= -_builtin_bcrypt = None - -def _load_builtin(): - global _builtin_bcrypt - if _builtin_bcrypt is None: - from passlib.utils._blowfish import raw_bcrypt as _builtin_bcrypt - IDENT_2 = u("$2$") IDENT_2A = u("$2a$") IDENT_2X = u("$2x$") @@ -237,41 +226,13 @@ class bcrypt(uh.HasManyIdents, uh.HasRounds, uh.HasSalt, uh.HasManyBackends, uh. return checksum #=================================================================== - # primary interface + # backend configuration #=================================================================== - backends = ("bcrypt", "pybcrypt", "bcryptor", "os_crypt", "builtin") - - @classproperty - def _has_backend_bcrypt(cls): - return _bcrypt is not None and hasattr(_bcrypt, "_ffi") - @classproperty - def _has_backend_pybcrypt(cls): - return _bcrypt is not None and not hasattr(_bcrypt, "_ffi") - - @classproperty - def _has_backend_bcryptor(cls): - return bcryptor_engine is not None - - @classproperty - def _has_backend_builtin(cls): - if os.environ.get("PASSLIB_BUILTIN_BCRYPT") not in ["enable","enabled"]: - return False - # look at it cross-eyed, and it loads itself - _load_builtin() - return True + backends = ("bcrypt", "pybcrypt", "bcryptor", "os_crypt", "builtin") - @classproperty - def _has_backend_os_crypt(cls): - # XXX: what to do if "2" isn't supported, but "2a" is? - # "2" is *very* rare, and can fake it using "2a"+repeat_string - h1 = '$2$04$......................1O4gOrCYaqBG3o/4LnT2ykQUt1wbyju' - h2 = '$2a$04$......................qiOQjkB8hxU8OzRhS.GhRMa4VUnkPty' - return test_crypt("test",h1) and test_crypt("test", h2) - - @classmethod - def _no_backends_msg(cls): - return "no bcrypt backends available - please install py-bcrypt" + # appended to HasManyBackends' "no backends available" error message + _no_backend_suggestion = " -- recommend you install one (e.g. 'pip install bcrypt')" def _calc_checksum(self, secret): "common backend code" @@ -284,23 +245,22 @@ class bcrypt(uh.HasManyIdents, uh.HasRounds, uh.HasSalt, uh.HasManyBackends, uh. raise uh.exc.NullPasswordError(self) return self._calc_checksum_backend(secret) - def _calc_checksum_os_crypt(self, secret): - config = self._get_config() - hash = safe_crypt(secret, config) - if hash: - assert hash.startswith(config) and len(hash) == len(config)+31 - return hash[-31:] - else: - # NOTE: it's unlikely any other backend will be available, - # but checking before we bail, just in case. - for name in self.backends: - if name != "os_crypt" and self.has_backend(name): - func = getattr(self, "_calc_checksum_" + name) - return func(secret) - raise uh.exc.MissingBackendError( - "password can't be handled by os_crypt, " - "recommend installing py-bcrypt.", - ) + #--------------------------------------------------------------- + # bcrypt backend + #--------------------------------------------------------------- + @classmethod + def _load_backend_bcrypt(cls): + # try to import bcrypt + global _bcrypt + try: + import bcrypt as _bcrypt + except ImportError: # pragma: no cover + return None + if not hasattr(_bcrypt, "_ffi"): + # pybcrypt was installed instead + _bcrypt = None + return None + return cls._calc_checksum_bcrypt def _calc_checksum_bcrypt(self, secret): # bcrypt behavior: @@ -323,6 +283,57 @@ class bcrypt(uh.HasManyIdents, uh.HasRounds, uh.HasSalt, uh.HasManyBackends, uh. assert isinstance(hash, bytes) return hash[-31:].decode("ascii") + #--------------------------------------------------------------- + # pybcrypt backend + #--------------------------------------------------------------- + + #: classwide thread lock used for pybcrypt < 0.3 + _calc_lock = None + + @classmethod + def _load_backend_pybcrypt(cls): + # try to import pybcrypt + global _pybcrypt + try: + import bcrypt as _pybcrypt + except ImportError: # pragma: no cover + return None + if hasattr(_pybcrypt, "_ffi"): + # bcrypt was installed instead + _pybcrypt = None + return None + + # determine pybcrypt version + try: + from bcrypt._bcrypt import __version__ as vstr + except ImportError: + log.warning("couldn't determine pybcrypt version", exc_info=True) + vstr = "?.?" + version = parse_version(vstr) + if not version: + log.warning("couldn't parse pybcrypt version string: %r", vstr) + version = (0, 0) + log.debug("found pybcrypt version %s", vstr) + + # return calc function based on version + if version < (0,3): + warn("py-bcrypt %s has a major security vulnerability, " + "you should upgrade to py-bcrypt 0.3 immediately." + % vstr, uh.exc.PasslibSecurityWarning) + if cls._calc_lock is None: + import threading + cls._calc_lock = threading.Lock() + return cls._calc_checksum_pybcrypt_threadsafe + else: + return cls._calc_checksum_pybcrypt + + def _calc_checksum_pybcrypt_threadsafe(self, secret): + # as workaround for pybcrypt < 0.3's concurrency issue, + # we wrap everything in a thread lock. as long as bcrypt is only + # used through passlib, this should be safe. + with self._calc_lock: + return self._calc_checksum_pybcrypt(secret) + def _calc_checksum_pybcrypt(self, secret): # py-bcrypt behavior: # py2: unicode secret/hash encoded as ascii bytes before use, @@ -330,10 +341,23 @@ class bcrypt(uh.HasManyIdents, uh.HasRounds, uh.HasSalt, uh.HasManyBackends, uh. # py3: unicode secret encoded as utf-8 bytes, # hash encoded as ascii bytes, returns ascii unicode. config = self._get_config() - hash = _bcrypt.hashpw(secret, config) + hash = _pybcrypt.hashpw(secret, config) assert hash.startswith(config) and len(hash) == len(config)+31 return str_to_uascii(hash[-31:]) + #--------------------------------------------------------------- + # bcryptor backend + #--------------------------------------------------------------- + @classmethod + def _load_backend_bcryptor(cls): + # try to import bcryptor + global _bcryptor_engine + try: + from bcryptor.engine import Engine as _bcryptor_engine + except ImportError: # pragma: no cover + return None + return cls._calc_checksum_bcryptor + def _calc_checksum_bcryptor(self, secret): # bcryptor behavior: # py2: unicode secret/hash encoded as ascii bytes before use, @@ -348,10 +372,46 @@ class bcrypt(uh.HasManyIdents, uh.HasRounds, uh.HasSalt, uh.HasManyBackends, uh. config = self._get_config(IDENT_2A) else: config = self._get_config() - hash = bcryptor_engine(False).hash_key(secret, config) + hash = _bcryptor_engine(False).hash_key(secret, config) assert hash.startswith(config) and len(hash) == len(config)+31 return str_to_uascii(hash[-31:]) + #--------------------------------------------------------------- + # os crypt() backend + #--------------------------------------------------------------- + @classmethod + def _load_backend_os_crypt(cls): + # XXX: what to do if "2" isn't supported, but "2a" is? + # "2" is *very* rare, and can fake it using "2a"+repeat_string + h1 = '$2$04$......................1O4gOrCYaqBG3o/4LnT2ykQUt1wbyju' + h2 = '$2a$04$......................qiOQjkB8hxU8OzRhS.GhRMa4VUnkPty' + if test_crypt("test", h1) and test_crypt("test", h2): + return cls._calc_checksum_os_crypt + return None + + def _calc_checksum_os_crypt(self, secret): + config = self._get_config() + hash = safe_crypt(secret, config) + if hash: + assert hash.startswith(config) and len(hash) == len(config)+31 + return hash[-31:] + # get here mainly if 1) under py3, and 2) secret is latin-1 or other non-unicode bytes. + # in this case, another backend like pybcrypt should be able to get around + # py3's limitations. + return self._try_alternate_backends(secret) + + #--------------------------------------------------------------- + # builtin backend + #--------------------------------------------------------------- + @classmethod + def _load_backend_builtin(cls): + if os.environ.get("PASSLIB_BUILTIN_BCRYPT") not in ["enable","enabled"]: + return None + global _builtin_bcrypt + if _builtin_bcrypt is None: + from passlib.utils._blowfish import raw_bcrypt as _builtin_bcrypt + return cls._calc_checksum_builtin + def _calc_checksum_builtin(self, secret): chk = _builtin_bcrypt(secret, self.ident.strip("$"), self.salt.encode("ascii"), self.rounds) diff --git a/passlib/handlers/cisco.py b/passlib/handlers/cisco.py index 1588e80..be2956f 100644 --- a/passlib/handlers/cisco.py +++ b/passlib/handlers/cisco.py @@ -10,8 +10,8 @@ from warnings import warn # site # pkg from passlib.utils import h64, right_pad_string, to_unicode -from passlib.utils.compat import b, bascii_to_str, bytes, unicode, u, join_byte_values, \ - join_byte_elems, byte_elem_value, iter_byte_values, uascii_to_str, str_to_uascii +from passlib.utils.compat import unicode, u, join_byte_values, \ + join_byte_elems, iter_byte_values, uascii_to_str import passlib.utils.handlers as uh # local __all__ = [ diff --git a/passlib/handlers/des_crypt.py b/passlib/handlers/des_crypt.py index dc28783..3da3e41 100644 --- a/passlib/handlers/des_crypt.py +++ b/passlib/handlers/des_crypt.py @@ -8,7 +8,7 @@ import logging; log = logging.getLogger(__name__) from warnings import warn # site # pkg -from passlib.utils import classproperty, h64, h64big, safe_crypt, test_crypt, to_unicode +from passlib.utils import h64, h64big, safe_crypt, test_crypt, to_unicode from passlib.utils.compat import b, bytes, byte_elem_value, u, uascii_to_str, unicode from passlib.utils.des import des_encrypt_int_block import passlib.utils.handlers as uh @@ -176,14 +176,14 @@ class des_crypt(uh.HasManyBackends, uh.HasSalt, uh.GenericHandler): #=================================================================== backends = ("os_crypt", "builtin") - _has_backend_builtin = True - - @classproperty - def _has_backend_os_crypt(cls): - return test_crypt("test", 'abgOeLfPimXQo') - - def _calc_checksum_builtin(self, secret): - return _raw_des_crypt(secret, self.salt.encode("ascii")).decode("ascii") + #--------------------------------------------------------------- + # os_crypt backend + #--------------------------------------------------------------- + @classmethod + def _load_backend_os_crypt(cls): + if test_crypt("test", 'abgOeLfPimXQo'): + return cls._calc_checksum_os_crypt + return None def _calc_checksum_os_crypt(self, secret): # NOTE: safe_crypt encodes unicode secret -> utf8 @@ -192,8 +192,17 @@ class des_crypt(uh.HasManyBackends, uh.HasSalt, uh.GenericHandler): if hash: assert hash.startswith(self.salt) and len(hash) == 13 return hash[2:] - else: - return self._calc_checksum_builtin(secret) + return self._try_alternate_backends(secret) + + #--------------------------------------------------------------- + # builtin backend + #--------------------------------------------------------------- + @classmethod + def _load_backend_builtin(cls): + return cls._calc_checksum_builtin + + def _calc_checksum_builtin(self, secret): + return _raw_des_crypt(secret, self.salt.encode("ascii")).decode("ascii") #=================================================================== # eoc @@ -316,14 +325,14 @@ class bsdi_crypt(uh.HasManyBackends, uh.HasRounds, uh.HasSalt, uh.GenericHandler #=================================================================== backends = ("os_crypt", "builtin") - _has_backend_builtin = True - - @classproperty - def _has_backend_os_crypt(cls): - return test_crypt("test", '_/...lLDAxARksGCHin.') - - def _calc_checksum_builtin(self, secret): - return _raw_bsdi_crypt(secret, self.rounds, self.salt.encode("ascii")).decode("ascii") + #--------------------------------------------------------------- + # os_crypt backend + #--------------------------------------------------------------- + @classmethod + def _load_backend_os_crypt(cls): + if test_crypt("test", '_/...lLDAxARksGCHin.'): + return cls._calc_checksum_os_crypt + return None def _calc_checksum_os_crypt(self, secret): config = self.to_string() @@ -331,8 +340,17 @@ class bsdi_crypt(uh.HasManyBackends, uh.HasRounds, uh.HasSalt, uh.GenericHandler if hash: assert hash.startswith(config[:9]) and len(hash) == 20 return hash[-11:] - else: - return self._calc_checksum_builtin(secret) + return self._try_alternate_backends(secret) + + #--------------------------------------------------------------- + # builtin backend + #--------------------------------------------------------------- + @classmethod + def _load_backend_builtin(cls): + return cls._calc_checksum_builtin + + def _calc_checksum_builtin(self, secret): + return _raw_bsdi_crypt(secret, self.rounds, self.salt.encode("ascii")).decode("ascii") #=================================================================== # eoc diff --git a/passlib/handlers/digests.py b/passlib/handlers/digests.py index 402c670..39ef4b4 100644 --- a/passlib/handlers/digests.py +++ b/passlib/handlers/digests.py @@ -6,11 +6,10 @@ # core import hashlib import logging; log = logging.getLogger(__name__) -from warnings import warn # site # pkg from passlib.utils import to_native_str, to_bytes, render_bytes, consteq -from passlib.utils.compat import bascii_to_str, bytes, unicode, str_to_uascii +from passlib.utils.compat import unicode, str_to_uascii import passlib.utils.handlers as uh from passlib.utils.md4 import md4 # local diff --git a/passlib/handlers/django.py b/passlib/handlers/django.py index cdb853b..0413f7b 100644 --- a/passlib/handlers/django.py +++ b/passlib/handlers/django.py @@ -6,14 +6,12 @@ from base64 import b64encode from binascii import hexlify from hashlib import md5, sha1, sha256 -import re import logging; log = logging.getLogger(__name__) -from warnings import warn # site # pkg from passlib.hash import bcrypt, pbkdf2_sha1, pbkdf2_sha256 from passlib.utils import to_unicode, classproperty -from passlib.utils.compat import b, bytes, str_to_uascii, uascii_to_str, unicode, u +from passlib.utils.compat import str_to_uascii, uascii_to_str, unicode, u from passlib.utils.pbkdf2 import pbkdf2 import passlib.utils.handlers as uh # local diff --git a/passlib/handlers/fshp.py b/passlib/handlers/fshp.py index 6efc782..81f5004 100644 --- a/passlib/handlers/fshp.py +++ b/passlib/handlers/fshp.py @@ -8,7 +8,6 @@ from base64 import b64encode, b64decode import re import logging; log = logging.getLogger(__name__) -from warnings import warn # site # pkg from passlib.utils import to_unicode diff --git a/passlib/handlers/ldap_digests.py b/passlib/handlers/ldap_digests.py index fb378c0..54a7517 100644 --- a/passlib/handlers/ldap_digests.py +++ b/passlib/handlers/ldap_digests.py @@ -8,13 +8,11 @@ from base64 import b64encode, b64decode from hashlib import md5, sha1 import logging; log = logging.getLogger(__name__) import re -from warnings import warn # site # pkg from passlib.handlers.misc import plaintext -from passlib.utils import to_native_str, unix_crypt_schemes, \ - classproperty, to_unicode -from passlib.utils.compat import b, bytes, uascii_to_str, unicode, u +from passlib.utils import unix_crypt_schemes, classproperty, to_unicode +from passlib.utils.compat import b, uascii_to_str, unicode, u import passlib.utils.handlers as uh # local __all__ = [ diff --git a/passlib/handlers/md5_crypt.py b/passlib/handlers/md5_crypt.py index bb28b16..64b78bb 100644 --- a/passlib/handlers/md5_crypt.py +++ b/passlib/handlers/md5_crypt.py @@ -4,13 +4,11 @@ #============================================================================= # core from hashlib import md5 -import re import logging; log = logging.getLogger(__name__) -from warnings import warn # site # pkg -from passlib.utils import classproperty, h64, safe_crypt, test_crypt, repeat_string -from passlib.utils.compat import b, bytes, irange, unicode, u +from passlib.utils import h64, safe_crypt, test_crypt, repeat_string +from passlib.utils.compat import b, bytes, unicode, u import passlib.utils.handlers as uh # local __all__ = [ @@ -267,14 +265,14 @@ class md5_crypt(uh.HasManyBackends, _MD5_Common): backends = ("os_crypt", "builtin") - _has_backend_builtin = True - - @classproperty - def _has_backend_os_crypt(cls): - return test_crypt("test", '$1$test$pi/xDtU5WFVRqYS6BMU8X/') - - def _calc_checksum_builtin(self, secret): - return _raw_md5_crypt(secret, self.salt) + #--------------------------------------------------------------- + # os_crypt backend + #--------------------------------------------------------------- + @classmethod + def _load_backend_os_crypt(cls): + if test_crypt("test", '$1$test$pi/xDtU5WFVRqYS6BMU8X/'): + return cls._calc_checksum_os_crypt + return None def _calc_checksum_os_crypt(self, secret): config = self.ident + self.salt @@ -282,8 +280,17 @@ class md5_crypt(uh.HasManyBackends, _MD5_Common): if hash: assert hash.startswith(config) and len(hash) == len(config) + 23 return hash[-22:] - else: - return self._calc_checksum_builtin(secret) + return self._try_alternate_backends(secret) + + #--------------------------------------------------------------- + # builtin backend + #--------------------------------------------------------------- + @classmethod + def _load_backend_builtin(cls): + return cls._calc_checksum_builtin + + def _calc_checksum_builtin(self, secret): + return _raw_md5_crypt(secret, self.salt) #=================================================================== # eoc diff --git a/passlib/handlers/oracle.py b/passlib/handlers/oracle.py index 3cd3ba1..eb84161 100644 --- a/passlib/handlers/oracle.py +++ b/passlib/handlers/oracle.py @@ -7,11 +7,10 @@ from binascii import hexlify, unhexlify from hashlib import sha1 import re import logging; log = logging.getLogger(__name__) -from warnings import warn # site # pkg -from passlib.utils import to_unicode, to_native_str, xor_bytes -from passlib.utils.compat import b, bytes, bascii_to_str, irange, u, \ +from passlib.utils import to_unicode, xor_bytes +from passlib.utils.compat import b, bytes, irange, u, \ uascii_to_str, unicode, str_to_uascii from passlib.utils.des import des_encrypt_block import passlib.utils.handlers as uh diff --git a/passlib/handlers/pbkdf2.py b/passlib/handlers/pbkdf2.py index caf793d..856a825 100644 --- a/passlib/handlers/pbkdf2.py +++ b/passlib/handlers/pbkdf2.py @@ -5,13 +5,11 @@ # core from binascii import hexlify, unhexlify from base64 import b64encode, b64decode -import re import logging; log = logging.getLogger(__name__) -from warnings import warn # site # pkg from passlib.utils import ab64_decode, ab64_encode, to_unicode -from passlib.utils.compat import b, bytes, str_to_bascii, u, uascii_to_str, unicode +from passlib.utils.compat import b, str_to_bascii, u, uascii_to_str, unicode from passlib.utils.pbkdf2 import pbkdf2 import passlib.utils.handlers as uh # local diff --git a/passlib/handlers/phpass.py b/passlib/handlers/phpass.py index c1e8a5f..058471d 100644 --- a/passlib/handlers/phpass.py +++ b/passlib/handlers/phpass.py @@ -10,13 +10,11 @@ phpass context - blowfish, bsdi_crypt, phpass #============================================================================= # core from hashlib import md5 -import re import logging; log = logging.getLogger(__name__) -from warnings import warn # site # pkg from passlib.utils import h64 -from passlib.utils.compat import b, bytes, u, uascii_to_str, unicode +from passlib.utils.compat import u, uascii_to_str, unicode import passlib.utils.handlers as uh # local __all__ = [ diff --git a/passlib/handlers/postgres.py b/passlib/handlers/postgres.py index b8683dd..634b77e 100644 --- a/passlib/handlers/postgres.py +++ b/passlib/handlers/postgres.py @@ -4,13 +4,11 @@ #============================================================================= # core from hashlib import md5 -import re import logging; log = logging.getLogger(__name__) -from warnings import warn # site # pkg from passlib.utils import to_bytes -from passlib.utils.compat import b, bytes, str_to_uascii, unicode, u +from passlib.utils.compat import str_to_uascii, unicode, u import passlib.utils.handlers as uh # local __all__ = [ diff --git a/passlib/handlers/scram.py b/passlib/handlers/scram.py index d9f1be7..06fc40e 100644 --- a/passlib/handlers/scram.py +++ b/passlib/handlers/scram.py @@ -3,20 +3,13 @@ # imports #============================================================================= # core -from binascii import hexlify, unhexlify -from base64 import b64encode, b64decode -import hashlib -import re import logging; log = logging.getLogger(__name__) -from warnings import warn # site # pkg -from passlib.exc import PasslibHashWarning from passlib.utils import ab64_decode, ab64_encode, consteq, saslprep, \ - to_native_str, xor_bytes, splitcomma -from passlib.utils.compat import b, bytes, bascii_to_str, iteritems, \ - PY3, u, unicode -from passlib.utils.pbkdf2 import pbkdf2, get_prf, norm_hash_name + to_native_str, splitcomma +from passlib.utils.compat import bytes, bascii_to_str, iteritems, u +from passlib.utils.pbkdf2 import pbkdf2, norm_hash_name import passlib.utils.handlers as uh # local __all__ = [ diff --git a/passlib/handlers/sha1_crypt.py b/passlib/handlers/sha1_crypt.py index 885c67f..d8f6fd6 100644 --- a/passlib/handlers/sha1_crypt.py +++ b/passlib/handlers/sha1_crypt.py @@ -6,16 +6,12 @@ #============================================================================= # core -from hmac import new as hmac -from hashlib import sha1 -import re import logging; log = logging.getLogger(__name__) -from warnings import warn # site # pkg -from passlib.utils import classproperty, h64, safe_crypt, test_crypt -from passlib.utils.compat import b, bytes, u, uascii_to_str, unicode -from passlib.utils.pbkdf2 import get_prf +from passlib.utils import h64, safe_crypt, test_crypt +from passlib.utils.compat import b, u, unicode, irange +from passlib.utils.pbkdf2 import get_keyed_prf import passlib.utils.handlers as uh # local __all__ = [ @@ -23,7 +19,6 @@ __all__ = [ #============================================================================= # sha1-crypt #============================================================================= -_hmac_sha1 = get_prf("hmac-sha1")[0] _BNULL = b('\x00') class sha1_crypt(uh.HasManyBackends, uh.HasRounds, uh.HasSalt, uh.GenericHandler): @@ -85,7 +80,6 @@ class sha1_crypt(uh.HasManyBackends, uh.HasRounds, uh.HasSalt, uh.GenericHandler #=================================================================== # formatting #=================================================================== - @classmethod def from_string(cls, hash): rounds, salt, chk = uh.parse_mc3(hash, cls.ident, handler=cls) @@ -100,12 +94,30 @@ class sha1_crypt(uh.HasManyBackends, uh.HasRounds, uh.HasSalt, uh.GenericHandler #=================================================================== backends = ("os_crypt", "builtin") - _has_backend_builtin = True + #--------------------------------------------------------------- + # os_crypt backend + #--------------------------------------------------------------- + @classmethod + def _load_backend_os_crypt(cls): + if test_crypt("test", '$sha1$1$Wq3GL2Vp$C8U25GvfHS8qGHim' + 'ExLaiSFlGkAe'): + return cls._calc_checksum_os_crypt + return None - @classproperty - def _has_backend_os_crypt(cls): - return test_crypt("test", '$sha1$1$Wq3GL2Vp$C8U25GvfHS8qGHim' - 'ExLaiSFlGkAe') + def _calc_checksum_os_crypt(self, secret): + config = self.to_string(config=True) + hash = safe_crypt(secret, config) + if hash: + assert hash.startswith(config) and len(hash) == len(config) + 29 + return hash[-28:] + return self._try_alternate_backends(secret) + + #--------------------------------------------------------------- + # builtin backend + #--------------------------------------------------------------- + @classmethod + def _load_backend_builtin(cls): + return cls._calc_checksum_builtin def _calc_checksum_builtin(self, secret): if isinstance(secret, unicode): @@ -116,10 +128,9 @@ class sha1_crypt(uh.HasManyBackends, uh.HasRounds, uh.HasSalt, uh.GenericHandler # NOTE: this seed value is NOT the same as the config string result = (u("%s$sha1$%s") % (self.salt, rounds)).encode("ascii") # NOTE: this algorithm is essentially PBKDF1, modified to use HMAC. - r = 0 - while r < rounds: - result = _hmac_sha1(secret, result) - r += 1 + keyed_hmac = get_keyed_prf("hmac-sha1", secret)[0] + for _ in irange(rounds): + result = keyed_hmac(result) return h64.encode_transposed_bytes(result, self._chk_offsets).decode("ascii") _chk_offsets = [ @@ -132,15 +143,6 @@ class sha1_crypt(uh.HasManyBackends, uh.HasRounds, uh.HasSalt, uh.GenericHandler 0,19,18, ] - def _calc_checksum_os_crypt(self, secret): - config = self.to_string(config=True) - hash = safe_crypt(secret, config) - if hash: - assert hash.startswith(config) and len(hash) == len(config) + 29 - return hash[-28:] - else: - return self._calc_checksum_builtin(secret) - #=================================================================== # eoc #=================================================================== diff --git a/passlib/handlers/sha2_crypt.py b/passlib/handlers/sha2_crypt.py index 11b485e..74b3036 100644 --- a/passlib/handlers/sha2_crypt.py +++ b/passlib/handlers/sha2_crypt.py @@ -5,12 +5,11 @@ # core import hashlib import logging; log = logging.getLogger(__name__) -from warnings import warn # site # pkg -from passlib.utils import classproperty, h64, safe_crypt, test_crypt, \ +from passlib.utils import h64, safe_crypt, test_crypt, \ repeat_string, to_unicode -from passlib.utils.compat import b, bytes, byte_elem_value, irange, u, \ +from passlib.utils.compat import b, bytes, byte_elem_value, u, \ uascii_to_str, unicode import passlib.utils.handlers as uh # local @@ -335,13 +334,18 @@ class _SHA2_Common(uh.HasManyBackends, uh.HasRounds, uh.HasSalt, #=================================================================== backends = ("os_crypt", "builtin") - _has_backend_builtin = True + #--------------------------------------------------------------- + # os_crypt backend + #--------------------------------------------------------------- - # _has_backend_os_crypt - provided by subclass + #: test hash for OS detection -- provided by subclass + _test_hash = None - def _calc_checksum_builtin(self, secret): - return _raw_sha2_crypt(secret, self.salt, self.rounds, - self._cdb_use_512) + @classmethod + def _load_backend_os_crypt(cls): + if test_crypt(*cls._test_hash): + return cls._calc_checksum_os_crypt + return None def _calc_checksum_os_crypt(self, secret): hash = safe_crypt(secret, self.to_string()) @@ -351,8 +355,18 @@ class _SHA2_Common(uh.HasManyBackends, uh.HasRounds, uh.HasSalt, cs = self.checksum_size assert hash.startswith(self.ident) and hash[-cs-1] == _UDOLLAR return hash[-cs:] - else: - return self._calc_checksum_builtin(secret) + return self._try_alternate_backends(secret) + + #--------------------------------------------------------------- + # builtin backend + #--------------------------------------------------------------- + @classmethod + def _load_backend_builtin(cls): + return cls._calc_checksum_builtin + + def _calc_checksum_builtin(self, secret): + return _raw_sha2_crypt(secret, self.salt, self.rounds, + self._cdb_use_512) #=================================================================== # eoc @@ -407,10 +421,8 @@ class sha256_crypt(_SHA2_Common): #=================================================================== # backends #=================================================================== - @classproperty - def _has_backend_os_crypt(cls): - return test_crypt("test", "$5$rounds=1000$test$QmQADEXMG8POI5W" - "Dsaeho0P36yK3Tcrgboabng6bkb/") + _test_hash = ("test", "$5$rounds=1000$test$QmQADEXMG8POI5W" + "Dsaeho0P36yK3Tcrgboabng6bkb/") #=================================================================== # eoc @@ -470,12 +482,10 @@ class sha512_crypt(_SHA2_Common): #=================================================================== # backend #=================================================================== - @classproperty - def _has_backend_os_crypt(cls): - return test_crypt("test", "$6$rounds=1000$test$2M/Lx6Mtobqj" - "Ljobw0Wmo4Q5OFx5nVLJvmgseatA6oMn" - "yWeBdRDx4DU.1H3eGmse6pgsOgDisWBG" - "I5c7TZauS0") + _test_hash = ("test", "$6$rounds=1000$test$2M/Lx6Mtobqj" + "Ljobw0Wmo4Q5OFx5nVLJvmgseatA6oMn" + "yWeBdRDx4DU.1H3eGmse6pgsOgDisWBG" + "I5c7TZauS0") #=================================================================== # eoc diff --git a/passlib/handlers/windows.py b/passlib/handlers/windows.py index 3f911be..6c16808 100644 --- a/passlib/handlers/windows.py +++ b/passlib/handlers/windows.py @@ -4,13 +4,12 @@ #============================================================================= # core from binascii import hexlify -import re import logging; log = logging.getLogger(__name__) from warnings import warn # site # pkg from passlib.utils import to_unicode, right_pad_string -from passlib.utils.compat import b, bytes, str_to_uascii, u, unicode, uascii_to_str +from passlib.utils.compat import b, bytes, unicode from passlib.utils.md4 import md4 import passlib.utils.handlers as uh # local diff --git a/passlib/hosts.py b/passlib/hosts.py index 7df3efd..01a2440 100644 --- a/passlib/hosts.py +++ b/passlib/hosts.py @@ -3,7 +3,6 @@ # imports #============================================================================= # core -import sys from warnings import warn # pkg from passlib.context import LazyCryptContext diff --git a/passlib/pwd.py b/passlib/pwd.py new file mode 100644 index 0000000..44a1e51 --- /dev/null +++ b/passlib/pwd.py @@ -0,0 +1,652 @@ +"""passlib.pwd -- password generation helpers. + +current api +=========== +generation + * frontend: generate() + * backends: PhraseGenerator(), WordGenerator() + +strength + * strength(), classify() + * XXX: consider redo-ing as returning an informational object, + ala ``https://github.com/lowe/zxcvbn``'s result object + +TODO +==== +This module's design is in flux, and may be changed before release. +The following known bits remain: + +misc +---- +* the terminology about what's being measured by _average_entropy() etc + may not be correct. this needs fixing before the module is released. + need to find a good reference on information theory, to make sure terminology + and formulas are correct :) + + * when researching, also need to find any papers attempting to measure + guessing entropy (w/ respect to cracker's attack model), + rather than entropy with respect to a particular password + generation algorithm. + +* add a "crack time" estimation to generate & classify? + might be useful to give people better idea of what measurements mean. + +generation +---------- +* unittests for generation code +* add create_generator() frontend? +* straighten out any unicode issues this code may have. + - primarily, this should always return unicode (currently doesn't) +* don't like existing wordsets. + - diceware has some weird bordercases that average users may not like + - electrum's set isn't large enough for these purposes + - looking into modified version of wordfrequency.info's 5k list + (could merge w/ diceware, and remove commonly used passwords) + +strength +-------- +* unittests for strength measurement +* improve api for strength measurement + * one issue: need way to indicate when measurement is a lower/upper + bound, rather than and/or the accuracy of a given measurement. + * need to present this in a way which makes it easy to write + a password-strength meter, + * yet can have it's scale tweaked if the heuristics are revised. + * could look at https://github.com/lowe/zxcvbn for some ideas. +* add more strength measurement algorithms + * NIST 800-63 should be easy + * zxcvbn (https://tech.dropbox.com/2012/04/zxcvbn-realistic-password-strength-estimation/) + might also be good, and has approach similar to composite approach + i was already thinking about. + * passfault (https://github.com/c-a-m/passfault) looks *very* thorough, + but may have licensing issues, plus porting to python + looks like very big job :( + * give a look at running things through zlib - might be able to cheaply + catch extra redundancies. +""" +#============================================================================= +# imports +#============================================================================= +from __future__ import division +# core +from collections import defaultdict +from hashlib import sha256 +from math import ceil, log as logf +import logging; log = logging.getLogger(__name__) +import os +import zlib +# site +# pkg +from passlib.utils.compat import PY3, irange, itervalues, u, chain_from_iterable +from passlib.utils import rng, getrandstr +# local +__all__ = [ + 'generate', + 'strength', + 'classify', +] + +#============================================================================= +# constants +#============================================================================= + +#: default entropy amount for generated passwords +default_entropy = 48 + +#: default threshold for rejecting low self-information sequences, +#: measured as % of maximum possible self-information for string & alphabet size. +#: (todo: defend this choice of value -- 'twas picked via experimentation) +default_min_complexity = 0.4 + +#: default presets +default_charset = "safe52" +default_wordset = "beale" + +#: dict of preset characters sets +charsets = dict( + safe52='2346789ABCDEFGHJKMNPQRTUVWXYZabcdefghjkmnpqrstuvwxyz', +) + +#: dict of preset word sets, +#: values set to None are lazy-loaded from disk by _load_wordset() +wordsets = dict( + diceware=None, + beale=None, + electrum=None, +) + +#: sha256 digest for wordset files, used as sanity check by _load_wordset() +_wordset_checksums = dict( + diceware="b39e6c367066a75208424cb591f64f188bb6ad69c61da52195718203c18b93d6", + beale="4b3ca06b22094df07b078e28f632845191ef927deb5a7c77b0f788b336fb80e6", + electrum="d4975b36cff7002332f6e8dff5477af52089c48ad6535272bbff6fb850ffe206", + ) + +#: misc helper constants +_PCW_MSG = "`preset`, `charset`, and `wordset` are mutually exclusive" +_USPACE = u(" ") +_UEMPTY = u("") + +#============================================================================= +# internal helpers +#============================================================================= + +# XXX: would this be more appropriate as _self_info()? +def _average_entropy(source, total=False): + """returns the rate of self-information in a sequence of symbols, + (or total self-information if total=True). + + this is eqvuialent to the average entropy of a given symbol, + using the sequence itself as the symbol probability distribution. + if all elements of the source are unique, this should equal + ``log(len(source), 2)``. + + :arg source: + iterable containing 0+ symbols + :param total: + instead of returning average entropy rate, + return total self-information + :returns: + float bits + """ + try: + size = len(source) + except TypeError: + # if len() doesn't work, calculate size by summing counts later + size = None + counts = defaultdict(int) + for char in source: + counts[char] += 1 + if size is None: + values = counts.values() + size = sum(values) + else: + values = itervalues(counts) + if not size: + return 0 + ### NOTE: below code performs the calculation + ### ``- sum(value / size * logf(value / size, 2) for value in values)``, + ### and then multplies by ``size`` if total is True, + ### it just does it with fewer operations. + tmp = sum(value * logf(value, 2) for value in values) + if total: + return size * logf(size, 2) - tmp + else: + return logf(size, 2) - tmp / size + +def _max_average_entropy(target, source): + """calculate maximum _average_entropy() of all possible + strings of length <target>, if drawn from a set of symbols + of size <source>. + """ + # NOTE: this accomplishes it's purpose by assuming maximum self-information + # would be a string repeating all symbols ``floor(target/source)`` + # times, followed by the first ``target % source`` symbols repeated + # once more. + assert target > 0 + assert source > 0 + if target < source: + # special case of general equation, to prevent intermediate DomainError. + return logf(target, 2) + else: + q, r = divmod(target, source) + p1 = (q + 1) / target + p2 = q / target + return -(r * p1 * logf(p1, 2) + (source - r) * p2 * logf(p2, 2)) + +def _average_wordset_entropy(wordset): + """return the average entropy per character in a given wordset, + using each char's frequency in the wordset as the probability of occurrence. + + :arg wordset: + iterable containing 1+ words, each of which are themselves + iterables containing 1+ characters. + :returns: + float bits of entropy + """ + return _average_entropy(chain_from_iterable(wordset)) + +def _load_wordset(name): + "helper load compressed wordset from package data" + # load wordset from data file + source = os.path.join(os.path.dirname(__file__), "_data", + "%s.wordset.z" % name) + with open(source, "rb") as fh: + data = fh.read() + + # verify against checksum + try: + checksum = _wordset_checksums[name] + except KeyError: # pragma: no cover -- sanity check + raise AssertionError("no checksum for wordset: %r" % name) + if sha256(data).hexdigest() != checksum: + raise RuntimeError("%r wordset file corrupted" % name) + + # decompress and return wordset + words = wordsets[name] = zlib.decompress(data).decode("utf-8").splitlines() + log.debug("loaded %d-element wordset from %r", len(words), source) + return words + +#============================================================================= +# password generators +#============================================================================= +class SequenceGenerator(object): + """base class used by word & phrase generators. + + These objects take a series of options, corresponding + to those of the :func:`generate` function. + They act as callables which can be used to generate a password + or a list of 1+ passwords. They also expose some read-only + informational attributes. + + :param entropy: + Optionally specify the amount of entropy the resulting passwords + should contain (as measured with respect to the generator itself). + This will be used to autocalculate the required password size. + + Also exposed as a readonly attribute. + + :param size: + Optionally specify the size of password to generate, + measured in whatever symbols the subclass uses (characters or words). + Note that if both ``size`` and ``entropy`` are specified, + the larger requested size will be used. + + Also exposed as a readonly attribute. + + :param min_complexity: + By default, generators derived from this class will avoid + generating passwords with excessively high per-symbol redundancy + (e.g. ``aaaaaaaa``). This is done by rejecting any strings + whose self-information per symbol is below a certain + percentage of the maximum possible a given string and alphabet + size. This defaults to 40%, or ``min_complexity=0.4``. + + .. autoattribute:: entropy_rate + """ + #============================================================================= + # instance attrs + #============================================================================= + + #: minimum complexity threshold for rejecting generating strings. + _min_entropy = None + + #: entropy rate per symbol of generated password (character or word) + entropy_rate = None + + #: requested size of final passwords + size = None + + #: random number source to use + rng = rng + + #============================================================================= + # init + #============================================================================= + def __init__(self, size=None, entropy=None, rng=None, min_complexity=None, + **kwds): + # NOTE: subclass should have already set .entropy_rate + if size is None: + size = 1 + if entropy is None: + entropy = default_entropy + elif size < 1: + raise ValueError("`size` must be positive integer") + if entropy is not None: + if entropy <= 0: + raise ValueError("`entropy` must be positive number") + size = max(size, int(ceil(entropy / self.entropy_rate))) + self.size = size + if rng is not None: + self.rng = rng + if min_complexity is None: + min_complexity = default_min_complexity + if min_complexity < 0 or min_complexity > 1: + raise ValueError("min_complexity must be between 0 and 1") + self._max_entropy = _max_average_entropy(size, 2**self.entropy_rate) + self._min_entropy = min_complexity * self._max_entropy + super(SequenceGenerator, self).__init__(**kwds) + + #============================================================================= + # helpers + #============================================================================= + @property + def entropy(self): + """entropy of generated passwords ( + measured with respect to the generation scheme)""" + return self.size * self.entropy_rate + + def _gen(self): + """main generation function""" + raise NotImplementedError("implement in subclass") + + #============================================================================= + # iter & callable frontend + #============================================================================= + def __call__(self, count=None): + """create and return passwords""" + if count is None: + return self._gen() + else: + return [self._gen() for _ in irange(count)] + + def __iter__(self): + return self + + if PY3: + def __next__(self): + return self._gen() + else: + def next(self): + return self._gen() + + #============================================================================= + # eoc + #============================================================================= + +class WordGenerator(SequenceGenerator): + """class which generates passwords by randomly choosing + from a string of unique characters. + + :param charset: + charset to draw from. + :param preset: + name of preset charset to use instead of explict charset. + :param \*\*kwds: + all other keywords passed to :class:`SequenceGenerator`. + + .. autoattribute:: charset + """ + #============================================================================= + # instance attrs + #============================================================================= + + #: charset used by this generator + charset = None + + #============================================================================= + # init + #============================================================================= + def __init__(self, charset=None, preset=None, **kwds): + if not (charset or preset): + preset = default_charset + if preset: + if charset: + raise TypeError(_PCW_MSG) + charset = charsets[preset] + if len(set(charset)) != len(charset): + raise ValueError("`charset` cannot contain duplicate elements") + self.charset = charset + self.entropy_rate = logf(len(charset), 2) + super(WordGenerator, self).__init__(**kwds) + ##log.debug("WordGenerator(): entropy/char=%r", self.entropy_rate) + + #============================================================================= + # helpers + #============================================================================= + def _gen(self): + while True: + secret = getrandstr(self.rng, self.charset, self.size) + # check that it satisfies minimum self-information limit + # set by min_complexity. i.e., reject strings like "aaaaaaaa" + if _average_entropy(secret) >= self._min_entropy: + return secret + + #============================================================================= + # eoc + #============================================================================= + +class PhraseGenerator(SequenceGenerator): + """class which generates passphrases by randomly choosing + from a list of unique words. + + :param wordset: + wordset to draw from. + :param preset: + name of preset wordlist to use instead of ``wordset``. + :param spaces: + whether to insert spaces between words in output (defaults to ``True``). + :param \*\*kwds: + all other keywords passed to :class:`SequenceGenerator`. + + .. autoattribute:: wordset + """ + #============================================================================= + # instance attrs + #============================================================================= + + #: list of words to draw from + wordset = None + + #: average entropy per char within wordset + _entropy_per_char = None + + #: minimum size string this will output, to prevent low-entropy + #: phrases from leaking through. + _min_chars = None + + #============================================================================= + # init + #============================================================================= + def __init__(self, wordset=None, preset=None, spaces=True, **kwds): + if not (wordset or preset): + preset = default_wordset + if preset: + if wordset: + raise TypeError(_PCW_MSG) + wordset = wordsets[preset] + if wordset is None: + wordset = _load_wordset(preset) + if len(set(wordset)) != len(wordset): + raise ValueError("`wordset` cannot contain duplicate elements") + if not isinstance(wordset, (list, tuple)): + wordset = tuple(wordset) + self.wordset = wordset + self.entropy_rate = logf(len(wordset), 2) + super(PhraseGenerator, self).__init__(**kwds) + # NOTE: regarding min_chars: + # in order to ensure a brute force attack against underlying + # charset isn't more successful than one against the wordset, + # we need to reject any passwords which contain so many short + # words that ``chars_in_phrase * entropy_per_char < + # words_in_phrase * entropy_per_word``. + # this is done by finding the minimum chars required to invalidate + # the inequality, and then rejecting any phrases that are shorter. + self._entropy_per_char = _average_wordset_entropy(wordset) + self._min_chars = int(self.entropy / self._entropy_per_char) + if spaces: + self._min_chars += self.size-1 + self._sep = _USPACE + else: + self._sep = _UEMPTY + ##log.debug("PhraseGenerator(): entropy/word=%r entropy/char=%r min_chars=%r", + ## self.entropy_rate, self._entropy_per_char, self._min_chars) + + #============================================================================= + # helpers + #============================================================================= + def _gen(self): + while True: + symbols = [self.rng.choice(self.wordset) for _ in irange(self.size)] + # check that it satisfies minimum self-information limit + # set by min_complexity. i.e., reject strings like "aaaaaaaa" + if _average_entropy(symbols) > self._min_entropy: + secret = self._sep.join(symbols) + # check that we don't fall below per-character limit + # on self information. see __init__ for explanation + if len(secret) >= self._min_chars: + return secret + + #============================================================================= + # eoc + #============================================================================= + +def generate(size=None, entropy=None, count=None, + preset=None, charset=None, wordset=None, + **kwds): + """Generate one or more random password / passphrases. + + This function uses :mod:`random.SystemRandom` to generate + one or more passwords; it can be configured to generate + alphanumeric passwords, or full english phrases. + The complexity of the password can be specified + by size, or by the desired amount of entropy. + + Usage Example:: + + >>> # generate random english phrase with 48 bits of entropy + >>> from passlib import pwd + >>> pwd.generate() + 'cairn pen keys flaw' + + >>> # generate a random alphanumeric string with default 52 bits of entropy + >>> pwd.generate(entropy=52, preset="safe52") + 'DnBHvDjMK6' + + :param size: + Size of resulting password, measured in characters or words. + If omitted, the size is autocalculated based on the ``entropy`` parameter. + + :param entropy: + Strength of resulting password, measured in bits of Shannon entropy + (defaults to 48). + + Based on the mode in use, the ``size`` parameter will be + autocalculated so that that an attacker will need an average of + ``2**(entropy-1)`` attempts to correctly guess the password + (this measurement assumes the attacker knows the mode + and configuration options in use, but nothing of the RNG state). + + If both ``entropy`` and ``size`` are specified, + the larger effective size will be used. + + :param count: + By default this generates a single password. + However, if ``count`` is specified, it will return a list + containing ``count`` passwords instead. + + :param preset: + Optionally use a pre-defined word-set or character-set + when generating a password. This option cannot be combined + with ``charset`` or ``wordset``; if all three are omitted, + this function defaults to ``preset="beale"``. + + There are currently three presets available: + + ``"safe52"`` + + preset which outputs random alphanumeric passwords, + using a 52-element character set containing the characters A-Z and 0-9, + except for ``1IiLl0OoS5`` (which were omitted due to their visual similarity). + This charset has ~5.7 bits of entropy per character. + + ``"diceware"`` + + preset which outputs random english phrases, + drawn randomly from a list of 7776 english words set down + by the `Diceware <http://world.std.com/~reinhold/diceware.html>`_ project. + This wordset has ~12.9 bits of entropy per word. + + ``"beale"`` + + variant of the Diceware wordlist as edited by + Alan Beale, also available from the diceware project. + This wordset has ~12.9 bits of entropy per word. + + :param charset: + Optionally specifies a string of characters to use when randomly + generating a password. This option cannot be combined + with ``preset`` or ``wordset``. + + :param wordset: + Optionally specifies a list/set of words to use when randomly + generating a passphrase. This option cannot be combined + with ``preset`` or ``charset``. + + :param spaces: + When generating a passphrase, controls whether spaces + should be inserted between the words. Defaults to ``True``. + + :returns: + :class:`!str` containing randomly generated password, + or list of 1+ passwords if ``count`` is specified. + """ + # create generator from options + kwds.update(size=size, entropy=entropy) + if wordset: + # create generator from wordset + if preset or charset: + raise TypeError(_PCW_MSG) + gen = PhraseGenerator(wordset, **kwds) + elif charset: + # create generator from charset + if preset: + raise TypeError(_PCW_MSG) + gen = WordGenerator(charset, **kwds) + else: + # create generator from preset + kwds.update(preset=preset) + if not preset or preset in wordsets: + assert preset not in charsets + gen = PhraseGenerator(**kwds) + elif preset in charsets: + gen = WordGenerator(**kwds) + else: + raise KeyError("unknown preset: %r" % preset) + + # return passwords + return gen(count) + +#============================================================================= +# password strength measurement +#============================================================================= +def strength(symbols): + """ + roughly estimate the strength of the password. + this is a bit better than just using len(password). + + param symbols: a sequence of symbols (e.g. password string/unicode) + returns: password strength estimate [float] + """ + return _average_entropy(symbols, total=True) + +CLASSIFICATIONS = [ + (10, 0), # everything < 10 returns 0 (weak) + (20, 1), # 10 <= s < 20 returns 1 (maybe still too weak) + (None, 2), # everything else returns 2 + # last tuple must be (None, MAXVAL) +] + +def classify(symbols, classifications=CLASSIFICATIONS): + """ + roughly classify the strength of the password. + this is a bit better than just using len(password). + + :param symbols: + a sequence of symbols (e.g. password string/unicode) + :param classifications: + list of tuples with the format ``(limit, classification)``. + + :returns: + classification value + + Usage Example:: + + >>> from passlib import pwd + >>> pwd.classify("10011001") + 0 + >>> pwd.classify("secret") + 1 + >>> pwd.classify("Eer6aiya") + 2 + """ + s = strength(symbols) + for limit, classification in classifications: + if limit is None or s < limit: + return classification + else: + raise ValueError("classifications needs to end with a (None, MAXVAL) tuple") + +#============================================================================= +# eof +#============================================================================= diff --git a/passlib/tests/backports.py b/passlib/tests/backports.py index 58ce18f..1868259 100644 --- a/passlib/tests/backports.py +++ b/passlib/tests/backports.py @@ -226,7 +226,7 @@ class TestCase(unittest.TestCase): expected_regex = re.compile(expected_regex) if not expected_regex.search(text): msg = msg or "Regex didn't match: " - std = '%r not found in %r' % (msg, expected_regex.pattern, text) + std = '%r not found in %r' % (expected_regex.pattern, text) raise self.failureException(self._formatMessage(msg, std)) #=================================================================== diff --git a/passlib/tests/test_apache.py b/passlib/tests/test_apache.py index 0792d60..3c7b07f 100644 --- a/passlib/tests/test_apache.py +++ b/passlib/tests/test_apache.py @@ -4,16 +4,14 @@ #============================================================================= from __future__ import with_statement # core -import hashlib from logging import getLogger import os -import time # site # pkg from passlib import apache -from passlib.utils.compat import irange, unicode -from passlib.tests.utils import TestCase, get_file, set_file, catch_warnings, ensure_mtime_changed -from passlib.utils.compat import b, bytes, u +from passlib.utils.compat import irange +from passlib.tests.utils import TestCase, get_file, set_file, ensure_mtime_changed +from passlib.utils.compat import b, u # module log = getLogger(__name__) diff --git a/passlib/tests/test_context.py b/passlib/tests/test_context.py index f2f86b6..d0d2e79 100644 --- a/passlib/tests/test_context.py +++ b/passlib/tests/test_context.py @@ -9,22 +9,18 @@ if PY3: from configparser import NoSectionError else: from ConfigParser import NoSectionError -import hashlib import logging; log = logging.getLogger(__name__) -import re import os -import time import warnings -import sys # site # pkg from passlib import hash from passlib.context import CryptContext, LazyCryptContext from passlib.exc import PasslibConfigWarning -from passlib.utils import tick, to_bytes, to_unicode +from passlib.utils import tick, to_unicode from passlib.utils.compat import irange, u, unicode, str_to_uascii, PY2 import passlib.utils.handlers as uh -from passlib.tests.utils import TestCase, catch_warnings, set_file, TICK_RESOLUTION, quicksleep +from passlib.tests.utils import TestCase, set_file, TICK_RESOLUTION, quicksleep from passlib.registry import (register_crypt_handler_path, _has_crypt_handler as has_crypt_handler, _unload_handler_name as unload_handler_name, diff --git a/passlib/tests/test_context_deprecated.py b/passlib/tests/test_context_deprecated.py index df9e1b3..2cfdb9c 100644 --- a/passlib/tests/test_context_deprecated.py +++ b/passlib/tests/test_context_deprecated.py @@ -10,12 +10,9 @@ it's being preserved here to ensure the old api doesn't break #============================================================================= from __future__ import with_statement # core -import hashlib from logging import getLogger import os -import time import warnings -import sys # site try: from pkg_resources import resource_filename @@ -24,15 +21,13 @@ except ImportError: # pkg from passlib import hash from passlib.context import CryptContext, CryptPolicy, LazyCryptContext -from passlib.exc import PasslibConfigWarning -from passlib.utils import tick, to_bytes, to_unicode -from passlib.utils.compat import irange, u, bytes +from passlib.utils import to_bytes, to_unicode +from passlib.utils.compat import bytes import passlib.utils.handlers as uh -from passlib.tests.utils import TestCase, catch_warnings, set_file +from passlib.tests.utils import TestCase, set_file from passlib.registry import (register_crypt_handler_path, _has_crypt_handler as has_crypt_handler, _unload_handler_name as unload_handler_name, - get_crypt_handler, ) # module log = getLogger(__name__) diff --git a/passlib/tests/test_ext_django.py b/passlib/tests/test_ext_django.py index 2862ab9..d1834ee 100644 --- a/passlib/tests/test_ext_django.py +++ b/passlib/tests/test_ext_django.py @@ -6,7 +6,6 @@ from __future__ import with_statement # core import logging; log = logging.getLogger(__name__) import sys -import warnings # site # pkg from passlib.apps import django10_context, django14_context, django16_context @@ -14,9 +13,8 @@ from passlib.context import CryptContext import passlib.exc as exc from passlib.utils.compat import iteritems, unicode, get_method_function, u, PY3 from passlib.utils import memoized_property -from passlib.registry import get_crypt_handler # tests -from passlib.tests.utils import TestCase, skipUnless, catch_warnings, TEST_MODE, has_active_backend +from passlib.tests.utils import TestCase, skipUnless, TEST_MODE, has_active_backend from passlib.tests.test_handlers import get_handler_case # local diff --git a/passlib/tests/test_handlers.py b/passlib/tests/test_handlers.py index 142e9e0..87e56a4 100644 --- a/passlib/tests/test_handlers.py +++ b/passlib/tests/test_handlers.py @@ -4,7 +4,6 @@ #============================================================================= from __future__ import with_statement # core -import hashlib import logging; log = logging.getLogger(__name__) import os import sys @@ -15,7 +14,7 @@ from passlib import hash from passlib.utils import repeat_string from passlib.utils.compat import irange, PY3, u, get_method_function from passlib.tests.utils import TestCase, HandlerCase, skipUnless, \ - TEST_MODE, b, catch_warnings, UserHandlerMixin, randintgauss, EncodingHandlerMixin + TEST_MODE, b, UserHandlerMixin, randintgauss, EncodingHandlerMixin # module #============================================================================= diff --git a/passlib/tests/test_handlers_bcrypt.py b/passlib/tests/test_handlers_bcrypt.py index 35a7db1..d43dfad 100644 --- a/passlib/tests/test_handlers_bcrypt.py +++ b/passlib/tests/test_handlers_bcrypt.py @@ -1,10 +1,9 @@ -"""passlib.tests.test_handlers_bcrypt - tests for passlib hash algorithms""" +"""passlib.tests.test_handlers - tests for passlib hash algorithms""" #============================================================================= # imports #============================================================================= from __future__ import with_statement # core -import hashlib import logging; log = logging.getLogger(__name__) import os import sys @@ -15,7 +14,7 @@ from passlib import hash from passlib.utils import repeat_string from passlib.utils.compat import irange, PY3, u, get_method_function from passlib.tests.utils import TestCase, HandlerCase, skipUnless, \ - TEST_MODE, b, catch_warnings, UserHandlerMixin, randintgauss, EncodingHandlerMixin + TEST_MODE, b, UserHandlerMixin, randintgauss, EncodingHandlerMixin from passlib.tests.test_handlers import UPASS_WAV, UPASS_USD, UPASS_TABLE # module @@ -23,7 +22,7 @@ from passlib.tests.test_handlers import UPASS_WAV, UPASS_USD, UPASS_TABLE # bcrypt #============================================================================= class _bcrypt_test(HandlerCase): - "base for BCrypt test cases" + """base for BCrypt test cases""" handler = hash.bcrypt secret_size = 72 reduce_default_rounds = True @@ -208,27 +207,33 @@ class _bcrypt_test(HandlerCase): def fuzz_verifier_pybcrypt(self): # test against py-bcrypt, if available - from passlib.handlers.bcrypt import IDENT_2, IDENT_2A, IDENT_2X, IDENT_2Y + from passlib.handlers.bcrypt import IDENT_2A, IDENT_2Y, bcrypt from passlib.utils import to_native_str try: - import bcrypt + import bcrypt as bcrypt_mod except ImportError: return - if hasattr(bcrypt, "_ffi"): + if hasattr(bcrypt_mod, "_ffi"): return + bcrypt._load_backend_pybcrypt() + lock = bcrypt._calc_lock # reuse threadlock workaround for pybcrypt 0.2 def check_pybcrypt(secret, hash): """pybcrypt""" secret = to_native_str(secret, self.fuzz_password_encoding) if hash.startswith(IDENT_2Y): hash = IDENT_2A + hash[4:] try: - return bcrypt.hashpw(secret, hash) == hash + if lock: + with lock: + return bcrypt_mod.hashpw(secret, hash) == hash + else: + return bcrypt_mod.hashpw(secret, hash) == hash except ValueError: raise ValueError("py-bcrypt rejected hash: %r" % (hash,)) return check_pybcrypt def fuzz_verifier_bcryptor(self): - # test against bcryptor, if available + # test against bcryptor if available from passlib.handlers.bcrypt import IDENT_2, IDENT_2A, IDENT_2Y from passlib.utils import to_native_str try: @@ -338,25 +343,20 @@ class _bcrypt_test(HandlerCase): with self.assertWarningList([]): self.assertEqual(bcrypt.genhash(pwd, good), good) - # - # and that verify() works good & bad - # - with self.assertWarningList([corr_desc]): - self.assertTrue(bcrypt.verify(pwd, bad)) - with self.assertWarningList([]): - self.assertTrue(bcrypt.verify(pwd, good)) + # make sure verify() works correctly with good & bad hashes + with self.assertWarningList([corr_desc]): + self.assertTrue(bcrypt.verify(pwd, bad)) + with self.assertWarningList([]): + self.assertTrue(bcrypt.verify(pwd, good)) - # - # test normhash cleans things up correctly - # - for pwd, bad, good in samples: + # make sure normhash() corrects bad hashes, leaves good unchanged with self.assertWarningList([corr_desc]): self.assertEqual(bcrypt.normhash(bad), good) with self.assertWarningList([]): self.assertEqual(bcrypt.normhash(good), good) - self.assertEqual(bcrypt.normhash("$md5$abc"), "$md5$abc") -hash.bcrypt._no_backends_msg() # call this for coverage purposes + # make sure normhash() leaves non-bcrypt hashes alone + self.assertEqual(bcrypt.normhash("$md5$abc"), "$md5$abc") # create test cases for specific backends bcrypt_bcrypt_test, bcrypt_pybcrypt_test, bcrypt_bcryptor_test, bcrypt_os_crypt_test, bcrypt_builtin_test = \ diff --git a/passlib/tests/test_handlers_django.py b/passlib/tests/test_handlers_django.py index 248be3a..d6ac220 100644 --- a/passlib/tests/test_handlers_django.py +++ b/passlib/tests/test_handlers_django.py @@ -4,7 +4,6 @@ #============================================================================= from __future__ import with_statement # core -import hashlib import logging; log = logging.getLogger(__name__) import os import warnings @@ -14,7 +13,7 @@ from passlib import hash from passlib.utils import repeat_string from passlib.utils.compat import irange, PY3, u, get_method_function from passlib.tests.utils import TestCase, HandlerCase, skipUnless, \ - TEST_MODE, b, catch_warnings, UserHandlerMixin, randintgauss, EncodingHandlerMixin + TEST_MODE, b, UserHandlerMixin, randintgauss, EncodingHandlerMixin from passlib.tests.test_handlers import UPASS_WAV, UPASS_USD, UPASS_TABLE # module diff --git a/passlib/tests/test_hosts.py b/passlib/tests/test_hosts.py index c1572ae..cbf93ab 100644 --- a/passlib/tests/test_hosts.py +++ b/passlib/tests/test_hosts.py @@ -5,7 +5,6 @@ from __future__ import with_statement # core import logging; log = logging.getLogger(__name__) -import warnings # site # pkg from passlib import hosts, hash as hashmod diff --git a/passlib/tests/test_pwd.py b/passlib/tests/test_pwd.py new file mode 100644 index 0000000..914a50f --- /dev/null +++ b/passlib/tests/test_pwd.py @@ -0,0 +1,99 @@ +"""passlib.tests -- tests for passlib.pwd""" +#============================================================================= +# imports +#============================================================================= +# core +import logging; log = logging.getLogger(__name__) +# site +# pkg +from passlib.tests.utils import TestCase +# local +__all__ = [ + "UtilsTest", + "GenerateTest", + "StrengthTest", +] + +#============================================================================= +# +#============================================================================= +class UtilsTest(TestCase): + """test internal utilities""" + descriptionPrefix = "passlib.pwd" + + def test_average_entropy(self): + "_average_entropy()" + from passlib.pwd import _average_entropy + + self.assertEqual(_average_entropy(""), 0) + self.assertEqual(_average_entropy("", True), 0) + + self.assertEqual(_average_entropy("a"*8), 0) + self.assertEqual(_average_entropy("a"*8, True), 0) + + self.assertEqual(_average_entropy("ab"), 1) + self.assertEqual(_average_entropy("ab"*8), 1) + self.assertEqual(_average_entropy("ab", True), 2) + self.assertEqual(_average_entropy("ab"*8, True), 16) + + self.assertEqual(_average_entropy("abcd"), 2) + self.assertEqual(_average_entropy("abcd"*8), 2) + self.assertAlmostEqual(_average_entropy("abcdaaaa"), 1.5488, 4) + self.assertEqual(_average_entropy("abcd", True), 8) + self.assertEqual(_average_entropy("abcd"*8, True), 64) + self.assertAlmostEqual(_average_entropy("abcdaaaa", True), 12.3904, 4) + +#============================================================================= +# generation +#============================================================================= +class GenerateTest(TestCase): + """test generation routines""" + descriptionPrefix = "passlib.pwd" + + def test_PhraseGenerator(self): + """PhraseGenerator()""" + from passlib.pwd import PhraseGenerator + + # test wordset can be any iterable + results = PhraseGenerator(size=3, wordset=set("abc"))(5000) + self.assertEqual(len(set(results)), 27) + +#============================================================================= +# strength +#============================================================================= +class StrengthTest(TestCase): + """test strength measurements""" + descriptionPrefix = "passlib.pwd" + + reference = [ + # (password, classify() output) + + # "weak" + ("", 0), + ("0"*8, 0), + ("0"*48, 0), + ("1001"*2, 0), + ("123", 0), + ("123"*2, 0), + ("1234", 0), + + # "somewhat weak" + ("12345", 1), + ("1234"*2, 1), + ("secret", 1), + + # "not weak" + ("reallysecret", 2), + ("12345"*2, 2), + ("Eer6aiya", 2), + ] + + def test_classify(self): + """classify()""" + from passlib.pwd import classify + for secret, result in self.reference: + self.assertEqual(classify(secret), result, "classify(%r):" % secret) + +#============================================================================= +# eof +#============================================================================= diff --git a/passlib/tests/test_registry.py b/passlib/tests/test_registry.py index 80cfc12..6e96e63 100644 --- a/passlib/tests/test_registry.py +++ b/passlib/tests/test_registry.py @@ -4,10 +4,7 @@ #============================================================================= from __future__ import with_statement # core -import hashlib from logging import getLogger -import os -import time import warnings import sys # site diff --git a/passlib/tests/test_totp.py b/passlib/tests/test_totp.py new file mode 100644 index 0000000..b0f425a --- /dev/null +++ b/passlib/tests/test_totp.py @@ -0,0 +1,33 @@ +"""passlib.tests -- test passlib.totp""" +#============================================================================= +# imports +#============================================================================= +# core +import logging; log = logging.getLogger(__name__) +# site +# pkg +from passlib.tests.utils import TestCase +# local +__all__ = [ + "EngineTest", +] + +#============================================================================= +# TOTP Engine +#============================================================================= +class EngineTest(TestCase): + descriptionPrefix = "passlib.ext.totp.TOTPEngine" + + def test_basic(self): + """reference vectors""" + from passlib.totp import TotpEngine + + # NOTE: these are the defaults, but just to make our test case explicit. + engine = TotpEngine(time_step=30, digits=6, prf="hmac-sha1") + + # verify counter is being calculated correctly + engine.gentoken() + +#============================================================================= +# eof +#============================================================================= diff --git a/passlib/tests/test_utils.py b/passlib/tests/test_utils.py index 936b739..a5036a0 100644 --- a/passlib/tests/test_utils.py +++ b/passlib/tests/test_utils.py @@ -4,16 +4,14 @@ #============================================================================= from __future__ import with_statement # core -from binascii import hexlify, unhexlify -import sys +from binascii import unhexlify import random -import warnings # site # pkg # module -from passlib.utils.compat import b, bytes, bascii_to_str, irange, PY2, PY3, u, \ +from passlib.utils.compat import b, bytes, irange, PY3, u, \ unicode, join_bytes, SUPPORTS_DIR_METHOD -from passlib.tests.utils import TestCase, catch_warnings +from passlib.tests.utils import TestCase def hb(source): return unhexlify(b(source)) diff --git a/passlib/tests/test_utils_crypto.py b/passlib/tests/test_utils_crypto.py index 0784ef3..4829ee5 100644 --- a/passlib/tests/test_utils_crypto.py +++ b/passlib/tests/test_utils_crypto.py @@ -6,9 +6,6 @@ from __future__ import with_statement # core from binascii import hexlify, unhexlify import hashlib -import hmac -import sys -import random import warnings # site try: @@ -17,9 +14,8 @@ except ImportError: M2Crypto = None # pkg # module -from passlib.utils.compat import b, bytes, bascii_to_str, irange, PY2, PY3, u, \ - unicode, join_bytes, PYPY, JYTHON -from passlib.tests.utils import TestCase, TEST_MODE, catch_warnings, skipUnless, skipIf +from passlib.utils.compat import b, bascii_to_str, PY3, u, PYPY, JYTHON +from passlib.tests.utils import TestCase, TEST_MODE, catch_warnings, skipUnless #============================================================================= # support @@ -75,7 +71,57 @@ class CryptoTest(TestCase): "name=%r, format=%r:" % (value, format)) - # TODO: write full test of get_prf(), currently relying on pbkdf2 testing + def test_get_hash_info(self): + """test get_hash_info()""" + import hashlib + from passlib.utils.pbkdf2 import get_hash_info + + # invalid names should be rejected + self.assertRaises(ValueError, get_hash_info, "new") + self.assertRaises(ValueError, get_hash_info, "__name__") + + # 1. should return hashlib builtin if found + self.assertEqual(get_hash_info("md5"), (hashlib.md5, 16, 64)) + + # 2. should return wrapper around hashlib.new() if found + try: + hashlib.new("sha") + has_sha = True + except ValueError: + has_sha = False + if has_sha: + record = get_hash_info("sha") + const = record[0] + self.assertEqual(record, (const, 20, 64)) + self.assertEqual(hexlify(const(b("abc")).digest()), + b("0164b8a914cd2a5e74c4f7ff082c4d97f1edf880")) + + else: + self.assertRaises(ValueError, get_hash_info, "sha") + + # 3. should fall back to builtin md4 + try: + hashlib.new("md4") + has_md4 = True + except ValueError: + has_md4 = False + record = get_hash_info("md4") + const = record[0] + if not has_md4: + from passlib.utils.md4 import md4 + self.assertIs(const, md4) + self.assertEqual(record, (const, 16, 64)) + self.assertEqual(hexlify(const(b("abc")).digest()), + b("a448017aaf21d8525fc10ae87aa6729d")) + + # 4. unknown names should be rejected + self.assertRaises(ValueError, get_hash_info, "xxx256") + + # should memoize records + self.assertIs(get_hash_info("md5"), get_hash_info("md5")) + + # TODO: write full test of get_prf() + # TODO: write full test of get_keyed_prf() -- currently relying on pbkdf2() tests #============================================================================= # test DES routines @@ -403,20 +449,13 @@ class Pbkdf1_Test(TestCase): #============================================================================= class _Pbkdf2_Test(TestCase): """test pbkdf2() support""" - _disable_m2crypto = False def setUp(self): super(_Pbkdf2_Test, self).setUp() - import passlib.utils.pbkdf2 as mod - - # disable m2crypto support, and use software backend - if M2Crypto and self._disable_m2crypto: - self.addCleanup(setattr, mod, "_EVP", mod._EVP) - mod._EVP = None - # flush cached prf functions, since we're screwing with their backend. - mod._clear_prf_cache() - self.addCleanup(mod._clear_prf_cache) + from passlib.utils.pbkdf2 import _clear_caches + _clear_caches() + self.addCleanup(_clear_caches) pbkdf2_test_vectors = [ # (result, secret, salt, rounds, keylen, prf="sha1") @@ -583,14 +622,25 @@ class _Pbkdf2_Test(TestCase): result = pbkdf2(b('secret'), b('salt'), 1000, 20, prf) self.assertEqual(result, hb('5fe7ce9f7e379d3f65cbc66ba8aa6440474a6849')) -# create subclasses to test with and without m2crypto +#------------------------------------------------------------------------ +# create subclasses to test with- and without- m2crypto +#------------------------------------------------------------------------ class Pbkdf2_M2Crypto_Test(_Pbkdf2_Test): descriptionPrefix = "pbkdf2 (m2crypto backend)" + Pbkdf2_M2Crypto_Test = skipUnless(M2Crypto, "M2Crypto not found")(Pbkdf2_M2Crypto_Test) class Pbkdf2_Builtin_Test(_Pbkdf2_Test): descriptionPrefix = "pbkdf2 (builtin backend)" - _disable_m2crypto = True + + def setUp(self): + super(Pbkdf2_Builtin_Test, self).setUp() + # disable m2crypto support, and force pure-python backend + if M2Crypto: + import passlib.utils.pbkdf2 as mod + self.addCleanup(setattr, mod, "_EVP", mod._EVP) + mod._EVP = None + Pbkdf2_Builtin_Test = skipUnless(TEST_MODE("full") or not M2Crypto, "skipped under current test mode")(Pbkdf2_Builtin_Test) diff --git a/passlib/tests/test_utils_handlers.py b/passlib/tests/test_utils_handlers.py index 8e408ca..b95bc17 100644 --- a/passlib/tests/test_utils_handlers.py +++ b/passlib/tests/test_utils_handlers.py @@ -11,15 +11,12 @@ import warnings # site # pkg from passlib.hash import ldap_md5, sha256_crypt -from passlib.registry import _unload_handler_name as unload_handler_name, \ - register_crypt_handler, get_crypt_handler from passlib.exc import MissingBackendError, PasslibHashWarning -from passlib.utils import getrandstr, JYTHON, rng -from passlib.utils.compat import b, bytes, bascii_to_str, str_to_uascii, \ +from passlib.utils.compat import b, bytes, str_to_uascii, \ uascii_to_str, unicode, PY_MAX_25, SUPPORTS_DIR_METHOD import passlib.utils.handlers as uh from passlib.tests.utils import HandlerCase, TestCase, catch_warnings -from passlib.utils.compat import u, PY3 +from passlib.utils.compat import u # module log = getLogger(__name__) @@ -363,6 +360,74 @@ class SkeletonTest(TestCase): backends = ("a", "b") + @classmethod + def _load_backend_a(cls): + return None + + @classmethod + def _load_backend_b(cls): + return None + + def _calc_checksum_a(self, secret): + return 'a' + + def _calc_checksum_b(self, secret): + return 'b' + + # test no backends + self.assertRaises(MissingBackendError, d1.get_backend) + self.assertRaises(MissingBackendError, d1.set_backend) + self.assertRaises(MissingBackendError, d1.set_backend, 'any') + self.assertRaises(MissingBackendError, d1.set_backend, 'default') + self.assertFalse(d1.has_backend()) + + # enable 'b' backend + d1._load_backend_b = classmethod(lambda cls: cls._calc_checksum_b) + + # test lazy load + obj = d1() + self.assertEqual(obj._calc_checksum('s'), 'b') + + # test repeat load + d1.set_backend('b') + d1.set_backend('any') + self.assertEqual(obj._calc_checksum('s'), 'b') + + # test unavailable + self.assertRaises(MissingBackendError, d1.set_backend, 'a') + self.assertTrue(d1.has_backend('b')) + self.assertFalse(d1.has_backend('a')) + + # enable 'a' backend also + d1._load_backend_a = classmethod(lambda cls: cls._calc_checksum_a) + + # test explicit + self.assertTrue(d1.has_backend()) + d1.set_backend('a') + self.assertEqual(obj._calc_checksum('s'), 'a') + + # test unknown backend + self.assertRaises(ValueError, d1.set_backend, 'c') + self.assertRaises(ValueError, d1.has_backend, 'c') + + # test error thrown if _has & _load are mixed + class d2(d1): + _has_backend_a = True + self.assertRaises(AssertionError, d2.has_backend, "a") + + def test_41_backends(self): + """test GenericHandler + HasManyBackends mixin (deprecated api)""" + warnings.filterwarnings("ignore", + category=DeprecationWarning, + message=r".* support for \._has_backend_.* is deprecated.*", + ) + + class d1(uh.HasManyBackends, uh.GenericHandler): + name = 'd1' + setting_kwds = () + + backends = ("a", "b") + _has_backend_a = False _has_backend_b = False @@ -408,6 +473,52 @@ class SkeletonTest(TestCase): self.assertRaises(ValueError, d1.set_backend, 'c') self.assertRaises(ValueError, d1.has_backend, 'c') + def test_42_tab(self): + """test HasManyBackends._try_alternate_backends() helper""" + class d1(uh.HasManyBackends, uh.GenericHandler): + name = 'd1' + setting_kwds = () + + backends = ("a", "b", "c") + + @classmethod + def _load_backend_a(cls): + return cls._calc_a + + def _calc_a(self, secret): + if secret == "a": + return "a" + return self._try_alternate_backends(secret) + + @classmethod + def _load_backend_b(cls): + return cls._calc_b + + def _calc_b(self, secret): + if secret == "b": + return "b" + return self._try_alternate_backends(secret) + + @classmethod + def _load_backend_c(cls): + return None + + handler = d1() + + # A backend active + handler.set_backend("a") + self.assertEqual(handler._calc_checksum("a"), "a") # uses a + self.assertEqual(handler._calc_checksum("b"), "b") # falls back to b + self.assertRaises(uh.exc.MissingBackendError, + handler._calc_checksum, "c") # no fallback + + # B backend active + handler.set_backend("b") + self.assertEqual(handler._calc_checksum("b"), "b") # uses b + self.assertEqual(handler._calc_checksum("a"), "a") # falls back to a + self.assertRaises(uh.exc.MissingBackendError, + handler._calc_checksum, "c") # no fallback + def test_50_norm_ident(self): """test GenericHandler + HasManyIdents""" # setup helpers diff --git a/passlib/tests/test_win32.py b/passlib/tests/test_win32.py index 6bcdaf5..e818b62 100644 --- a/passlib/tests/test_win32.py +++ b/passlib/tests/test_win32.py @@ -3,7 +3,6 @@ # imports #============================================================================= # core -from binascii import hexlify import warnings # site # pkg diff --git a/passlib/tests/utils.py b/passlib/tests/utils.py index 13d6293..c884d0f 100644 --- a/passlib/tests/utils.py +++ b/passlib/tests/utils.py @@ -9,6 +9,7 @@ import re import os import sys import tempfile +import threading import time from passlib.exc import PasslibHashWarning from passlib.utils.compat import PY27, PY_MIN_32, PY3, JYTHON @@ -259,9 +260,6 @@ class TestCase(_TestCase): return name.startswith("_") or \ getattr(cls, "_%s__unittest_skip" % name, False) - # make this mirror nose's '__test__' attr - return not getattr(cls, "__test__", True) - @classproperty def __test__(cls): # make nose just proxy __unittest_skip__ @@ -1021,20 +1019,19 @@ class HandlerCase(TestCase): raise AssertionError("default_salt_size must be <= max_salt_size") # check for 'salt_size' keyword - if 'salt_size' not in cls.setting_kwds and \ - (not mx_set or cls.min_salt_size < cls.max_salt_size): - # NOTE: only bothering to issue warning if default_salt_size - # isn't maxed out - if (not mx_set or cls.default_salt_size < cls.max_salt_size): - warn("%s: hash handler supports range of salt sizes, " - "but doesn't offer 'salt_size' setting" % (cls.name,)) + # NOTE: skipping warning if default salt size is already maxed out + # (might change that in future) + if 'salt_size' not in cls.setting_kwds and (not mx_set or cls.default_salt_size < cls.max_salt_size): + warn('%s: hash handler supports range of salt sizes, ' + 'but doesn\'t offer \'salt_size\' setting' % (cls.name,)) # check salt_chars & default_salt_chars if cls.salt_chars: if not cls.default_salt_chars: raise AssertionError("default_salt_chars must not be empty") - if any(c not in cls.salt_chars for c in cls.default_salt_chars): - raise AssertionError("default_salt_chars must be subset of salt_chars: %r not in salt_chars" % (c,)) + for c in cls.default_salt_chars: + if c not in cls.salt_chars: + raise AssertionError("default_salt_chars must be subset of salt_chars: %r not in salt_chars" % (c,)) else: if not cls.default_salt_chars: raise AssertionError("default_salt_chars MUST be specified if salt_chars is empty") @@ -1741,6 +1738,51 @@ class HandlerCase(TestCase): self.descriptionPrefix, count, len(verifiers), ", ".join(vname(v) for v in verifiers)) + def test_78_fuzz_threading(self): + """run test_77 simultaneously in multiple threads + in an attempt to detect any concurrency issues + (e.g. the bug fixed by pybcrypt 0.3) + """ + import threading + + # check if this test should run + if self.is_disabled_handler: + raise self.skipTest("not applicable") + thread_count = self.fuzz_thread_count + if not thread_count or self.max_fuzz_time <= 0: + raise self.skipTest("disabled by test mode") + + # buffer to hold errors thrown by threads + failed_lock = threading.Lock() + failed = [0] + + # launch <thread count> threads, all of which run + # test_77_fuzz_input(), and see if any errors get thrown. + # if hash has concurrency issues, this should reveal it. + def wrapper(): + try: + self.test_77_fuzz_input() + except: + with failed_lock: + failed[0] += 1 + raise + def launch(n): + name = "Fuzz-Thread-%d (%s.test_78_fuzz_threading)" % (n, self.__class__.__name__) + thread = threading.Thread(target=wrapper, name=name) + thread.setDaemon(True) + thread.start() + return thread + threads = [launch(n) for n in irange(thread_count)] + + # wait until all threads exit + for thread in threads: + thread.join() + + # if any thread threw an error, raise one ourselves. + if failed[0]: + raise self.fail("%d/%d threads failed concurrent fuzz testing " + "(see error log for details)" % (failed[0], thread_count)) + #--------------------------------------------------------------- # fuzz constants & helpers #--------------------------------------------------------------- @@ -1764,6 +1806,19 @@ class HandlerCase(TestCase): else: return 5 + @property + def fuzz_thread_count(self): + "number of threads for threaded fuzz testing" + value = int(os.environ.get("PASSLIB_TEST_FUZZ_THREADS") or 0) + if value: + return value + elif TEST_MODE(max="quick"): + return 0 + elif TEST_MODE(max="default"): + return 10 + else: + return 20 + def os_supports_ident(self, ident): """whether native OS crypt() supports particular ident value""" return True diff --git a/passlib/totp.py b/passlib/totp.py new file mode 100644 index 0000000..8466a7c --- /dev/null +++ b/passlib/totp.py @@ -0,0 +1,337 @@ +"""passlib.totp -- TOTP / RFC6238 / Google Authenticator utilities. + +Todo +==== +* This module currently contains a functional TotpEngine() object, + which does provide all the basic primitives. However, for the final + release I'd like to have a hash-string looking object which stores + entire state in a single string, and provide module-level primitives + for easily manipulating them. + +* The hash string should probably contain a minimum of: + - prefix ("{TOTP}" or "$totp$") + - engine parameters (period, digits, alg) + - shared key + - optionally pbkdf2+xor encrypt using user password (+ application pepper)? + - last authenticated timestamp (so app can reject subsequent ones) + - drift of last authentication + - xxx: need to find good reference for how to make this secure+useful + +* Unittests, once api is finished. + +References +========== +* Google's OTP uri spec, used for qrcodes -- http://code.google.com/p/google-authenticator/wiki/KeyUriFormat +* php-based OTP project, might have skew management logic -- http://www.multiotp.net/ +* base32 -- http://tools.ietf.org/html/rfc3548#page-6 +""" +#============================================================================= +# imports +#============================================================================= +from __future__ import division +# core +import logging; log = logging.getLogger(__name__) +import struct +import time +import re +import urllib +# site +# pkg +from passlib.utils import to_unicode, consteq, getrandbytes, rng +from passlib.utils.compat import (u, int_types, num_types, base_string_types, + irange, bytes, byte_elem_value, BytesIO, + join_byte_values, join_unicode, iter_byte_values) +from passlib.utils.pbkdf2 import get_prf, norm_hash_name +# local +__all__ = [ + "TotpEngine", +] + +#============================================================================= +# internal helpers +#============================================================================= + +# used to clean whitespace from tokens for comparison +_token_cleaner = re.compile(u("\s|[-]")) + +#============================================================================= +# +#============================================================================= + +class TotpEngine(object): + """provides quick generation and matching of TOTP codes. + + Each instance gets configured with the options for a specific TOTP + implementation, and then offers methods for creating & validating + TOTP codes based on that configuration. + + :param key_size: + size of generated keys, in bytes. defaults to digest size of selected + prf. (note the base32-encoded key will be 1.6x longer). + :param period: + time step in seconds (defaults to ``30``) + :param digits: + number of digits to return (defaults to ``6``) + :param prf: + name of prf to use (defaults to ``"hmac-sha1"``) + :param timer: + timer function for generating new codes (defaults to :func:`time.time`) + :param time_start: + timer value to start counting time steps (defaults to ``0``). + """ + #============================================================================= + # instance attrs + #============================================================================= + + #: size of keys to generate + key_size = None + + #: time step in seconds + period = 30 + + #: number of digits in output code + digits = 6 + + #: name of hash algorithm in use (e.g. "sha-1") + alg = None + + #: prf callable implementing HMAC-<alg> + _prf = None + + #: alg digest size + digest_size = None + + #: timer function + timer = time.time + + #: agreed-upon timer offset + time_start = 0 + + #============================================================================= + # init + #============================================================================= + def __init__(self, key_size=None, period=30, digits=6, alg="sha1", + timer=time.time, time_start=0, rng=rng): + + # validate period + if not isinstance(period, int_types): + raise TypeError("period must be an integer, not a %r" % type(period)) + if period < 1: + raise ValueError("period must be a positive integer") + self.period = period + + # validate digits + if not isinstance(digits, int_types): + raise TypeError("digits must be an integer, not a %r" % type(digits)) + if digits < 6 or digits > 9: + raise ValueError("digits must in range 6..9 inclusive") + self.digits = digits + + # validate prf, resolve to callable + self.alg = norm_hash_name(alg) + self._prf, self.digest_size = get_prf("hmac-" + self.alg) + assert self.digest_size > 4, "how did you find this crazy hash?" + + # validate key size + if key_size is None: + key_size = self.digest_size + if not isinstance(key_size, int_types): + raise TypeError("key_size must be an integer, not a %r" % type(key_size)) + if key_size < 1: + raise ValueError("key_size must be a positive integer") + self.key_size = key_size + + # store timer & rng + self.timer = timer + self.rng = rng + + # validate time_start + if not isinstance(time_start, num_types): + raise TypeError("time_start must be a number, not a %r" % type(time_start)) + self.time_start = time_start + + #============================================================================= + # key manipulation + #============================================================================= + + def normkey(self, key): + """normalize key representation""" + return encode_base32(decode_base32(key)) + + def genkey(self, key_size=None): + """generate new base32-encoded key""" + if key_size is None: + key_size = self.key_size + raw_key = getrandbytes(self.rng, key_size) + return encode_base32(raw_key) + + #============================================================================= + # token manipulation + #============================================================================= + def normtoken(self, token): + """normalize token representation""" + if isinstance(token, int_types): + return u("%0*d") % (self.digits, token) + else: + token = to_unicode(token, param="token") + # XXX: should we left-pad w/ zeros up to self.digits? + return _token_cleaner.sub(u(""), token) + + def gentoken(self, key, time=None): + """generate TOTP code for specified key & timestamp. + + :arg key: user-specific key as base32-encoded string + :arg time: timestamp as float/int (if None, uses current time) + :returns: string containing decimal token + """ + # decode key + if not isinstance(key, base_string_types): + raise TypeError("key must be a string, not a %r" % type(key)) + raw_key = decode_base32(key) + + # generate counter & digest + if time is None: + time = self.timer() + counter = int((time - self.time_start) // self.period) + assert counter >= 0 # FIXME: does RFC define behavior? or throw error? + digest = self._prf(raw_key, struct.pack(">Q", counter)) + assert len(digest) == self.digest_size, "sanity check failed" + + # truncate and derive token + offset = byte_elem_value(digest[-1]) % (len(digest)-4) + value = struct.unpack(">I", digest[offset:offset+4])[0] & 0x7fffffff + return u("%0*d") % (self.digits, value % (10**self.digits)) + + def makeuri(self, key, label): + """convert key to uri (including current engine settings)""" + assert "?" not in label + key = self.normkey(key) + # NOTE: reference examples seem to indicate the '@' in a label + # shouldn't be escaped, though google's spec doesn't address this. + label = urllib.quote_plus(label, '@') + result = u("otpauth://totp/%s?secret=%s") % (label, key) + if self.alg != "sha1": + result = u("%s&algorithm=%s") % (result, self.alg.upper()) + if self.digits != 6: + result = u("%s&digits=%d") % (result, self.digits) + if self.period != 30: + result = u("%s&period=%d") % (result, self.period) + return result + + def makeqrcode(self, key, label): + """convert key to qrcode (including current engine settings) + + .. note:: + + This method requires the external libraries + ``qrcode`` and ``PIL``. + """ + # XXX: is there a pure-python way to do this? + # saw a pure-python png library somewhere, + # maybe see about contributing patch to qrcode + from passlib.utils.compat import BytesIO + import qrcode + buf = BytesIO() + qrcode.make(self.makeuri(key, label)).save(buf) + return buf.getvalue() + + #============================================================================= + # verification + #============================================================================= + def verify(self, key, token, time=None): + """verify token against counter. if time unset, uses current time""" + return consteq(self.normtoken(token), self.gentoken(key, time)) + + def verify_window(self, key, token, time=None, window=None): + """wrapper around :meth:`verify` which tries to validate + against tokens for +/- window seconds from time. + returns (True/False, skew) + """ + if time is None: + time = self.timer() + if window is None: + window = self.period + assert window >= 0 + skew = 0 + while skew <= window: + if self.verify(key, token, time + skew): + return True, skew + if skew and self.verify(key, token, time - skew): + return True, -skew + skew += self.period + return False, None + + #============================================================================= + # eoc + #============================================================================= + +#============================================================================= +# base32 codec +#============================================================================= + +# NOTE: stdlib offers base64.b32encode / b32decode, +# but they are fragile and demand padding chars. +# should look into a wrapper around them, +# might be faster than scrap of code below: + +_base32_alphabet = u('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567') +_base32_map = dict((c,i) for i, c in enumerate(_base32_alphabet)) +_base32_map.update((c.lower(), i) for i,c in enumerate(_base32_alphabet) + if c.isalpha()) +_base32_map.update(**{ + # map some commonly mistyped chars + u("0"): _base32_map[u("O")], + u("1"): _base32_map[u("L")], + u("8"): _base32_map[u("B")], + ##u("9"): _base32_map[u("G")], # TODO: find out if this is generally accepted + + # common garbage/padding characters that we ignore entirely + u("-"): None, + u("="): None, + u("~"): None, +}) +assert all(v<32 for v in _base32_map.values()) + +def decode_base32(source): + """decode base32-encoded string""" + def helper(): + cur = 0 + bits = 0 + for char in to_unicode(source, param="source"): + if char.isspace(): + continue + try: + value = _base32_map[char] + except KeyError: + raise ValueError("invalid characters in base32 string") + cur = (cur<<5)|value + bits += 5 + if bits > 7: + bits -= 8 + yield cur >> bits + cur &= (1<<bits)-1 + if bits and cur: + # if cur isn't set, these are just padding bits we can ignore + raise ValueError("unexpected end of base32 string") + return join_byte_values(helper()) + +# TODO: have this (optionally?) include padding +def encode_base32(source): + """convert raw bytes to base32-encoded string""" + def helper(): + cur = 0 + bits = 0 + for value in iter_byte_values(source): + cur = (cur<<8)|value + bits += 8 + while bits > 4: # pop off and render 5 bits worth + bits -= 5 + yield _base32_alphabet[cur >> bits] + cur &= (1<<bits)-1 + if bits: + yield _base32_alphabet[cur<<(5-bits)] # insert padding bits + return join_unicode(helper()) + +#============================================================================= +# eof +#============================================================================= diff --git a/passlib/utils/__init__.py b/passlib/utils/__init__.py index b4c3f90..de3e9f2 100644 --- a/passlib/utils/__init__.py +++ b/passlib/utils/__init__.py @@ -12,6 +12,7 @@ import math import os import sys import random +import re if JYTHON: # pragma: no cover -- runtime detection # Jython 2.5.2 lacks stringprep module - # see http://bugs.jython.org/issue1758320 @@ -1430,6 +1431,13 @@ else: # On most other platforms the best timer is time.time() from time import time as tick +def parse_version(source): + """helper to parse version string""" + m = re.search(r"(\d+(?:\.\d+)+)", source) + if m: + return tuple(int(elem) for elem in m.group(1).split(".")) + return None + #============================================================================= # randomness #============================================================================= @@ -1540,6 +1548,8 @@ def getrandstr(rng, charset, count): _52charset = '2346789ABCDEFGHJKMNPQRTUVWXYZabcdefghjkmnpqrstuvwxyz' +@deprecated_function(deprecated="1.7", removed="2.0", + replacement="passlib.pwd.generate()") def generate_password(size=10, charset=_52charset): """generate random password using given length & charset diff --git a/passlib/utils/compat.py b/passlib/utils/compat.py index ecaaffe..ce61ac9 100644 --- a/passlib/utils/compat.py +++ b/passlib/utils/compat.py @@ -260,8 +260,14 @@ if PY_MAX_25: return itr.next() except StopIteration: return default + def chain_from_iterable(itr): + for subitr in itr: + for elem in subitr: + yield elem else: + from itertools import chain next = builtins.next + chain_from_iterable = chain.from_iterable #============================================================================= # typing diff --git a/passlib/utils/handlers.py b/passlib/utils/handlers.py index b25d203..1eca2ee 100644 --- a/passlib/utils/handlers.py +++ b/passlib/utils/handlers.py @@ -4,12 +4,7 @@ #============================================================================= from __future__ import with_statement # core -import inspect -import re -import hashlib import logging; log = logging.getLogger(__name__) -import time -import os from warnings import warn # site # pkg @@ -22,7 +17,7 @@ from passlib.utils import classproperty, consteq, getrandstr, getrandbytes,\ BASE64_CHARS, HASH64_CHARS, rng, to_native_str, \ is_crypt_handler, to_unicode, \ MAX_PASSWORD_SIZE -from passlib.utils.compat import b, join_byte_values, bytes, irange, u, \ +from passlib.utils.compat import b, join_byte_values, bytes, irange, u, callable, \ uascii_to_str, join_unicode, unicode, str_to_uascii, \ join_unicode, base_string_types, PY2, int_types # local @@ -1305,24 +1300,38 @@ class HasManyBackends(GenericHandler): offers a way to specify alternate :meth:`_calc_checksum` methods, and will dynamically chose the best one at runtime. - Backend Methods - --------------- + Public API + ---------- + + .. attribute:: backends + + This attribute should be a tuple containing the names of the backends + which are supported. Two common names are ``"os_crypt"`` (if backend + uses :mod:`crypt`), and ``"builtin"`` (if the backend is a pure-python + fallback). .. automethod:: get_backend .. automethod:: set_backend .. automethod:: has_backend - Subclass Hooks - -------------- + Private API (Subclass Hooks) + ---------------------------- The following attributes and methods should be filled in by the subclass which is using :class:`HasManyBackends` as a mixin: - .. attribute:: backends + .. attribute:: _load_backend_{name} - This attribute should be a tuple containing the names of the backends - which are supported. Two common names are ``"os_crypt"`` (if backend - uses :mod:`crypt`), and ``"builtin"`` (if the backend is a pure-python - fallback). + private class method that should try to load the specified backend, + one of which should be provided for each backend listed in :attr:`backends`. + + * if backend isn't available, it should return ``None``. + * if backend is available, it should return a callable + which implements :meth:`_calc_checksum`. + * it may also do things like import modules, run tests, issue warnings, + etc; though it should avoid doing things which would change the operation + of other backends (e.g. modify ``cls.default_rounds``). + + .. versionadded:: 1.7 .. attribute:: _has_backend_{name} @@ -1331,24 +1340,34 @@ class HasManyBackends(GenericHandler): or ``False``. One of these should be provided by the subclass for each backend listed in :attr:`backends`. + .. deprecated:: 1.7 + + use :attr:`_load_backend_{name}` instead. + support for this attribute will be removed in Passlib 2.0. + .. classmethod:: _calc_checksum_{name} private class method that should implement :meth:`_calc_checksum` for a given backend. it will only be called if the backend has been selected by :meth:`set_backend`. One of these should be provided by the subclass for each backend listed in :attr:`backends`. - """ - # NOTE: - # subclass must provide: - # * attr 'backends' containing list of known backends (top priority backend first) - # * attr '_has_backend_xxx' for each backend 'xxx', indicating if backend is available on system - # * attr '_calc_checksum_xxx' for each backend 'xxx', containing calc_checksum implementation using that backend + .. deprecated:: 1.7 + use :attr:`_load_backend_{name}` instead. + this attribute will be ignored in Passlib 2.0. + """ backends = None # list of backend names, provided by subclass. _backend = None # holds currently loaded backend (if any) or None + #: optional class-specific text containing suggestion about what to do + #: when no backends are available. + _no_backend_suggestion = None + + #: flag used by _try_alternate_backend to prevent recursion + __tab_active = None + @classmethod def get_backend(cls): """return name of currently active backend. @@ -1360,12 +1379,10 @@ class HasManyBackends(GenericHandler): :returns: name of active backend """ - name = cls._backend - if not name: + if not cls._backend: cls.set_backend() - name = cls._backend - assert name, "set_backend() didn't load any backends" - return name + assert cls._backend, "set_backend() failed to load a default backend" + return cls._backend @classmethod def has_backend(cls, name="any"): @@ -1381,19 +1398,16 @@ class HasManyBackends(GenericHandler): :returns: ``True`` if backend is currently supported, else ``False``. """ - if name in ("any", "default"): - if name == "any" and cls._backend: + if name == "any" or name == "default": + if cls._backend: + return True + try: + cls.set_backend() return True - return any(getattr(cls, "_has_backend_" + name) - for name in cls.backends) - elif name in cls.backends: - return getattr(cls, "_has_backend_" + name) + except exc.MissingBackendError: + return False else: - raise ValueError("unknown backend: %r" % (name,)) - - @classmethod - def _no_backends_msg(cls): - return "no %s backends available" % (cls.name,) + return cls._load_backend(name) is not None @classmethod def set_backend(cls, name="any"): @@ -1426,27 +1440,71 @@ class HasManyBackends(GenericHandler): and *no* backends are currently available. :returns: - The return value of this function should be ignored. """ - if name == "any": - name = cls._backend - if name: - return name - name = "default" - if name == "default": + if name == "any" and cls._backend: + # keep active backend + return cls._backend + elif name == "any" or name == "default": + # select default backend for name in cls.backends: - if cls.has_backend(name): + calc = cls._load_backend(name) + if calc: break + assert calc is None else: - raise exc.MissingBackendError(cls._no_backends_msg()) - elif not cls.has_backend(name): - raise exc.MissingBackendError("%s backend not available: %r" % - (cls.name, name)) - cls._calc_checksum_backend = getattr(cls, "_calc_checksum_" + name) + msg = "%s: no backends available" % cls.name + if cls._no_backend_suggestion: + msg += cls._no_backend_suggestion + raise exc.MissingBackendError(msg) + else: + # select specific backend + calc = cls._load_backend(name) + if not calc: + assert calc is None + raise exc.MissingBackendError("%s: backend not available: %s" % + (cls.name, name)) + # load backend into class + assert callable(calc) + cls._calc_checksum_backend = calc cls._backend = name return name + @classmethod + def _load_backend(cls, name): + """helper used by has_backend() & set_backend(), loads specified backend. + + :raises ValueError: if invalid backend name is provided + + :returns: + * ``None`` if backend can't be loaded. + * backend-specific ``_calc_checksum()`` callable on success. + """ + # validate name + if name not in cls.backends: + raise ValueError("%s: unknown backend: %r" % (cls.name, name)) + + # new in v1.7: check for _load_backend_xxx() function + load = getattr(cls, "_load_backend_" + name, None) + if load is not None: + assert not hasattr(cls, "_has_backend_" + name), ( + "%s: can't specify both ._load_backend_%s() " + "and ._has_backend_%s" % (cls.name, name, name) + ) + return load() + + # fallback to _has_backend_xxx + _calc_checksum_xxx() style + value = getattr(cls, "_has_backend_" + name) + warn("%s: support for ._has_backend_%s is deprecated as of Passlib 1.7, " + "and will be removed in Passlib 2.0, please implement " + "._load_backend_%s() instead" % (cls.name, name, name), + DeprecationWarning, + ) + if value: + return getattr(cls, "_calc_checksum_" + name) + else: + return None + def _calc_checksum_backend(self, secret): """ stub for _calc_checksum_backend(), @@ -1461,9 +1519,48 @@ class HasManyBackends(GenericHandler): return self._calc_checksum_backend(secret) def _calc_checksum(self, secret): - """wrapper for backend, for common code""" + "wrapper for backend, for common code""" return self._calc_checksum_backend(secret) + def _try_alternate_backends(self, secret): + """helper for _calc_checksum_backend implementations to hand off + to other backends on a per-hash basis. + + :raises MissingBackendError: if *no* backends can handle secret + """ + # if we're recursing, throw back to higher-level invocation (below) + if self.__tab_active: + raise exc.MissingBackendError("catch me") + + # backup current backend + current = self.get_backend() + self.__tab_active = True + try: + # run through all others until one works + for backend in self.backends: + if backend == current: + continue + try: + # may throw MissingBackendError if unavaiable + self.set_backend(backend) + + # if recurses to this function, + # will also throw MissingBackendError (above) + return self._calc_checksum_backend(secret) + except exc.MissingBackendError: + pass + finally: + # restore previous backend + self.__tab_active = False + self.set_backend(current) + + # no backend could handle things - give up + msg = "%s: password/hash can't be handled by any available backend" % (self.name,) + suggestion = self._no_backend_suggestion + if suggestion: + msg += suggestion + raise exc.MissingBackendError(msg) + #============================================================================= # wrappers #============================================================================= diff --git a/passlib/utils/pbkdf2.py b/passlib/utils/pbkdf2.py index ee245d6..6985ed5 100644 --- a/passlib/utils/pbkdf2.py +++ b/passlib/utils/pbkdf2.py @@ -14,28 +14,44 @@ from struct import pack from warnings import warn # site try: - from M2Crypto import EVP as _EVP + import M2Crypto.EVP as _EVP except ImportError: _EVP = None +#_EVP = None # pkg from passlib.exc import PasslibRuntimeWarning, ExpectedTypeError from passlib.utils import join_bytes, to_native_str, bytes_to_int, int_to_bytes, join_byte_values -from passlib.utils.compat import b, bytes, BytesIO, irange, callable, int_types +from passlib.utils.compat import b, bytes, BytesIO, irange, callable, int_types, PYPY # local __all__ = [ + # hash utils + "norm_hash_name", + "get_hash_info", + + # prf utils "get_prf", + "get_keyed_prf", + + # kdfs "pbkdf1", "pbkdf2", ] +def _clear_caches(): + """unittest helper -- clears get_hash_info() / get_prf() caches""" + _ghi_cache.clear() + _prf_cache.clear() + #============================================================================= # hash helpers #============================================================================= -# known hash names +# indexes into _nhn_hash_names _nhn_formats = dict(hashlib=0, iana=1) + +# known hash names _nhn_hash_names = [ - # (hashlib/ssl name, iana name or standin, ... other known aliases) + # format: (hashlib/ssl name, iana name or standin, other known aliases ...) # hashes with official IANA-assigned names # (as of 2012-03 - http://www.iana.org/assignments/hash-function-text-names) @@ -81,6 +97,8 @@ def norm_hash_name(name, format="hashlib"): :returns: Hash name, returned as native :class:`!str`. + + .. versionadded:: 1.6 """ # check cache try: @@ -130,106 +148,181 @@ def norm_hash_name(name, format="hashlib"): row = _nhn_cache[orig] = (name2, name) return row[idx] -# TODO: get_hash() func which wraps norm_hash_name(), hashlib.<attr>, and hashlib.new +def _get_hash_const(name): + """internal helper used by :func:`get_hash_info`""" + # typecheck + if not isinstance(name, str): + raise TypeError("expected digest name") + + # abort on bad values, and on hashlib attrs which aren't hashes + if name.startswith("_") or name in ("new", "algorithms"): + return None + + # first, check hashlib.<attr> for an efficient constructor + try: + return getattr(hashlib, name) + except AttributeError: + pass + + # second, check hashlib.new() in case SSL supports the digest + try: + # new() should throw ValueError if alg is unknown + tmp = hashlib.new(name, b("")) + if PYPY and not tmp.digest(): + # detect https://bugs.pypy.org/issue957, fixed in PyPy 1.8 + raise ValueError("not actually supported") + except ValueError: + pass + else: + # create wrapper function + # XXX: find a better way to just return hash constructor + def const(msg=b("")): + return hashlib.new(name, msg) + const.__name__ = "new(%r)" % name + const.__module__ = "hashlib" + const.__doc__ = "wrapper for %s hash constructor" % name + return const + + # third, use md4 fallback if needed + if name == "md4": + from passlib.utils.md4 import md4 + return md4 + + # finally, give up! + return None + +# cache for get_hash_const() lookups +_ghi_cache = {} + +def get_hash_info(name): + """Lookup hash constructor & stats by name. + + This is a thin wrapper around :mod:`hashlib`. It looks up a hash by name, + and returns a hash constructor, along with the digest & block sizes. + Calls to this method are cached, making it a lot faster + than looking up a hash and then creating a temporary instance + in order to read the digest size. Additionally, this function includes + workarounds and fallbacks for various VM-specific issues. + + :arg name: hashlib-compatible name of hash function + + :raises ValueError: if hash is unknown or unsupported. + + :returns: `(hash_constructor, digest_size, block_size)` + + .. versionadded:: 1.7 + """ + try: + return _ghi_cache[name] + except KeyError: + pass + const = _get_hash_const(name) + if not const: + raise ValueError("unknown hash algorithm: %r" % name) + tmp = const() + if len(tmp.digest()) != tmp.digest_size: + raise RuntimeError("%r constructor failed sanity check" % name) + record = _ghi_cache[name] = (const, tmp.digest_size, tmp.block_size) + return record #============================================================================= -# general prf lookup +# prf lookup #============================================================================= + _BNULL = b('\x00') -_XY_DIGEST = b(',\x1cb\xe0H\xa5\x82M\xfb>\xd6\x98\xef\x8e\xf9oQ\x85\xa3i') -_trans_5C = join_byte_values((x ^ 0x5C) for x in irange(256)) -_trans_36 = join_byte_values((x ^ 0x36) for x in irange(256)) +# sanity check +_TEST_HMAC_SHA1 = b(',\x1cb\xe0H\xa5\x82M\xfb>\xd6\x98\xef\x8e\xf9oQ\x85\xa3i') + +# xlat tables used by hmac routines +_TRANS_5C = join_byte_values((x ^ 0x5C) for x in irange(256)) +_TRANS_36 = join_byte_values((x ^ 0x36) for x in irange(256)) + +# prefixes for recognizing hmac-{digest} prf names +_HMAC_PREFIXES = ("hmac_", "hmac-") +#------------------------------------------------------------------------ +# general prf lookup +#------------------------------------------------------------------------ def _get_hmac_prf(digest): - """helper to return HMAC prf for specific digest""" + """helper for get_prf() -- returns HMAC-based prf for specified digest""" + # helpers def tag_wrapper(prf): + """helper to document generated wrappers""" prf.__name__ = "hmac_" + digest prf.__doc__ = ("hmac_%s(key, msg) -> digest;" " generated by passlib.utils.pbkdf2.get_prf()" % digest) - if _EVP and digest == "sha1": + # use m2crypto if it's present and supports requested digest + if _EVP: # use m2crypto function directly for sha1, since that's its default digest - try: - result = _EVP.hmac(b('x'),b('y')) - except ValueError: # pragma: no cover - pass - else: - if result == _XY_DIGEST: - return _EVP.hmac, 20 - # don't expect to ever get here, but will fall back to pure-python if we do. - warn("M2Crypto.EVP.HMAC() returned unexpected result " # pragma: no cover -- sanity check - "during Passlib self-test!", PasslibRuntimeWarning) - elif _EVP: - # use m2crypto if it's present and supports requested digest + if digest == "sha1": + if _EVP.hmac(b('x'), b('y')) != _TEST_HMAC_SHA1: + # don't expect to ever get here, but just in case + raise RuntimeError("M2Crypto.EVP.hmac() failed sanity check") + return _EVP.hmac, 20 + + # else check if it supports given digest as an option try: result = _EVP.hmac(b('x'), b('y'), digest) except ValueError: pass else: - # it does. so use M2Crypto's hmac & digest code - hmac_const = _EVP.hmac + const = _EVP.hmac def prf(key, msg): - return hmac_const(key, msg, digest) + return const(key, msg, digest) digest_size = len(result) tag_wrapper(prf) return prf, digest_size - # fall back to hashlib-based implementation - digest_const = getattr(hashlib, digest, None) - if not digest_const: - raise ValueError("unknown hash algorithm: %r" % (digest,)) - tmp = digest_const() - block_size = tmp.block_size + # fall back to hashlib-based implementation -- + # this is a simplified version of stdlib's hmac module. + const, digest_size, block_size = get_hash_info(digest) assert block_size >= 16, "unacceptably low block size" - digest_size = tmp.digest_size - del tmp def prf(key, msg): - # simplified version of stdlib's hmac module - if len(key) > block_size: - key = digest_const(key).digest() - key += _BNULL * (block_size - len(key)) - tmp = digest_const(key.translate(_trans_36) + msg).digest() - return digest_const(key.translate(_trans_5C) + tmp).digest() + klen = len(key) + if klen > block_size: + key = const(key).digest() + klen = digest_size + if klen < block_size: + key += _BNULL * (block_size - klen) + tmp = const(key.translate(_TRANS_36) + msg).digest() + return const(key.translate(_TRANS_5C) + tmp).digest() tag_wrapper(prf) return prf, digest_size # cache mapping prf name/func -> (func, digest_size) _prf_cache = {} -def _clear_prf_cache(): - """helper for unit tests""" - _prf_cache.clear() - def get_prf(name): - """lookup pseudo-random family (prf) by name. + """Lookup pseudo-random family (PRF) by name. :arg name: - this must be the name of a recognized prf. - currently this only recognizes names with the format + This must be the name of a recognized prf. + Currently this only recognizes names with the format :samp:`hmac-{digest}`, where :samp:`{digest}` is the name of a hash function such as ``md5``, ``sha256``, etc. - this can also be a callable with the signature - ``prf(secret, message) -> digest``, + This can also be a callable with the signature + ``prf_func(secret, message) -> digest``, in which case it will be returned unchanged. :raises ValueError: if the name is not known :raises TypeError: if the name is not a callable or string :returns: - a tuple of :samp:`({func}, {digest_size})`. + a tuple of :samp:`({prf_func}, {digest_size})`, where: - * :samp:`{func}` is a function implementing - the specified prf, and has the signature - ``func(secret, message) -> digest``. + * :samp:`{prf_func}` is a function implementing + the specified PRF, and has the signature + ``prf_func(secret, message) -> digest``. * :samp:`{digest_size}` is an integer indicating the number of bytes the function returns. - usage example:: + Usage example:: >>> from passlib.utils.pbkdf2 import get_prf >>> hmac_sha256, dsize = get_prf("hmac-sha256") @@ -239,26 +332,94 @@ def get_prf(name): 32 >>> digest = hmac_sha256('password', 'message') - this function will attempt to return the fastest implementation - it can find; if M2Crypto is present, and supports the specified prf, + This function will attempt to return the fastest implementation + it can find. Primarily, if M2Crypto is present, and supports the specified PRF, :func:`M2Crypto.EVP.hmac` will be used behind the scenes. """ global _prf_cache if name in _prf_cache: return _prf_cache[name] if isinstance(name, str): - if name.startswith("hmac-") or name.startswith("hmac_"): - retval = _get_hmac_prf(name[5:]) + if name.startswith(_HMAC_PREFIXES): + record = _get_hmac_prf(name[5:]) else: raise ValueError("unknown prf algorithm: %r" % (name,)) elif callable(name): # assume it's a callable, use it directly - digest_size = len(name(b('x'),b('y'))) - retval = (name, digest_size) + digest_size = len(name(b('x'), b('y'))) + record = (name, digest_size) else: raise ExpectedTypeError(name, "str or callable", "prf name") - _prf_cache[name] = retval - return retval + _prf_cache[name] = record + return record + +#------------------------------------------------------------------------ +# keyed prf generation +#------------------------------------------------------------------------ + +def _get_keyed_hmac_prf(digest, key): + """get_keyed_prf() helper -- returns efficent hmac() function + hardcoded with specific digest and key. + """ + # all the following was adapted from stdlib's hmac module + + # resolve digest, get info + const, digest_size, block_size = get_hash_info(digest) + assert block_size >= 16, "unacceptably low block size" + + # prepare key + klen = len(key) + if klen > block_size: + key = const(key).digest() + klen = digest_size + if klen < block_size: + key += _BNULL * (block_size - klen) + + # return optimized hmac function for given key + inner_proto = const(key.translate(_TRANS_36)) + outer_proto = const(key.translate(_TRANS_5C)) + def kprf(msg): + inner = inner_proto.copy() + inner.update(msg) + outer = outer_proto.copy() + outer.update(inner.digest()) + return outer.digest() + + ##kprf.__name__ = "keyed_%s_hmac" % digest + ##kprf.__doc__ = "keyed %s-hmac function, " \ + ## "generated by passlib.utils.pbkdf2.get_keyed_prf()" % digest + return kprf, digest_size + +def get_keyed_prf(name, key): + """Lookup psuedo-random function family by name, + and return a psuedo-random function bound to a specific key. + + :arg name: + name of psuedorandom family. + accepts same inputs as :func:`get_prf`. + + :arg key: + key encoded as bytes. + + :returns: + tuple of :samp:`({bound_prf_func}, {digest_size})`, + where function has signature `bound_prf_func(message) -> digest`. + + .. versionadded:: 1.7 + """ + # check for optimized functions (common case) + if isinstance(name, str) and name.startswith(_HMAC_PREFIXES): + return _get_keyed_hmac_prf(name[5:], key) + + # fallback to making a generic wrapper + prf, digest_size = get_prf(name) + def kprf(message): + return prf(key, message) + + ##kprf.__name__ = "keyed_%s" % prf.__name__ + ##kprf.__doc__ = "keyed %s function, " \ + ## "generated by passlib.utils.pbkdf2.get_keyed_prf()" % prf.__name__ + return kprf, digest_size #============================================================================= # pbkdf1 support @@ -281,7 +442,6 @@ def pbkdf1(secret, salt, rounds, keylen=None, hash="sha1"): This algorithm has been deprecated, new code should use PBKDF2. Among other limitations, ``keylen`` cannot be larger than the digest size of the specified hash. - """ # validate secret & salt if not isinstance(secret, bytes): @@ -296,45 +456,34 @@ def pbkdf1(secret, salt, rounds, keylen=None, hash="sha1"): raise ValueError("rounds must be at least 1") # resolve hash - try: - hash_const = getattr(hashlib, hash) - except AttributeError: - # check for ssl hash - # NOTE: if hash unknown, new() will throw ValueError, which we'd just - # reraise anyways; so instead of checking, we just let it get - # thrown during first use, below - # TODO: use builtin md4 class if hashlib doesn't have it. - def hash_const(msg): - return hashlib.new(hash, msg) - - # prime pbkdf1 loop, get block size - block = hash_const(secret + salt).digest() + const, digest_size, block_size = get_hash_info(hash) # validate keylen if keylen is None: - keylen = len(block) + keylen = digest_size elif not isinstance(keylen, int_types): raise ExpectedTypeError(keylen, "int or None", "keylen") elif keylen < 0: raise ValueError("keylen must be at least 0") - elif keylen > len(block): + elif keylen > digest_size: raise ValueError("keylength too large for digest: %r > %r" % - (keylen, len(block))) + (keylen, digest_size)) # main pbkdf1 loop - for _ in irange(rounds-1): - block = hash_const(block).digest() + block = secret + salt + for _ in irange(rounds): + block = const(block).digest() return block[:keylen] #============================================================================= # pbkdf2 #============================================================================= -MAX_BLOCKS = 0xffffffff # 2**32-1 -MAX_HMAC_SHA1_KEYLEN = MAX_BLOCKS*20 + # NOTE: the pbkdf2 spec does not specify a maximum number of rounds. # however, many of the hashes in passlib are currently clamped -# at the 32-bit limit, just for sanity. once realistic pbkdf2 rounds -# start approaching 24 bits, this limit will be raised. +# at the 32-bit limit, just for sanity. Once realistic pbkdf2 rounds +# start approaching 24 bits or so, this limit will be raised. +_MAX_BLOCKS = 0xffffffff # 2**32-1 def pbkdf2(secret, salt, rounds, keylen=None, prf="hmac-sha1"): """pkcs#5 password-based key derivation v2.0 @@ -366,46 +515,39 @@ def pbkdf2(secret, salt, rounds, keylen=None, prf="hmac-sha1"): if rounds < 1: raise ValueError("rounds must be at least 1") + # generated keyed prf helper + keyed_prf, digest_size = get_keyed_prf(prf, secret) + # validate keylen - if keylen is not None: - if not isinstance(keylen, int_types): - raise ExpectedTypeError(keylen, "int or None", "keylen") - elif keylen < 0: - raise ValueError("keylen must be at least 0") - - # special case for m2crypto + hmac-sha1 - if prf == "hmac-sha1" and _EVP: - if keylen is None: - keylen = 20 - # NOTE: doing check here, because M2crypto won't take 'long' instances - # (which this is when running under 32bit) - if keylen > MAX_HMAC_SHA1_KEYLEN: - raise ValueError("key length too long for digest") - - # NOTE: as of 2012-4-4, m2crypto has buffer overflow issue - # which may cause segfaults if keylen > 32 (EVP_MAX_KEY_LENGTH). - # therefore we're avoiding m2crypto for large keys until that's fixed. - # see https://bugzilla.osafoundation.org/show_bug.cgi?id=13052 - if keylen < 32: - return _EVP.pbkdf2(secret, salt, rounds, keylen) - - # resolve prf - prf_func, digest_size = get_prf(prf) if keylen is None: keylen = digest_size + elif not isinstance(keylen, int_types): + raise ExpectedTypeError(keylen, "int or None", "keylen") + elif keylen < 0: + raise ValueError("keylen must be at least 0") + + # m2crypto's pbkdf2-hmac-sha1 is faster than ours, so use it if available. + # NOTE: as of 2012-4-4, m2crypto has buffer overflow issue which frequently + # causes segfaults if keylen > 32 (EVP_MAX_KEY_LENGTH). + # therefore we're avoiding m2crypto for large keys until that's fixed. + # (https://bugzilla.osafoundation.org/show_bug.cgi?id=13052) + if prf == "hmac-sha1" and _EVP and keylen < 32: + return _EVP.pbkdf2(secret, salt, rounds, keylen) - # figure out how many blocks we'll need - block_count = (keylen+digest_size-1)//digest_size - if block_count >= MAX_BLOCKS: - raise ValueError("key length too long for digest") + # work out min block count s.t. keylen <= block_count * digest_size + block_count = (keylen + digest_size - 1) // digest_size + if block_count >= _MAX_BLOCKS: + raise ValueError("keylen too long for digest") # build up result from blocks def gen(): for i in irange(block_count): - digest = prf_func(secret, salt + pack(">L", i+1)) + digest = keyed_prf(salt + pack(">L", i+1)) accum = bytes_to_int(digest) + # speed-critical loop of pbkdf2 + # NOTE: currently converting digests to integers since that XORs faster. for _ in irange(rounds-1): - digest = prf_func(secret, digest) + digest = keyed_prf(digest) accum ^= bytes_to_int(digest) yield int_to_bytes(accum, digest_size) return join_bytes(gen())[:keylen] |
