diff options
| author | Eli Collins <elic@assurancetechnologies.com> | 2016-06-29 11:43:07 -0400 |
|---|---|---|
| committer | Eli Collins <elic@assurancetechnologies.com> | 2016-06-29 11:43:07 -0400 |
| commit | 501ee83d2602e497e704760c97b6916ef2633888 (patch) | |
| tree | cee41f6def33ce513c8bb40fea86dd3d6cf329b3 /passlib | |
| parent | 165283cc679059ed16dbf38897bbe07f7ed163c3 (diff) | |
| download | passlib-501ee83d2602e497e704760c97b6916ef2633888.tar.gz | |
passlib.hash: Improved handling of hashes which truncate passwords
* Added PasswordHash.truncate_size info attribute, to detect hashes
which truncate the password.
* All such hashes (bcrypt, des_crypt, some others) now accept a "truncate_error"
option, allowing them to be switched from silent truncation to throwing
an error instead. This option is also supported by CryptContext.
* tests/HandlerCase:
- removed .secret_size config flag, can now just read handler.truncate_size instead.
- reworked truncation tests to use new API, and test 'truncate_error' policy support.
Diffstat (limited to 'passlib')
| -rw-r--r-- | passlib/exc.py | 14 | ||||
| -rw-r--r-- | passlib/handlers/bcrypt.py | 26 | ||||
| -rw-r--r-- | passlib/handlers/cisco.py | 26 | ||||
| -rw-r--r-- | passlib/handlers/des_crypt.py | 50 | ||||
| -rw-r--r-- | passlib/handlers/django.py | 17 | ||||
| -rw-r--r-- | passlib/handlers/windows.py | 22 | ||||
| -rw-r--r-- | passlib/ifc.py | 4 | ||||
| -rw-r--r-- | passlib/tests/test_context.py | 5 | ||||
| -rw-r--r-- | passlib/tests/test_handlers.py | 6 | ||||
| -rw-r--r-- | passlib/tests/test_handlers_bcrypt.py | 3 | ||||
| -rw-r--r-- | passlib/tests/test_handlers_django.py | 2 | ||||
| -rw-r--r-- | passlib/tests/utils.py | 40 | ||||
| -rw-r--r-- | passlib/utils/__init__.py | 27 | ||||
| -rw-r--r-- | passlib/utils/handlers.py | 34 |
14 files changed, 243 insertions, 33 deletions
diff --git a/passlib/exc.py b/passlib/exc.py index 35ca816..1cdb860 100644 --- a/passlib/exc.py +++ b/passlib/exc.py @@ -39,6 +39,20 @@ class PasswordSizeError(ValueError): # this also prevents a glibc crypt segfault issue, detailed here ... # http://www.openwall.com/lists/oss-security/2011/11/15/1 +class PasswordTruncateError(PasswordSizeError): + """ + Error raised if password would be truncated by hash. + This derives from :exc:`PasswordSizeError` and :exc:`ValueError`. + + Hashers such as :class:`~passlib.hash.bcrypt` can be configured to raises + this error by setting ``truncate_error=True``. + + .. versionadded:: 1.7 + """ + def __init__(self, cls): + msg = ("Password too long (%s truncates to %d characters)" % + (cls.name, cls.truncate_size)) + ValueError.__init__(self, msg) class PasslibSecurityError(RuntimeError): """ diff --git a/passlib/handlers/bcrypt.py b/passlib/handlers/bcrypt.py index 137e5c3..1283e21 100644 --- a/passlib/handlers/bcrypt.py +++ b/passlib/handlers/bcrypt.py @@ -82,7 +82,7 @@ def _detect_pybcrypt(): #============================================================================= # handler #============================================================================= -class bcrypt(uh.HasManyIdents, uh.HasRounds, uh.HasSalt, uh.HasManyBackends, uh.GenericHandler): +class bcrypt(uh.TruncateMixin, uh.HasManyIdents, uh.HasRounds, uh.HasSalt, uh.HasManyBackends, uh.GenericHandler): """This class implements the BCrypt password hash, and follows the :ref:`password-hash-api`. It supports a fixed-length salt, and a variable number of rounds. @@ -115,6 +115,13 @@ class bcrypt(uh.HasManyIdents, uh.HasRounds, uh.HasSalt, uh.HasManyBackends, uh. identical to ``"2a"`` in all but name. * ``"2b"`` - latest revision of the official BCrypt algorithm (will be default in Passlib 1.7). + :param bool truncate_error: + By default, BCrypt will silently truncate passwords larger than 72 bytes. + Setting ``truncate_error=True`` will cause :meth:`~passlib.ifc.PasswordHash.hash` + to raise a :exc:`~passlib.exc.PasswordTruncateError` instead. + + .. versionadded:: 1.7 + :type relaxed: bool :param relaxed: By default, providing an invalid value for one of the other @@ -146,7 +153,7 @@ class bcrypt(uh.HasManyIdents, uh.HasRounds, uh.HasSalt, uh.HasManyBackends, uh. # PasswordHash #-------------------- name = "bcrypt" - setting_kwds = ("salt", "rounds", "ident") + setting_kwds = ("salt", "rounds", "ident", "truncate_error") #-------------------- # GenericHandler @@ -177,6 +184,11 @@ class bcrypt(uh.HasManyIdents, uh.HasRounds, uh.HasSalt, uh.HasManyBackends, uh. max_rounds = 31 # 32-bit integer limit (since real_rounds=1<<rounds) rounds_cost = "log2" + #-------------------- + # TruncateMixin + #-------------------- + truncate_size = 72 + #=================================================================== # formatting #=================================================================== @@ -387,6 +399,10 @@ class bcrypt(uh.HasManyIdents, uh.HasRounds, uh.HasSalt, uh.HasManyBackends, uh. if isinstance(secret, unicode): secret = secret.encode("utf-8") + # check for truncation (during .hash() calls only) + if self.use_defaults: + self._check_truncate_policy(secret) + # NOTE: especially important to forbid NULLs for bcrypt, since many # backends (bcryptor, bcrypt) happily accept them, and then # silently truncate the password at first NULL they encounter! @@ -626,6 +642,8 @@ class bcrypt_sha256(bcrypt): Now defaults to '2b' bcrypt algorithm. """ name = "bcrypt_sha256" + setting_kwds = tuple(elem for elem in bcrypt.setting_kwds if elem not in ["truncate_error"]) + truncate_size = None # this is locked at 2a/2b for now. ident_values = (IDENT_2A, IDENT_2B) @@ -703,6 +721,10 @@ class bcrypt_sha256(bcrypt): # hand result off to normal bcrypt algorithm return super(bcrypt_sha256, self)._calc_checksum(key) + def _check_truncate_policy(self, secret): + # disable check performed by bcrypt(), since this doesn't truncate passwords. + pass + # patch set_backend so it modifies bcrypt class, not this one... # else the bcrypt.set_backend() tests will call the wrong class. # XXX: move this (and a get_backend wrapper) to bcrypt? diff --git a/passlib/handlers/cisco.py b/passlib/handlers/cisco.py index 9519700..fb1082b 100644 --- a/passlib/handlers/cisco.py +++ b/passlib/handlers/cisco.py @@ -22,7 +22,7 @@ __all__ = [ #============================================================================= # cisco pix firewall hash #============================================================================= -class cisco_pix(uh.HasUserContext, uh.StaticHandler): +class cisco_pix(uh.TruncateMixin, uh.HasUserContext, uh.StaticHandler): """This class implements the password hash used by (older) Cisco PIX firewalls, and follows the :ref:`password-hash-api`. It does a single round of hashing, and relies on the username @@ -43,6 +43,13 @@ class cisco_pix(uh.HasUserContext, uh.StaticHandler): hash passwords which don't have an associated user account (such as the "enable" password). + :param bool truncate_error: + By default, this will silently truncate passwords larger than 16 bytes. + Setting ``truncate_error=True`` will cause :meth:`~passlib.ifc.PasswordHash.hash` + to raise a :exc:`~passlib.exc.PasswordTruncateError` instead. + + .. versionadded:: 1.7 + .. versionadded:: 1.6 """ #=================================================================== @@ -53,6 +60,7 @@ class cisco_pix(uh.HasUserContext, uh.StaticHandler): # PasswordHash #-------------------- name = "cisco_pix" + setting_kwds = ("truncate_error",) #-------------------- # GenericHandler @@ -61,6 +69,11 @@ class cisco_pix(uh.HasUserContext, uh.StaticHandler): checksum_chars = uh.HASH64_CHARS #-------------------- + # TruncateMixin + #-------------------- + truncate_size = 16 + + #-------------------- # custom #-------------------- @@ -84,6 +97,10 @@ class cisco_pix(uh.HasUserContext, uh.StaticHandler): secret = secret.encode("utf-8") seclen = len(secret) + # check for truncation (during .hash() calls only) + if self.use_defaults: + self._check_truncate_policy(secret) + # PIX/ASA: Per-user accounts use the first 4 chars of the username as the salt, # whereas global "enable" passwords don't have any salt at all. # ASA only: Don't append user if password is 28 or more characters. @@ -125,6 +142,8 @@ class cisco_asa(cisco_pix): but will generate a different hash for anything larger (See the `Format & Algorithm`_ section for the details). + Unlike cisco_pix, this will truncate passwords larger than 32 bytes. + .. versionadded:: 1.7 """ #=================================================================== @@ -137,6 +156,11 @@ class cisco_asa(cisco_pix): name = "cisco_asa" #-------------------- + # TruncateMixin + #-------------------- + truncate_size = 32 + + #-------------------- # cisco_pix #-------------------- _is_asa = True diff --git a/passlib/handlers/des_crypt.py b/passlib/handlers/des_crypt.py index e04bd7e..73db920 100644 --- a/passlib/handlers/des_crypt.py +++ b/passlib/handlers/des_crypt.py @@ -9,7 +9,7 @@ from warnings import warn # site # pkg from passlib.utils import h64, h64big, safe_crypt, test_crypt, to_unicode -from passlib.utils.compat import byte_elem_value, u, uascii_to_str, unicode +from passlib.utils.compat import byte_elem_value, u, uascii_to_str, unicode, suppress_cause from passlib.crypto.des import des_encrypt_int_block import passlib.utils.handlers as uh # local @@ -108,7 +108,7 @@ def _raw_bsdi_crypt(secret, rounds, salt): #============================================================================= # handlers #============================================================================= -class des_crypt(uh.HasManyBackends, uh.HasSalt, uh.GenericHandler): +class des_crypt(uh.TruncateMixin, uh.HasManyBackends, uh.HasSalt, uh.GenericHandler): """This class implements the des-crypt password hash, and follows the :ref:`password-hash-api`. It supports a fixed-length salt. @@ -121,6 +121,13 @@ class des_crypt(uh.HasManyBackends, uh.HasSalt, uh.GenericHandler): If not specified, one will be autogenerated (this is recommended). If specified, it must be 2 characters, drawn from the regexp range ``[./0-9A-Za-z]``. + :param bool truncate_error: + By default, des_crypt will silently truncate passwords larger than 8 bytes. + Setting ``truncate_error=True`` will cause :meth:`~passlib.ifc.PasswordHash.hash` + to raise a :exc:`~passlib.exc.PasswordTruncateError` instead. + + .. versionadded:: 1.7 + :type relaxed: bool :param relaxed: By default, providing an invalid value for one of the other @@ -139,7 +146,7 @@ class des_crypt(uh.HasManyBackends, uh.HasSalt, uh.GenericHandler): # PasswordHash #-------------------- name = "des_crypt" - setting_kwds = ("salt",) + setting_kwds = ("salt", "truncate_error") #-------------------- # GenericHandler @@ -153,6 +160,11 @@ class des_crypt(uh.HasManyBackends, uh.HasSalt, uh.GenericHandler): min_salt_size = max_salt_size = 2 salt_chars = uh.HASH64_CHARS + #-------------------- + # TruncateMixin + #-------------------- + truncate_size = 8 + #=================================================================== # formatting #=================================================================== @@ -175,6 +187,16 @@ class des_crypt(uh.HasManyBackends, uh.HasSalt, uh.GenericHandler): return uascii_to_str(hash) #=================================================================== + # digest calculation + #=================================================================== + def _calc_checksum(self, secret): + # check for truncation (during .hash() calls only) + if self.use_defaults: + self._check_truncate_policy(secret) + + return self._calc_checksum_backend(secret) + + #=================================================================== # backend #=================================================================== backends = ("os_crypt", "builtin") @@ -457,7 +479,7 @@ class bigcrypt(uh.HasSalt, uh.GenericHandler): # eoc #=================================================================== -class crypt16(uh.HasSalt, uh.GenericHandler): +class crypt16(uh.TruncateMixin, uh.HasSalt, uh.GenericHandler): """This class implements the crypt16 password hash, and follows the :ref:`password-hash-api`. It supports a fixed-length salt. @@ -470,6 +492,13 @@ class crypt16(uh.HasSalt, uh.GenericHandler): If not specified, one will be autogenerated (this is recommended). If specified, it must be 2 characters, drawn from the regexp range ``[./0-9A-Za-z]``. + :param bool truncate_error: + By default, crypt16 will silently truncate passwords larger than 16 bytes. + Setting ``truncate_error=True`` will cause :meth:`~passlib.ifc.PasswordHash.hash` + to raise a :exc:`~passlib.exc.PasswordTruncateError` instead. + + .. versionadded:: 1.7 + :type relaxed: bool :param relaxed: By default, providing an invalid value for one of the other @@ -488,7 +517,7 @@ class crypt16(uh.HasSalt, uh.GenericHandler): # PasswordHash #-------------------- name = "crypt16" - setting_kwds = ("salt",) + setting_kwds = ("salt", "truncate_error") #-------------------- # GenericHandler @@ -502,6 +531,11 @@ class crypt16(uh.HasSalt, uh.GenericHandler): min_salt_size = max_salt_size = 2 salt_chars = uh.HASH64_CHARS + #-------------------- + # TruncateMixin + #-------------------- + truncate_size = 16 + #=================================================================== # internal helpers #=================================================================== @@ -531,11 +565,15 @@ class crypt16(uh.HasSalt, uh.GenericHandler): if isinstance(secret, unicode): secret = secret.encode("utf-8") + # check for truncation (during .hash() calls only) + if self.use_defaults: + self._check_truncate_policy(secret) + # parse salt value try: salt_value = h64.decode_int12(self.salt.encode("ascii")) except ValueError: # pragma: no cover - caught by class - raise ValueError("invalid chars in salt") + raise suppress_cause(ValueError("invalid chars in salt")) # convert first 8 byts of secret string into an integer, key1 = _crypt_secret_to_key(secret) diff --git a/passlib/handlers/django.py b/passlib/handlers/django.py index a09c33a..2b9547e 100644 --- a/passlib/handlers/django.py +++ b/passlib/handlers/django.py @@ -328,7 +328,7 @@ class django_pbkdf2_sha1(django_pbkdf2_sha256): #============================================================================= # other #============================================================================= -class django_des_crypt(uh.HasSalt, uh.GenericHandler): +class django_des_crypt(uh.TruncateMixin, uh.HasSalt, uh.GenericHandler): """This class implements Django's :class:`des_crypt` wrapper, and follows the :ref:`password-hash-api`. It supports a fixed-length salt. @@ -341,6 +341,13 @@ class django_des_crypt(uh.HasSalt, uh.GenericHandler): If not specified, one will be autogenerated (this is recommended). If specified, it must be 2 characters, drawn from the regexp range ``[./0-9A-Za-z]``. + :param bool truncate_error: + By default, django_des_crypt will silently truncate passwords larger than 8 bytes. + Setting ``truncate_error=True`` will cause :meth:`~passlib.ifc.PasswordHash.hash` + to raise a :exc:`~passlib.exc.PasswordTruncateError` instead. + + .. versionadded:: 1.7 + This should be compatible with the hashes generated by Django 1.4's :class:`!CryptPasswordHasher` class. Note that Django only supports this hash on Unix systems @@ -353,11 +360,12 @@ class django_des_crypt(uh.HasSalt, uh.GenericHandler): """ name = "django_des_crypt" django_name = "crypt" - setting_kwds = ("salt", "salt_size") + setting_kwds = ("salt", "salt_size", "truncate_error") ident = u("crypt$") checksum_chars = salt_chars = uh.HASH64_CHARS checksum_size = 11 min_salt_size = default_salt_size = 2 + truncate_size = 8 # NOTE: regarding duplicate salt field: # @@ -409,6 +417,9 @@ class django_des_crypt(uh.HasSalt, uh.GenericHandler): global des_crypt if des_crypt is None: _import_des_crypt() + # check for truncation (during .hash() calls only) + if self.use_defaults: + self._check_truncate_policy(secret) return des_crypt(salt=self.salt[:2])._calc_checksum(secret) class django_disabled(uh.ifc.DisabledHash, uh.StaticHandler): @@ -423,7 +434,7 @@ class django_disabled(uh.ifc.DisabledHash, uh.StaticHandler): .. note:: - Django 1.6 prepends a randomly generate 40-char alphanumeric string + Django 1.6 prepends a randomly generated 40-char alphanumeric string to each unusuable password. This class recognizes such strings, but for backwards compatibility, still returns ``"!"``. diff --git a/passlib/handlers/windows.py b/passlib/handlers/windows.py index 7c84430..e17beba 100644 --- a/passlib/handlers/windows.py +++ b/passlib/handlers/windows.py @@ -25,11 +25,21 @@ __all__ = [ #============================================================================= # lanman hash #============================================================================= -class lmhash(uh.HasEncodingContext, uh.StaticHandler): +class lmhash(uh.TruncateMixin, uh.HasEncodingContext, uh.StaticHandler): """This class implements the Lan Manager Password hash, and follows the :ref:`password-hash-api`. It has no salt and a single fixed round. + The :meth:`~passlib.ifc.PasswordHash.using` method accepts a single + optional keyword: + + :param bool truncate_error: + By default, this will silently truncate passwords larger than 14 bytes. + Setting ``truncate_error=True`` will cause :meth:`~passlib.ifc.PasswordHash.hash` + to raise a :exc:`~passlib.exc.PasswordTruncateError` instead. + + .. versionadded:: 1.7 + The :meth:`~passlib.ifc.PasswordHash.hash` and :meth:`~passlib.ifc.PasswordHash.verify` methods accept a single optional keyword: @@ -51,6 +61,7 @@ class lmhash(uh.HasEncodingContext, uh.StaticHandler): # PasswordHash #-------------------- name = "lmhash" + setting_kwds = ("truncate_error",) #-------------------- # GenericHandler @@ -59,6 +70,11 @@ class lmhash(uh.HasEncodingContext, uh.StaticHandler): checksum_size = 32 #-------------------- + # TruncateMixin + #-------------------- + truncate_size = 14 + + #-------------------- # custom #-------------------- default_encoding = "cp437" @@ -71,6 +87,10 @@ class lmhash(uh.HasEncodingContext, uh.StaticHandler): return hash.lower() def _calc_checksum(self, secret): + # check for truncation (during .hash() calls only) + if self.use_defaults: + self._check_truncate_policy(secret) + return hexlify(self.raw(secret, self.encoding)).decode("ascii") # magic constant used by LMHASH diff --git a/passlib/ifc.py b/passlib/ifc.py index 3a1215b..00231e7 100644 --- a/passlib/ifc.py +++ b/passlib/ifc.py @@ -59,6 +59,10 @@ class PasswordHash(object): #: depend on the provided password. is_disabled = False + #: if not None, should be an integer, indicating hash + #: will truncate any secrets larger than this value. + truncate_size = None + #--------------------------------------------------------------- # salt information -- if 'salt' in setting_kwds #--------------------------------------------------------------- diff --git a/passlib/tests/test_context.py b/passlib/tests/test_context.py index 78e835b..84dbf9c 100644 --- a/passlib/tests/test_context.py +++ b/passlib/tests/test_context.py @@ -744,6 +744,7 @@ sha512_crypt__min_rounds = 45000 # this checks that (3 schemes, 3 categories) inherit options correctly. # the 'user' category is not present in the options. cc4 = CryptContext( + truncate_error=True, schemes = [ "sha512_crypt", "des_crypt", "bsdi_crypt"], deprecated = ["sha512_crypt", "des_crypt"], all__vary_rounds = 0.1, @@ -758,6 +759,7 @@ sha512_crypt__min_rounds = 45000 # # sha512_crypt + # NOTE: 'truncate_error' shouldn't be passed along... # self.assertEqual(options(cc4, "sha512_crypt"), dict( deprecated=True, @@ -783,14 +785,17 @@ sha512_crypt__min_rounds = 45000 # self.assertEqual(options(cc4, "des_crypt"), dict( deprecated=True, + truncate_error=True, )) self.assertEqual(options(cc4, "des_crypt", "user"), dict( deprecated=True, # unconfigured category inherits from default + truncate_error=True, )) self.assertEqual(options(cc4, "des_crypt", "admin"), dict( deprecated=True, # unchanged though overidden + truncate_error=True, )) # diff --git a/passlib/tests/test_handlers.py b/passlib/tests/test_handlers.py index 9e3c875..c5a0c8a 100644 --- a/passlib/tests/test_handlers.py +++ b/passlib/tests/test_handlers.py @@ -202,7 +202,6 @@ bsdi_crypt_builtin_test = _bsdi_crypt_test.create_backend_case("builtin") #============================================================================= class cisco_pix_test(UserHandlerMixin, HandlerCase): handler = hash.cisco_pix - secret_size = 16 requires_user = False known_correct_hashes = [ @@ -266,10 +265,8 @@ def _get_secret(value): class cisco_asa_test(UserHandlerMixin, HandlerCase): handler = hash.cisco_asa - secret_size = 32 requires_user = False - known_correct_hashes = [ # format: ((secret, user), hash) @@ -432,7 +429,6 @@ class cisco_type7_test(HandlerCase): #============================================================================= class crypt16_test(HandlerCase): handler = hash.crypt16 - secret_size = 16 # TODO: find an authortative source of test vectors known_correct_hashes = [ @@ -462,7 +458,6 @@ class crypt16_test(HandlerCase): class _des_crypt_test(HandlerCase): """test des-crypt algorithm""" handler = hash.des_crypt - secret_size = 8 known_correct_hashes = [ # @@ -813,7 +808,6 @@ ldap_sha1_crypt_os_crypt_test = _ldap_sha1_crypt_test.create_backend_case("os_cr #============================================================================= class lmhash_test(EncodingHandlerMixin, HandlerCase): handler = hash.lmhash - secret_size = 14 secret_case_insensitive = True known_correct_hashes = [ diff --git a/passlib/tests/test_handlers_bcrypt.py b/passlib/tests/test_handlers_bcrypt.py index 78ba6d5..b2b7b5b 100644 --- a/passlib/tests/test_handlers_bcrypt.py +++ b/passlib/tests/test_handlers_bcrypt.py @@ -24,7 +24,6 @@ from passlib.tests.test_handlers import UPASS_WAV, UPASS_USD, UPASS_TABLE class _bcrypt_test(HandlerCase): """base for BCrypt test cases""" handler = hash.bcrypt - secret_size = 72 reduce_default_rounds = True fuzz_salts_need_bcrypt_repair = True has_os_crypt_fallback = False @@ -433,7 +432,7 @@ class _bcrypt_sha256_test(HandlerCase): '$bcrypt-sha256$2a,5$.US1fQ4TQS.ZTz/uJ5Kyn.$QNdPDOTKKT5/sovNz1iWg26quOU4Pje'), # test >72 chars is hashed correctly -- under bcrypt these hash the same. - # NOTE: test_60_secret_size() handles this already, this is just for overkill :) + # NOTE: test_60_truncate_size() handles this already, this is just for overkill :) (repeat_string("abc123",72), '$bcrypt-sha256$2a,5$X1g1nh3g0v4h6970O68cxe$r/hyEtqJ0teqPEmfTLoZ83ciAI1Q74.'), (repeat_string("abc123",72)+"qwr", diff --git a/passlib/tests/test_handlers_django.py b/passlib/tests/test_handlers_django.py index 08d371b..7810ce0 100644 --- a/passlib/tests/test_handlers_django.py +++ b/passlib/tests/test_handlers_django.py @@ -108,7 +108,6 @@ class django_disabled_test(HandlerCase): class django_des_crypt_test(HandlerCase, _DjangoHelper): """test django_des_crypt""" handler = hash.django_des_crypt - secret_size = 8 known_correct_hashes = [ # ensures only first two digits of salt count. @@ -249,7 +248,6 @@ class django_pbkdf2_sha1_test(HandlerCase, _DjangoHelper): class django_bcrypt_test(HandlerCase, _DjangoHelper): """test django_bcrypt""" handler = hash.django_bcrypt - secret_size = 72 fuzz_salts_need_bcrypt_repair = True known_correct_hashes = [ diff --git a/passlib/tests/utils.py b/passlib/tests/utils.py index a2b62c4..18fc0b7 100644 --- a/passlib/tests/utils.py +++ b/passlib/tests/utils.py @@ -786,10 +786,10 @@ class HandlerCase(TestCase): # use 1.7 api return (handler or self.handler).using(**settings).hash(secret, **context) - def do_verify(self, secret, hash, **kwds): + def do_verify(self, secret, hash, handler=None, **kwds): """call handler's verify method""" secret = self.populate_context(secret, kwds) - return self.handler.verify(secret, hash, **kwds) + return (handler or self.handler).verify(secret, hash, **kwds) def do_identify(self, hash): """call handler's identify method""" @@ -1890,32 +1890,54 @@ class HandlerCase(TestCase): #=================================================================== # passwords #=================================================================== - def test_60_secret_size(self): + def test_60_truncate_size(self): """test password size limits""" - sc = self.secret_size + handler = self.handler + + sc = handler.truncate_size base = "too many secrets" # 16 chars alt = 'x' # char that's not in base string if sc is not None: # hash only counts the first <sc> characters; eg: bcrypt, des-crypt + self.assertGreaterEqual(sc, 1) + self.assertIn("truncate_error", handler.setting_kwds) + + without_error = handler.using(truncate_error=False) + with_error = handler.using(truncate_error=True) # create & hash string that's exactly sc+1 chars secret = repeat_string(base, sc+1) - hash = self.do_encrypt(secret) + hash = self.do_encrypt(secret, handler=without_error) + + # with errors enabled, should forbid truncation. + self.assertRaises(uh.exc.PasswordTruncateError, + self.do_encrypt, secret, handler=with_error) + + # make sure we can create & hash string that's exactly sc chars + self.do_encrypt(secret[:-1], handler=with_error) # check sc value isn't too large by verifying that sc-1'th char # affects hash secret2 = secret[:-2] + alt + secret[-1] - self.assertFalse(self.do_verify(secret2, hash), - "secret_size value is too large") + self.assertFalse(self.do_verify(secret2, hash, handler=with_error), + "truncate_size value is too large") # check sc value isn't too small by verifying adding sc'th char # *doesn't* affect hash secret3 = secret[:-1] + alt - self.assertTrue(self.do_verify(secret3, hash), - "secret_size value is too small") + self.assertTrue(self.do_verify(secret3, hash, handler=with_error), + "truncate_size value is too small") + + # test parse values + self.assertEqual(handler.using(truncate_error=True).truncate_error, True) + self.assertEqual(handler.using(truncate_error="true").truncate_error, True) + self.assertEqual(handler.using(truncate_error=False).truncate_error, False) + self.assertEqual(handler.using(truncate_error="false").truncate_error, False) + self.assertRaises(ValueError, handler.using, truncate_error="xxx") else: # hash counts all characters; e.g. md5-crypt + self.assertNotIn("truncate_error", handler.setting_kwds) # NOTE: this doesn't do an exhaustive search to verify algorithm # doesn't have some cutoff point, it just tries diff --git a/passlib/utils/__init__.py b/passlib/utils/__init__.py index 5e5f73b..09b0fcb 100644 --- a/passlib/utils/__init__.py +++ b/passlib/utils/__init__.py @@ -37,6 +37,7 @@ from passlib.exc import ExpectedStringError from passlib.utils.compat import (add_doc, join_bytes, join_byte_values, join_byte_elems, irange, imap, PY3, u, join_unicode, unicode, byte_elem_value, nextgetter, + unicode_or_bytes_types, get_method_function, suppress_cause) # local __all__ = [ @@ -729,6 +730,32 @@ def to_hash_str(source, encoding="ascii"): # pragma: no cover -- deprecated & un """deprecated, use to_native_str() instead""" return to_native_str(source, encoding, param="hash") +_true_set = set("true t yes y on 1".split()) +_false_set = set("false f no n off 0".split()) +_none_set = set(["", "none"]) + +def as_bool(value, none=None, param="boolean"): + """ + helper to convert value to boolean. + recognizes strings such as "true", "false" + """ + assert none in [True, False, None] + if isinstance(value, unicode_or_bytes_types): + clean = value.lower().strip() + if clean in _true_set: + return True + if clean in _false_set: + return False + if clean in _none_set: + return none + raise ValueError("unrecognized %s value: %r" % (param, value)) + elif isinstance(value, bool): + return value + elif value is None: + return none + else: + return bool(value) + #============================================================================= # base64-variant encoding #============================================================================= diff --git a/passlib/utils/handlers.py b/passlib/utils/handlers.py index 1199da0..50afddb 100644 --- a/passlib/utils/handlers.py +++ b/passlib/utils/handlers.py @@ -18,7 +18,7 @@ from passlib.registry import get_crypt_handler from passlib.utils import classproperty, consteq, getrandstr, getrandbytes,\ BASE64_CHARS, HASH64_CHARS, rng, to_native_str, \ is_crypt_handler, to_unicode, deprecated_method, \ - MAX_PASSWORD_SIZE, accepts_keyword + MAX_PASSWORD_SIZE, accepts_keyword, as_bool from passlib.utils.compat import join_byte_values, irange, u, native_string_types, \ uascii_to_str, join_unicode, unicode, str_to_uascii, \ join_unicode, unicode_or_bytes_types, PY2, int_types @@ -399,6 +399,37 @@ class MinimalHandler(PasswordHash): # eoc #=================================================================== +class TruncateMixin(MinimalHandler): + """ + PasswordHash mixin which provides a method + that will check if secret would be truncated, + and can be configured to throw an error. + """ + + #: whether passwords large enough to be truncated + #: should cause a PasswordTruncateError to be raised, + #: instead of being silently truncated. + truncate_error = False + + @classmethod + def using(cls, truncate_error=None, **kwds): + subcls = super(TruncateMixin, cls).using(**kwds) + if truncate_error is not None: + truncate_error = as_bool(truncate_error, param="truncate_error") + if truncate_error is not None: + subcls.truncate_error = truncate_error + return subcls + + @classmethod + def _check_truncate_policy(cls, secret): + """ + make sure secret won't be truncated. + NOTE: this should only be called for .hash(), not for .verify() + """ + assert cls.truncate_size is not None, "truncate_size must be set by subclass" + if cls.truncate_error and len(secret) > cls.truncate_size: + raise exc.PasswordTruncateError(cls) + #============================================================================= # GenericHandler #============================================================================= @@ -2409,6 +2440,7 @@ class PrefixWrapper(object): "default_salt_size", "min_salt_size", "max_salt_size", "salt_chars", "default_salt_chars", "backends", "has_backend", "get_backend", "set_backend", + "truncate_size", ) def __repr__(self): |
