diff options
| author | Eli Collins <elic@assurancetechnologies.com> | 2017-01-30 21:50:25 -0500 |
|---|---|---|
| committer | Eli Collins <elic@assurancetechnologies.com> | 2017-01-30 21:50:25 -0500 |
| commit | aed70ef83940df4a056aec36e402ba2b2df8e464 (patch) | |
| tree | 2403a8e14a4b6382f061244926600e0d1aefbeff | |
| parent | 33afd1a6752c81692712919997873cc440de6a70 (diff) | |
| parent | 02e207bd5a870ee3fafab73d47f43ee52321479a (diff) | |
| download | passlib-aed70ef83940df4a056aec36e402ba2b2df8e464.tar.gz | |
Merge with stable
31 files changed, 1378 insertions, 780 deletions
@@ -1,12 +1,3 @@ -glob:*.pyc -glob:*.egg-info -glob:.coverage -glob:cover -glob:build -glob:dist -glob:*$py.class -glob:MANIFEST -glob:.tox -glob:app.yaml -glob:.noseids -^\.idea$ +^\.idea|\.coverage|cover|build|dist|MANIFEST|\.tox|\.noseids$ +^.*\.(pyc|egg-info|\$py\.class)$ +^hg-checklink.*$ @@ -17,7 +17,7 @@ Passlib is (c) `Assurance Technologies <http://www.assurancetechnologies.com>`_, and is released under the `BSD license <http://www.opensource.org/licenses/bsd-license.php>`_:: Passlib - Copyright (c) 2008-2016 Assurance Technologies, LLC. + Copyright (c) 2008-2017 Assurance Technologies, LLC. All rights reserved. Redistribution and use in source and binary forms, with or without diff --git a/admin/plot_verify_timing.py b/admin/plot_verify_timing.py new file mode 100644 index 0000000..3f6255f --- /dev/null +++ b/admin/plot_verify_timing.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python3 +""" +small helper script used to compare timing of verify() & dummy_verify() +""" +# core +from __future__ import absolute_import, division, print_function, unicode_literals +from argparse import ArgumentParser +import sys +from timeit import default_timer as tick +# site +import matplotlib.pyplot as plt +from matplotlib.backends.backend_pdf import PdfPages +# pkg +from passlib.context import CryptContext +# local +__all__ = [ + "main" +] + +def main(*args): + # + # parse args + # + parser = ArgumentParser("""plot hash timing""") + parser.add_argument("-n", "--number", help="number of iterations", + type=int, default=300) + parser.add_argument("-o", "--output", help="pdf file", + default="plot_hash.pdf") + + opts = parser.parse_args(args) + + # + # init vars + # + ctx = CryptContext(schemes=["pbkdf2_sha256"]) + + secret = "a9w3857naw958ioa" + wrong_secret = "q0389wairuowieru" + hash = ctx.hash(secret) + ctx.dummy_verify() + + correct = [] + wrong = [] + missing = [] + + loops = opts.number + + # + # run timing loop + # + for _ in range(loops): + # correct pwd + start = tick() + ctx.verify(secret, hash) + delta = tick() - start + correct.append(delta) + + # wrong pwd + start = tick() + ctx.verify(wrong_secret, hash) + delta = tick() - start + wrong.append(delta) + + # wrong user / dummy verify + start = tick() + ctx.dummy_verify() + delta = tick() - start + missing.append(delta) + + # + # calc quartiles for verify() samples + # + samples = sorted(correct + wrong) + count = len(samples) + q1 = samples[count // 4] + q3 = samples[count * 3 // 4] + iqr = q3 - q1 + ub = q3 + 1.5 * iqr + lb = q1 - 1.5 * iqr + + # + # add in dummy samples, calc bounds + # + samples.extend(missing) + ymin = min(min(samples), lb - 0.5 * iqr) + ymax = max(max(samples), ub) + + # + # generate graph + # + with PdfPages(opts.output) as pdf: + plt.plot(range(loops), correct, 'go', label="verify success") + plt.plot(range(loops), wrong, 'yo', label="verify failed") + plt.plot(range(loops), missing, 'ro', label="dummy_verify()") + + plt.axis([0, loops, ymin, ymax]) + + plt.axhline(y=q1, xmax=count, color="r") + plt.axhline(y=q3, xmax=count, color="r") + plt.axhline(y=lb, xmax=count, color="orange") + plt.axhline(y=ub, xmax=count, color="orange") + + plt.ylabel('elapsed time') + plt.xlabel('loop count') + plt.legend(shadow=True, title="Legend", fancybox=True) + + plt.title('%s verify timing' % ctx.handler().name) + pdf.savefig() + plt.close() + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) + diff --git a/admin/upload.sh b/admin/upload.sh index 5aaa053..8b6c321 100755 --- a/admin/upload.sh +++ b/admin/upload.sh @@ -13,7 +13,7 @@ SEP2="-----------------------------------------------------" export SETUP_TAG_RELEASE=no if [ -z "$DRY_RUN" ]; then - echo "DRY_RUN not set" + echo "DRY_RUN not set (0 or 1)" exit 1 elif [ "$DRY_RUN" -eq 1 ]; then echo "dry run" diff --git a/docs/_fragments/asa_verify_callout.rst b/docs/_fragments/asa_verify_callout.rst new file mode 100644 index 0000000..46cfdb7 --- /dev/null +++ b/docs/_fragments/asa_verify_callout.rst @@ -0,0 +1,15 @@ +.. rst-class:: float-right without-title + +.. todo:: + + **Caveat Emptor** + + Passlib's implementations of :class:`cisco_pix` and :class:`cisco_asa` both need verification. + For those with access to Cisco PIX and ASA systems, verifying Passlib's reference vectors + would be a great help (see :issue:`51`). In the mean time, there are no guarantees + that passlib correctly replicates the official implementation. + + .. versionchanged:: 1.7.1 + + A number of :ref:`bugs <passlib-asa96-bug>` were fixed after expanding + the reference vectors, and testing against an ASA 9.6 system. diff --git a/docs/conf.py b/docs/conf.py index 7adac8b..6883743 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -63,7 +63,7 @@ extensions = [ 'cloud_sptheme.ext.index_styling', # inserts toc into right hand nav bar (ala old style python docs) - 'cloud_sptheme.ext.relbar_toc', + 'cloud_sptheme.ext.relbar_links', # add "issue" role 'cloud_sptheme.ext.issue_tracker', diff --git a/docs/history/1.7.rst b/docs/history/1.7.rst index 60319dd..14e115f 100644 --- a/docs/history/1.7.rst +++ b/docs/history/1.7.rst @@ -2,21 +2,46 @@ Passlib 1.7 =========== -**1.7.1** (NOT YET RELEASED) -============================ +**1.7.1** (2017-1-30) +===================== -.. py:currentmodule:: passlib.ifc +This release rolls up assorted bug & compatibility fixes since 1.7.0. -* bugfix: :meth:`PasswordHash.hash` will now warn if passed any settings +Bugfixes +-------- +* .. py:currentmodule:: passlib.hash + + :class:`cisco_asa` and :class:`cisco_pix`: Fixed a number of issues + which under :ref:`certain conditions <passlib-asa96-bug>` + caused prior releases to generate hashes that were unverifiable + on Cisco systems. + +* .. py:currentmodule:: passlib.ifc + + :meth:`PasswordHash.hash` will now warn if passed any settings keywords. This usage was deprecated in 1.7.0, but warning wasn't properly enabled. See :ref:`hash-configuring` for the preferred way to pass settings. -* bugfix: setup.py: prevent erroneous version strings when run from an sdist. +* **setup.py**: Don't append timestamp when run from an sdist. + This should fix some downstream build issues. + +* :mod:`!passlib.tests.test_totp`: Test suite now traps additional errors that :func:`datetime.utcfromtimestamp` + may throw under python 3, which should fix some test failures on architectures with rarer ILP sizes. + It also works around Python 3.6 bug `29100 <https://bugs.python.org/issue29100>`_. + +Deprecations +------------ -* bugfix: TOTP tests: test setup now traps additional errors utcfromtimestamp() - may throw under python 3. +* :class:`~passlib.context.CryptContext`: The ``harden_verify`` flag has been turned into a NOOP and deprecated. + It will be removed in passlib 1.8 along with the already-deprecated ``min_verify_time`` (:issue:`83`). -* various documentation updates +Other Changes +------------- + +* :mod:`!passlib.tests.utils`: General truncation policy details were hammered out, + and additional hasher tests were added to enforce them. + +* **documentation**: Various updates & corrections. .. rst-class:: emphasize-children toc-always-open @@ -92,12 +117,6 @@ New Features methods for dealing with hashes representing :ref:`disabled accounts <context-disabled-hashes>` (:issue:`45`). - * The :class:`~passlib.context.CryptContext` object now supports - a :ref:`harden_verify <context-harden-verify-option>` option, - allowing applications to introduce a delay in verification - to help prevent attackers discovering weak or missing hashes - through timing attacks. - * All hashers which truncate passwords (e.g. :class:`~passlib.hash.bcrypt` and :class:`~passlib.hash.des_crypt`) can now be configured to raise a :exc:`~passlib.exc.PasswordTruncateError` when a overly-large password is provided. @@ -304,8 +323,6 @@ Scheduled removal of features: * **[minor]** :mod:`passlib.context`: The ``min_verify_time`` keyword that was deprecated in release 1.6, is now completely ignored. Support will be removed entirely in release 1.8. - See the new :ref:`harden_verify <context-harden-verify-option>` keyword - that replaces it. * **[trivial]** :mod:`passlib.hash`: The internal :meth:`!PasswordHash.parse_rounds` method, deprecated in 1.6, has been removed. diff --git a/docs/install.rst b/docs/install.rst index 2c4ec6a..be11d5d 100644 --- a/docs/install.rst +++ b/docs/install.rst @@ -139,7 +139,7 @@ If you wish to generate your own copy of the documentation, you will need to: 1. Install `Sphinx <http://sphinx.pocoo.org/>`_ (1.4 or newer) -2. Install the `Cloud Sphinx Theme <http://packages.python.org/cloud_sptheme>`_ (1.8 or newer). +2. Install the `Cloud Sphinx Theme <http://packages.python.org/cloud_sptheme>`_ (1.8.2 or newer). 3. Download the Passlib source 4. From the Passlib source directory, run :samp:`python setup.py build_sphinx`. 5. Once Sphinx completes its run, point a web browser to the file at :samp:`{SOURCE}/build/sphinx/html/index.html` diff --git a/docs/lib/passlib.apache.rst b/docs/lib/passlib.apache.rst index 4e81b09..969ead0 100644 --- a/docs/lib/passlib.apache.rst +++ b/docs/lib/passlib.apache.rst @@ -16,7 +16,7 @@ htpasswd and htdigest files; though the use of two helper classes. .. versionchanged:: 1.7 - These classes will now preserve blank lines & "#" comments when updating + These classes will now preserve blank lines and "#" comments when updating htpasswd files; previous releases would throw a parse error. .. versionchanged:: 1.8 diff --git a/docs/lib/passlib.context.rst b/docs/lib/passlib.context.rst index b1b6a86..5f2dd17 100644 --- a/docs/lib/passlib.context.rst +++ b/docs/lib/passlib.context.rst @@ -170,29 +170,14 @@ Options which directly affect the behavior of the CryptContext instance: ``harden_verify`` - If set to ``true``, CryptContext will pause the first time :meth:`verify` - is called, in order to calculate the "average" time it would take - to verify a hash created using the default settings. + Companion to ``min_verify_time``, currently ignored. - Subsequent :meth:`verify` calls using will have their time padded - to this minimum time, in order to make it harder for an attacker - to guess which accounts have weak hashes. - - Applications may also wish to call :meth:`~CryptContext.dummy_verify` for login - attempts where the user does not exist, in order to mask which - users accounts have valid hashes. - - This option can be set to ``True`` or ``False`` (the default). - - The default (may) be changed in a later 2.x release. + .. versionadded:: 1.7 - .. warning:: + .. deprecated:: 1.7.1 - This feature is new, and adjustments may need to be made - to when (and how) the code calculates what the "minimum verification time" - is supposed to be. - - .. versionadded:: 1.7 + This option is ignored by 1.7.1, and will be removed in 1.8 + along with ``min_verify_time``. .. _context-algorithm-options: @@ -535,3 +520,9 @@ if any invalid-but-correctable values are encountered Other Helpers ============= .. autoclass:: LazyCryptContext([schemes=None,] \*\*kwds [, onload=None]) + +.. rst-class:: html-toggle + +The CryptPolicy Class (deprecated) +================================== +.. autoclass:: CryptPolicy diff --git a/docs/lib/passlib.hash.cisco_asa.rst b/docs/lib/passlib.hash.cisco_asa.rst index 3b9e757..5875214 100644 --- a/docs/lib/passlib.hash.cisco_asa.rst +++ b/docs/lib/passlib.hash.cisco_asa.rst @@ -1,7 +1,7 @@ .. index:: Cisco; ASA hash ================================================================== -:class:`passlib.hash.cisco_asa` - Cisco ASA hash +:class:`passlib.hash.cisco_asa` - Cisco ASA MD5 hash ================================================================== .. include:: ../_fragments/insecure_hash_warning.rst @@ -10,9 +10,11 @@ .. versionadded:: 1.7 -The :class:`!cisco_asa` handler provides support for the 2005 revision of the older :class:`!cisco_pix` hash. -The usage, functionality, and format is the same as for :class:`!cisco_pix`, +.. include:: ../_fragments/asa_verify_callout.rst -.. seealso:: +The :class:`!cisco_asa` class provides support for Cisco ASA "encrypted" hash format. +This is a revision of the older :class:`!cisco_pix` hash; +and the usage and format is the same. - :doc:`cisco_pix <passlib.hash.cisco_pix>` documentation page. +**See the** :doc:`cisco_pix <passlib.hash.cisco_pix>` **documentation page** +for combined details of both these classes. diff --git a/docs/lib/passlib.hash.cisco_pix.rst b/docs/lib/passlib.hash.cisco_pix.rst index 5b00b83..f9978f2 100644 --- a/docs/lib/passlib.hash.cisco_pix.rst +++ b/docs/lib/passlib.hash.cisco_pix.rst @@ -1,57 +1,57 @@ .. index:: Cisco; PIX hash ================================================================== -:class:`passlib.hash.cisco_pix` - Cisco PIX hash +:class:`passlib.hash.cisco_pix` - Cisco PIX MD5 hash ================================================================== +.. currentmodule:: passlib.hash + .. include:: ../_fragments/insecure_hash_warning.rst .. versionadded:: 1.6 -.. todo:: - - Passlib currently lack a thorough set of test cases for the :class:`cisco_asa` hash - For people with access to such a system, verifying passlib's reference vectors - would be a great help (see :issue:`51`). - In the mean time, there are no guarantees that its behavior correctly replicates - the official implementation. *caveat emptor*. - -.. warning:: - - This class does not correctly handle hashes generated by - Pix/ASA 7.0 (2005) or newer; particularly for passwords 13 characters or more - (:issue:`51`). A new :class:`!cisco_asa` will be added in Passlib 1.7 to support these hashes. +Overview +======== +.. include:: ../_fragments/asa_verify_callout.rst -.. currentmodule:: passlib.hash +The :class:`cisco_asa` class implements the "encrypted" password hash algorithm commonly found on Cisco +ASA systems. The companion :class:`cisco_pix` class +implements the older variant found on Cisco PIX. +Aside from internal differences, and slightly different limitations, +the two hashes have the same format, and in some cases the same output. -The :class:`cisco_pix` class implements the password hash algorithm commonly found on older Cisco -PIX firewalls. The :class:`cisco_asa` class implements a newer variant found Cisco ASA 7.0 and -newer systems. They can be used directly as follows:: +These classes can be used directly to generate or verify a hash for a specific +user. Specifying the user account name is required for this hash:: - >>> from passlib.hash import cisco_pix as pix + >>> from passlib.hash import cisco_asa >>> # hash password using specified username - >>> hash = pix.hash("password", user="user") + >>> hash = cisco_asa.hash("password", user="user") >>> hash 'A5XOy94YKDPXCo7U' >>> # verify correct password - >>> pix.verify("password", hash, user="user") + >>> cisco_asa.verify("password", hash, user="user") True + >>> # verify correct password w/ wrong username - >>> pm.verify("password", hash, user="other") + >>> cisco_asa.verify("password", hash, user="other") False + >>> # verify incorrect password - >>> pm.verify("letmein", hash, user="user") + >>> cisco_asa.verify("letmein", hash, user="user") False +The main "enable" password can be hashes / verified just by omitting +the ``user`` parameter, or setting ``user=""``:: + >>> # hash password without associated user account - >>> hash2 = pix.hash("password") + >>> hash2 = cisco_asa.hash("password") >>> hash2 'NuLKvvWGg.x9HEKO' >>> # verify password without associated user account - >>> pix.verify("password", hash2) + >>> cisco_asa.verify("password", hash2) True .. seealso:: the generic :ref:`PasswordHash usage examples <password-hash-examples>` @@ -66,8 +66,8 @@ Interface .. note:: These hash algorithms have a context-sensitive peculiarity. - It takes in an optional username, used to salt the hash, - but with specific restrictions... + They take in an optional username to salt the hash, + but have specific restrictions... * The username *must* be provided in order to correctly hash passwords associated with a user account on the Cisco device. @@ -80,15 +80,19 @@ Interface Format & Algorithm ================== -Cisco PIX / ASA hashes consist of a 12 byte digest, encoded as a 16 character +Cisco PIX & ASA hashes consist of a 12 byte digest, encoded as a 16 character :data:`HASH64 <passlib.utils.binary.h64>`-encoded string. An example -hash (of ``"password"``) is ``"NuLKvvWGg.x9HEKO"``. +hash (of ``"password"``, with user ``""``) is ``"NuLKvvWGg.x9HEKO"``. The PIX / ASA digests are calculated as follows: -1. The password is encoded using an ``ASCII``-compatible encoding - (all known references are strict 7-bit ascii, and Passlib uses ``UTF-8`` - to provide unicode support). +1. The password is encoded using ``UTF-8`` (though entering non-ASCII + characters is subject to interface-specific issues, and may lead + to problems such as double-encoding). + + If the result is greater than 16 bytes (for PIX), or 32 bytes (for ASA), + the password is not allowed -- it will be rejected when set, + and simplify not verify during authentication. 2. If the hash is associated with a user account, append the first four bytes of the user account name @@ -96,14 +100,18 @@ The PIX / ASA digests are calculated as follows: with a user account (e.g. it's the "enable" password), this step should be omitted. + If the user account is 1-3 bytes, it is repeated until all 4 bytes are filled + up (e.g. "usr" becomes "usru"). + For :class:`!cisco_asa`, this step is omitted if the password is 28 bytes or more. -3. The password should be truncated to 16 bytes, or the right side NULL - padded to 16 bytes, as appropriate. +3. The password+user string is truncated, or right-padded with NULLs, + until it's 16 bytes in size. For :class:`!cisco_asa`, - if the password is 13 or more bytes, the truncate/padding size is increased to 32 bytes. + if the password+user string is 16 or more bytes, + a padding size of 32 is used instead. 4. Run the result of step 3 through MD5. @@ -112,6 +120,10 @@ The PIX / ASA digests are calculated as follows: 6. Encode the 12-byte result using :data:`HASH64 <passlib.utils.binary.h64>`. +.. versionchanged:: 1.7.1 + + Updated to reflect current understanding of the algorithm. + Security Issues =============== This algorithm is not suitable for *any* use besides manipulating existing @@ -138,22 +150,44 @@ Cisco PIX hashes, due to the following flaws: Deviations ========== -This implementation differs from the standard in one main way: +This implementation tries to adhere to the canonical Cisco implementation, +but without an official specification, there may be other unknown deviations. +The following are known issues: * Unicode Policy: - The official Cisco PIX algorithm is primarily used with ``ascii`` passwords, - how it handles other characters is not known. + ASA documentation [#charset]_ indicates it uses UTF-8 encoding, + and Passlib does as well. However, some ASA interfaces + have issues such as: ASDM may double-encode unicode characters, + and SSH connections may drop non-ASCII characters entirely. + +* How usernames are added is not entirely pinned down. Under ASA, 3-character + usernames have their last character repeated to make a string of length 4. + It is currently assumed that a similar repetition would be applied to + usernames of 1-2 characters, and that this applies to PIX as well; + though neither assumption has been confirmed. + +* .. _passlib-asa96-bug: - In order to provide support for unicode strings, - Passlib will encode unicode passwords using ``utf-8`` - before running them through this algorithm. If a different - encoding is desired by an application, the password should be encoded - before handing it to Passlib. + **Passlib 1.7.1 Bugfix**: Prior releases of Passlib had a number of issues + with their implementation of the PIX & ASA algorithms. As of 1.7.1, + the reference vectors were greatly expanded, and then tested against + an ASA 9.6 system. This revealed a number of errors in passlib's implementation, + which under the following conditions would create hashes that were + unverifiable on a Cisco system: -* While this implementation agrees with all known references, - the actual algorithm has not been published by Cisco, so there may be other - unknown deviations. + - PIX and ASA: Usernames containing 1-3 characters were not appended correctly (step 2, above). + + - ASA omits the user entirely (step 2, above) for passwords with >= 28 characters, + not >= 27. Non-enable passwords of exactly 27 characters were previous hashed + incorrectly. + + - ASA's padding size decision (step 3, above) is made after the user + has been appended, not before. This caused prior releases to + incorrectly hash non-enable passwords of length 13-15. + + Anyone relying on cisco_asa or cisco_pix should upgrade to Passlib 1.7.1 or newer + to avoid these issues. .. rubric:: Footnotes @@ -166,3 +200,6 @@ This implementation differs from the standard in one main way: .. [#] Partial description of ASA algorithm - `<https://github.com/stekershaw/asa-password-encrypt/blob/master/README.md>`_ + +.. [#charset] Character set used by ASA 8.4 - + `<http://www.cisco.com/c/en/us/td/docs/security/asa/asa84/configuration/guide/asa_84_cli_config/ref_cli.html#Supported_Character_Sets>`_ diff --git a/docs/lib/passlib.hash.rst b/docs/lib/passlib.hash.rst index 3211066..94580e8 100644 --- a/docs/lib/passlib.hash.rst +++ b/docs/lib/passlib.hash.rst @@ -238,20 +238,65 @@ no identifying markers, identifying them is pretty much context-dependant. Cisco Hashes ============ -The following hashes are used in various places on Cisco IOS and ASA devices: +.. + TODO: + + What was/were IOS types 1, 2, 3, and 6? Don't see many references. + Think type 6 is a reversible encryption format ala type 7, + per https://supportforums.cisco.com/discussion/11733226/when-use-type-6-encrypted-or-type-7-encrypted + + +**Cisco IOS** + +The following hashes are used in various places on Cisco IOS, and +are usually referred to by a Cisco-assigned "type" code: + +.. rst-class:: hidden .. toctree:: :maxdepth: 1 - passlib.hash.cisco_pix - passlib.hash.cisco_asa + passlib.hash.cisco_type7 + +* :doc:`passlib.hash.md5_crypt <passlib.hash.md5_crypt>` -- "Type 5" hashes are actually just the standard + Unix MD5-Crypt hash, the format is identical. + +* :doc:`passlib.hash.cisco_type7 <passlib.hash.cisco_type7>` -- "Type 7" isn't actually a hash, + but a reversible encoding designed to obscure passwords from idle view. + +* "Type 8" hashes are based on PBKDF2-HMAC-SHA256; + but not currently supported by passlib (:issue:`87`). -* **Cisco "Type 5" hashes** - these are the same as :doc:`md5_crypt <passlib.hash.md5_crypt>` +* "Type 9" hashes are based on scrypt; + but not currently supported by passlib (:issue:`87`). + +**Cisco PIX & ASA** + +Separately from this, Cisco PIX & ASA firewalls have their own hash formats, +generally identified by the "format" parameter in the :samp:`username {user} password {hash} {format}` config line +they occur in. The following are known & handled by passlib: + +.. rst-class:: hidden .. toctree:: :maxdepth: 1 - passlib.hash.cisco_type7 + passlib.hash.cisco_pix + passlib.hash.cisco_asa + +* :doc:`passlib.hash.cisco_pix <passlib.hash.cisco_pix>` -- PIX "encrypted" hashes + use a simple unsalted MD5-based algorithm. + +* :doc:`passlib.hash.cisco_asa <passlib.hash.cisco_asa>` -- ASA "encrypted" hashes + use a similar algorithm to PIX, with some minor improvements. + +* ASA "nt-encrypted" hashes + are the same as :class:`passlib.hash.nthash`, + except that they use base64 encoding rather than hexadecimal. + +* ASA 9.5 added support for "pbkdf2" hashes + (based on PBKDF2-HMAC-SHA512); which aren't currently supported + by passlib (:issue:`87`). .. _other-hashes: diff --git a/docs/lib/passlib.hash.scrypt.rst b/docs/lib/passlib.hash.scrypt.rst index 19751ca..5c3677c 100644 --- a/docs/lib/passlib.hash.scrypt.rst +++ b/docs/lib/passlib.hash.scrypt.rst @@ -55,7 +55,7 @@ Scrypt Backends This class will use the first available of two possible backends: -1. The C-accelarated `scrypt <https://pypi.python.org/pypi/scrypt>`_ package, if installed. +1. The C-accelerated `scrypt <https://pypi.python.org/pypi/scrypt>`_ package, if installed. 2. A pure-python implementation of SCrypt, built into Passlib. .. warning:: diff --git a/docs/narr/context-tutorial.rst b/docs/narr/context-tutorial.rst index 8e4cb7a..af093fa 100644 --- a/docs/narr/context-tutorial.rst +++ b/docs/narr/context-tutorial.rst @@ -371,7 +371,6 @@ If an existing hash below the minimum is tested, it will show up as needing reha Undocumented Features ===================== -.. todo:: Document usage of the :ref:`harden_verify <context-harden-verify-option>` option. .. todo:: Document usage of the :ref:`context-disabled-hashes` options. .. rst-class:: html-toggle @@ -420,9 +419,6 @@ All of the documented :ref:`context-options` are allowed. admin__pbkdf2_sha1__min_rounds = 18000 admin__pbkdf2_sha1__default_rounds = 20000 - ; delay failed verify() calls to mask hashes with weak rounds - harden_verify = true - Initializing the CryptContext ----------------------------- Applications which choose to use a policy file will typically want diff --git a/passlib/apache.py b/passlib/apache.py index cbf3ed9..0803708 100644 --- a/passlib/apache.py +++ b/passlib/apache.py @@ -458,8 +458,8 @@ def _init_htpasswd_context(): # (https://bz.apache.org/bugzilla/show_bug.cgi?id=49288) "bcrypt", - # not supported by apache (unless natively), but useful for editing htpasswd under - # windows and then deploying under unix. + # support not "builtin" to apache, instead it requires support through host's crypt(). + # adding them here to allow editing htpasswd under windows and then deploying under unix. "sha256_crypt", "sha512_crypt", "des_crypt", @@ -475,8 +475,8 @@ def _init_htpasswd_context(): ] # apache can verify anything supported by the native crypt(), - # though htpasswd can only generate des_crypt hashes. - # (may overlap w/ builtin apache schemes) + # though htpasswd tool can only generate a limited set of hashes. + # (this list may overlap w/ builtin apache schemes) schemes.extend(registry.get_supported_os_crypt_schemes()) # hack to remove dups and sort into preferred order diff --git a/passlib/context.py b/passlib/context.py index e5afe7b..87d6009 100644 --- a/passlib/context.py +++ b/passlib/context.py @@ -228,6 +228,8 @@ class _CryptConfig(object): raise KeyError("'schemes' context option is not allowed " "per category") key, value = norm_context_option(cat, key, value) + if key == "min_verify_time": # ignored in 1.7, to be removed in 1.8 + continue # store in context_options # map structure: context_options[key][category] = value @@ -283,9 +285,9 @@ class _CryptConfig(object): raise KeyError("deprecated scheme not found " "in policy: %r" % (scheme,)) elif key == "harden_verify": - if cat: - raise ValueError("'harden_verify' cannot be specified per category") - value = as_bool(value, param="harden_verify") + warn("'harden_verify' is deprecated & ignored as of Passlib 1.7.1, " + " and will be removed in 1.8", + DeprecationWarning) elif key != "schemes": raise KeyError("unknown CryptContext keyword: %r" % (key,)) return key, value @@ -1029,7 +1031,7 @@ class CryptContext(object): #----------------------------------------------------------- config = _CryptConfig(source) self._config = config - self.reset_min_verify_time() + self._reset_dummy_verify() self._get_record = config.get_record self._identify_record = config.identify_record if config.context_kwds: @@ -1151,6 +1153,7 @@ class CryptContext(object): via the *schemes* option. .. versionadded:: 1.6 + This was previously available as ``CryptContext().policy.schemes()`` .. seealso:: the :ref:`schemes <context-schemes-option>` option for usage example. """ @@ -1246,6 +1249,7 @@ class CryptContext(object): be one of the objects from :mod:`passlib.hash`) .. versionadded:: 1.6 + This was previously available as ``CryptContext().policy.get_handler()`` .. versionchanged:: 1.7 @@ -1343,6 +1347,7 @@ class CryptContext(object): 'ldap_plaintext']} .. versionadded:: 1.6 + This was previously available as ``CryptContext().policy.to_dict()`` .. seealso:: the :ref:`context-serialization-example` example in the tutorial. """ @@ -1384,6 +1389,7 @@ class CryptContext(object): schemes = ldap_salted_sha1, ldap_salted_md5, ldap_sha1, ldap_md5, ldap_plaintext .. versionadded:: 1.6 + This was previously available as ``CryptContext().policy.to_string()`` .. seealso:: the :ref:`context-serialization-example` example in the tutorial. """ @@ -1417,151 +1423,20 @@ class CryptContext(object): #=================================================================== # verify() hardening + # NOTE: this entire feature has been disabled. + # all contents of this section are NOOPs as of 1.7.1, + # and will be removed in 1.8. #=================================================================== - # NOTE: the estimation is currently algorithm is a little rough, so - # the control values are exposed here to make "poking" at them easier. - - #: maximum samples to take when estimating min_verify_time - mvt_estimate_max_samples = 10 - - #: minimum samples to take when estimating min_verify_time - mvt_estimate_min_samples = 4 - - #: maximum time to spend estimating min_verify_time - #: (this value is overridden by min_samples) - mvt_estimate_max_time = 1.2 - - #: minimum measurement resolution required by estimate - mvt_estimate_resolution = 0.05 - - # XXX: make writable? could store a lot of cryptcontext config directly in objects, - # (persisting hash state *in* the hashers), and then have to_dict() just extract - # current state. - @memoized_property - def harden_verify(self): - return self._config.get_context_option_with_flag(None, "harden_verify")[0] - - #: global lock used to prevent multiple copies of _calc_min_verify_time() - #: from running at the same time (whether as part of same context or not); - #: as this would cause inaccurate measurements - _mvt_lock = threading.Lock() - - # XXX: how to handle multiple categories? admin cateogry would stand out. - # but dont' want multiple levels of min_verify_time, *right*? - # maybe want to have CryptContext switch into a "nested" mode - # if categories are put in place, and have it act like multiple contexts. - - @memoized_property - def min_verify_time(self): - """ - minimum time verify() should take, to mask presence of weak hashes. - when first accessed, an estimate is performed based on - how long default hash takes. - can be overridden by manually writing to this attribute. - - will default to 0 (no estimate performed) unless 'harden_verify = true' - passed in CryptContext config. - """ - with self._mvt_lock: - # check if value was set in another thread - value = type(self).min_verify_time.peek_cache(self) - if value is None: - # value wasn't set, use calc function - value = self._calc_min_verify_time() - return value - - def _calc_min_verify_time(self): - """ - calculate min_verify_time based on system performance. - - .. warning:: - this assumes caller has acquired :attr:`_mvt_lock` - - :return: - estimated min_verify_time value - """ - # load config - log.debug("estimating min_verify_time") - min_samples = self.mvt_estimate_min_samples - max_samples = self.mvt_estimate_max_samples - record = self._get_record(None, None) - repeat = 1 - - # generate random secret to test against, - # and generate sample hash - secret = getrandstr(rng, BASE64_CHARS, 16) - start = timer() - hash = record.hash(secret) - samples = [timer() - start] - - # gather samples until condition met - loop_end = start + self.mvt_estimate_max_time - while True: - # gather sample - start = timer() - for _ in irange(repeat): - # XXX: using record.verify() instead of self.verify() - # since that would cause recursion errors back to here - # (and we can't temporarily set .min_verify_time=0 - # without temporarily letting other threads through - # w/o any delay). presuming there's not a noticeable - # overhead for the CryptContext.verify() wrapper. - record.verify(secret, hash) - end = timer() - elapsed = end - start - - # make sure we're far enough above timer's minimum resolution - if elapsed < self.mvt_estimate_resolution: - repeat *= 2 - continue - samples.append(elapsed / repeat) - - # stop as soon as possible if we have plenty of samples - if len(samples) > max_samples: - break - - # otherwise stop after max time, as long as we have bare minimum. - if end > loop_end and len(samples) > min_samples: - break - - # calc median, to cheaply exclude outliers - samples.sort() - result = round(samples[(len(samples)+1)//2], 3) - log.debug("setting min_verify_time=%f (median of %d samples)", - result, len(samples)) - return result + mvt_estimate_max_samples = 20 + mvt_estimate_min_samples = 10 + mvt_estimate_max_time = 2 + mvt_estimate_resolution = 0.01 + harden_verify = None + min_verify_time = 0 def reset_min_verify_time(self): - """ - clear min_verify_time estimate, - will be recalculated next time :attr:`min_verify_time` is accessed - (i.e. when :meth:`verify` is called). - """ - type(self).harden_verify.clear_cache(self) - type(self).min_verify_time.clear_cache(self) - - def dummy_verify(self, elapsed=0): - """ - Helper that applications can call when user wasn't found, - in order to simulate time it would take to hash a password. - - Invokes :func:`time.sleep` for amount of time needed to make - total elapsed time >= :attr:`min_verify_time`. - - :param elapsed: - optional amount of time spent hashing so far - (mainly used internally by :meth:`verify` and :meth:`verify_and_update`). - - See :ref:`harden_verify <context-harden-verify-option>` for details - about this feature. - - .. versionadded:: 1.7 - """ - assert elapsed >= 0 - remaining = self.min_verify_time - elapsed - if remaining > 0: - time.sleep(remaining) + self._reset_dummy_verify() #=================================================================== # password hash api @@ -1897,19 +1772,14 @@ class CryptContext(object): DeprecationWarning) if hash is None: # convenience feature -- let apps pass in hash=None when user - # isn't found / has no hash; mainly to get dummy_verify() benefit. - if self.harden_verify: - self.dummy_verify() + # isn't found / has no hash; useful because it invokes dummy_verify() + self.dummy_verify() return False record = self._get_or_identify_record(hash, scheme, category) strip_unused = self._strip_unused_context_kwds if strip_unused: strip_unused(kwds, record) - start = timer() - ok = record.verify(secret, hash, **kwds) - if not ok and self.harden_verify: - self.dummy_verify(timer() - start) - return ok + return record.verify(secret, hash, **kwds) def verify_and_update(self, secret, hash, scheme=None, category=None, **kwds): """verify password and re-hash the password if needed, all in a single call. @@ -1981,9 +1851,8 @@ class CryptContext(object): DeprecationWarning) if hash is None: # convenience feature -- let apps pass in hash=None when user - # isn't found / has no hash; mainly to get dummy_verify() benefit. - if self.harden_verify: - self.dummy_verify() + # isn't found / has no hash; useful because it invokes dummy_verify() + self.dummy_verify() return False, None record = self._get_or_identify_record(hash, scheme, category) strip_unused = self._strip_unused_context_kwds @@ -1996,10 +1865,7 @@ class CryptContext(object): # api to combine verify & needs_update to single call, # potentially saving some round-trip parsing. # but might make these codepaths more complex... - start = timer() if not record.verify(secret, hash, **clean_kwds): - if self.harden_verify: - self.dummy_verify(timer() - start) return False, None elif record.deprecated or record.needs_update(hash, secret=secret): # NOTE: we re-hash with default scheme, not current one. @@ -2008,6 +1874,45 @@ class CryptContext(object): return True, None #=================================================================== + # missing-user helper + #=================================================================== + + #: secret used for dummy_verify() + _dummy_secret = "too many secrets" + + @memoized_property + def _dummy_hash(self): + """ + precalculated hash for dummy_verify() to use + """ + return self.hash(self._dummy_secret) + + def _reset_dummy_verify(self): + """ + flush memoized values used by dummy_verify() + """ + type(self)._dummy_hash.clear_cache(self) + + def dummy_verify(self, elapsed=0): + """ + Helper that applications can call when user wasn't found, + in order to simulate time it would take to hash a password. + + Runs verify() against a dummy hash, to simulate verification + of a real account password. + + :param elapsed: + + .. deprecated:: 1.7.1 + + this option is ignored, and will be removed in passlib 1.8. + + .. versionadded:: 1.7 + """ + self.verify(self._dummy_secret, self._dummy_hash) + return False + + #=================================================================== # disabled hash support #=================================================================== diff --git a/passlib/crypto/scrypt/__init__.py b/passlib/crypto/scrypt/__init__.py index 2ad1cc6..16b9feb 100644 --- a/passlib/crypto/scrypt/__init__.py +++ b/passlib/crypto/scrypt/__init__.py @@ -116,51 +116,53 @@ def scrypt(secret, salt, n, r, p=1, keylen=32): raise ValueError("keylen too large, must be <= %d" % MAX_KEYLEN) return _scrypt(secret, salt, n, r, p, keylen) -#: list of potential backends -backend_values = ("scrypt", "builtin") -def _builtin_first_run(*args, **kwds): +def _load_builtin_backend(): """ - wrapper which issues warning first time it's used, - then replaces itself with actual function - (assumes this will be installed as _scrypt global when called) + Load pure-python scrypt implementation built into passlib. """ slowdown = 10 if PYPY else 100 warn("Using builtin scrypt backend, which is %dx slower than is required " "for adequate security. Installing scrypt support (via 'pip install scrypt') " "is strongly recommended" % slowdown, exc.PasslibSecurityWarning) from ._builtin import ScryptEngine - global _scrypt - _scrypt = ScryptEngine.execute - return _scrypt(*args, **kwds) + return ScryptEngine.execute -def _load_backend(name): + +def _load_cffi_backend(): """ - try to load specified scrypt backend + Try to import the ctypes-based scrypt hash function provided by the + ``scrypt <https://pypi.python.org/pypi/scrypt/>``_ package. """ - if name == "scrypt": - # try to import the ctypes-based scrypt hash function provided by the - # ``scrypt <https://pypi.python.org/pypi/scrypt/>``_ package. - try: - from scrypt import hash - return hash - except ImportError: - pass - try: - import scrypt - except ImportError as err: - if "scrypt" not in str(err): - # e.g. if cffi isn't set up right - # user should try importing scrypt explicitly to diagnose problem. - warn("'scrypt' package failed to import correctly (possible installation issue?)", - exc.PasslibWarning) - # else: package just isn't installed - else: - warn("'scrypt' package is too old (lacks ``hash()`` method)", exc.PasslibWarning) - return None - if name == "builtin": - return _builtin_first_run - raise ValueError("unknown scrypt backend %r" % name) + try: + from scrypt import hash + return hash + except ImportError: + pass + # not available, but check to see if package present but outdated / not installed right + try: + import scrypt + except ImportError as err: + if "scrypt" not in str(err): + # e.g. if cffi isn't set up right + # user should try importing scrypt explicitly to diagnose problem. + warn("'scrypt' package failed to import correctly (possible installation issue?)", + exc.PasslibWarning) + # else: package just isn't installed + else: + warn("'scrypt' package is too old (lacks ``hash()`` method)", exc.PasslibWarning) + return None + + +#: list of potential backends +backend_values = ("scrypt", "builtin") + +#: dict mapping backend name -> loader +_backend_loaders = dict( + scrypt=_load_cffi_backend, # XXX: rename backend constant to "cffi"? + builtin=_load_builtin_backend, +) + def _set_backend(name, dryrun=False): """ @@ -171,19 +173,23 @@ def _set_backend(name, dryrun=False): .. note:: mainly intended to be called by unittests, and scrypt hash handler """ if name == "any": - return True + return elif name == "default": for name in backend_values: try: - _set_backend(name, dryrun=dryrun) - return + return _set_backend(name, dryrun=dryrun) except exc.MissingBackendError: continue raise exc.MissingBackendError("no scrypt backends available") else: - hash = _load_backend(name) + loader = _backend_loaders.get(name) + if not loader: + raise ValueError("unknown scrypt backend: %r" % (name,)) + hash = loader() if not hash: raise exc.MissingBackendError("scrypt backend %r not available" % name) + if dryrun: + return global _scrypt, backend backend = name _scrypt = hash @@ -191,6 +197,14 @@ def _set_backend(name, dryrun=False): # initialize backend _set_backend("default") + +def _has_backend(name): + try: + _set_backend(name, dryrun=True) + return True + except exc.MissingBackendError: + return False + #========================================================================== # eof #========================================================================== diff --git a/passlib/exc.py b/passlib/exc.py index 95a0707..c4b78b4 100644 --- a/passlib/exc.py +++ b/passlib/exc.py @@ -28,8 +28,10 @@ class MissingBackendError(RuntimeError): """ class PasswordSizeError(ValueError): - """Error raised if a password exceeds the maximum size allowed - by Passlib (4096 characters). + """ + Error raised if a password exceeds the maximum size allowed + by Passlib (by default, 4096 characters); or if password exceeds + a hash-specific size limitation. Many password hash algorithms take proportionately larger amounts of time and/or memory depending on the size of the password provided. This could present diff --git a/passlib/handlers/cisco.py b/passlib/handlers/cisco.py index 186c247..e715e1a 100644 --- a/passlib/handlers/cisco.py +++ b/passlib/handlers/cisco.py @@ -1,4 +1,6 @@ -"""passlib.handlers.cisco - Cisco password hashes""" +""" +passlib.handlers.cisco -- Cisco password hashes +""" #============================================================================= # imports #============================================================================= @@ -9,7 +11,7 @@ import logging; log = logging.getLogger(__name__) from warnings import warn # site # pkg -from passlib.utils import right_pad_string, to_unicode +from passlib.utils import right_pad_string, to_unicode, repeat_string, to_bytes from passlib.utils.binary import h64 from passlib.utils.compat import unicode, u, join_byte_values, \ join_byte_elems, iter_byte_values, uascii_to_str @@ -17,23 +19,37 @@ import passlib.utils.handlers as uh # local __all__ = [ "cisco_pix", + "cisco_asa", "cisco_type7", ] #============================================================================= +# utils +#============================================================================= + +#: dummy bytes used by spoil_digest var in cisco_pix._calc_checksum() +_DUMMY_BYTES = b'\xFF' * 32 + +#============================================================================= # cisco pix firewall hash #============================================================================= -class cisco_pix(uh.TruncateMixin, uh.HasUserContext, uh.StaticHandler): - """This class implements the password hash used by (older) Cisco PIX firewalls, +class cisco_pix(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 as the salt. - The :meth:`~passlib.ifc.PasswordHash.hash`, :meth:`~passlib.ifc.PasswordHash.genhash`, and :meth:`~passlib.ifc.PasswordHash.verify` methods - have the following extra keyword: + This class only allows passwords <= 16 bytes, anything larger + will result in a :exc:`~passlib.exc.PasswordSizeError` if passed to :meth:`~cisco_pix.hash`, + and be silently rejected if passed to :meth:`~cisco_pix.verify`. + + The :meth:`~passlib.ifc.PasswordHash.hash`, + :meth:`~passlib.ifc.PasswordHash.genhash`, and + :meth:`~passlib.ifc.PasswordHash.verify` methods + all support the following extra keyword: - :type user: str - :param user: + :param str user: String containing name of user account this password is associated with. This is *required* in order to correctly hash passwords associated @@ -44,14 +60,13 @@ class cisco_pix(uh.TruncateMixin, 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.6 - .. versionadded:: 1.7 + .. versionchanged:: 1.7.1 - .. versionadded:: 1.6 + Passwords > 16 bytes are now rejected / throw error instead of being silently truncated, + to match Cisco behavior. A number of :ref:`bugs <passlib-asa96-bug>` were fixed + which caused prior releases to generate unverifiable hashes in certain cases. """ #=================================================================== # class attrs @@ -61,7 +76,13 @@ class cisco_pix(uh.TruncateMixin, uh.HasUserContext, uh.StaticHandler): # PasswordHash #-------------------- name = "cisco_pix" - setting_kwds = ("truncate_error",) + + truncate_size = 16 + + # NOTE: these are the default policy for PasswordHash, + # but want to set them explicitly for now. + truncate_error = True + truncate_verify_reject = True #-------------------- # GenericHandler @@ -70,63 +91,155 @@ class cisco_pix(uh.TruncateMixin, uh.HasUserContext, uh.StaticHandler): checksum_chars = uh.HASH64_CHARS #-------------------- - # TruncateMixin - #-------------------- - truncate_size = 16 - - #-------------------- # custom #-------------------- - #: control flag signalling "cisco_asa" mode + #: control flag signalling "cisco_asa" mode, set by cisco_asa class _is_asa = False #=================================================================== # methods #=================================================================== def _calc_checksum(self, secret): - - # This function handles both the cisco_pix & cisco_asa formats: - # * PIX had a limit of 16 character passwords, and always appended the username. - # * ASA 7.0 (2005) increases this limit to 32, and conditionally appends the username. - # The two behaviors are controlled based on the _is_asa class-level flag. + """ + This function implements the "encrypted" hash format used by Cisco + PIX & ASA. It's behavior has been confirmed for ASA 9.6, + but is presumed correct for PIX & other ASA releases, + as it fits with known test vectors, and existing literature. + + While nearly the same, the PIX & ASA hashes have slight differences, + so this function performs differently based on the _is_asa class flag. + Noteable changes from PIX to ASA include password size limit + increased from 16 -> 32, and other internal changes. + """ + # select PIX vs or ASA mode asa = self._is_asa - # XXX: No idea what unicode policy is, but all examples are - # 7-bit ascii compatible, so using UTF-8. + # + # encode secret + # + # per ASA 8.4 documentation, + # http://www.cisco.com/c/en/us/td/docs/security/asa/asa84/configuration/guide/asa_84_cli_config/ref_cli.html#Supported_Character_Sets, + # it supposedly uses UTF-8 -- though some double-encoding issues have + # been observed when trying to actually *set* a non-ascii password + # via ASDM, and access via SSH seems to strip 8-bit chars. + # if isinstance(secret, unicode): 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. + # + # check if password too large + # + # Per ASA 9.6 changes listed in + # http://www.cisco.com/c/en/us/td/docs/security/asa/roadmap/asa_new_features.html, + # prior releases had a maximum limit of 32 characters. + # Testing with an ASA 9.6 system bears this out -- + # setting 32-char password for a user account, + # and logins will fail if any chars are appended. + # (ASA 9.6 added new PBKDF2-based hash algorithm, + # which supports larger passwords). + # + # Per PIX documentation + # http://www.cisco.com/en/US/docs/security/pix/pix50/configuration/guide/commands.html, + # it would not allow passwords > 16 chars. + # + # Thus, we unconditionally throw a password size error here, + # as nothing valid can come from a larger password. + # NOTE: assuming PIX has same behavior, but at 16 char limit. + # + spoil_digest = None + if len(secret) > self.truncate_size: + if self.use_defaults: + # called from hash() + msg = "Password too long (%s allows at most %d bytes)" % \ + (self.name, self.truncate_size) + raise uh.exc.PasswordSizeError(self.truncate_size, msg=msg) + else: + # called from verify() -- + # We don't want to throw error, or return early, + # as that would let attacker know too much. Instead, we set a + # flag to add some dummy data into the md5 digest, so that + # output won't match truncated version of secret, or anything + # else that's fixed and predictable. + spoil_digest = secret + _DUMMY_BYTES + + # + # append user to secret + # + # Policy appears to be: + # + # * Nothing appended for enable password (user = "") + # + # * ASA: If user present, but secret is >= 28 chars, nothing appended. + # + # * 1-2 byte users not allowed. + # DEVIATION: we're letting them through, and repeating their + # chars ala 3-char user, to simplify testing. + # Could issue warning in the future though. + # + # * 3 byte user has first char repeated, to pad to 4. + # (observed under ASA 9.6, assuming true elsewhere) + # + # * 4 byte users are used directly. + # + # * 5+ byte users are truncated to 4 bytes. + # user = self.user - if user and not (asa and seclen > 27): + if user: if isinstance(user, unicode): user = user.encode("utf-8") - secret += user[:4] - - # PIX: null-pad or truncate to 16 bytes. - # ASA: increase to 32 bytes if password is 13 or more characters. - if asa and seclen > 12: - padsize = 32 + if not asa or len(secret) < 28: + secret += repeat_string(user, 4) + + # + # pad / truncate result to limit + # + # While PIX always pads to 16 bytes, ASA increases to 32 bytes IFF + # secret+user > 16 bytes. This makes PIX & ASA have different results + # where secret size in range(13,16), and user is present -- + # PIX will truncate to 16, ASA will truncate to 32. + # + if asa and len(secret) > 16: + pad_size = 32 else: - padsize = 16 - secret = right_pad_string(secret, padsize) + pad_size = 16 + secret = right_pad_string(secret, pad_size) + # # md5 digest - hash = md5(secret).digest() + # + if spoil_digest: + # make sure digest won't match truncated version of secret + secret += spoil_digest + digest = md5(secret).digest() + # # drop every 4th byte - hash = join_byte_elems(c for i,c in enumerate(hash) if i & 3 < 3) + # NOTE: guessing this was done because it makes output exactly + # 16 bytes, which may have been a general 'char password[]' + # size limit under PIX + # + digest = join_byte_elems(c for i, c in enumerate(digest) if (i + 1) & 3) + # # encode using Hash64 - return h64.encode_bytes(hash).decode("ascii") + # + return h64.encode_bytes(digest).decode("ascii") + + # NOTE: works, but needs UTs. + # @classmethod + # def same_as_pix(cls, secret, user=""): + # """ + # test whether (secret + user) combination should + # have the same hash under PIX and ASA. + # + # mainly present to help unittests. + # """ + # # see _calc_checksum() above for details of this logic. + # size = len(to_bytes(secret, "utf-8")) + # if user and size < 28: + # size += 4 + # return size < 17 #=================================================================== # eoc @@ -140,12 +253,20 @@ class cisco_asa(cisco_pix): to the older :class:`cisco_pix` class. For passwords less than 13 characters, this should be identical to :class:`!cisco_pix`, - but will generate a different hash for anything larger + but will generate a different hash for most larger inputs (See the `Format & Algorithm`_ section for the details). - Unlike cisco_pix, this will truncate passwords larger than 32 bytes. + This class only allows passwords <= 32 bytes, anything larger + will result in a :exc:`~passlib.exc.PasswordSizeError` if passed to :meth:`~cisco_asa.hash`, + and be silently rejected if passed to :meth:`~cisco_asa.verify`. .. versionadded:: 1.7 + + .. versionchanged:: 1.7.1 + + Passwords > 32 bytes are now rejected / throw error instead of being silently truncated, + to match Cisco behavior. A number of :ref:`bugs <passlib-asa96-bug>` were fixed + which caused prior releases to generate unverifiable hashes in certain cases. """ #=================================================================== # class attrs @@ -174,7 +295,8 @@ class cisco_asa(cisco_pix): # type 7 #============================================================================= class cisco_type7(uh.GenericHandler): - """This class implements the Type 7 password encoding used by Cisco IOS, + """ + This class implements the "Type 7" password encoding used by Cisco IOS, and follows the :ref:`password-hash-api`. It has a simple 4-5 bit salt, but is nonetheless a reversible encoding instead of a real hash. diff --git a/passlib/ifc.py b/passlib/ifc.py index 7adf665..1a1aef2 100644 --- a/passlib/ifc.py +++ b/passlib/ifc.py @@ -58,10 +58,34 @@ 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. + #: Should be None, or a positive integer indicating hash + #: doesn't support secrets larger than this value. + #: Whether hash throws error or silently truncates secret + #: depends on .truncate_error and .truncate_verify_reject flags below. + #: NOTE: calls may treat as boolean, since value will never be 0. + #: .. versionadded:: 1.7 + #: .. TODO: passlib 1.8: deprecate/rename this attr to "max_secret_size"? truncate_size = None + # NOTE: these next two default to the optimistic "ideal", + # most hashes in passlib have to default to False + # for backward compat and/or expected behavior with existing hashes. + + #: If True, .hash() should throw a :exc:`~passlib.exc.PasswordSizeError` for + #: any secrets larger than .truncate_size. Many hashers default to False + #: for historical / compatibility purposes, indicating they will silently + #: truncate instead. All such hashers SHOULD support changing + #: the policy via ``.using(truncate_error=True)``. + #: .. versionadded:: 1.7 + #: .. TODO: passlib 1.8: deprecate/rename this attr to "truncate_hash_error"? + truncate_error = True + + #: If True, .verify() should reject secrets larger than max_password_size. + #: Many hashers default to False for historical / compatibility purposes, + #: indicating they will match on the truncated portion instead. + #: .. versionadded:: 1.7.1 + truncate_verify_reject = True + #--------------------------------------------------------------- # salt information -- if 'salt' in setting_kwds #--------------------------------------------------------------- diff --git a/passlib/tests/test_context.py b/passlib/tests/test_context.py index 7ad26cd..89fb9fe 100644 --- a/passlib/tests/test_context.py +++ b/passlib/tests/test_context.py @@ -1580,106 +1580,32 @@ sha512_crypt__min_rounds = 45000 #=================================================================== def test_harden_verify_parsing(self): """harden_verify -- parsing""" + warnings.filterwarnings("ignore", ".*harden_verify.*", + category=DeprecationWarning) # valid values ctx = CryptContext(schemes=["sha256_crypt"]) self.assertEqual(ctx.harden_verify, None) self.assertEqual(ctx.using(harden_verify="").harden_verify, None) - self.assertEqual(ctx.using(harden_verify="true").harden_verify, True) - self.assertEqual(ctx.using(harden_verify="false").harden_verify, False) - - # invalid value - self.assertRaises(ValueError, ctx.using, harden_verify="foo") - - # forbid w/ category - self.assertRaises(ValueError, ctx.using, admin__context__harden_verify="true") - - def test_harden_verify_estimate(self): - """harden_verify -- min_verify_time estimation""" - # setup - handler = DelayHash.using() - ctx = CryptContext(schemes=[handler]) - maxtime = 0.25 - scale = 0.01 - accuracy = scale * 0.1 - secret = "secret" - hash = handler.hash(secret) - - # establish baseline w/ 0 delay - elapsed, _ = time_call(partial(ctx.verify, secret, hash), maxtime=maxtime) - self.assertAlmostEqual(elapsed, 0, delta=accuracy) - - # run min_verify_time calc, see what it gets - ctx.reset_min_verify_time() - self.assertAlmostEqual(ctx.min_verify_time, 0, delta=accuracy) - - # add delay, make sure verify sees it - handler.delay = scale - elapsed, _ = time_call(partial(ctx.verify, secret, hash), maxtime=maxtime) - self.assertAlmostEqual(elapsed, scale, delta=accuracy) - - # re-run min_verify_time calc, see what it gets - ctx.reset_min_verify_time() - self.assertAlmostEqual(ctx.min_verify_time, scale, delta=accuracy) - - # TODO: * check that min_verify_time honors thread lock - # * check that min_verify_time correctly uses median - # * check that mvt_* config settings are honored + self.assertEqual(ctx.using(harden_verify="true").harden_verify, None) + self.assertEqual(ctx.using(harden_verify="false").harden_verify, None) def test_dummy_verify(self): - """harden_verify -- min_verify_time honored by dummy_verify() methods""" - # setup + """ + dummy_verify() method + """ + # check dummy_verify() takes expected time + expected = 0.05 + accuracy = 0.2 handler = DelayHash.using() - maxtime = 0.25 - scale = 0.01 - accuracy = scale * 0.1 - - ctx = CryptContext(schemes=[handler], harden_verify=False) - ctx.min_verify_time = scale - - # check dummy_verify() honors mvt even if hardening is off - elapsed, _ = time_call(partial(ctx.dummy_verify), maxtime=maxtime) - self.assertAlmostEqual(elapsed, scale, delta=accuracy) - - # check dummy_verify() honors elapsed kwd - elapsed, _ = time_call(partial(ctx.dummy_verify, elapsed=scale/2), maxtime=maxtime) - self.assertAlmostEqual(elapsed, scale/2, delta=accuracy) + handler.delay = expected + ctx = CryptContext(schemes=[handler]) + ctx.dummy_verify() # prime the memoized helpers + elapsed, _ = time_call(ctx.dummy_verify) + self.assertAlmostEqual(elapsed, expected, delta=expected * accuracy) - def test_harden_verify_w_verify(self, verify_and_update=False): - """harden_verify -- min_verify_time honored by verify()""" - # setup - handler = DelayHash.using() - maxtime = 0.25 - scale = 0.01 - accuracy = scale * 0.1 - secret = "secret" - other = "other" - hash = handler.hash(secret) - - def time_verify(pwd): - if verify_and_update: - func = partial(ctx.verify_and_update, pwd, hash) - else: - func = partial(ctx.verify, pwd, hash) - elapsed, _ = time_call(func, maxtime=maxtime) - return elapsed - - # w/o harden_verify, verify() should ignore min_verify_time even if failed - ctx = CryptContext(schemes=[handler], harden_verify=False) - ctx.min_verify_time = scale - self.assertAlmostEqual(time_verify(other), 0, delta=accuracy) - - # w/ harden_verify, verify() should ignore min_verify_time if successful - ctx.update(harden_verify=True) - ctx.min_verify_time = scale - self.assertAlmostEqual(time_verify(secret), 0, delta=accuracy) - - # w/ harden_verify, verify() should honor min_verify_time if failed - self.assertAlmostEqual(time_verify(other), scale, delta=accuracy) - - def test_harden_verify_w_verify_and_update(self): - """harden_verify -- min_verify_time honored by verify_and_update()""" - self.test_harden_verify_w_verify(verify_and_update=True) + # TODO: test dummy_verify() invoked by .verify() when hash is None, + # and same for .verify_and_update() #=================================================================== # feature tests diff --git a/passlib/tests/test_crypto_scrypt.py b/passlib/tests/test_crypto_scrypt.py index 06b8b29..9666667 100644 --- a/passlib/tests/test_crypto_scrypt.py +++ b/passlib/tests/test_crypto_scrypt.py @@ -8,6 +8,7 @@ import hashlib import logging; log = logging.getLogger(__name__) import struct import warnings +warnings.filterwarnings("ignore", ".*using builtin scrypt backend.*") # site # pkg from passlib import exc @@ -392,7 +393,7 @@ class _CommonScryptTest(TestCase): # get available backends orig = scrypt_mod.backend available = set(name for name in scrypt_mod.backend_values - if scrypt_mod._load_backend(name)) + if scrypt_mod._has_backend(name)) scrypt_mod._set_backend(orig) available.discard(self.backend) if not available: diff --git a/passlib/tests/test_ext_django_source.py b/passlib/tests/test_ext_django_source.py index b86e9ee..4b42e59 100644 --- a/passlib/tests/test_ext_django_source.py +++ b/passlib/tests/test_ext_django_source.py @@ -226,9 +226,8 @@ if test_hashers_mod: # that anyways? get_hashers_by_algorithm() should throw KeyError, right? test_pbkdf2_upgrade_new_hasher = _OMIT - # TODO: need to support wrapping django's harden-runtime feature w/ our own. - # still won't be able to pass their tests, because what they test for - # isn't how CryptContext.harden_verify works. + # TODO: support wrapping django's harden-runtime feature? + # would help pass their tests. test_check_password_calls_harden_runtime = _OMIT test_bcrypt_harden_runtime = _OMIT test_pbkdf2_harden_runtime = _OMIT diff --git a/passlib/tests/test_handlers.py b/passlib/tests/test_handlers.py index 72330be..c90ebc3 100644 --- a/passlib/tests/test_handlers.py +++ b/passlib/tests/test_handlers.py @@ -31,6 +31,17 @@ PASS_TABLE_UTF8 = b't\xc3\xa1\xd0\x91\xe2\x84\x93\xc9\x99' # utf-8 # handlers which support multiple backends, but don't have multi-backend tests. _omitted_backend_tests = ["django_bcrypt", "django_bcrypt_sha256", "django_argon2"] +#: modules where get_handler_case() should search for test cases. +_handler_test_modules = [ + "test_handlers", + "test_handlers_argon2", + "test_handlers_bcrypt", + "test_handlers_cisco", + "test_handlers_django", + "test_handlers_pbkdf2", + "test_handlers_scrypt", +] + def get_handler_case(scheme): """return HandlerCase instance for scheme, used by other tests""" from passlib.registry import get_crypt_handler @@ -41,8 +52,7 @@ def get_handler_case(scheme): name = "%s_%s_test" % (scheme, backend) else: name = "%s_test" % scheme - for module in ("test_handlers", "test_handlers_argon2", "test_handlers_bcrypt", - "test_handlers_django", "test_handlers_pbkdf2", "test_handlers_scrypt"): + for module in _handler_test_modules: modname = "passlib.tests." + module __import__(modname) mod = sys.modules[modname] @@ -198,233 +208,6 @@ bsdi_crypt_os_crypt_test = _bsdi_crypt_test.create_backend_case("os_crypt") bsdi_crypt_builtin_test = _bsdi_crypt_test.create_backend_case("builtin") #============================================================================= -# cisco pix -#============================================================================= -class cisco_pix_test(UserHandlerMixin, HandlerCase): - handler = hash.cisco_pix - requires_user = False - - known_correct_hashes = [ - # - # http://www.perlmonks.org/index.pl?node_id=797623 - # - ("cisco", "2KFQnbNIdI.2KYOU"), - - # - # http://www.hsc.fr/ressources/breves/pix_crack.html.en - # - ("hsc", "YtT8/k6Np8F1yz2c"), - - # - # www.freerainbowtables.com/phpBB3/viewtopic.php?f=2&t=1441 - # - ("", "8Ry2YjIyt7RRXU24"), - (("cisco", "john"), "hN7LzeyYjw12FSIU"), - (("cisco", "jack"), "7DrfeZ7cyOj/PslD"), - - # - # http://comments.gmane.org/gmane.comp.security.openwall.john.user/2529 - # - (("ripper", "alex"), "h3mJrcH0901pqX/m"), - (("cisco", "cisco"), "3USUcOPFUiMCO4Jk"), - (("cisco", "cisco1"), "3USUcOPFUiMCO4Jk"), - (("CscFw-ITC!", "admcom"), "lZt7HSIXw3.QP7.R"), - ("cangetin", "TynyB./ftknE77QP"), - (("cangetin", "rramsey"), "jgBZqYtsWfGcUKDi"), - - # - # http://openwall.info/wiki/john/sample-hashes - # - (("phonehome", "rharris"), "zyIIMSYjiPm0L7a6"), - - # - # from JTR 1.7.9 - # - ("test1", "TRPEas6f/aa6JSPL"), - ("test2", "OMT6mXmAvGyzrCtp"), - ("test3", "gTC7RIy1XJzagmLm"), - ("test4", "oWC1WRwqlBlbpf/O"), - ("password", "NuLKvvWGg.x9HEKO"), - ("0123456789abcdef", ".7nfVBEIEu4KbF/1"), - - # - # custom - # - (("cisco1", "cisco1"), "jmINXNH6p1BxUppp"), - - # ensures utf-8 used for unicode - (UPASS_TABLE, 'CaiIvkLMu2TOHXGT'), - ] - -def _get_secret(value): - """extract secret from secret or (secret, user) tuple""" - if isinstance(value, tuple): - return value[0] - else: - return value - -class cisco_asa_test(UserHandlerMixin, HandlerCase): - handler = hash.cisco_asa - requires_user = False - - known_correct_hashes = [ - # format: ((secret, user), hash) - - # - # passlib test vectors - # TODO: these have not been confirmed by an outside source, - # nor tested against an official implementation. - # for now, these only confirm we haven't had a regression. - # - - # 8 char password -- should be same as pix - (('01234567', ''), '0T52THgnYdV1tlOF'), - (('01234567', '36'), 'oY0Dh6RVC9KFlopL'), - (('01234567', 'user'), 'PNZ4ycbbZ0jp1.j1'), - (('01234567', 'user1234'), 'PNZ4ycbbZ0jp1.j1'), - - # 12 char password -- should be same as pix - (('0123456789ab', ''), 'S31BxZOGlAigndcJ'), - (('0123456789ab', '36'), 'JqCXavOaaaTn9B5y'), - (('0123456789ab', 'user'), 'f.T4BKdzdNkjxQl7'), - (('0123456789ab', 'user1234'), 'f.T4BKdzdNkjxQl7'), - - # 13 char password -- ASA should switch to larger padding - (('0123456789abc', ''), 'XGUn8JhVAnJsaJ69'), # e.g: cisco_pix is 'eacOpB7vE7ZDukSF' - (('0123456789abc', '36'), 'feNbQYEDXynZXMJH'), - (('0123456789abc', 'user'), '8Q/FZeam5ai1A47p'), - (('0123456789abc', 'user1234'), '8Q/FZeam5ai1A47p'), - - # 16 char password -- verify fencepost - (('0123456789abcdef', ''), 'YO.dC.tE77bB35aH'), - (('0123456789abcdef', '36'), 'ekOxFx1Mqt8hL3vJ'), - (('0123456789abcdef', 'user'), 'IneB.wc9sfRzLPoh'), - (('0123456789abcdef', 'user1234'), 'IneB.wc9sfRzLPoh'), - - # 27 char password -- ASA should still append user - (('0123456789abcdefqwertyuiopa', ''), '4wp19zS3OCe.2jt5'), - (('0123456789abcdefqwertyuiopa', '36'), 'GlGggqfEc19br12c'), - (('0123456789abcdefqwertyuiopa', 'user'), 'zynfWw3UtszxLMgL'), - (('0123456789abcdefqwertyuiopa', 'user1234'), 'zynfWw3UtszxLMgL'), - - # 28 char password -- ASA shouldn't append user anymore - (('0123456789abcdefqwertyuiopas', ''), 'W6nbOddI0SutTK7m'), - (('0123456789abcdefqwertyuiopas', '36'), 'W6nbOddI0SutTK7m'), - (('0123456789abcdefqwertyuiopas', 'user'), 'W6nbOddI0SutTK7m'), - (('0123456789abcdefqwertyuiopas', 'user1234'), 'W6nbOddI0SutTK7m'), - - # 32 char password -- verify fencepost - (('0123456789abcdefqwertyuiopasdfgh', ''), '5hPT/iC6DnoBxo6a'), - (('0123456789abcdefqwertyuiopasdfgh', '36'), '5hPT/iC6DnoBxo6a'), - (('0123456789abcdefqwertyuiopasdfgh', 'user'), '5hPT/iC6DnoBxo6a'), - (('0123456789abcdefqwertyuiopasdfgh', 'user1234'), '5hPT/iC6DnoBxo6a'), - - # 33 char password -- ASA should truncate to 32 (should be same as above) - (('0123456789abcdefqwertyuiopasdfghj', ''), '5hPT/iC6DnoBxo6a'), - (('0123456789abcdefqwertyuiopasdfghj', '36'), '5hPT/iC6DnoBxo6a'), - (('0123456789abcdefqwertyuiopasdfghj', 'user'), '5hPT/iC6DnoBxo6a'), - (('0123456789abcdefqwertyuiopasdfghj', 'user1234'), '5hPT/iC6DnoBxo6a'), - - # unicode password -- assumes cisco will use utf-8 encoding - ((u('t\xe1ble'), ''), 'xQXX755BKYRl0ZpQ'), - ((u('t\xe1ble'), '36'), 'Q/43xXKmIaKLycSj'), - ((u('t\xe1ble'), 'user'), 'Og8fB4NyF0m5Ed9c'), - ((u('t\xe1ble'), 'user1234'), 'Og8fB4NyF0m5Ed9c'), - ] - - # append all the cisco_pix hashes w/ password < 13 chars ... those should be the same. - known_correct_hashes.extend(row for row in cisco_pix_test.known_correct_hashes - if len(_get_secret(row[0])) < 13) - -#============================================================================= -# cisco type 7 -#============================================================================= -class cisco_type7_test(HandlerCase): - handler = hash.cisco_type7 - salt_bits = 4 - salt_type = int - - known_correct_hashes = [ - # - # http://mccltd.net/blog/?p=1034 - # - ("secure ", "04480E051A33490E"), - - # - # http://insecure.org/sploits/cisco.passwords.html - # - ("Its time to go to lunch!", - "153B1F1F443E22292D73212D5300194315591954465A0D0B59"), - - # - # http://blog.ioshints.info/2007/11/type-7-decryption-in-cisco-ios.html - # - ("t35t:pa55w0rd", "08351F1B1D431516475E1B54382F"), - - # - # http://www.m00nie.com/2011/09/cisco-type-7-password-decryption-and-encryption-with-perl/ - # - ("hiImTesting:)", "020E0D7206320A325847071E5F5E"), - - # - # http://packetlife.net/forums/thread/54/ - # - ("cisco123", "060506324F41584B56"), - ("cisco123", "1511021F07257A767B"), - - # - # source ? - # - ('Supe&8ZUbeRp4SS', "06351A3149085123301517391C501918"), - - # - # custom - # - - # ensures utf-8 used for unicode - (UPASS_TABLE, '0958EDC8A9F495F6F8A5FD'), - ] - - known_unidentified_hashes = [ - # salt with hex value - "0A480E051A33490E", - - # salt value > 52. this may in fact be valid, but we reject it for now - # (see docs for more). - '99400E4812', - ] - - def test_90_decode(self): - """test cisco_type7.decode()""" - from passlib.utils import to_unicode, to_bytes - - handler = self.handler - for secret, hash in self.known_correct_hashes: - usecret = to_unicode(secret) - bsecret = to_bytes(secret) - self.assertEqual(handler.decode(hash), usecret) - self.assertEqual(handler.decode(hash, None), bsecret) - - self.assertRaises(UnicodeDecodeError, handler.decode, - '0958EDC8A9F495F6F8A5FD', 'ascii') - - def test_91_salt(self): - """test salt value border cases""" - handler = self.handler - self.assertRaises(TypeError, handler, salt=None) - handler(salt=None, use_defaults=True) - self.assertRaises(TypeError, handler, salt='abc') - self.assertRaises(ValueError, handler, salt=-10) - self.assertRaises(ValueError, handler, salt=100) - - self.assertRaises(TypeError, handler.using, salt='abc') - self.assertRaises(ValueError, handler.using, salt=-10) - self.assertRaises(ValueError, handler.using, salt=100) - with self.assertWarningList("salt/offset must be.*"): - subcls = handler.using(salt=100, relaxed=True) - self.assertEqual(subcls(use_defaults=True).salt, 52) - -#============================================================================= # crypt16 #============================================================================= class crypt16_test(HandlerCase): diff --git a/passlib/tests/test_handlers_cisco.py b/passlib/tests/test_handlers_cisco.py new file mode 100644 index 0000000..ea6594b --- /dev/null +++ b/passlib/tests/test_handlers_cisco.py @@ -0,0 +1,457 @@ +""" +passlib.tests.test_handlers_cisco - tests for Cisco-specific algorithms +""" +#============================================================================= +# imports +#============================================================================= +from __future__ import absolute_import, division, print_function +# core +import logging +log = logging.getLogger(__name__) +# site +# pkg +from passlib import hash, exc +from passlib.utils.compat import u +from .utils import UserHandlerMixin, HandlerCase, repeat_string +from .test_handlers import UPASS_TABLE +# module +__all__ = [ + "cisco_pix_test", + "cisco_asa_test", + "cisco_type7_test", +] +#============================================================================= +# shared code for cisco PIX & ASA +#============================================================================= + +class _PixAsaSharedTest(UserHandlerMixin, HandlerCase): + """ + class w/ shared info for PIX & ASA tests. + """ + __unittest_skip = True # for TestCase + requires_user = False # for UserHandlerMixin + + #: shared list of hashes which should be identical under pix & asa7 + #: (i.e. combined secret + user < 17 bytes) + pix_asa_shared_hashes = [ + # + # http://www.perlmonks.org/index.pl?node_id=797623 + # + (("cisco", ""), "2KFQnbNIdI.2KYOU"), # confirmed ASA 9.6 + + # + # http://www.hsc.fr/ressources/breves/pix_crack.html.en + # + (("hsc", ""), "YtT8/k6Np8F1yz2c"), # confirmed ASA 9.6 + + # + # www.freerainbowtables.com/phpBB3/viewtopic.php?f=2&t=1441 + # + (("", ""), "8Ry2YjIyt7RRXU24"), # confirmed ASA 9.6 + (("cisco", "john"), "hN7LzeyYjw12FSIU"), + (("cisco", "jack"), "7DrfeZ7cyOj/PslD"), + + # + # http://comments.gmane.org/gmane.comp.security.openwall.john.user/2529 + # + (("ripper", "alex"), "h3mJrcH0901pqX/m"), + (("cisco", "cisco"), "3USUcOPFUiMCO4Jk"), + (("cisco", "cisco1"), "3USUcOPFUiMCO4Jk"), + (("CscFw-ITC!", "admcom"), "lZt7HSIXw3.QP7.R"), + ("cangetin", "TynyB./ftknE77QP"), + (("cangetin", "rramsey"), "jgBZqYtsWfGcUKDi"), + + # + # http://openwall.info/wiki/john/sample-hashes + # + (("phonehome", "rharris"), "zyIIMSYjiPm0L7a6"), + + # + # http://www.openwall.com/lists/john-users/2010/08/08/3 + # + (("cangetin", ""), "TynyB./ftknE77QP"), + (("cangetin", "rramsey"), "jgBZqYtsWfGcUKDi"), + + # + # from JTR 1.7.9 + # + ("test1", "TRPEas6f/aa6JSPL"), + ("test2", "OMT6mXmAvGyzrCtp"), + ("test3", "gTC7RIy1XJzagmLm"), + ("test4", "oWC1WRwqlBlbpf/O"), + ("password", "NuLKvvWGg.x9HEKO"), + ("0123456789abcdef", ".7nfVBEIEu4KbF/1"), + + # + # http://www.cisco.com/en/US/docs/security/pix/pix50/configuration/guide/commands.html#wp5472 + # + (("1234567890123456", ""), "feCkwUGktTCAgIbD"), # canonical source + (("watag00s1am", ""), "jMorNbK0514fadBh"), # canonical source + + # + # custom + # + (("cisco1", "cisco1"), "jmINXNH6p1BxUppp"), + + # ensures utf-8 used for unicode + (UPASS_TABLE, 'CaiIvkLMu2TOHXGT'), + + # + # passlib reference vectors + # + # Some of these have been confirmed on various ASA firewalls, + # and the exact version is noted next to each hash. + # Would like to verify these under more PIX & ASA versions. + # + # Those without a note are generally an extrapolation, + # to ensure the code stays consistent, but for various reasons, + # hasn't been verified. + # + # * One such case is usernames w/ 1 & 2 digits -- + # ASA (9.6 at least) requires 3+ digits in username. + # + # The following hashes (below 13 chars) should be identical for PIX/ASA. + # Ones which differ are listed separately in the known_correct_hashes + # list for the two test classes. + # + + # 4 char password + (('1234', ''), 'RLPMUQ26KL4blgFN'), # confirmed ASA 9.6 + + # 8 char password + (('01234567', ''), '0T52THgnYdV1tlOF'), # confirmed ASA 9.6 + (('01234567', '3'), '.z0dT9Alkdc7EIGS'), + (('01234567', '36'), 'CC3Lam53t/mHhoE7'), + (('01234567', '365'), '8xPrWpNnBdD2DzdZ'), # confirmed ASA 9.6 + (('01234567', '3333'), '.z0dT9Alkdc7EIGS'), # confirmed ASA 9.6 + (('01234567', '3636'), 'CC3Lam53t/mHhoE7'), # confirmed ASA 9.6 + (('01234567', '3653'), '8xPrWpNnBdD2DzdZ'), # confirmed ASA 9.6 + (('01234567', 'adm'), 'dfWs2qiao6KD/P2L'), # confirmed ASA 9.6 + (('01234567', 'adma'), 'dfWs2qiao6KD/P2L'), # confirmed ASA 9.6 + (('01234567', 'admad'), 'dfWs2qiao6KD/P2L'), # confirmed ASA 9.6 + (('01234567', 'user'), 'PNZ4ycbbZ0jp1.j1'), # confirmed ASA 9.6 + (('01234567', 'user1234'), 'PNZ4ycbbZ0jp1.j1'), # confirmed ASA 9.6 + + # 12 char password + (('0123456789ab', ''), 'S31BxZOGlAigndcJ'), # confirmed ASA 9.6 + (('0123456789ab', '36'), 'wFqSX91X5.YaRKsi'), + (('0123456789ab', '365'), 'qjgo3kNgTVxExbno'), # confirmed ASA 9.6 + (('0123456789ab', '3333'), 'mcXPL/vIZcIxLUQs'), # confirmed ASA 9.6 + (('0123456789ab', '3636'), 'wFqSX91X5.YaRKsi'), # confirmed ASA 9.6 + (('0123456789ab', '3653'), 'qjgo3kNgTVxExbno'), # confirmed ASA 9.6 + (('0123456789ab', 'user'), 'f.T4BKdzdNkjxQl7'), # confirmed ASA 9.6 + (('0123456789ab', 'user1234'), 'f.T4BKdzdNkjxQl7'), # confirmed ASA 9.6 + + # NOTE: remaining reference vectors for 13+ char passwords + # are split up between cisco_pix & cisco_asa tests. + + # unicode passwords + # ASA supposedly uses utf-8 encoding, but entering non-ascii + # chars is error-prone, and while UTF-8 appears to be intended, + # observed behaviors include: + # * ssh cli stripping non-ascii chars entirely + # * ASDM web iface double-encoding utf-8 strings + ((u("t\xe1ble").encode("utf-8"), 'user'), 'Og8fB4NyF0m5Ed9c'), + ((u("t\xe1ble").encode("utf-8").decode("latin-1").encode("utf-8"), + 'user'), 'cMvFC2XVBmK/68yB'), # confirmed ASA 9.6 when typed into ASDM + ] + + def test_calc_digest_spoiler(self): + """ + _calc_checksum() -- spoil oversize passwords during verify + + for details, see 'spoil_digest' flag instead that function. + this helps cisco_pix/cisco_asa implement their policy of + ``.truncate_verify_reject=True``. + """ + def calc(secret, for_hash=False): + return self.handler(use_defaults=for_hash)._calc_checksum(secret) + + # short (non-truncated) password + short_secret = repeat_string("1234", self.handler.truncate_size) + short_hash = calc(short_secret) + + # longer password should have totally different hash, + # to prevent verify from matching (i.e. "spoiled"). + long_secret = short_secret + "X" + long_hash = calc(long_secret) + self.assertNotEqual(long_hash, short_hash) + + # spoiled hash should depend on whole secret, + # so that output isn't predictable + alt_long_secret = short_secret + "Y" + alt_long_hash = calc(alt_long_secret) + self.assertNotEqual(alt_long_hash, short_hash) + self.assertNotEqual(alt_long_hash, long_hash) + + # for hash(), should throw error if password too large + calc(short_secret, for_hash=True) + self.assertRaises(exc.PasswordSizeError, calc, long_secret, for_hash=True) + self.assertRaises(exc.PasswordSizeError, calc, alt_long_secret, for_hash=True) + +#============================================================================= +# cisco pix +#============================================================================= +class cisco_pix_test(_PixAsaSharedTest): + handler = hash.cisco_pix + + #: known correct pix hashes + known_correct_hashes = _PixAsaSharedTest.pix_asa_shared_hashes + [ + # + # passlib reference vectors (PIX-specific) + # + # NOTE: See 'pix_asa_shared_hashes' for general PIX+ASA vectors, + # and general notes about the 'passlib reference vectors' test set. + # + # All of the following are PIX-specific, as ASA starts + # to use a different padding size at 13 characters. + # + # TODO: these need confirming w/ an actual PIX system. + # + + # 13 char password + (('0123456789abc', ''), 'eacOpB7vE7ZDukSF'), + (('0123456789abc', '3'), 'ylJTd/qei66WZe3w'), + (('0123456789abc', '36'), 'hDx8QRlUhwd6bU8N'), + (('0123456789abc', '365'), 'vYOOtnkh1HXcMrM7'), + (('0123456789abc', '3333'), 'ylJTd/qei66WZe3w'), + (('0123456789abc', '3636'), 'hDx8QRlUhwd6bU8N'), + (('0123456789abc', '3653'), 'vYOOtnkh1HXcMrM7'), + (('0123456789abc', 'user'), 'f4/.SALxqDo59mfV'), + (('0123456789abc', 'user1234'), 'f4/.SALxqDo59mfV'), + + # 14 char password + (('0123456789abcd', ''), '6r8888iMxEoPdLp4'), + (('0123456789abcd', '3'), 'f5lvmqWYj9gJqkIH'), + (('0123456789abcd', '36'), 'OJJ1Khg5HeAYBH1c'), + (('0123456789abcd', '365'), 'OJJ1Khg5HeAYBH1c'), + (('0123456789abcd', '3333'), 'f5lvmqWYj9gJqkIH'), + (('0123456789abcd', '3636'), 'OJJ1Khg5HeAYBH1c'), + (('0123456789abcd', '3653'), 'OJJ1Khg5HeAYBH1c'), + (('0123456789abcd', 'adm'), 'DbPLCFIkHc2SiyDk'), + (('0123456789abcd', 'adma'), 'DbPLCFIkHc2SiyDk'), + (('0123456789abcd', 'user'), 'WfO2UiTapPkF/FSn'), + (('0123456789abcd', 'user1234'), 'WfO2UiTapPkF/FSn'), + + # 15 char password + (('0123456789abcde', ''), 'al1e0XFIugTYLai3'), + (('0123456789abcde', '3'), 'lYbwBu.f82OIApQB'), + (('0123456789abcde', '36'), 'lYbwBu.f82OIApQB'), + (('0123456789abcde', '365'), 'lYbwBu.f82OIApQB'), + (('0123456789abcde', '3333'), 'lYbwBu.f82OIApQB'), + (('0123456789abcde', '3636'), 'lYbwBu.f82OIApQB'), + (('0123456789abcde', '3653'), 'lYbwBu.f82OIApQB'), + (('0123456789abcde', 'adm'), 'KgKx1UQvdR/09i9u'), + (('0123456789abcde', 'adma'), 'KgKx1UQvdR/09i9u'), + (('0123456789abcde', 'user'), 'qLopkenJ4WBqxaZN'), + (('0123456789abcde', 'user1234'), 'qLopkenJ4WBqxaZN'), + + # 16 char password + (('0123456789abcdef', ''), '.7nfVBEIEu4KbF/1'), + (('0123456789abcdef', '36'), '.7nfVBEIEu4KbF/1'), + (('0123456789abcdef', '365'), '.7nfVBEIEu4KbF/1'), + (('0123456789abcdef', '3333'), '.7nfVBEIEu4KbF/1'), + (('0123456789abcdef', '3636'), '.7nfVBEIEu4KbF/1'), + (('0123456789abcdef', '3653'), '.7nfVBEIEu4KbF/1'), + (('0123456789abcdef', 'user'), '.7nfVBEIEu4KbF/1'), + (('0123456789abcdef', 'user1234'), '.7nfVBEIEu4KbF/1'), + ] + + +#============================================================================= +# cisco asa +#============================================================================= +class cisco_asa_test(_PixAsaSharedTest): + handler = hash.cisco_asa + + known_correct_hashes = _PixAsaSharedTest.pix_asa_shared_hashes + [ + # + # passlib reference vectors (ASA-specific) + # + # NOTE: See 'pix_asa_shared_hashes' for general PIX+ASA vectors, + # and general notes about the 'passlib reference vectors' test set. + # + + # 13 char password + # NOTE: past this point, ASA pads to 32 bytes instead of 16 + # for all cases where user is set (secret + 4 bytes > 16), + # but still uses 16 bytes for enable pwds (secret <= 16). + # hashes w/ user WON'T match PIX, but "enable" passwords will. + (('0123456789abc', ''), 'eacOpB7vE7ZDukSF'), # confirmed ASA 9.6 + (('0123456789abc', '36'), 'FRV9JG18UBEgX0.O'), + (('0123456789abc', '365'), 'NIwkusG9hmmMy6ZQ'), # confirmed ASA 9.6 + (('0123456789abc', '3333'), 'NmrkP98nT7RAeKZz'), # confirmed ASA 9.6 + (('0123456789abc', '3636'), 'FRV9JG18UBEgX0.O'), # confirmed ASA 9.6 + (('0123456789abc', '3653'), 'NIwkusG9hmmMy6ZQ'), # confirmed ASA 9.6 + (('0123456789abc', 'user'), '8Q/FZeam5ai1A47p'), # confirmed ASA 9.6 + (('0123456789abc', 'user1234'), '8Q/FZeam5ai1A47p'), # confirmed ASA 9.6 + + # 14 char password + (('0123456789abcd', ''), '6r8888iMxEoPdLp4'), # confirmed ASA 9.6 + (('0123456789abcd', '3'), 'yxGoujXKPduTVaYB'), + (('0123456789abcd', '36'), 'W0jckhnhjnr/DiT/'), + (('0123456789abcd', '365'), 'HuVOxfMQNahaoF8u'), # confirmed ASA 9.6 + (('0123456789abcd', '3333'), 'yxGoujXKPduTVaYB'), # confirmed ASA 9.6 + (('0123456789abcd', '3636'), 'W0jckhnhjnr/DiT/'), # confirmed ASA 9.6 + (('0123456789abcd', '3653'), 'HuVOxfMQNahaoF8u'), # confirmed ASA 9.6 + (('0123456789abcd', 'adm'), 'RtOmSeoCs4AUdZqZ'), # confirmed ASA 9.6 + (('0123456789abcd', 'adma'), 'RtOmSeoCs4AUdZqZ'), # confirmed ASA 9.6 + (('0123456789abcd', 'user'), 'rrucwrcM0h25pr.m'), # confirmed ASA 9.6 + (('0123456789abcd', 'user1234'), 'rrucwrcM0h25pr.m'), # confirmed ASA 9.6 + + # 15 char password + (('0123456789abcde', ''), 'al1e0XFIugTYLai3'), # confirmed ASA 9.6 + (('0123456789abcde', '3'), 'nAZrQoHaL.fgrIqt'), + (('0123456789abcde', '36'), '2GxIQ6ICE795587X'), + (('0123456789abcde', '365'), 'QmDsGwCRBbtGEKqM'), # confirmed ASA 9.6 + (('0123456789abcde', '3333'), 'nAZrQoHaL.fgrIqt'), # confirmed ASA 9.6 + (('0123456789abcde', '3636'), '2GxIQ6ICE795587X'), # confirmed ASA 9.6 + (('0123456789abcde', '3653'), 'QmDsGwCRBbtGEKqM'), # confirmed ASA 9.6 + (('0123456789abcde', 'adm'), 'Aj2aP0d.nk62wl4m'), # confirmed ASA 9.6 + (('0123456789abcde', 'adma'), 'Aj2aP0d.nk62wl4m'), # confirmed ASA 9.6 + (('0123456789abcde', 'user'), 'etxiXfo.bINJcXI7'), # confirmed ASA 9.6 + (('0123456789abcde', 'user1234'), 'etxiXfo.bINJcXI7'), # confirmed ASA 9.6 + + # 16 char password + (('0123456789abcdef', ''), '.7nfVBEIEu4KbF/1'), # confirmed ASA 9.6 + (('0123456789abcdef', '36'), 'GhI8.yFSC5lwoafg'), + (('0123456789abcdef', '365'), 'KFBI6cNQauyY6h/G'), # confirmed ASA 9.6 + (('0123456789abcdef', '3333'), 'Ghdi1IlsswgYzzMH'), # confirmed ASA 9.6 + (('0123456789abcdef', '3636'), 'GhI8.yFSC5lwoafg'), # confirmed ASA 9.6 + (('0123456789abcdef', '3653'), 'KFBI6cNQauyY6h/G'), # confirmed ASA 9.6 + (('0123456789abcdef', 'user'), 'IneB.wc9sfRzLPoh'), # confirmed ASA 9.6 + (('0123456789abcdef', 'user1234'), 'IneB.wc9sfRzLPoh'), # confirmed ASA 9.6 + + # 17 char password + # NOTE: past this point, ASA pads to 32 bytes instead of 16 + # for ALL cases, since secret > 16 bytes even for enable pwds; + # and so none of these rest here should match PIX. + (('0123456789abcdefq', ''), 'bKshl.EN.X3CVFRQ'), # confirmed ASA 9.6 + (('0123456789abcdefq', '36'), 'JAeTXHs0n30svlaG'), + (('0123456789abcdefq', '365'), '4fKSSUBHT1ChGqHp'), # confirmed ASA 9.6 + (('0123456789abcdefq', '3333'), 'USEJbxI6.VY4ecBP'), # confirmed ASA 9.6 + (('0123456789abcdefq', '3636'), 'JAeTXHs0n30svlaG'), # confirmed ASA 9.6 + (('0123456789abcdefq', '3653'), '4fKSSUBHT1ChGqHp'), # confirmed ASA 9.6 + (('0123456789abcdefq', 'user'), '/dwqyD7nGdwSrDwk'), # confirmed ASA 9.6 + (('0123456789abcdefq', 'user1234'), '/dwqyD7nGdwSrDwk'), # confirmed ASA 9.6 + + # 27 char password + (('0123456789abcdefqwertyuiopa', ''), '4wp19zS3OCe.2jt5'), # confirmed ASA 9.6 + (('0123456789abcdefqwertyuiopa', '36'), 'PjUoGqWBKPyV9qOe'), + (('0123456789abcdefqwertyuiopa', '365'), 'bfCy6xFAe5O/gzvM'), # confirmed ASA 9.6 + (('0123456789abcdefqwertyuiopa', '3333'), 'rd/ZMuGTJFIb2BNG'), # confirmed ASA 9.6 + (('0123456789abcdefqwertyuiopa', '3636'), 'PjUoGqWBKPyV9qOe'), # confirmed ASA 9.6 + (('0123456789abcdefqwertyuiopa', '3653'), 'bfCy6xFAe5O/gzvM'), # confirmed ASA 9.6 + (('0123456789abcdefqwertyuiopa', 'user'), 'zynfWw3UtszxLMgL'), # confirmed ASA 9.6 + (('0123456789abcdefqwertyuiopa', 'user1234'), 'zynfWw3UtszxLMgL'), # confirmed ASA 9.6 + + # 28 char password + # NOTE: past this point, ASA stops appending the username AT ALL, + # even though there's still room for the first few chars. + (('0123456789abcdefqwertyuiopas', ''), 'W6nbOddI0SutTK7m'), # confirmed ASA 9.6 + (('0123456789abcdefqwertyuiopas', '36'), 'W6nbOddI0SutTK7m'), + (('0123456789abcdefqwertyuiopas', '365'), 'W6nbOddI0SutTK7m'), # confirmed ASA 9.6 + (('0123456789abcdefqwertyuiopas', 'user'), 'W6nbOddI0SutTK7m'), # confirmed ASA 9.6 + (('0123456789abcdefqwertyuiopas', 'user1234'), 'W6nbOddI0SutTK7m'), # confirmed ASA 9.6 + + # 32 char password + # NOTE: this is max size that ASA allows, and throws error for larger + (('0123456789abcdefqwertyuiopasdfgh', ''), '5hPT/iC6DnoBxo6a'), # confirmed ASA 9.6 + (('0123456789abcdefqwertyuiopasdfgh', '36'), '5hPT/iC6DnoBxo6a'), + (('0123456789abcdefqwertyuiopasdfgh', '365'), '5hPT/iC6DnoBxo6a'), # confirmed ASA 9.6 + (('0123456789abcdefqwertyuiopasdfgh', 'user'), '5hPT/iC6DnoBxo6a'), # confirmed ASA 9.6 + (('0123456789abcdefqwertyuiopasdfgh', 'user1234'), '5hPT/iC6DnoBxo6a'), # confirmed ASA 9.6 + ] + + +#============================================================================= +# cisco type 7 +#============================================================================= +class cisco_type7_test(HandlerCase): + handler = hash.cisco_type7 + salt_bits = 4 + salt_type = int + + known_correct_hashes = [ + # + # http://mccltd.net/blog/?p=1034 + # + ("secure ", "04480E051A33490E"), + + # + # http://insecure.org/sploits/cisco.passwords.html + # + ("Its time to go to lunch!", + "153B1F1F443E22292D73212D5300194315591954465A0D0B59"), + + # + # http://blog.ioshints.info/2007/11/type-7-decryption-in-cisco-ios.html + # + ("t35t:pa55w0rd", "08351F1B1D431516475E1B54382F"), + + # + # http://www.m00nie.com/2011/09/cisco-type-7-password-decryption-and-encryption-with-perl/ + # + ("hiImTesting:)", "020E0D7206320A325847071E5F5E"), + + # + # http://packetlife.net/forums/thread/54/ + # + ("cisco123", "060506324F41584B56"), + ("cisco123", "1511021F07257A767B"), + + # + # source ? + # + ('Supe&8ZUbeRp4SS', "06351A3149085123301517391C501918"), + + # + # custom + # + + # ensures utf-8 used for unicode + (UPASS_TABLE, '0958EDC8A9F495F6F8A5FD'), + ] + + known_unidentified_hashes = [ + # salt with hex value + "0A480E051A33490E", + + # salt value > 52. this may in fact be valid, but we reject it for now + # (see docs for more). + '99400E4812', + ] + + def test_90_decode(self): + """test cisco_type7.decode()""" + from passlib.utils import to_unicode, to_bytes + + handler = self.handler + for secret, hash in self.known_correct_hashes: + usecret = to_unicode(secret) + bsecret = to_bytes(secret) + self.assertEqual(handler.decode(hash), usecret) + self.assertEqual(handler.decode(hash, None), bsecret) + + self.assertRaises(UnicodeDecodeError, handler.decode, + '0958EDC8A9F495F6F8A5FD', 'ascii') + + def test_91_salt(self): + """test salt value border cases""" + handler = self.handler + self.assertRaises(TypeError, handler, salt=None) + handler(salt=None, use_defaults=True) + self.assertRaises(TypeError, handler, salt='abc') + self.assertRaises(ValueError, handler, salt=-10) + self.assertRaises(ValueError, handler, salt=100) + + self.assertRaises(TypeError, handler.using, salt='abc') + self.assertRaises(ValueError, handler.using, salt=-10) + self.assertRaises(ValueError, handler.using, salt=100) + with self.assertWarningList("salt/offset must be.*"): + subcls = handler.using(salt=100, relaxed=True) + self.assertEqual(subcls(use_defaults=True).salt, 52) + +#============================================================================= +# eof +#============================================================================= diff --git a/passlib/tests/test_handlers_scrypt.py b/passlib/tests/test_handlers_scrypt.py index d7f1c83..bbd3cd7 100644 --- a/passlib/tests/test_handlers_scrypt.py +++ b/passlib/tests/test_handlers_scrypt.py @@ -5,6 +5,7 @@ # core import logging; log = logging.getLogger(__name__) import warnings +warnings.filterwarnings("ignore", ".*using builtin scrypt backend.*") # site # pkg from passlib import hash @@ -84,9 +85,9 @@ class _scrypt_test(HandlerCase): '$scrypt$ln=10,r=134217728,p=8$wvif8/4fg1Cq9V7L2dv73w$bJcLia1lyfQ1X2x0xflehwVXPzWIUQWWdnlGwfVzBeQ', ] - def setUp(self): - super(_scrypt_test, self).setUp() - warnings.filterwarnings("ignore", "Using builtin scrypt backend.*") + def setUpWarnings(self): + super(_scrypt_test, self).setUpWarnings() + warnings.filterwarnings("ignore", ".*using builtin scrypt backend.*") def populate_settings(self, kwds): # builtin is still just way too slow. diff --git a/passlib/tests/test_totp.py b/passlib/tests/test_totp.py index 54a9d91..1229da7 100644 --- a/passlib/tests/test_totp.py +++ b/passlib/tests/test_totp.py @@ -76,19 +76,28 @@ def _get_max_time_t(): # * int out of range for host's time_t: # py2 throws ValueError, py3 throws OverflowError. # - return value-1 + break # Workaround for python 3.6.0 issue -- # Instead of throwing ValueError if year out of range for datetime, # Python 3.6 will do some weird behavior that masks high bits # e.g. (1<<40) -> year 36812, but (1<<41) -> year 6118. - # (Filed as bug -- http://bugs.python.org/issue29346) + # (Appears to be bug http://bugs.python.org/issue29100) # This check stops at largest non-wrapping bit size. if next_year < year: - return value-1 + break value = next_value + # 'value-1' is maximum. + value -= 1 + + # check for crazy case where we're beyond what datetime supports + # (caused by bug 29100 again). compare to max value that datetime + # module supports -- datetime.datetime(9999, 12, 31, 23, 59, 59, 999999) + max_datetime_timestamp = 253402318800 + return min(value, max_datetime_timestamp) + #: Rough approximation of max value acceptable by hosts's time_t. #: This is frequently ~2**37 on 64 bit, and ~2**31 on 32 bit systems. max_time_t = _get_max_time_t() diff --git a/passlib/tests/utils.py b/passlib/tests/utils.py index e1b7b0e..1ac52fd 100644 --- a/passlib/tests/utils.py +++ b/passlib/tests/utils.py @@ -22,6 +22,7 @@ import warnings from warnings import warn # site # pkg +from passlib import exc from passlib.exc import MissingBackendError import passlib.registry as registry from passlib.tests.backports import TestCase as _TestCase, skip, skipIf, skipUnless, SkipTest @@ -1984,69 +1985,182 @@ class HandlerCase(TestCase): self.assertEqual(subcls.default_ident, ident, msg="alias %r:" % alias) #=================================================================== - # passwords + # password size limits #=================================================================== - def test_60_truncate_size(self): - """test password size limits""" - handler = self.handler + def test_truncate_error_setting(self): + """ + validate 'truncate_error' setting & related attributes + """ + # If it doesn't have truncate_size set, + # it shouldn't support truncate_error + hasher = self.handler + if hasher.truncate_size is None: + self.assertNotIn("truncate_error", hasher.setting_kwds) + return + + # if hasher defaults to silently truncating, + # it MUST NOT use .truncate_verify_reject, + # because resulting hashes wouldn't verify! + if not hasher.truncate_error: + self.assertFalse(hasher.truncate_verify_reject) - 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) + # if hasher doesn't have configurable policy, + # it must throw error by default + if "truncate_error" not in hasher.setting_kwds: + self.assertTrue(hasher.truncate_error) + return + # test value parsing + def parse_value(value): + return hasher.using(truncate_error=value).truncate_error + self.assertEqual(parse_value(None), hasher.truncate_error) + self.assertEqual(parse_value(True), True) + self.assertEqual(parse_value("true"), True) + self.assertEqual(parse_value(False), False) + self.assertEqual(parse_value("false"), False) + self.assertRaises(ValueError, parse_value, "xxx") + + def test_secret_wo_truncate_size(self): + """ + test no password size limits enforced (if truncate_size=None) + """ + # skip if hasher has a maximum password size + hasher = self.handler + if hasher.truncate_size is not None: + self.assertGreaterEqual(hasher.truncate_size, 1) + raise self.skipTest("truncate_size is set") + + # NOTE: this doesn't do an exhaustive search to verify algorithm + # doesn't have some cutoff point, it just tries + # 1024-character string, and alters the last char. + # as long as algorithm doesn't clip secret at point <1024, + # the new secret shouldn't verify. + + # hash a 1024-byte secret + secret = "too many secrets" * 16 + alt = "x" + hash = self.do_encrypt(secret) + + # check that verify doesn't silently reject secret + # (i.e. hasher mistakenly honors .truncate_verify_reject) + verify_success = not hasher.is_disabled + self.assertEqual(self.do_verify(secret, hash), verify_success, + msg="verify rejected correct secret") + + # alter last byte, should get different hash, which won't verify + alt_secret = secret[:-1] + alt + self.assertFalse(self.do_verify(alt_secret, hash), + "full password not used in digest") + + def test_secret_w_truncate_size(self): + """ + test password size limits raise truncate_error (if appropriate) + """ + #-------------------------------------------------- + # check if test is applicable + #-------------------------------------------------- + handler = self.handler + truncate_size = handler.truncate_size + if not truncate_size: + raise self.skipTest("truncate_size not set") + + #-------------------------------------------------- + # setup vars + #-------------------------------------------------- + # try to get versions w/ and w/o truncate_error set. + # set to None if policy isn't configruable + size_error_type = exc.PasswordSizeError + if "truncate_error" in 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, handler=without_error) + size_error_type = exc.PasswordTruncateError + elif handler.truncate_error: + without_error = None + with_error = handler + else: + # NOTE: this mode is currently an error in test_truncate_error_setting() + without_error = handler + with_error = None + + # create some test secrets + base = "too many secrets" + alt = "x" # char that's not in base, used to mutate test secrets + long_secret = repeat_string(base, truncate_size+1) + short_secret = long_secret[:-1] + alt_long_secret = long_secret[:-1] + alt + alt_short_secret = short_secret[:-1] + alt + + # init flags + short_verify_success = not handler.is_disabled + long_verify_success = short_verify_success and \ + not handler.truncate_verify_reject + + #-------------------------------------------------- + # do tests on <truncate_size> length secret, and resulting hash. + # should pass regardless of truncate_error policy. + #-------------------------------------------------- + assert without_error or with_error + for cand_hasher in [without_error, with_error]: + + # create & hash string that's exactly <truncate_size> chars. + short_hash = self.do_encrypt(short_secret, handler=cand_hasher) + + # check hash verifies, regardless of .truncate_verify_reject + self.assertEqual(self.do_verify(short_secret, short_hash, + handler=cand_hasher), + short_verify_success) + + # changing <truncate_size-1>'th char should invalidate hash + # if this fails, means (reported) truncate_size is too large. + self.assertFalse(self.do_verify(alt_short_secret, short_hash, + handler=with_error), + "truncate_size value is too large") + + # verify should truncate long secret before comparing + # (unless truncate_verify_reject is set) + self.assertEqual(self.do_verify(long_secret, short_hash, + handler=cand_hasher), + long_verify_success) + + #-------------------------------------------------- + # do tests on <truncate_size+1> length secret, + # w/ truncate error disabled (should silently truncate) + #-------------------------------------------------- + if without_error: + + # create & hash string that's exactly truncate_size+1 chars + long_hash = self.do_encrypt(long_secret, handler=without_error) + + # check verifies against secret (unless truncate_verify_reject=True) + self.assertEqual(self.do_verify(long_secret, long_hash, + handler=without_error), + short_verify_success) + + # check mutating last char doesn't change outcome. + # if this fails, means (reported) truncate_size is too small. + self.assertEqual(self.do_verify(alt_long_secret, long_hash, + handler=without_error), + short_verify_success) + + # check short_secret verifies against this hash + # if this fails, means (reported) truncate_size is too large. + self.assertTrue(self.do_verify(short_secret, long_hash, + handler=without_error)) + + #-------------------------------------------------- + # do tests on <truncate_size+1> length secret, + # w/ truncate error + #-------------------------------------------------- + if with_error: # with errors enabled, should forbid truncation. - err = self.assertRaises(uh.exc.PasswordTruncateError, - self.do_encrypt, secret, handler=with_error) - self.assertEqual(err.max_size, sc) - - # 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, 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, 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 - # 1024-character string, and alters the last char. - # as long as algorithm doesn't clip secret at point <1024, - # the new secret shouldn't verify. - secret = base * 64 - hash = self.do_encrypt(secret) - secret2 = secret[:-1] + alt - self.assertFalse(self.do_verify(secret2, hash), - "full password not used in digest") + err = self.assertRaises(size_error_type, self.do_encrypt, + long_secret, handler=with_error) + self.assertEqual(err.max_size, truncate_size) + #=================================================================== + # password contents + #=================================================================== def test_61_secret_case_sensitive(self): """test password case sensitivity""" hash_insensitive = self.secret_case_insensitive is True @@ -2099,6 +2213,7 @@ class HandlerCase(TestCase): self.assertRaises(TypeError, self.do_genhash, 1, hash) self.assertRaises(TypeError, self.do_verify, 1, hash) + # xxx: move to password size limits section, above? def test_63_large_secret(self): """test MAX_PASSWORD_SIZE is enforced""" from passlib.exc import PasswordSizeError @@ -2729,12 +2844,29 @@ class HandlerCase(TestCase): rng = self.rng if rng.random() < .0001: return u('') - # otherwise alternate between large and small passwords. - if rng.random() < .5: - size = self.randintgauss(1, 50, 15, 15) + + # check if truncate size needs to be considered + handler = self.handler + truncate_size = handler.truncate_error and handler.truncate_size + max_size = truncate_size or 999999 + + # pick endpoint + if max_size < 50 or rng.random() < .5: + # chance of small password (~15 chars) + size = self.randintgauss(1, min(max_size, 50), 15, 15) else: - size = self.randintgauss(50, 99, 70, 20) - return getrandstr(rng, self.password_alphabet, size) + # otherwise large password (~70 chars) + size = self.randintgauss(50, min(max_size, 99), 70, 20) + + # generate random password + result = getrandstr(rng, self.password_alphabet, size) + + # trim ones that encode past truncate point. + if truncate_size and isinstance(result, unicode): + while len(result.encode("utf-8")) > truncate_size: + result = result[:-1] + + return result def accept_password_pair(self, secret, other): """verify fuzz pair contains different passwords""" diff --git a/passlib/utils/handlers.py b/passlib/utils/handlers.py index 76613bf..ef37061 100644 --- a/passlib/utils/handlers.py +++ b/passlib/utils/handlers.py @@ -405,12 +405,19 @@ 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. + + .. warning:: + + Hashers using this mixin will generally need to override + the default PasswordHash.truncate_error policy of "True", + and will similarly want to override .truncate_verify_reject as well. + + TODO: This should be done explicitly, but for now this mixin sets + these flags implicitly. """ - #: whether passwords large enough to be truncated - #: should cause a PasswordTruncateError to be raised, - #: instead of being silently truncated. truncate_error = False + truncate_verify_reject = False @classmethod def using(cls, truncate_error=None, **kwds): @@ -425,7 +432,8 @@ class TruncateMixin(MinimalHandler): def _check_truncate_policy(cls, secret): """ make sure secret won't be truncated. - NOTE: this should only be called for .hash(), not for .verify() + NOTE: this should only be called for .hash(), not for .verify(), + which should honor the .truncate_verify_reject policy. """ assert cls.truncate_size is not None, "truncate_size must be set by subclass" if cls.truncate_error and len(secret) > cls.truncate_size: @@ -2509,6 +2517,7 @@ class PrefixWrapper(object): "salt_chars", "default_salt_chars", "backends", "has_backend", "get_backend", "set_backend", "is_disabled", "truncate_size", "truncate_error", + "truncate_verify_reject", # internal info attrs needed for test inspection "_salt_is_bytes", @@ -2,9 +2,6 @@ # Passlib configuration for TOX #=========================================================================== # -# TODO: figure out best way to pass extra args to all nosetest calls. -# needed for jenkins to pass "--with-xunit --xunit-file=nosetests-{envname}.xml" -# #----------------------------------------------------------------------- # config options #----------------------------------------------------------------------- @@ -48,6 +45,7 @@ minversion=2.3 envlist = # default tests # TODO: would like to 'default-pyston' but doesnt quite work + # TODO: also add default-jython27 default-py{26,27,33,34,35,36,py,py3}, # pbkdf2 backend testing @@ -106,29 +104,38 @@ basepython = pypy3: pypy3 jython27: jython2.7 -setenv = - PASSLIB_TEST_MODE = full - bcrypthash-builtin: PASSLIB_BUILTIN_BCRYPT = enabled - bcrypthash-disabled: PASSLIB_TEST_MODE = quick + passenv = + PASSLIB_TEST_MODE PASSLIB_TESTS_DJANGO_SOURCE_PATH NOSE_REDNOSE NOSE_REDNOSE_COLOR + +setenv = + # test mode setup + PASSLIB_TEST_MODE = {env:PASSLIB_TEST_MODE:full} + bcrypthash-builtin: PASSLIB_BUILTIN_BCRYPT = enabled + bcrypthash-disabled: PASSLIB_TEST_MODE = quick + + # nose option fragments + with_coverage: TEST_COVER_OPTS = --with-xunit --with-coverage --cover-xml --cover-package passlib + TEST_OPTS = --hide-skips --randomize {env:TEST_COVER_OPTS:} + changedir = {envdir} commands = - # default test - default: nosetests {posargs:--hide-skips --randomize passlib.tests} + # default tests + default: nosetests {posargs:{env:TEST_OPTS} passlib.tests} # crypto backend tests - pbkdf2: nosetests {posargs:--hide-skips --randomize passlib.tests.test_crypto_digest passlib.tests.test_handlers_pbkdf2} + pbkdf2: nosetests {posargs:{env:TEST_OPTS} passlib.tests.test_crypto_digest passlib.tests.test_handlers_pbkdf2} # hash backend tests - bcrypthash: nosetests {posargs:--hide-skips --randomize passlib.tests.test_handlers_bcrypt} - scrypthash: nosetests {posargs:--hide-skips --randomize passlib.tests.test_crypto_scrypt passlib.tests.test_handlers_scrypt} - argon2hash: nosetests {posargs:--hide-skips --randomize passlib.tests.test_handlers_argon2} + bcrypthash: nosetests {posargs:{env:TEST_OPTS} passlib.tests.test_handlers_bcrypt} + scrypthash: nosetests {posargs:{env:TEST_OPTS} passlib.tests.test_crypto_scrypt passlib.tests.test_handlers_scrypt} + argon2hash: nosetests {posargs:{env:TEST_OPTS} passlib.tests.test_handlers_argon2} # django tests - django{,18}: nosetests --hide-skips {posargs:--randomize passlib.tests.test_ext_django passlib.tests.test_handlers_django} + django{,18}: nosetests {posargs:{env:TEST_OPTS} passlib.tests.test_ext_django passlib.tests.test_handlers_django} deps = # common @@ -136,8 +143,7 @@ deps = rednose coverage randomize - py{2,26,27},pypy,jython27: unittest2 - py{3,33,34,35,36},pypy3: unittest2py3k + unittest2 # totp helper tests # NOTE: cryptography requires python-dev, libffi-dev, libssl-dev @@ -191,6 +197,7 @@ deps = basepython = python2.7 deps = nose + rednose nosegae unittest2 changedir = {envdir}/lib/python2.7/site-packages |
