diff options
| author | Eli Collins <elic@assurancetechnologies.com> | 2016-11-20 14:11:35 -0500 |
|---|---|---|
| committer | Eli Collins <elic@assurancetechnologies.com> | 2016-11-20 14:11:35 -0500 |
| commit | a54c5ba533592f7113fd3a4a86bf8a036baa7860 (patch) | |
| tree | 1c36f1329efb86a637ff365c3e7a6a8819ed3cc5 /docs/lib | |
| parent | b214f86b7523f3adaf8bdcf78ffbddf351c0fb3d (diff) | |
| download | passlib-a54c5ba533592f7113fd3a4a86bf8a036baa7860.tar.gz | |
docs: LARGE update to documentation, tutorials added, pages relocated
* moved a bunch of pages into 'docs/narr' narrative subsection.
added placeholder pages in old locations, to minimize inbound link breakage.
* split history into separate pages, was getting way too long.
removed toplevel CHANGES file, not feasible under new structure.
* passlib.ifc split into reference & tutorial portions,
tutorial allowed subsuming a bunch of other hash-usage examples.
* added standard fragments for warning about insecure hashes,
added them to top of a LOT of hash doc pages.
* updated references, various layout tweaks
Diffstat (limited to 'docs/lib')
31 files changed, 839 insertions, 1468 deletions
diff --git a/docs/lib/index.rst b/docs/lib/index.rst new file mode 100644 index 0000000..14f6d7d --- /dev/null +++ b/docs/lib/index.rst @@ -0,0 +1,55 @@ +============= +API Reference +============= + +The reference section contains documentation of Passlib's public API. +These chapters are focused on providing detailed reference of the individual +functions and classes; they will generally be cross-linked to any related walkthrough +documentation (which tries to provide a higher-level synthetic view). + +.. rst-class:: float-right without-title + +.. note:: + + **Primary modules:** + + The primary modules that will be of interest are: + + * :mod:`passlib.hash` + * :mod:`passlib.context` + * :mod:`passlib.totp` + * :mod:`passlib.exc` + +.. rst-class:: float-right without-title clear-right + +.. caution:: + + **Internal modules:** + + The following modules are mainly used internally, + may change structure between releases, + and are documented mainly for completeness: + + * :mod:`passlib.crypto` + * :mod:`passlib.registry` + * :mod:`passlib.utils` + +**Alphabetical module list:** + +.. toctree:: + :titlesonly: + :maxdepth: 1 + + passlib.apache + passlib.apps + passlib.context + passlib.crypto + passlib.exc + passlib.ext.django + passlib.hash + passlib.hosts + passlib.ifc + passlib.pwd + passlib.registry + passlib.totp + passlib.utils diff --git a/docs/lib/passlib.apps.rst b/docs/lib/passlib.apps.rst index ca22050..e89b804 100644 --- a/docs/lib/passlib.apps.rst +++ b/docs/lib/passlib.apps.rst @@ -7,7 +7,7 @@ .. _predefined-context-example: -This module contains a number of preconfigured :ref:`CryptContext <context-overview>` instances +This module contains a number of preconfigured :ref:`CryptContext <context-reference>` instances that are provided by Passlib for easily handling the hash formats used by various applications. .. rst-class:: html-toggle @@ -252,4 +252,4 @@ Custom Applications .. seealso:: - The :doc:`/new_app_quickstart` for additional details. + The :doc:`/narr/quickstart` for additional details. diff --git a/docs/lib/passlib.context-tutorial.rst b/docs/lib/passlib.context-tutorial.rst deleted file mode 100644 index 9d0cdc3..0000000 --- a/docs/lib/passlib.context-tutorial.rst +++ /dev/null @@ -1,547 +0,0 @@ -.. index:: CryptContext; overview - -.. _context-overview: -.. _context-tutorial: - -.. currentmodule:: passlib.context - -============================================== -:mod:`passlib.context` - CryptContext Tutorial -============================================== - -Overview -======== -The :mod:`passlib.context` module contains one main class: :class:`!passlib.context.CryptContext`. -This class is designed to take care of many of the more frequent -coding patterns which occur in applications that need to handle multiple -password hashes at once: - - * identifying the algorithm used by a hash, and then verify a password. - * configure the default algorithm, load in support for new algorithms, - deprecate old ones, set defaults for time-cost parameters, etc. - * migrate hashes / re-hash passwords when an algorithm has been deprecated. - * load said configuration from a sysadmin configurable file. - -The following sections contain a walkthrough of this class, starting -with some simple examples, and working up to a complex "full-integration" example. - -.. seealso:: The :mod:`passlib.context` api reference, - which lists all the options and methods supported by this class. - -.. index:: CryptContext; usage examples - -.. rst-class:: emphasize-children - -Tutorial / Walkthrough -====================== -* `Basic Usage`_ -* `Using Default Settings`_ -* `Loading & Saving a CryptContext`_ -* `Deprecation & Hash Migration`_ -* `Full Integration Example`_ - -.. todo:: - This tutorial doesn't yet cover the :ref:`user-categories` system; - and a few other parts could use elaboration. - -.. _context-basic-example: - -Basic Usage ------------ -At its base, the :class:`!CryptContext` class is just a list of -:class:`~passlib.ifc.PasswordHash` objects, imported by name -from the :mod:`passlib.hash` module. The following snippet creates -a new context object which supports three hash algorithms -(:doc:`sha256_crypt <passlib.hash.sha256_crypt>`, -:doc:`md5_crypt <passlib.hash.md5_crypt>`, and -:doc:`des_crypt <passlib.hash.des_crypt>`):: - - >>> from passlib.context import CryptContext - >>> myctx = CryptContext(schemes=["sha256_crypt", "md5_crypt", "des_crypt"]) - -This new object exposes a very similar set of methods to the :class:`!PasswordHash` -interface, and hashing and verifying passwords is equally as straightforward:: - - >>> # this loads first algorithm in the schemes list (sha256_crypt), - >>> # generates a new salt, and hashes the password: - >>> hash1 = myctx.hash("joshua") - >>> hash1 - '$5$rounds=80000$HFEGd1wnFknpibRl$VZqjyYcTenv7CtOf986hxuE0pRaGXnuLXyfb7m9xL69' - - >>> # when verifying a password, the algorithm is identified automatically: - >>> myctx.verify("gtnw", hash1) - False - >>> myctx.verify("joshua", hash1) - True - - >>> # alternately, you can explicitly pick one of the configured algorithms, - >>> # through this is rarely needed in practice: - >>> hash2 = myctx.hash("dogsnamehere", scheme="md5_crypt") - >>> hash2 - '$1$e2nig/AC$stejMS1ek6W0/UogYKFao/' - - >>> myctx.verify("letmein", hash2) - False - >>> myctx.verify("dogsnamehere", hash2) - True - -If not told otherwise, the context object will use the first algorithm listed -in ``schemes`` when encrypting new hashes. This default can be changed by -using the ``default`` keyword:: - - >>> myctx = CryptContext(schemes=["sha256_crypt", "md5_crypt", "des_crypt"], - default="des_crypt") - >>> hash = myctx.hash("password") - >>> hash - 'bIwNofDzt1LCY' - - >>> myctx.identify(hash) - 'des_crypt' - -This concludes the basics of how to use a CryptContext object. -The rest of the sections detail the various features it offers, -which probably provide a better argument for *why* you'd want to use it. - -.. seealso:: - - * the :meth:`CryptContext.hash`, :meth:`~CryptContext.verify`, and :meth:`~CryptContext.identify` methods. - * the :ref:`schemes <context-schemes-option>` and :ref:`default <context-default-option>` constructor options. - -.. _context-default-settings-example: - -Using Default Settings ----------------------- -While encrypting and verifying hashes is useful enough, it's not much -more than could be done by importing the objects into a list. -The next feature of the :class:`!CryptContext` class is that it -can store various customized settings for the different algorithms, -instead of hardcoding them into each :meth:`!hash` call. -As an example, the :class:`sha256_crypt <passlib.hash.sha256_crypt>` -algorithm supports a ``rounds`` parameter which defaults to 80000, -and the :class:`ldap_salted_md5 <passlib.hash.ldap_salted_md5>` algorithm uses -8-byte salts by default:: - - >>> from passlib.context import CryptContext - >>> myctx = CryptContext(["sha256_crypt", "ldap_salted_md5"]) - - >>> # sha256_crypt using 80000 rounds... - >>> myctx.hash("password", scheme="sha256_crypt") - '$5$rounds=80000$GgU/gwNBs9SaObqs$ohY23/zm.8O0TpkGx5fxk0aeVdFpaeKo9GUkMJ0VrMC' - ^^^^^ - - >>> # ldap_salted_md5 with an 8 byte salt... - >>> myctx.hash("password", scheme="ldap_salted_md5") - '{SMD5}cIYrPh5f/TeUKg9oghECB5fSeu8=' - ^^^^^^^^^^ - -Instead of having to pass ``rounds=91234`` or ``salt_size=16`` every time -:meth:`encrypt` is called, CryptContext supports setting algorithm-specific -defaults which will be used every time a CryptContext method is invoked. -These is done by passing the CryptContext constructor a keyword with the format :samp:`{scheme}__{setting}`:: - - >>> # this reconfigures the existing context object so that - >>> # sha256_crypt now uses 91234 rounds, - >>> # and ldap_salted_md5 will use 16 byte salts: - >>> myctx.update(sha256_crypt__default_rounds=91234, - ... ldap_salted_md5__salt_size=16) - - >>> # the effect of this can be seen the next time encrypt is called: - >>> myctx.hash("password", scheme="sha256_crypt") - '$5$rounds=91234$GgU/gwNBs9SaObqs$ohY23/zm.8O0TpkGx5fxk0aeVdFpaeKo9GUkMJ0VrMC' - ^^^^^ - - >>> myctx.hash("password", scheme="ldap_salted_md5") - '{SMD5}NnQh2S2pjnFxwtMhjbVH59TaG6P0/l/r3RsDwPj/n/M=' - ^^^^^^^^^^^^^^^^^^^^^ - -.. seealso:: - - * the :meth:`CryptContext.update` method. - * the :ref:`default_rounds <context-default-rounds-option>` and - :ref:`per-scheme setting <context-other-option>` constructor options. - -.. _context-serialization-example: - -Loading & Saving a CryptContext -------------------------------- -The previous example built up a :class:`!CryptContext` instance -in two stages, first by calling the constructor, and then the :meth:`update` -method to make some additional changes. The same configuration -could of course be done in one step:: - - >>> from passlib.context import CryptContext - >>> myctx = CryptContext(schemes=["sha256_crypt", "ldap_salted_md5"], - ... sha256_crypt__default_rounds=91234, - ... ldap_salted_md5__salt_size=16) - -This is not much more useful, since these settings still have to be -hardcoded somewhere in the application. This is where the CryptContext's -serialization abilities come into play. As a starting point, -every CryptContext object can dump its configuration as a dictionary -suitable for passing back into its constructor:: - - >>> myctx.to_dict() - {'schemes': ['sha256_crypt', 'ldap_salted_md5'], - 'ldap_salted_md5__salt_size': 16, - 'sha256_crypt__default_rounds': 91234} - -However, this has been taken a step further, as CryptContext objects -can also dump their configuration into a `ConfigParser <http://docs.python.org/library/configparser.html>`_-compatible -string, allowing the configuration to be written to a file:: - - >>> cfg = print myctx.to_string() - >>> print cfg - [passlib] - schemes = sha256_crypt, ldap_salted_md5 - ldap_salted_md5__salt_size = 16 - sha256_crypt__default_rounds = 912345 - -This "INI" format consists of a section named ``"[passlib]"``, -following by key/value pairs which correspond exactly to the CryptContext -constructor keywords (Keywords which accepts lists of names (such as ``schemes``) -are automatically converted to/from a comma-separated string) -This format allows CryptContext configurations to be created -in a separate file (say as part of an application's larger config file), -and loaded into the CryptContext at runtime. Such strings can be -loaded directly when creating the context object:: - - >>> # using the special from_string() constructor to - >>> # load the exported configuration created in the previous step: - >>> myctx2 = CryptContext.from_string(cfg) - - >>> # or it can be loaded from a local file: - >>> myctx3 = CryptContext.from_path("/some/path/on/local/system") - -This allows applications to completely extract their password hashing -policies from the code, and into a configuration file with other security settings. - -.. note:: - - For CryptContext instances which already exist, - the :meth:`~CryptContext.load` and :meth:`~CryptContext.load_path` - methods can be used to replace the existing state. - -.. seealso:: - - * the :meth:`~CryptContext.to_dict` and :meth:`~CryptContext.to_string` methods. - * the :meth:`CryptContext.from_string` and :meth:`CryptContext.from_path` constructors. - -.. _context-migration-example: - -Deprecation & Hash Migration ----------------------------- -The final and possibly most useful feature of the :class:`CryptContext` class -is that it can take care of deprecating and migrating existing hashes, -re-hashing them using the current default algorithm and settings. -All that is required is that a few settings be added to the configuration, -and that the application call one extra method whenever a user logs in. - -Deprecating Algorithms -...................... -The first setting that enables the hash migration features is the ``deprecated`` -setting. This should be a list algorithms which are no longer desirable to have -around, but are included in ``schemes`` to provide legacy support. -For example:: - - >>> # this sets a context that supports 3 algorithms, but considers - >>> # two of them (md5_crypt and des_crypt) to be deprecated... - >>> from passlib.context import CryptContext - >>> myctx = CryptContext(schemes=["sha256_crypt", "md5_crypt", "des_crypt"], - deprecated=["md5_crypt", "des_crypt"]) - -All of the basic methods of this object will behave normally, but after -an application has verified the user entered the correct password, it can -check to see if the hash has been deprecated using the -:meth:`~CryptContext.needs_update` method:: - - >>> # assume the user's password was stored as a sha256_crypt hash, - >>> # needs_update will show that the hash is still allowed. - >>> hash = '$5$rounds=80000$zWZFpsA2egmQY8R9$xp89Vvg1HeDCJ/bTDDN6qkdsCwcMM61vHtM1RNxXur.' - >>> myctx.needs_update(hash) - False - - >>> # but if the user's password was stored as md5_crypt hash, - >>> # need_update will indicate that it is deprecated, - >>> # and that the original password needs to be re-hashed... - >>> hash = '$1$fmWm78VW$uWjT69xZNMHWyEQjq852d1' - >>> myctx.needs_update(hash) - True - -.. note:: - - Internally, this is not the only thing :meth:`!needs_update` does. - It also checks for other issues, such as rounds / salts which are - known to be weak under certain algorithms, improperly encoded hash - strings, and other configurable behaviors that are detailed later. - -Integrating Hash Migration -.......................... -To summarize the process described in the previous section, -all the actions an application would usually need to -perform can be combined into the following bit of skeleton code: - -.. code-block:: python - :linenos: - - hash = get_hash_from_user(user) - if pass_ctx.verify(password, hash): - if pass_ctx.needs_update(hash): - new_hash = pass_ctx.hash(password) - replace_user_hash(user, new_hash) - do_successful_things() - else: - reject_user_login() - -Since this is a very common pattern, the CryptContext object provides -a shortcut: the :meth:`~CryptContext.verify_and_update` method, -which allows replacing the above skeleton code with the following -that uses 2 fewer calls (and is much more efficient internally): - -.. code-block:: python - :linenos: - - hash = get_hash_from_user(user) - valid, new_hash = pass_ctx.verify_and_update(password, hash) - if valid: - if new_hash: - replace_user_hash(user, new_hash) - do_successful_things() - else: - reject_user_login() - -.. _context-min-rounds-example: - -Settings Rounds Limitations -........................... -In addition to deprecating entire algorithms, the deprecations system -also allows you to place limits on algorithms that support the -variable time-cost parameter ``rounds``: - -As an example, take a typical system containing a number of user passwords, -all stored using :class:`~passlib.hash.sha256_crypt`. -As computers get faster, the minimum number of rounds that should be used -gets larger, yet the existing passwords will remain in the system -hashed using their original value. To solve this, the CryptContext -object lets you place minimum bounds on what ``rounds`` -values are allowed, using the :samp:`{scheme}__min_rounds` set of keywords... -any hashes whose rounds are outside this limit are considered deprecated, -and in need of re-encoding using the current policy: - -First, we set up a context which requires all :class:`!sha256_crypt` hashes -to have at least 131072 rounds:: - - >>> from passlib.context import CryptContext - >>> myctx = CryptContext(schemes="sha256_crypt", - ... sha256_crypt__min_rounds=131072) - -New hashes generated by this context will always honor the minimum -(just as if ``default_rounds`` was set to the same value):: - - >>> # plain call to encrypt: - >>> hash1 = myctx.hash("password") - '$5$rounds=131072$i6xuFK6j8r66ahGn$r.7H8HUk30qiH7fIWRJFJfhWG925nRZh90aYPMdewr3' - ^^^^^^ - >>> # hashes with enough rounds won't show up as deprecated... - >>> myctx.needs_update(hash1) - False - -If an existing hash below the minimum is tested, it will show up as needing rehashing:: - - >>> # this has only 80000 rounds: - >>> hash3 = '$5$rounds=80000$qoCFY.akJr.flB7V$8cIZXLwSTzuCRLcJbgHlxqYKEK0cVCENy6nFIlROj05' - >>> myctx.needs_update(hash3) - True - - >>> # and verify_and_update() will upgrade this hash automatically: - >>> myctx.verify_and_update("wrong", hash3) - (False, None) - >>> myctx.verify_and_update("password", hash3) - (True, '$5$rounds=131072$rnMqBaemVZ6QGu7v$vrAVQLEbsBoxhgem8ynvAbToCae8vpzl6ZuDS3/adlA') - ^^^^^^ - -.. seealso:: - - * the :ref:`deprecated <context-deprecated-option>`, - :ref:`min_rounds <context-min-rounds-option>`, - and :ref:`max_rounds <context-max-rounds-option>` constructor options. - - * the :meth:`~CryptContext.needs_update` and :meth:`~CryptContext.verify_and_update` methods. - -.. rst-class:: html-toggle - -Full Integration Example -======================== -The following is an extended example showing how to fully interface -a CryptContext object into your application. The sample configuration -is somewhat more ornate that would usually be needed, just to highlight -some features, but should none-the-less be secure. - -Policy Configuration File -------------------------- -The first thing to do is setup a configuration string for the CryptContext to use. -This can be a dictionary or string defined in a python config file, -or (in this example), part of a large INI-formatted config file. -All of the documented :ref:`context-options` are allowed. - -.. code-block:: ini - - ; the options file uses the INI file format, - ; and passlib will only read the section named "passlib", - ; so it can be included along with other application configuration. - - [passlib] - - ; setup the context to support pbkdf2_sha256, and some other hashes: - schemes = pbkdf2_sha256, sha512_crypt, sha256_crypt, md5_crypt, des_crypt - - ; flag md5_crypt and des_crypt as deprecated - deprecated = md5_crypt, des_crypt - - ; set boundaries for the pbkdf2 rounds parameter - ; (pbkdf2 hashes outside this range will be flagged as needs-updating) - pbkdf2_sha256__min_rounds = 10000 - pbkdf2_sha256__max_rounds = 50000 - - ; set the default rounds to use when encrypting new passwords. - pbkdf2_sha1__default_rounds = 15000 - - ; applications can choose to treat certain user accounts differently, - ; by assigning different types of account to a 'user category', - ; and setting special policy options for that category. - ; this create a category named 'admin', which will have a larger default - ; rounds value. - 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 -to create the CryptContext at the module level, and then load -the configuration once the application starts: - -1. Within a common module in your application (e.g. ``myapp.model.security``):: - - # - # create a crypt context that can be imported and used wherever is needed... - # the instance will be configured later. - # - from passlib.context import CryptContext - user_pwd_context = CryptContext() - -2. Within some startup function within your application:: - - # - # when the app starts, import the context from step 1 and - # configure it... such as by loading a policy file (see above) - # - - from myapp.model.security import user_pwd_context - - def myapp_startup(): - - # - # ... other code ... - # - - # - # load configuration from some application-specified path - # using load_path() ... or use the load() method, which can - # load a dict or in-memory string containing the INI file. - # - ##user_pwd_context.load(policy_config_string) - user_pwd_context.load_path(policy_config_path) - - # - # if you want to reconfigure the context without restarting the application, - # simply repeat the above step at another point. - # - - # - # ... other code ... - # - -Encrypting New Passwords ------------------------- -When it comes time to create a new user's password, insert -the following code in the correct function:: - - from myapp.model.security import user_pwd_context - - def handle_user_creation(): - - # - # ... other code ... - # - - # vars: - # 'secret' containing the putative password - # 'category' containing a category assigned to the user account - # - - hash = user_pwd_context.hash(secret, category=category) - - #... perform appropriate actions to store hash... - - # - # ... other code ... - # - -.. note:: - - In the above code, the 'category' kwd can be omitted entirely, *OR* - set to a string matching a user category specified in the policy file. - In the latter case, any category-specific policy settings will be enforced. - - For the purposes of this example (and the sample config file listed above), - it's assumed this value will be ``None`` for most users, and ``"admin"`` for special users. - This namespace is entirely up to the application, it just has to match the - category names used in the config file. - - See :ref:`user-categories` for more details. - -Verifying & Migrating Existing Passwords ----------------------------------------- -Finally, when it comes time to check a users' password, insert -the following code at the correct place:: - - from myapp.model.security import user_pwd_context - - def handle_user_login(): - - # - # ... other code ... - # - - # - # this example both checks the user's password AND upgrades deprecated hashes... - # - # vars: - # 'hash' containing the specified user's hash. - # 'secret' containing the putative password - # 'category' containing a category assigned to the user account - # - # NOTE: if the user account is missing, or has no hash, - # you can pass ``hash=None`` to verify_and_update() - # mask this from the attacker by simulating the delay - # a real verification would have taken. - # hash=None will never verify. - - ok, new_hash = user_pwd_context.verify_and_update(secret, hash, category=category) - if not ok: - # ... password did not match. do mean things ... - pass - - else: - #... password matched ... - - if new_hash: - # old hash was deprecated by policy. - - # ... replace hash w/ new_hash for user account ... - pass - - # ... do successful login actions ... - diff --git a/docs/lib/passlib.context.rst b/docs/lib/passlib.context.rst index 262ef46..2c95a74 100644 --- a/docs/lib/passlib.context.rst +++ b/docs/lib/passlib.context.rst @@ -14,7 +14,7 @@ and helper utilities. .. seealso:: - * :ref:`CryptContext Overview & Tutorial <context-overview>` -- + * :ref:`context-tutorial` -- overview of this class and walkthrough of how to use it. .. rst-class:: emphasize-children toc-always-open diff --git a/docs/lib/passlib.crypto.digest.rst b/docs/lib/passlib.crypto.digest.rst index 942f11d..91e2a4d 100644 --- a/docs/lib/passlib.crypto.digest.rst +++ b/docs/lib/passlib.crypto.digest.rst @@ -16,7 +16,7 @@ Hash Functions .. autofunction:: norm_hash_name .. autofunction:: lookup_hash -.. autoclass:: HashInfo() +.. rst-class:: float-center .. note:: @@ -24,6 +24,8 @@ Hash Functions as well as offered through :func:`hashlib.new`. It will also fallback to passlib's builtin MD4 implementation if one is not natively available. +.. autoclass:: HashInfo() + .. HMAC Functions ============== diff --git a/docs/lib/passlib.exc.rst b/docs/lib/passlib.exc.rst index 4b36a2b..10647a3 100644 --- a/docs/lib/passlib.exc.rst +++ b/docs/lib/passlib.exc.rst @@ -21,6 +21,8 @@ Exceptions .. autoexception:: PasslibSecurityError +.. autoexception:: UnknownHashError + TOTP Exceptions --------------- .. autoexception:: TokenError diff --git a/docs/lib/passlib.ext.django.rst b/docs/lib/passlib.ext.django.rst index b05c0e7..8fd4e83 100644 --- a/docs/lib/passlib.ext.django.rst +++ b/docs/lib/passlib.ext.django.rst @@ -14,7 +14,7 @@ This module contains a `Django <http://www.djangoproject.com>`_ plugin which overrides all of Django's password hashing functions, replacing them -with wrappers around a Passlib :ref:`CryptContext <context-overview>` object +with wrappers around a Passlib :ref:`CryptContext <context-reference>` object whose configuration is controlled from Django's ``settings``. While this extension's utility is diminished with the advent of Django 1.4's *hashers* framework, this plugin still has a number diff --git a/docs/lib/passlib.hash.apr_md5_crypt.rst b/docs/lib/passlib.hash.apr_md5_crypt.rst index 6c8a489..4ce222c 100644 --- a/docs/lib/passlib.hash.apr_md5_crypt.rst +++ b/docs/lib/passlib.hash.apr_md5_crypt.rst @@ -4,10 +4,7 @@ :class:`passlib.hash.apr_md5_crypt` - Apache's MD5-Crypt variant ====================================================================== -.. warning:: - - As of 2012-6-7, the MD5-Crypt algorithm is "no longer considered safe" - by its author, who urges migration to newer hash algorithms. +.. include:: ../_fragments/insecure_hash_warning.rst .. currentmodule:: passlib.hash diff --git a/docs/lib/passlib.hash.bigcrypt.rst b/docs/lib/passlib.hash.bigcrypt.rst index a958aa5..fa9542b 100644 --- a/docs/lib/passlib.hash.bigcrypt.rst +++ b/docs/lib/passlib.hash.bigcrypt.rst @@ -2,9 +2,7 @@ :class:`passlib.hash.bigcrypt` - BigCrypt ======================================================================= -.. warning:: - - This algorithm is dangerously weak, and should not be used if at all possible. +.. include:: ../_fragments/trivial_hash_warning.rst .. currentmodule:: passlib.hash diff --git a/docs/lib/passlib.hash.bsdi_crypt.rst b/docs/lib/passlib.hash.bsdi_crypt.rst index 63d4b0e..137a7c6 100644 --- a/docs/lib/passlib.hash.bsdi_crypt.rst +++ b/docs/lib/passlib.hash.bsdi_crypt.rst @@ -2,11 +2,9 @@ :class:`passlib.hash.bsdi_crypt` - BSDi Crypt ================================================================================= -.. currentmodule:: passlib.hash - -.. note:: +.. include:: ../_fragments/insecure_hash_warning.rst - This algorithm is weak by modern standards, and should not be used in new applications. +.. currentmodule:: passlib.hash This algorithm was developed by BSDi for their BSD/OS distribution. It's based on :class:`~passlib.hash.des_crypt`, and contains a larger diff --git a/docs/lib/passlib.hash.cisco_asa.rst b/docs/lib/passlib.hash.cisco_asa.rst index eb0b643..3b9e757 100644 --- a/docs/lib/passlib.hash.cisco_asa.rst +++ b/docs/lib/passlib.hash.cisco_asa.rst @@ -4,11 +4,15 @@ :class:`passlib.hash.cisco_asa` - Cisco ASA hash ================================================================== +.. include:: ../_fragments/insecure_hash_warning.rst + .. currentmodule:: passlib.hash .. 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`, + .. seealso:: - 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. It's documented on the :doc:`cisco_pix page <passlib.hash.cisco_pix>`. + :doc:`cisco_pix <passlib.hash.cisco_pix>` documentation page. diff --git a/docs/lib/passlib.hash.cisco_pix.rst b/docs/lib/passlib.hash.cisco_pix.rst index ab11a5f..9ad9fdd 100644 --- a/docs/lib/passlib.hash.cisco_pix.rst +++ b/docs/lib/passlib.hash.cisco_pix.rst @@ -4,12 +4,9 @@ :class:`passlib.hash.cisco_pix` - Cisco PIX hash ================================================================== -.. versionadded:: 1.6 - -.. warning:: +.. include:: ../_fragments/insecure_hash_warning.rst - These hashes are not secure, and should not be used for any purposes - besides manipulating existing hashes. +.. versionadded:: 1.6 .. todo:: diff --git a/docs/lib/passlib.hash.cisco_type7.rst b/docs/lib/passlib.hash.cisco_type7.rst index a6efb16..6512582 100644 --- a/docs/lib/passlib.hash.cisco_type7.rst +++ b/docs/lib/passlib.hash.cisco_type7.rst @@ -4,13 +4,13 @@ :class:`passlib.hash.cisco_type7` - Cisco "Type 7" hash ================================================================== -.. versionadded:: 1.6 - -.. warning:: +.. danger:: This is not a hash, this is a reversible plaintext encoding. **This format can be trivially decoded**. +.. versionadded:: 1.6 + .. currentmodule:: passlib.hash This class implements the "Type 7" password encoding used Cisco IOS. diff --git a/docs/lib/passlib.hash.crypt16.rst b/docs/lib/passlib.hash.crypt16.rst index 101d9dd..187c320 100644 --- a/docs/lib/passlib.hash.crypt16.rst +++ b/docs/lib/passlib.hash.crypt16.rst @@ -2,9 +2,7 @@ :class:`passlib.hash.crypt16` - Crypt16 ======================================================================= -.. warning:: - - This algorithm is dangerously weak, and should not be used if at all possible. +.. include:: ../_fragments/trivial_hash_warning.rst .. currentmodule:: passlib.hash diff --git a/docs/lib/passlib.hash.des_crypt.rst b/docs/lib/passlib.hash.des_crypt.rst index 373259f..dfd61f5 100644 --- a/docs/lib/passlib.hash.des_crypt.rst +++ b/docs/lib/passlib.hash.des_crypt.rst @@ -2,10 +2,7 @@ :class:`passlib.hash.des_crypt` - DES Crypt ======================================================================= -.. warning:: - - This algorithm is extremely weak by modern standards, - and should not be used if possible. +.. include:: ../_fragments/trivial_hash_warning.rst .. currentmodule:: passlib.hash diff --git a/docs/lib/passlib.hash.hex_digests.rst b/docs/lib/passlib.hash.hex_digests.rst index 0f8efc0..8e66b87 100644 --- a/docs/lib/passlib.hash.hex_digests.rst +++ b/docs/lib/passlib.hash.hex_digests.rst @@ -2,7 +2,7 @@ :samp:`passlib.hash.hex_{digest}` - Generic Hexadecimal Digests =============================================================== -.. warning:: +.. danger:: Using a single round of any cryptographic hash (especially without a salt) is so insecure diff --git a/docs/lib/passlib.hash.lmhash.rst b/docs/lib/passlib.hash.lmhash.rst index 0a9e627..26a4164 100644 --- a/docs/lib/passlib.hash.lmhash.rst +++ b/docs/lib/passlib.hash.lmhash.rst @@ -4,13 +4,9 @@ :class:`passlib.hash.lmhash` - LanManager Hash ================================================================== -.. versionadded:: 1.6 - -.. warning:: +.. include:: ../_fragments/insecure_hash_warning.rst - This scheme has been deprecated since Windows NT, and is notoriously weak. - It should be used for compatibility with existing systems; - **do not use** in new code. +.. versionadded:: 1.6 .. currentmodule:: passlib.hash @@ -122,9 +118,13 @@ the handling of non-ASCII characters. MS Windows implementation. Thus if an application wishes to provide support for non-ASCII passwords, - it must decide which encoding to use. Passlib uses ``cp437`` as a - default, but this may need to be overridden via - ``lmhash.hash(secret, encoding="some-other-codec")``. + it must decide which encoding to use. + + Passlib uses ``cp437`` as it's default encoding for unicode strings. + However, if your database used a different encoding, you will need to either + first encode the passwords into bytes, or override the default encoding + via ``lmhash.hash(secret, encoding="some-other-codec")`` + All known encodings are ``us-ascii``-compatible, so for ASCII passwords, the default should be sufficient. diff --git a/docs/lib/passlib.hash.md5_crypt.rst b/docs/lib/passlib.hash.md5_crypt.rst index 528367e..3251f12 100644 --- a/docs/lib/passlib.hash.md5_crypt.rst +++ b/docs/lib/passlib.hash.md5_crypt.rst @@ -4,14 +4,8 @@ :class:`passlib.hash.md5_crypt` - MD5 Crypt ================================================================== -.. warning:: - - As of 2012-6-7, this algorithm is "no longer considered safe" - by its author [#phk]_, citing the increased - speed of the MD5 hash on modern hardware, and MD5-Crypt's - lack of a variable time-cost parameter. See Passlib's - :ref:`recommended hashes <recommended-hashes>` for a replacement. - +.. include:: ../_fragments/insecure_hash_warning.rst + .. currentmodule:: passlib.hash This algorithm was developed for FreeBSD in 1994 by Poul-Henning Kamp, diff --git a/docs/lib/passlib.hash.msdcc.rst b/docs/lib/passlib.hash.msdcc.rst index 6c72aff..acfd87f 100644 --- a/docs/lib/passlib.hash.msdcc.rst +++ b/docs/lib/passlib.hash.msdcc.rst @@ -7,12 +7,9 @@ :class:`passlib.hash.msdcc` - Windows' Domain Cached Credentials ====================================================================== -.. versionadded:: 1.6 - -.. warning:: +.. include:: ../_fragments/insecure_hash_warning.rst - This hash is not very secure, and should mainly be used to verify - existing cached credentials. +.. versionadded:: 1.6 .. currentmodule:: passlib.hash diff --git a/docs/lib/passlib.hash.mssql2000.rst b/docs/lib/passlib.hash.mssql2000.rst index 416bce6..481008c 100644 --- a/docs/lib/passlib.hash.mssql2000.rst +++ b/docs/lib/passlib.hash.mssql2000.rst @@ -2,12 +2,9 @@ :class:`passlib.hash.mssql2000` - MS SQL 2000 password hash ================================================================== -.. versionadded:: 1.6 - -.. warning:: +.. include:: ../_fragments/insecure_hash_warning.rst - This hash is not very secure, and should not be used for any purposes - besides manipulating existing MSSQL 2000 password hashes. +.. versionadded:: 1.6 .. currentmodule:: passlib.hash diff --git a/docs/lib/passlib.hash.mssql2005.rst b/docs/lib/passlib.hash.mssql2005.rst index 3b997da..bb6b0ec 100644 --- a/docs/lib/passlib.hash.mssql2005.rst +++ b/docs/lib/passlib.hash.mssql2005.rst @@ -2,12 +2,9 @@ :class:`passlib.hash.mssql2005` - MS SQL 2005 password hash ================================================================== -.. versionadded:: 1.6 - -.. warning:: +.. include:: ../_fragments/insecure_hash_warning.rst - This hash is not very secure, and should not be used for any purposes - besides manipulating existing MSSQL 2005 password hashes. +.. versionadded:: 1.6 .. currentmodule:: passlib.hash diff --git a/docs/lib/passlib.hash.mysql323.rst b/docs/lib/passlib.hash.mysql323.rst index 207602b..eab3e3e 100644 --- a/docs/lib/passlib.hash.mysql323.rst +++ b/docs/lib/passlib.hash.mysql323.rst @@ -4,13 +4,9 @@ :class:`passlib.hash.mysql323` - MySQL 3.2.3 password hash ======================================================================== -.. currentmodule:: passlib.hash - -.. warning:: +.. include:: ../_fragments/insecure_hash_warning.rst - This algorithm is extremely weak, and should not be used - for any purposes besides manipulating existing Mysql 3.2.3-4.0 - password hashes. +.. currentmodule:: passlib.hash This class implements the first of MySQL's password hash functions, used to store its user account passwords. Introduced in MySQL 3.2.3 diff --git a/docs/lib/passlib.hash.mysql41.rst b/docs/lib/passlib.hash.mysql41.rst index b38d481..716181f 100644 --- a/docs/lib/passlib.hash.mysql41.rst +++ b/docs/lib/passlib.hash.mysql41.rst @@ -4,13 +4,9 @@ :class:`passlib.hash.mysql41` - MySQL 4.1 password hash ===================================================================== -.. currentmodule:: passlib.hash - -.. warning:: +.. include:: ../_fragments/insecure_hash_warning.rst - This algorithm is extremely weak, and should not be used - for any purposes besides manipulating existing Mysql 4.1+ - password hashes. +.. currentmodule:: passlib.hash This class implements the second of MySQL's password hash functions, used to store its user account passwords. Introduced in MySQL 4.1.1 diff --git a/docs/lib/passlib.hash.nthash.rst b/docs/lib/passlib.hash.nthash.rst index c93dff4..92c934e 100644 --- a/docs/lib/passlib.hash.nthash.rst +++ b/docs/lib/passlib.hash.nthash.rst @@ -4,14 +4,9 @@ :class:`passlib.hash.nthash` - Windows' NT-HASH ================================================================== -.. versionadded:: 1.6 - -.. warning:: +.. include:: ../_fragments/trivial_hash_warning.rst - This scheme is very weak, the MD4 digest - it is based on has been severely compromised for many years. - It should be used for compatibility with existing systems; - **do not use** in new code. +.. versionadded:: 1.6 .. currentmodule:: passlib.hash diff --git a/docs/lib/passlib.hash.oracle10.rst b/docs/lib/passlib.hash.oracle10.rst index d2c6524..3d697c2 100644 --- a/docs/lib/passlib.hash.oracle10.rst +++ b/docs/lib/passlib.hash.oracle10.rst @@ -2,12 +2,9 @@ :class:`passlib.hash.oracle10` - Oracle 10g password hash ================================================================== -.. currentmodule:: passlib.hash - -.. warning:: +.. include:: ../_fragments/trivial_hash_warning.rst - This hash is not secure, and should not be used for any purposes - besides manipulating existing Oracle 10 password hashes. +.. currentmodule:: passlib.hash This class implements the hash algorithm used by the Oracle Database up to version 10g Rel.2. It was superseded by a newer algorithm in :class:`Oracle 11 <passlib.hash.oracle11>`. diff --git a/docs/lib/passlib.hash.postgres_md5.rst b/docs/lib/passlib.hash.postgres_md5.rst index e14dc18..4627eb7 100644 --- a/docs/lib/passlib.hash.postgres_md5.rst +++ b/docs/lib/passlib.hash.postgres_md5.rst @@ -4,10 +4,7 @@ :class:`passlib.hash.postgres_md5` - PostgreSQL MD5 password hash ================================================================== -.. warning:: - - This hash is not secure, and should not be used for any purposes - besides manipulating existing PostgreSQL password hashes. +.. include:: ../_fragments/insecure_hash_warning.rst .. currentmodule:: passlib.hash diff --git a/docs/lib/passlib.hash.rst b/docs/lib/passlib.hash.rst index 03a28b1..f5a728c 100644 --- a/docs/lib/passlib.hash.rst +++ b/docs/lib/passlib.hash.rst @@ -9,11 +9,13 @@ Overview ======== The :mod:`!passlib.hash` module contains all the password hash algorithms built into Passlib. While each hash has its own options and output format, -they all inherit from the :mod:`passlib.ifc`.\ :class:`!PasswordHash` API. +they all inherit from the :mod:`~passlib.ifc.PasswordHash` base interface. The following pages describe each hash in detail, including its format, underlying algorithm, and known security issues. -.. warning:: +.. rst-class:: float-center + +.. danger:: **Many of the hash algorithms listed below are *NOT* secure.** @@ -21,61 +23,14 @@ including its format, underlying algorithm, and known security issues. support dealing with legacy data and systems. If you're looking to choose a hash algorithm for a new application, - see the :doc:`Quickstart Guide </new_app_quickstart>` instead of picking + see the :doc:`Quickstart Guide </narr/quickstart>` instead of picking one from this list. -.. rst-class:: html-toggle - -Usage ------ -All of the hashes in this module can be used in two ways: - -1. They can be imported from :mod:`!passlib.hash` and used directly, - as in the following example with the :class:`md5_crypt` hash:: - - >>> # import the desired hash - >>> from passlib.hash import md5_crypt - - >>> # hash the password - hash() takes care of salt generation, unicode encoding, etc. - >>> hash = md5_crypt.hash("password") - >>> hash - '$1$IU54yC7Y$nI1wF8ltcRvaRHwMIjiJq1' - - >>> # verify a password against an existing hash: - >>> md5_crypt.verify("password", hash) - True - -2. Alternately, when working with multiple algorithms at once, it is frequently useful - to construct a :ref:`CryptContext <context-overview>` object instead; - and reference the hashes by name only. For example, the following - code creates a :class:`!CryptContext` object which recognizes both - the :class:`md5_crypt` and :class:`des_crypt` hash algorithms:: - - >>> # import and create the context object - >>> from passlib.context import CryptContext - >>> pwd_context = CryptContext(schemes=["md5_crypt", "des_crypt"]) - - >>> # hash two different passwords (context objects used the first scheme as the default) - >>> hash1 = pwd_context.hash("password") - >>> hash1 - '$1$2y72Yi12$o6Yu2OyjN.9FiK.9HJ7i5.' - >>> hash2 = pwd_context.hash("letmein", scheme="des_crypt") - >>> hash2 - '0WMdk/ven8bok' - - >>> # the context object takes care of figuring out which hash belongs to which algorithm. - >>> pwd_context.verify("password", hash1) - True - >>> pwd_context.verify("letmein", hash1) - False - >>> pwd_context.verify("letmein", hash2) - True +.. rst-class:: float-center .. seealso:: - For additional details and usage examples, see the - :doc:`PasswordHash </password_hash_api>` and :doc:`CryptContext </lib/passlib.context>` - reference. + :ref:`hash-tutorial` -- for general usage examples .. _mcf-hashes: diff --git a/docs/lib/passlib.hash.scrypt.rst b/docs/lib/passlib.hash.scrypt.rst index 29f491a..6c2c061 100644 --- a/docs/lib/passlib.hash.scrypt.rst +++ b/docs/lib/passlib.hash.scrypt.rst @@ -14,8 +14,10 @@ as the of a new generation of "memory hard" functions. Be careful when using this algorithm, as the memory and CPU requirements needed to achieve adequate security are generally higher than acceptable for heavily used - production systems [#scrypt-cost]_: unlike many password hashes, increasing - the rounds value of scrypt will increase the *memory* required, as well as the time. + production systems [#scrypt-cost]_. This is because (unlike many password hashes), increasing + the rounds value of scrypt will increase the *memory* required as well as the time. + + Unless you know what you're doing, **You probably want** :doc:`argon2 <passlib.hash.argon2>` **instead.** This class can be used directly as follows:: diff --git a/docs/lib/passlib.hosts.rst b/docs/lib/passlib.hosts.rst index 3a0a02e..d72fef0 100644 --- a/docs/lib/passlib.hosts.rst +++ b/docs/lib/passlib.hosts.rst @@ -5,7 +5,7 @@ .. module:: passlib.hosts :synopsis: encrypting & verifying operating system passwords -This module provides some preconfigured :ref:`CryptContext <context-overview>` +This module provides some preconfigured :ref:`CryptContext <context-reference>` instances for encrypting & verifying password hashes tied to user accounts of various operating systems. While (most) of the objects are available cross-platform, their use is oriented primarily towards Linux and BSD variants. diff --git a/docs/lib/passlib.ifc.rst b/docs/lib/passlib.ifc.rst new file mode 100644 index 0000000..0cc99f0 --- /dev/null +++ b/docs/lib/passlib.ifc.rst @@ -0,0 +1,719 @@ +.. index:: + single: PasswordHash interface + single: custom hash handler; requirements + +.. module:: passlib.ifc + :synopsis: abstract interfaces used by Passlib + +============================================= +:mod:`passlib.ifc` -- Password Hash Interface +============================================= + +.. _password-hash-api: + +Overview +======== +This module provides the :class:`!PasswordHash` abstract base class. +This class defines the common methods and attributes present +on all the hashes importable from the :mod:`passlib.hash` module. +Additionally, the :class:`passlib.context.CryptContext` class is deliberately +designed to parallel many of this interface's methods. + +.. rst-class:: float-center + +.. seealso:: + + :ref:`hash-tutorial` -- Overview of this interface and how to use it. + +PasswordHash API +================ +.. class:: PasswordHash() + + This class provides an abstract interface for an arbitrary password hasher. + + Applications will generally not construct instances directly -- + most of the operations are performed via classmethods, allowing + instances of a given class to be an internal detail used to implement + the various operations. + + While :class:`!PasswordHash` offers a number of methods and attributes, + most applications will only need the two primary methods: + + * :meth:`PasswordHash.hash` - generate new salt, return hash of password. + * :meth:`PasswordHash.verify` - verify password against existing hash. + + Two additional support methods are also provided: + + * :meth:`PasswordHash.using` - create subclass with customized configuration. + * :meth:`PasswordHash.identify` - check if hash belongs to this algorithm. + + Each hash algorithm also provides a number of :ref:`informational attributes <informational-attributes>`, + allowing programmatic inspection of its options and parameter limits. + +.. seealso:: + + :ref:`hash-tutorial` -- Overview of this interface and how to use it. + +.. _primary-methods: + +Hashing & Verification Methods +============================== +Most applications will only need to use two methods: +:meth:`PasswordHash.hash` to generate new hashes, and :meth:`PasswordHash.verify` +to check passwords against existing hashes. +These methods provide an easy interface for working with a password hash, +and abstract away details such as salt generation, hash normalization, +and hash comparison. + +.. classmethod:: PasswordHash.hash(secret, \*\*kwds) + + Digest password using format-specific algorithm, + returning resulting hash string. + + For most hashes supported by Passlib, the returned string will contain: + an algorithm identifier, a cost parameter, the salt string, + and finally the password digest itself. + + :type secret: unicode or bytes + :arg secret: string containing the password to encode. + + :param \*\*kwds: + + All additional keywords are algorithm-specific, and will be listed + in that hash's documentation; though many of the more common keywords + are listed under :attr:`PasswordHash.setting_kwds` + and :attr:`PasswordHash.context_kwds`. + + .. deprecated:: 1.7 + + Passing :attr:`PasswordHash.setting_kwds` such as ``rounds`` and ``salt_size`` + directly into the :meth:`hash` method is deprecated. Callers should instead + use ``handler.using(**settings).hash(secret)``. Support for the old method + is is tentatively scheduled for removal in Passlib 2.0. + + Context keywords such as ``user`` should still be provided to :meth:`!hash`. + + :returns: + Resulting password hash, encoded in an algorithm-specific format. + This will always be an instance of :class:`!str` + (i.e. :class:`unicode` under Python 3, ``ascii``-encoded :class:`bytes` under Python 2). + + :raises ValueError: + + * If a ``kwd``'s value is invalid (e.g. if a ``salt`` string + is too small, or a ``rounds`` value is out of range). + + * If ``secret`` contains characters forbidden by the hash algorithm + (e.g. :class:`!des_crypt` forbids NULL characters). + + :raises TypeError: + + * if ``secret`` is not :class:`!unicode` or :class:`bytes`. + * if a ``kwd`` argument has an incorrect type. + * if an algorithm-specific required ``kwd`` is not provided. + + .. versionchanged:: 1.6 + Hashes now raise :exc:`TypeError` if a required keyword is missing, + rather than :exc:`ValueError` like in previous releases; in order + to conform with normal Python behavior. + + .. versionchanged:: 1.6 + Passlib is now much stricter about input validation: for example, + out-of-range ``rounds`` values now cause an error instead of being + clipped (though applications may set :ref:`relaxed=True <relaxed-keyword>` + to restore the old behavior). + + .. versionchanged:: 1.7 + + This method was renamed from :meth:`encrypt`. + Deprecated support for passing settings directly into :meth:`!hash`. + +.. classmethod:: PasswordHash.encrypt(secret, \*\*kwds) + + Legacy alias for :meth:`PasswordHash.hash`. + + .. deprecated:: 1.7 + + This method was renamed to :meth:`!hash` in version 1.7. + This alias will be removed in version 2.0, and should only + be used for compatibility with Passlib 1.3 - 1.6. + +.. classmethod:: PasswordHash.verify(secret, hash, \*\*context_kwds) + + Verify a secret using an existing hash. + + This checks if a secret matches against the one stored + inside the specified hash. + + :type secret: unicode or bytes + :param secret: + A string containing the password to check. + + :type secret: unicode or bytes + :param hash: + A string containing the hash to check against, + such as returned by :meth:`PasswordHash.hash`. + + Hashes may be specified as :class:`!unicode` or + ``ascii``-encoded :class:`!bytes`. + + :param \*\*kwds: + Very few hashes will have additional keywords. + + The ones that do typically require external contextual information + in order to calculate the digest. For these hashes, + the values must match the ones passed to the original + :meth:`PasswordHash.hash` call when the hash was generated, + or the password will not verify. + + These additional keywords are algorithm-specific, and will be listed + in that hash's documentation; though the more common keywords + are listed under :attr:`PasswordHash.context_kwds`. + Examples of common keywords include ``user``. + + :returns: + ``True`` if the secret matches, otherwise ``False``. + + :raises TypeError: + * if either ``secret`` or ``hash`` is not a unicode or bytes instance. + * if the hash requires additional ``kwds`` which are not provided, + * if a ``kwd`` argument has the wrong type. + + :raises ValueError: + * if ``hash`` does not match this algorithm's format. + * if the ``secret`` contains forbidden characters (see + :meth:`PasswordHash.hash`). + * if a configuration/salt string generated by :meth:`PasswordHash.genconfig` + is passed in as the value for ``hash`` (these strings look + similar to a full hash, but typically lack the digest portion + needed to verify a password). + + .. versionchanged:: 1.6 + This function now raises :exc:`ValueError` if ``None`` or a config string is provided + instead of a properly-formed hash; previous releases were inconsistent + in their handling of these two border cases. + +.. seealso:: + + * :ref:`hash-verifying` tutorial for a usage example + +.. _crypt-methods: + +.. rst-class:: html-toggle + +Crypt Methods +============= +Taken together, the :meth:`PasswordHash.genconfig` and :meth:`PasswordHash.genhash` +are two tightly-coupled methods that mimic the standard Unix +"crypt" interface. The first method generates salt / configuration +strings from a set of settings, and the second hashes the password +using the provided configuration string. + +.. seealso:: + + Most applications will find :meth:`PasswordHash.hash` much more useful, + as it combines the functionality of these two methods into one. + +.. classmethod:: PasswordHash.genconfig(\*\*setting_kwds) + + .. deprecated:: 1.7 + + As of 1.7, this method is deprecated, and slated for complete removal in Passlib 2.0. + + For all known real-world uses, ``.hash("", **settings)`` + should provide equivalent functionality. + + This deprecation may be reversed if a use-case presents itself in the mean time. + + Returns a configuration string encoding settings for hash generation. + + This function takes in all the same :attr:`PasswordHash.setting_kwds` + as :meth:`PasswordHash.hash`, fills in suitable defaults, + and encodes the settings into a single "configuration" string, + suitable passing to :meth:`PasswordHash.genhash`. + + :param \*\*kwds: + All additional keywords are algorithm-specific, and will be listed + in that hash's documentation; though many of the more common keywords + are listed under :attr:`PasswordHash.setting_kwds` + Examples of common keywords include ``salt`` and ``rounds``. + + :returns: + A configuration string (as :class:`!str`). + + :raises ValueError, TypeError: + This function raises exceptions for the same + reasons as :meth:`PasswordHash.hash`. + + .. versionchanged:: 1.7 + + This should now always return a full hash string, even in cases + where previous releases would return a truncated "configuration only" string, + or ``None``. + +.. classmethod:: PasswordHash.genhash(secret, config, \*\*context_kwds) + + Encrypt secret using specified configuration string. + + .. deprecated:: 1.7 + + As of 1.7, this method is deprecated, and slated for complete removal in Passlib 2.0. + + This deprecation may be reversed if a use-case presents itself in the mean time. + + This takes in a password and a configuration string, + and returns a hash for that password. + + :type secret: unicode or bytes + :arg secret: + string containing the password to be encrypted. + + :type config: unicode or bytes + :arg config: + configuration string to use when encrypting secret. + this can either be an existing hash that was previously + returned by :meth:`PasswordHash.genhash`, or a configuration string + that was previously created by :meth:`PasswordHash.genconfig`. + + .. versionchanged:: 1.7 + + ``None`` is no longer accepted for hashes which (prior to 1.7) + lacked a configuration string format. + + :param \*\*kwds: + Very few hashes will have additional keywords. + + The ones that do typically require external contextual information + in order to calculate the digest. For these hashes, + the values must match the ones passed to the original + :meth:`PasswordHash.hash` call when the hash was generated, + or the password will not verify. + + These additional keywords are algorithm-specific, and will be listed + in that hash's documentation; though the more common keywords + are listed under ::attr:`PasswordHash.context_kwds`. + Examples of common keywords include ``user``. + + :returns: + Encoded hash matching specified secret, config, and kwds. + This will always be a native :class:`!str` instance. + + :raises ValueError, TypeError: + This function raises exceptions for the same + reasons as :meth:`PasswordHash.hash`. + + .. warning:: + + Traditionally, password verification using the "crypt" interface + was done by testing if ``hash == genhash(password, hash)``. + This test is only reliable for a handful of algorithms, + as various hash representation issues may cause false results. + Applications are strongly urged to use :meth:`~PasswordHash.verify` instead. + +.. _support-methods: + +Factory Creation +================ +One powerful method offered by the :class:`!PasswordHash` class :meth:`PasswordHash.using`. +This method allows you to quickly create subclasses of a specific hash, +providing it with preconfigured defaults specific to your application: + +.. classmethod:: PasswordHash.using(relaxed=False, \*\*settings) + + This method takes in a set of algorithm-specific settings, + and returns a new handler object which uses the specified default settings instead. + + :param \*\*settings: + + All keywords are algorithm-specific, and will be listed + in that hash's documentation; though many of the more common keywords + are listed under :attr:`PasswordHash.setting_kwds`. + Examples of common keywords include ``rounds`` and ``salt_size``. + + :returns: + A new object which adheres to :class:`!PasswordHash` api. + + :raises ValueError: + + * If a keywords's value is invalid (e.g. if a ``salt`` string + is too small, or a ``rounds`` value is out of range). + + :raises TypeError: + + * if a ``kwd`` argument has an incorrect type. + + .. versionadded:: 1.7 + +.. seealso:: :ref:`hash-configuring` tutorial for a usage example + +Hash Inspection Methods +======================= +There are currently two hash inspection methods, :meth:`PasswordHash.identify` +and :meth:`PasswordHash.needs_update`. + +.. classmethod:: PasswordHash.identify(hash) + + Quickly identify if a hash string belongs to this algorithm. + + :type hash: unicode or bytes + :arg hash: + the candidate hash string to check + + :returns: + * ``True`` if the input is a configuration string or hash string + identifiable as belonging to this scheme (even if it's malformed). + * ``False`` if the input does not belong to this scheme. + + :raises TypeError: + if :samp:`{hash}` is not a unicode or bytes instance. + + .. note:: + + A small number of the hashes supported by Passlib lack a reliable + method of identification (e.g. :class:`~passlib.hash.lmhash` + and :class:`~passlib.hash.nthash` both consist of 32 hexadecimal characters, + with no distinguishing features). For such hashes, this method + may return false positives. + + .. seealso:: + + If you are considering using this method to select from multiple + algorithms (e.g. in order to verify a password), you will be better served + by the :ref:`CryptContext <context-reference>` class. + +.. automethod:: PasswordHash.needs_update + +.. + the undocumented and experimental support methods currently include + parsehash() and bitsize() + + + .. todo:: + + document the :attr:`is_disabled` and DisabledHash interface + added in passlib 1.7. + +.. _informational-attributes: + +.. _general-attributes: + +General Informational Attributes +================================ +Each hash provides a handful of informational attributes, allowing +programs to dynamically adapt to the requirements of different +hash algorithms. The following attributes should be defined for all +the hashes in passlib: + +.. attribute:: PasswordHash.name + + Name uniquely identifying this hash. + + For the hashes built into Passlib, this will always match + the location where it was imported from — :samp:`passlib.hash.{name}` — + though externally defined hashes may not adhere to this. + + This should always be a :class:`!str` consisting of lowercase ``a-z``, + the digits ``0-9``, and the underscore character ``_``. + +.. attribute:: PasswordHash.setting_kwds + + Tuple listing the keywords supported by :meth:`PasswordHash.using` control hash generation, + and which will be encoded into the resulting hash. + + (These keywords will also be accepted by :meth:`PasswordHash.hash` and :meth:`PasswordHash.genconfig`, + though that behavior is deprecated as of Passlib 1.7; and will be removed in Passlib 2.0). + + This list commonly includes keywords for controlling salt generation, + adjusting time-cost parameters, etc. Most of these settings are optional, + and suitable defaults will be chosen if they are omitted (e.g. salts + will be autogenerated). + + While the documentation for each hash should have a complete list of + the specific settings the hash uses, the following keywords should have + roughly the same behavior for all the hashes that support them: + + .. index:: + single: salt; PasswordHash keyword + + ``salt`` + Specifies a fixed salt string to use, rather than randomly + generating one. + + This option is supported by most of the hashes in Passlib, + though typically it isn't used, as random generation of a salt + is usually the desired behavior. + + Hashes typically require this to be a :class:`!unicode` or + :class:`!bytes` instance, with additional constraints + appropriate to the algorithm. + + .. index:: + single: salt_size; PasswordHash keyword + + ``salt_size`` + + Most algorithms which support the ``salt`` setting will + autogenerate a salt when none is provided. Most of those hashes + will also offer this option, which allows the caller to specify + the size of salt which should be generated. If omitted, + the hash's default salt size will be used. + + .. seealso:: the :ref:`salt info <salt-attributes>` attributes (below) + + .. index:: + single: rounds; PasswordHash keyword + + ``rounds`` + If present, this means the hash can vary the number + of internal rounds used in some part of its algorithm, + allowing the calculation to take a variable amount of processor + time, for increased security. + + While this is almost always a non-negative integer, + additional constraints may be present for each algorithm + (such as the cost varying on a linear or logarithmic scale). + + This value is typically omitted, in which case a default + value will be used. The defaults for all the hashes in Passlib + are periodically retuned to strike a balance between + security and responsiveness. + + .. seealso:: the :ref:`rounds info <rounds-attributes>` attributes (below) + + .. index:: + single: ident; PasswordHash keyword + + ``ident`` + If present, the class supports multiple formats for encoding + the same hash. The class's documentation will generally list + the allowed values, allowing alternate output formats to be selected. + + Note that these values will typically correspond to different + revision of the hash algorithm itself, and they may not all + offer the same level of security. + + ``truncate_error`` + + This will be present if and only if the hash truncates passwords + larger than some limit (reported via it's :attr:`truncate_size` attribute). + By default, they will silently truncate passwords above their limit. + Setting ``truncate_error=True`` will cause :meth:`PasswordHash.hash` + to raise a :exc:`~passlib.exc.PasswordTruncateError` instead. + + .. index:: + single: relaxed; PasswordHash keyword + + .. _relaxed-keyword: + + ``relaxed`` + By default, passing an invalid value to :meth:`PasswordHash.using` + will result in a :exc:`ValueError`. However, if ``relaxed=True`` + then Passlib will attempt to correct the error and (if successful) + issue a :exc:`~passlib.exc.PasslibHashWarning` instead. + This warning may then be filtered if desired. + Correctable errors include (but are not limited to): ``rounds`` + and ``salt_size`` values that are too low or too high, ``salt`` + strings that are too large. + + .. versionadded:: 1.6 + +.. _context-keywords: + +.. attribute:: PasswordHash.context_kwds + + Tuple listing the keywords supported by :meth:`PasswordHash.hash`, + :meth:`PasswordHash.verify`, and :meth:`PasswordHash.genhash`. + These keywords are different from the settings kwds in that the context keywords + affect the hash, but are not encoded within it, and thus must be provided each time + the hash is calculated. + + This list commonly includes a user account, http realm identifier, + etc. Most of these keywords are required by the hashes which support them, + as they are frequently used in place of an embedded salt parameter. + + *Most hash algorithms in Passlib will have no context keywords.* + + While the documentation for each hash should have a complete list of + the specific context keywords the hash uses, + the following keywords should have roughly the same behavior + for all the hashes that support them: + + .. index:: + single: user; PasswordHash keyword + + ``user`` + + If present, the class requires a username be specified whenever + performing a hash calculation (e.g. + :class:`~passlib.hash.postgres_md5` and + :class:`~passlib.hash.oracle10`). + + .. index:: + single: encoding; PasswordHash keyword + + ``encoding`` + + Some hashes have poorly-defined or host-dependant unicode behavior, + and properly hashing a non-ASCII password requires providing + the correct encoding (:class:`~passlib.hash.lmhash` is perhaps the worst offender). + Hashes which provide this keyword will always expose + their default encoding programmatically via the + :attr:`PasswordHash.default_encoding` attribute. + +.. attribute:: truncate_size + + A positive integer, indicating the hash will truncate any passwords larger than this many bytes. + If ``None`` (the more common case), indicates the hash will use + the entire password provided. + + Hashes which specify this setting will also support a ``truncate_error`` + flag via their :meth:`PasswordHash.using` method, to configure + how truncation is handled. + +.. seealso:: :ref:`hash-configuring` tutorial for a usage example + +.. _salt-attributes: + +Salt Information Attributes +=========================== +For schemes which support a salt string, +``"salt"`` should be listed in their :attr:`PasswordHash.setting_kwds`, +and the following attributes should be defined: + +.. attribute:: PasswordHash.max_salt_size + + The maximum number of bytes/characters allowed in the salt. + Should either be a positive integer, or ``None`` (indicating + the algorithm has no effective upper limit). + +.. attribute:: PasswordHash.min_salt_size + + The minimum number of bytes/characters required for the salt. + Must be an integer between 0 and :attr:`PasswordHash.max_salt_size`. + +.. attribute:: PasswordHash.default_salt_size + + The default salt size that will be used when generating a salt, + assuming ``salt_size`` is not set explicitly. This is typically + the same as :attr:`max_salt_size`, + or a sane default if ``max_salt_size=None``. + +.. attribute:: PasswordHash.salt_chars + + A unicode string containing all the characters permitted + in a salt string. + + For most :ref:`modular-crypt-format` hashes, + this is equal to :data:`passlib.utils.HASH64_CHARS`. + For the rare hashes where the ``salt`` parameter must be specified + in bytes, this will be a placeholder :class:`!bytes` object containing + all 256 possible byte values. + +.. + not yet documentated, want to make sure this is how we want to do things: + + .. attribute:: PasswordHash.default_salt_chars + + sequence of characters used to generate new salts. + this is typically the same as :attr:`PasswordHash.salt_chars`, but some + hashes accept a larger-than-useful range, and this will + contain only the "common" values used for generation. + +.. _rounds-attributes: + +Rounds Information Attributes +============================= +For schemes which support a variable time-cost parameter, +``"rounds"`` should be listed in their :attr:`PasswordHash.setting_kwds`, +and the following attributes should be defined: + +.. attribute:: PasswordHash.max_rounds + + The maximum number of rounds the scheme allows. + Specifying a value beyond this will result in a :exc:`ValueError`. + This will be either a positive integer, or ``None`` (indicating + the algorithm has no effective upper limit). + +.. attribute:: PasswordHash.min_rounds + + The minimum number of rounds the scheme allows. + Specifying a value below this will result in a :exc:`ValueError`. + Will always be an integer between 0 and :attr:`PasswordHash.max_rounds`. + +.. attribute:: PasswordHash.default_rounds + + The default number of rounds that will be used if none is explicitly + provided to :meth:`PasswordHash.hash`. + This will always be an integer between :attr:`PasswordHash.min_rounds` + and :attr:`PasswordHash.max_rounds`. + +.. attribute:: PasswordHash.rounds_cost + + While the cost parameter ``rounds`` is an integer, how it corresponds + to the amount of time taken can vary between hashes. This attribute + indicates the scale used by the hash: + + * ``"linear"`` - time taken scales linearly with rounds value + (e.g. :class:`~passlib.hash.sha512_crypt`) + * ``"log2"`` - time taken scales exponentially with rounds value + (e.g. :class:`~passlib.hash.bcrypt`) + +.. todo:: document the additional :meth:`PasswordHash.using` keywords + available for setting rounds limits. + +.. + todo: haven't decided if this is how I want the api look before + formally publishing it in the documentation: + + .. _password-hash-backends: + + Multiple Backends + ================= + .. note:: + + For the most part, applications will not need this interface, + outside of perhaps calling the :meth:`PasswordHash.get_backend` + to determine which the active backend. + + Some hashes provided by Passlib have multiple backends which they + select from at runtime, to provide the fastest implementation available. + Algorithms which offer multiple backends will expose the following + methods and attributes: + + .. attribute:: PasswordHash.backends + + Tuple listing names of potential backends (which may or may not be available). + If this attribute is not present, the hash does not support + multiple backends. + + While the names of the backends are specific to the hash algorithm, + the following standard names may be present: + + * ``"os_crypt"`` - backend which uses stdlib's :mod:`!crypt` module. + this backend will not be available if the underlying host OS + does not support the particular hash algorithm. + + * ``"builtin"`` - backend using pure-python implementation built into + Passlib. All hashes will have this as their last backend, as a fallback. + + .. method:: PasswordHash.get_backend() + + This method should return the name of the currently active backend + that will be used by :meth:`PasswordHash.hash` and :meth:`PasswordHash.verify`. + + :raises passlib.exc.MissingBackendError: + in the rare case that *no* backends can be loaded. + + .. method:: PasswordHash.has_backend(backend) + + This method can be used to test if a specific backend is available. + Returns ``True`` or ``False``. + + .. method:: PasswordHash.set_backend(backend) + + This method can be used to select a specific backend. + The ``backend`` argument must be one of the backends listed + in :attr:`PasswordHash.backends`, or the special value ``"default"``. + + :raises passlib.exc.MissingBackendError: + if the specified backend is not available. diff --git a/docs/lib/passlib.totp-tutorial.rst b/docs/lib/passlib.totp-tutorial.rst deleted file mode 100644 index e76029f..0000000 --- a/docs/lib/passlib.totp-tutorial.rst +++ /dev/null @@ -1,772 +0,0 @@ -.. index:: TOTP; overview -.. index:: TOTP; usage examples -.. _totp-tutorial: - -.. currentmodule:: passlib.totp - -=================================== -:mod:`passlib.totp` - TOTP Tutorial -=================================== - -Overview -======== -The :mod:`passlib.totp` module provides a set of classes for adding -two-factor authentication (2FA) support into your application, -using the widely supported TOTP specification (:rfc:`6238`). - -This module is based around the :class:`TOTP` class, which supports -a wide variety of use-cases, including: - - * Creating & transferring configured TOTP keys to client devices. - - * Generating & verifying tokens. - - * Securely storing configured TOTP keys. - -.. seealso:: The :mod:`passlib.totp` API reference, - which lists all details of all the classes and methods mentioned here. - -Walkthrough -=========== -There are a number of different ways to integrate TOTP support into a server application. -The following is a general outline of one of way to do this. Some details and -alternate choices are omitted for brevity, see the remaining sections -of this tutorial for more detailed information about these steps. - -.. _totp-walkthrough-step-1: - -1. Generate an Application Secret ---------------------------------- -First, generate a strong application secret to use when encrypting TOTP keys for storage. -Passlib offers a :meth:`generate_secret` method to help with this:: - - >>> from passlib.totp import generate_secret - >>> generate_secret() - 'pO7SwEFcUPvIDeAJr7INBj0TjsSZJr1d2ddsFL9r5eq' - -This key should be assigned a numeric tag (e.g. "1", a timestamp, or an iso date such as "2016-11-10"); -and should be stored in a file *separate* from your application's configuration. -Ideally, after this file has been loaded by the TOTP constructor below, -the application should give up access permissions to the file. - -Example file contents:: - - 2016-11-10: pO7SwEFcUPvIDeAJr7INBj0TjsSZJr1d2ddsFL9r5eq - -This key will be used in a later step to encrypt TOTP keys for storage in your database. -The sequential tag is used so that if your database (or the application secrets) -are ever compromised, you can add a new application secret (with a newer tag), -and gracefully migrate the compromised TOTP keys. - -.. rst-class:: without-title float-center - -.. seealso:: **For more details see** :ref:`totp-encryption-setup` (below). - -2. TOTP Factory Initialization ------------------------------- -When your application is being initialized, create a TOTP factory which is configured -for your application, and is set up to use the application secrets defined in step 1. -You can also set a default issuer here, instead of having to provide one explicitly in step 4:: - - >>> from passlib.totp import TOTP - >>> TotpFactory = TOTP.using(secrets_path='/path/to/secret/file/in/step/1', - ... issuer="myapp.example.org") - -The ``TotpFactory`` object returned by :meth:`TOTP.using` is actually a subclass -of :class:`TOTP` itself, and has the same methods and attributes. The main difference is that (because -an application secret has been provided), the TOTP key will automatically be encrypted / decrypted -when serializing the object to disk. - -.. rst-class:: without-title float-center - -.. seealso:: **For more details see** :ref:`totp-creation` (below). - -3. Rate-Limiting & Cache Initialization ---------------------------------------- -As part of your application initialization, it **critically important** to -set up infrastructure to rate limit how many token verification -attempts a user / ip address is allowed to make, otherwise TOTP can be bypassed. - -.. rst-class:: without-title float-center - -.. seealso:: **For more details see** :ref:`totp-rate-limiting` (below) - -.. rst-class:: clear - -It's also **strongly recommended** to set up a per-user cache which can store the last matched TOTP counter (an integer) -for a period of a few minutes (e.g. using `dogpile.cache <https://pypi.python.org/pypi/dogpile.cache>`_, -memcached, redis, etc). This cache is used by later steps to protect your application during a narrow window of time -where TOTP would otherwise be vulnerable to a replay attack. - -.. rst-class:: without-title float-center - -.. seealso:: **For more details see** :ref:`totp-reuse-warning` (below) - -4. Setting up TOTP for a User ------------------------------ -To set up TOTP for a new user: create a new TOTP object and key using :meth:`TOTP.new`. -This can then be rendered into a provisioning URI, and transferred to the user's TOTP client -of choice. - -Rendering to a provisioning URI using :meth:`TOTP.to_uri` requires picking an "issuer" string -to uniquely identify your application, and a "label" string to uniquely identify the user. -The following example creates a new TOTP instance with a new key, -and renders it to a URI, plugging in application-specific information. - -Using the ``TotpFactory`` object set up in step 2:: - - >>> totp = TotpFactory.new() - >>> uri = totp.to_uri(issuer="myapp.example.org", label="username") - >>> uri - 'otpauth://totp/username?secret=D6RZI4ROAUQKJNAWQKYPN7W7LNV43GOT&issuer=myapp.example.org' - -This URI is generally passed to a QRCode renderer, though -as fallback it's recommended to also display the key using :meth:`TOTP.pretty_key`. - -.. rst-class:: without-title float-center - -.. seealso:: **For more details, and more about QR Codes, see** :ref:`totp-configuring-clients` (below). - -5. Storing the TOTP object --------------------------- -Before enabling TOTP for the user's account, it's good practice to first have the -user successfully verify a token (per step 6); thus confirming their client h -as been correctly configured. - -Once this is done, you can store the TOTP object in your database. -This can be done via the :meth:`TOTP.to_json` method:: - - >>> totp.to_json() - '{"enckey":{"c":14,"k":"FLEQC3VO6SIT3T7GN2GIG6ONPXADG5CZ","s":"UL2J4MZG4SONHOWXLKFQ","t":"1","v":1},"type":"totp","v":1}' - -Note that if there is no application secret configured, the key will not be encrypted, -and instead look like this:: - - >>> totp.to_json() - '{"key":"D6RZI4ROAUQKJNAWQKYPN7W7LNV43GOT","type":"totp","v":1}' - -To ensure you always save an encrypted token, you can use ``totp.to_json(encrypted=True)``. - -.. rst-class:: float-center without-title - -.. seealso:: **For more details see** :ref:`totp-storing-instances` - -6. Verifying a Token --------------------- -Whenever attempting to verify a token provided by the user, -first load the serialized TOTP object from the database (stored step 5), -as well as the last counter value from the cache (set up in step 3). -You should use these values to call the :meth:`TOTP.verify` method. - -If verify() succeeds, it will return a :class:`TotpMatch` object. -This object contains information about the match, -including :attr:`TotpMatch.counter` (a time-dependant integer tied to this token), -and :attr:`TotpMatch.cache_seconds` (minimum time this counter should be cached). - -If verify() fails, it will raise one of the :exc:`passlib.exc.TokenError` subclasses -indicating what went wrong. This will be one of three cases: the token was -malformed (e.g. too few digits), the token was invalid (didn't match), -or a recent token was reused. - -A skeleton example of how this should function:: - - >>> from passlib.exc import TokenError, MalformedTokenError - - >>> # pull information from your application - >>> token = # ... token string provided by user ... - >>> source = # ... load totp json string from database ... - >>> last_counter = # ... load counter value from cache ... - - >>> # ... check attempt rate limit for this account / address (per step 3 above) ... - - >>> # using the TotpFactory object defined in step 2, invoke verify - >>> try: - ... match = TotpFactory.verify(token, source, last_counter=last_counter) - ... except MalformedTokenError as err: - ... # --- malformed token --- - ... # * inform user, e.g. by displaying str(err) - ... except TokenError as err: - ... # --- invalid or reused token --- - ... # * add to rate limit counter - ... # * inform user, e.g. by displaying str(err) - ... else: - ... # --- successful match --- - ... # * reset rate-limit counter - ... # * store 'match.counter' in per-user cache for at least 'match.cache_seconds' - -.. rst-class:: float-center without-title - -.. seealso:: **For more details see** :ref:`totp-verifying` (below) - -.. rst-class:: html-toggle - -Alternate Caching Strategy -.......................... -As an alternative to storing ``match.counter`` in the cache, -applications using a cache such as memcached may wish to simply set a key -based on ``user + token`` for ``match.cache_seconds``, and reject any -tokens coming in for that user who are marked in the cache. - -In that case, they should run the tokens through :meth:`TOTP.normalize_token` -first, to make sure the token strings are normalized before comparison. -In this case, the skeleton example can be amended to:: - - >>> # pull information from your application - >>> token = # ... token string provided by user ... - >>> source = # ... load totp json string from database ... - >>> user_id = # ... user identifier for cache - - >>> # ... check attempt rate limit for this account / address (per step 3 above) ... - - >>> # check token format - >>> try: - ... token = TotpFactory.normalize_token(token) - ... except MalformedTokenError as err: - ... # --- malformed token --- - ... # * inform user, e.g. by displaying str(err) - ... return - - >>> # check if token has been used, using app-defined present_in_cache() helper - >>> cache_key = "totp-token-%s-%s" % (user_id, token) - >>> if present_in_cache(cache_key): - ... # * add to rate limit counter - ... # * present 'token already used' message - ... return - - >>> # using the TotpFactory object defined in step 2, invoke verify - >>> try: - ... match = TotpFactory.verify(token, source) - ... except TokenError as err: - ... # --- invalid token --- - ... # * add to rate limit counter - ... # * inform user, e.g. by displaying str(err) - ... else: - ... # --- successful match --- - ... # * reset rate-limit counter - ... # * set 'cache_key' in per-user cache for at least 'match.cache_seconds' - -7. Reserializing Existing Objects ---------------------------------- -An organization's security policy may require that a developer periodically -change the application secret key used to decrypt/encrypt TOTP objects. -Alternately, the application secret may become compromised. - -In either case, a new application secret will need to be created, and a new tag assigned -(per step 1). Any deprecated secret(s) will need to be retained in the collection passed to the ``TotpFactory``, -in order to be able to decrypt existing TOTP objects. - -.. rst-class:: float-right - -.. note:: - - You can verify which secret is will be used - to encrypt new keys by inspecting ``tag = TotpFactory.wallet.default_tag``. - -.. rst-class:: clear - -Once the new secret has been added, you will need to update all the serialized TOTP objects in the database, -decrypting them using the old secret, and encrypting them with the new one. - -This can be done in a few ways. The following skeleton example gives a simple loop that can be used, -which would ideally be run in a process that's separate from your normal application:: - - >>> # presuming query_user_totp() queries your database for all user rows, - >>> # and update_user_totp() updates a specific row. - >>> for user_id, totp_source in query_user_totp(): - >>> totp = TotpFactory.from_source(totp_source) - >>> if totp.changed: - >>> update_user_totp(user_id, totp.to_json()) - -This uses the :attr:`TOTP.changed` attribute, which is set to ``True`` if -:meth:`TOTP.from_source` (or other constructor) detects the source data is -encrypted with an old secret, is using outdated encryption settings, -or is stored in deprecated serialization format. - -Some refinements that may need to be made for specific situations: - -* For applications with a large number of users, it may be faster to accumulate ``(user_id, totp.to_json())`` - pairs in a buffer, and do a bulk SQL update once every 100-1000 rows. - -* Depending on the dbapi layer in use, it may take care of JSON serialization for you, - in which case you'll need to use ``totp.to_dict()`` instead of ``totp.to_json()``. - -Once all references to a deprecated secret have been replaced, -it can be removed from the secrets file. - -.. rst-class:: float-center without-title - -.. seealso:: **For more details see** :ref:`Step 1 <totp-walkthrough-step-1>` (above), or :ref:`totp-encryption-setup` (below) - -.. _totp-creation: - -Creating TOTP Instances -======================= - -Direct Creation ---------------- -Creating TOTP instances is straightforward: -The :class:`TOTP` class can be called directly to constructor a TOTP instance -from it's component configuration:: - - >>> from passlib.totp import TOTP - >>> totp = TOTP(key='GVDOQ7NP6XPJWE4CWCLFFSXZH6DTAZWM', digits=9) - >>> totp.generate() - '29387414' - -You can also use a number of the alternate constructors, -such as :meth:`TOTP.new` or :meth:`TOTP.from_source`:: - - >>> # create new instance w/ automatically generated key - >>> totp = TOTP.new() - - >>> # or deserializing it from a string (e.g. the output of TOTP.to_json) - >>> totp = TOTP.from_source('{"key":"D6RZI4ROAUQKJNAWQKYPN7W7LNV43GOT","type":"totp","v":1}') - -Once created, you can inspect the object for it's configuration and key:: - - >>> otp.base32_key - 'GVDOQ7NP6XPJWE4CWCLFFSXZH6DTAZWM' - >>> otp.alg - "sha1" - >>> otp.period - 30 - -If you want a non-standard alg or period, you can specify it via the constructor. -You can also create TOTP instances from an existing key -(see the :class:`TOTP` constructor's ``key`` and ``format`` options for more details):: - - >>> otp2 = TOTP(new=True, period=60, alg="sha256") - >>> otp2.alg - 'sha256' - >>> otp2.period - 60 - - >>> otp3 = TOTP(key='GVDOQ7NP6XPJWE4CWCLFFSXZH6DTAZWM') - -Using a Factory ---------------- -Most applications will have some default configuration which they want -all TOTP instances to have. This includes application secrets (for encrypting -TOTP keys for storage), or setting a default issuer label (for rendering URIs). - -Instead of having to call the :class:`TOTP` constructor each time and provide -all these options, you can use the :meth:`TOTP.using` method. -This method takes in a number of the same options as the TOTP constructor, -and returns a :class:`TOTP` subclass which has these options pre-programmed -in as defaults:: - - >>> # here we create a TOTP factory with a random encryption secret and a default issuer - >>> from passlib.totp import TOTP, generate_secret - >>> TotpFactory = TOTP.using(issuer="myapp.example.org", secrets={"1": generate_secret()}) - -Since this object is a subclass of :class:`TOTP`, you can use all it's normal -methods. The difference is that it will integrate the information provided by using():: - - >>> totp = TotpFactory.new() - >>> totp.issuer - 'myapp.example.org' - - >>> totp.to_json() - '{"enckey":{"c":14,"k":"FLEQC3VO6SIT3T7GN2GIG6ONPXADG5CZ","s":"UL2J4MZG4SONHOWXLKFQ","t":"1","v":1},"type":"totp","v":1}' - -In typical usage, a server application will want to create a TotpFactory -as part of it's initialization, and then use that class for all operations, -instead of referencing :class:`TOTP` directly. - -.. rst-class:: float-center - -.. seealso:: - - * :ref:`totp-configuring-clients` for details about the ``issuer`` option - * :ref:`totp-storing-instances` for details about storage and key encryption - -.. _totp-configuring-clients: - -Configuring Clients -=================== -Once a TOTP instance & key has been generated on the server, -it needs to be transferred to the client TOTP program for installation. -This can be done by having the user manually type the key into their TOTP client, -but an easier method is to render the TOTP configuration to a URI stored in a QR Code. - -Rendering URIs --------------- -The `KeyUriFormat <https://github.com/google/google-authenticator/wiki/Key-Uri-Format>`_ -is a de facto standard for encoding TOTP keys & configuration -information into a string. Once the URI is rendered as a QR Code, -it can easily be imported into many smartphone clients (such as Authy and Google Authenticator) -via the smartphone's camera. - -When transferring the TOTP configuration this way, you will need to provide unique identifiers -for both your application, and the user's account. This allows TOTP clients to distinguish -this key from the others in it's database. This can be done via the ``issuer`` and ``label`` -parameters of the :meth:`TOTP.to_uri` method. - -The ``issuer`` string should be a globally unique label for your application -(e.g. it's domain name). Since the issuer string shouldn't change across users, -you can create a customized TOTP factory, and provide it with a default issuer. -*(If you skip this step, the issuer will need to be provided at every* -:meth:`TOTP.to_uri` *call)*:: - - >>> from passlib.totp import TOTP - >>> TotpFactory = TOTP.using(issuer="myapp.example.org") - -Once this is done, rendering to a provisioning URI just requires -picking a ``label`` for the URI. This label should identify the user -within your application (e.g. their login or their email):: - - >>> # assume an existing TOTP instance has been created - >>> totp = TotpFactory.new() - - >>> # serialize the object to a URI, along with label for user - >>> uri = totp.to_uri(label="demo-user") - >>> uri - 'otpauth://totp/demo-user?secret=GVDOQ7NP6XPJWE4CWCLFFSXZH6DTAZWM&issuer=myapp.example.org' - -Rendering QR Codes ------------------- -This URI can then be encoded as a QR Code, using various python & javascript qrcode libraries. -As an example, the following uses `PyQrCode <https://pypi.python.org/pypi/PyQRCode>`_ -to render the URI to the console as a text-based QR code:: - - >>> import pyqrcode - >>> uri = totp.to_uri(label="demo-user") - >>> print(pyqrcode.create(uri).terminal(quiet_zone=1)) - ... very large ascii-art qrcode here... - -As a fallback to the QR Code, it's recommended to alternately / also display -the key itself, so that users with camera-less TOTP clients can still enter it. -The :meth:`TOTP.pretty_key` method is provided to help with this:: - - >>> totp.pretty_key() - 'D6RZ-I4RO-AUQK-JNAW-QKYP-N7W7-LNV4-3GOT' - -Note that if you use a non-default ``alg``, ``digits``, or ``period`` values, -these should also be displayed next to the key. - -Parsing URIs ------------- -On the client side, passlib offers the :meth:`TOTP.from_uri` constructor creating -a TOTP object from a provisioning URI. This can also be useful for testing URI encoding & output -during development:: - - >>> # create new TOTP instance from a provisioning uri: - >>> from passlib.totp import TOTP - >>> totp = TOTP.from_uri('otpauth://totp/demo-user?secret=GVDOQ7NP6XPJWE4CWCLFFSXZH6DTAZWM&issuer=myapp.example.org') - >>> otp.base32_key - 'GVDOQ7NP6XPJWE4CWCLFFSXZH6DTAZWM' - >>> otp.alg - "sha1" - >>> otp.period - 30 - >>> otp.generate().token - '897453' - -.. _totp-storing-instances: - -Storing TOTP instances -====================== -Once a TOTP object has been created, it inevitably needs to be stored -in a database. Using :meth:`~TOTP.to_uri` to serialize it to a URI -has a few disadvantages - it always includes an issuer & a label -(wasting storage space), and it stores the key in an unencrypted format. - -JSON Serialization ------------------- -To help with this passlib offers a way to serialize TOTP objects to and from -a simple JSON format, which can optionally encrypt the keys for storage. - -To serialize a TOTP object to a string, use :meth:`TOTP.to_json`:: - - >>> from passlib.totp import TOTP - >>> totp = TOTP.new() - >>> data = totp.to_json() - >>> data - '{"key":"GVDOQ7NP6XPJWE4CWCLFFSXZH6DTAZWM","type":"totp","v":1}' - -This string can be stored in a database, and then deserialized as needed -using the :meth:`TOTP.from_json` constructor:: - - >>> totp2 = TOTP.from_json(data) - >>> totp2.base32_key - 'GVDOQ7NP6XPJWE4CWCLFFSXZH6DTAZWM' - -There are also corresponding :meth:`TOTP.to_dict` and :meth:`TOTP.from_dict` -methods for applications that want to serialize the object without converting -it all the way into a JSON string. - -.. rst-class:: float-center - -.. caution:: - - The above procedure should only be used for development purposes, - as it will NOT encrypt the keys; and the IETF **strongly recommends** - encrypting the keys for storage (`RFC-6238 sec 5.1 <https://tools.ietf.org/html/rfc6238#section-5.1>`_). - Encrypting the keys is covered below. - -.. _totp-encryption-setup: - -Application Secrets -------------------- -The one thing lacking about the example above is that the resulting -data contained the plaintext key. If the server were compromised, -the TOTP keys could be used directly to impersonate the user. -To solve this, Passlib offers a method for providing an application-wide -secret that :meth:`TOTP.to_json` will use to encrypt keys. - -Per :ref:`Step 1 <totp-walkthrough-step-1>` of the walkthrough (above), -applications can use the :func:`generate_secret` helper to create new secrets. -All existing secrets (the current one, and any deprecated / compromised ones) -should be assigned an identifying tag, and stored in a dict or file. - -Ideally, these secrets should be stored in a location which the application's process -does not have access to once it has been initialized. Once this data is loaded, -applications can create a factory function using :meth:`TOTP.using`, -and provide these secrets as part of it's arguments. -This can take the form of a file path, a loaded string, or a dictionary:: - - >>> # load from dict - >>> from passlib.totp import TOTP - >>> TotpFactory = TOTP.using(secrets={"1": "'pO7SwEFcUPvIDeAJr7INBj0TjsSZJr1d2ddsFL9r5eq'"}) - - >>> # load from filepath - >>> TotpFactory = TOTP.using(secrets_path="/path/to/secret/file") - -The ``secrets`` and ``secrets_path`` values can be anything accepted -by the :class:`AppWallet` constructor (the internal class that's -used to load & store the application secrets in memory). An instance -of this object is accessible for inspection from the :attr:`!TOTP.wallet` attribute -of each factory:: - - >>> TotpFactory.wallet - <passlib.totp.AppWallet at 0x2ba5310> - -Encrypting Keys ---------------- -Once you have a TOTP factory configured with one or more application secrets, -any objects you create through the factory will automatically have access -to the application secrets, and will use them to encrypt the key when -serializing to json. - -Assuming ``TotpFactory`` is set up from the previous step, -contrast the output of this with the plain JSON serialization example above:: - - >>> totp = TotpFactory.new() - >>> data = totp.to_json() - >>> data - '{"enckey":{"c":14,"k":"FLEQC3VO6SIT3T7GN2GIG6ONPXADG5CZ","s":"UL2J4MZG4SONHOWXLKFQ","t":"1","v":1},"type":"totp","v":1}' - -This data can be stored in the database like normal, but -will require access to the application secret in order to decrypt:: - - >>> data = '{"enckey":{"c":14,"k":"FLEQC3VO6SIT3T7GN2GIG6ONPXADG5CZ","s":"UL2J4MZG4SONHOWXLKFQ","t":"1","v":1},"type":"totp","v":1}' - >>> totp = TotpFactory.from_source(data) - >>> totp.base32_key - 'FLEQC3VO6SIT3T7GN2GIG6ONPXADG5CZ' - -Whereas trying to decode without a secret configured will result in:: - - >>> totp = TOTP.from_source(data) - ... - TypeError: no application secrets present, can't decrypt TOTP key - -Note that when loading TOTP objects this way, you can check the :attr:`TOTP.changed` -attr to see if the object needs to be re-serialized (e.g. deprecated secret, -too few encryption rounds, deprecated serialization format). - -Generating Tokens (Client-Side Only) -==================================== -Finally, the whole point of TOTP: generating and verifying tokens. -The TOTP protocol generates a new time & key -dependant token every <period> seconds (usually 30). - -Generating a totp token is done with the :meth:`TOTP.generate` method, -which returns a :class:`TotpToken` instance. This object looks and acts -like a tuple of ``(token, expire_time)``, but offers some additional -informational attributes:: - - >>> from passlib import totp - >>> otp = TOTP(key='GVDOQ7NP6XPJWE4CWCLFFSXZH6DTAZWM') - - >>> # generate a TOTP token for the current timestamp - >>> # (your output will vary based on system time) - >>> otp.generate() - <TotpToken token='589720' expire_time=1475342400> - - >>> # to get just the token, not the TotpToken instance... - >>> otp.generate().token - '359275' - - >>> # you can generate a token for a specific time as well... - >>> otp.generate(time=1475338840).token - '359275' - -.. rst-class:: float-right - -.. seealso:: - - For more details, see the :meth:`TOTP.generate` method. - -.. _totp-verifying: - -Verifying Tokens -================ -In order for successful authentication, the user must generate the token -on the client, and provide it to your server before the :attr:`TOTP.period` ends. - -Since this there will always be a little transmission delay (and sometimes -client clock drift) TOTP verification usually uses a small verification window, -allowing a user to enter a token a few seconds after the period has ended. -This window is usually kept as small as possible, and in passlib defaults to 30 seconds. - -Match & Verify --------------- -To verify a token a user has provided, you can use the :meth:`TOTP.match` method. -If unsuccessful, a :exc:`passlib.exc.TokenError` subclass will be raised. -If successful, this will return a :class:`TotpMatch` instance, with details about the match. -This object acts like a tuple of ``(counter, timestamp)``, but offers some additional -informational attributes:: - - >>> # NOTE: all of the following was done at a fixed time, to make these - >>> # examples repeatable. in real-world use, you would omit the 'time' parameter - >>> # from all these calls. - - >>> # assuming TOTP key & config was deserialized from database store - >>> from passlib import totp - >>> otp = TOTP(key='GVDOQ7NP6XPJWE4CWCLFFSXZH6DTAZWM') - - >>> # user provides malformed token: - >>> otp.match('359', time=1475338840) - ... - MalformedTokenError: Token must have exactly 6 digits - - >>> # user provides token that isn't valid w/in time window: - >>> otp.match('123456', time=1475338840) - ... - InvalidTokenError: Token did not match - - >>> # user provides correct token - >>> otp.match('359275', time=1475338840) - <TotpMatch counter=49177961 time=1475338840 cache_seconds=60> - -As a further optimization, the :meth:`TOTP.verify` method allows deserializing -and matching a token in a single step. Not only does this save a little code, -it has a signature much more similar to that of Passlib's :meth:`passlib.ifc.PasswordHash.verify`. - -Typically applications will provide the TOTP key in whatever format it's stored by the server. -This will usually be a JSON string (as output by :meth:`TOTP.to_json`), but can be any -format accepted by :meth:`TOTP.from_source`. -As an example:: - - >>> # application loads json-serialized TOTP key - >>> from passlib.totp import TOTP - >>> totp_source = '{"v": 1, "type": "totp", "key": "otxl2f5cctbprpzx"}' - - >>> # parse & match the token in a single call - >>> match = TOTP.verify('123456', totp_source) - -.. rst-class:: float-right - -.. seealso:: - - For more details, see the :meth:`TOTP.match` and :meth:`TOTP.verify` methods. - -.. _totp-reuse-warning: - -Preventing Token Reuse ----------------------- -Even if an attacker is able to observe a user entering a TOTP token, -it will do them no good once ``period + window`` seconds have passed (typically 60). -This is because the current time will now have advanced far enough that -:meth:`!TOTP.match` will *never* match against the stolen token. - -However, this leaves a small window in which the attacker can observe and replay -a token, successfully impersonating the user. -To prevent this, applications are strongly encouraged to record the -latest :attr:`TotpMatch.counter` value that's returned by the :meth:`!TOTP.match` method. - -This value should be stored per-user in a temporary cache for at least -``period + window`` seconds. (This is typically 60 seconds, but for an exact value, -applications may check the :attr:`TotpMatch.cache_seconds` value returned by -the :meth:`!TOTP.match` method). - -Any subsequent calls to verify should check this cache, -and pass in that value to :meth:`!TOTP.match`'s "last_counter" parameter -(or ``None`` if no value found). Doing so will ensure that tokens -can only be used once, preventing replay attacks. - -As an example:: - - >>> # NOTE: all of the following was done at a fixed time, to make these - >>> # examples repeatable. in real-world use, you would omit the 'time' parameter - >>> # from all these calls. - - >>> # assuming TOTP key & config was deserialized from database store - >>> from passlib.totp import TOTP - >>> otp = TOTP(key='GVDOQ7NP6XPJWE4CWCLFFSXZH6DTAZWM') - - >>> # retrieve per-user counter from cache - >>> last_counter = ...consult application cache... - - >>> # if user provides valid value, a TotpMatch object will be returned. - >>> # (if they provide an invalid value, a TokenError will be raised). - >>> match = otp.match('359275', last_counter=last_counter, time=1475338830) - >>> match.counter - 49177961 - >>> match.cache_seconds - 60 - - >>> # application should now cache the new 'match.counter' value - >>> # for at least 'match.cache_seconds'. - - >>> # now that last_counter has been properly updated: say that - >>> # 10 seconds later attacker attempts to re-use token user just entered: - >>> last_counter = 49177961 - >>> match = otp.match('359275', last_counter=last_counter, time=1475338840) - ... - UsedTokenError: Token has already been used, please wait for another. - -.. rst-class:: float-right - -.. seealso:: - - For more details, see the :meth:`TOTP.match` method; - for more examples, see Step 6 above. - -.. _totp-rate-limiting: - -Why Rate-Limiting is Critical ------------------------------ - -The :meth:`TOTP.match` method offers a ``window`` -parameter, expanding the search range to account for the client getting -slightly out of sync. - -While it's tempting to be user-friendly, and make this window as large as possible, -there is a security downside: Since any token within the window will be -treated as valid, the larger you make the window, the more likely it is -that an attacker will be able to guess the correct token by random luck. - -Because of this, **it's critical for applications implementing OTP to rate-limit -the number of attempts on an account**, since an unlimited number of attempts -guarantees an attacker will be able to guess any given token. - -**The Gory Details** - -For TOTP, the formula is ``odds = guesses * (1 + 2 * window / period) / 10**digits``; -where ``window`` in this case is the :meth:`TOTP.match` window (measured in seconds), -and ``period`` is the number of seconds before the token is rotated. - -This formula can be inverted to give the maximum window we want to allow -for a given configuration, rate limit, and desired odds: -``max_window = floor((odds * 10**digits / guesses - 1) * period / 2)``. - -For example (assuming TOTP with 7 digits and 30 second period), -if you want an attacker's odds to be no better than 1 in 10000, -and plan to lock an account after 4 failed attempts -- -the maximum window you should use would be -``floor((1/10000 * 10**6 / 4 - 1) * 30 / 2)`` or 360 seconds. - -.. - xxx: The above formulas are not accurate for 10 digit tokens, since the 10th - digit takes on fewer values -- subtitute ``3e9`` instead of ``10**digits`` - in this case. |
