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/narr | |
| 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/narr')
| -rw-r--r-- | docs/narr/context-tutorial.rst | 554 | ||||
| -rw-r--r-- | docs/narr/hash-tutorial.rst | 310 | ||||
| -rw-r--r-- | docs/narr/index.rst | 30 | ||||
| -rw-r--r-- | docs/narr/overview.rst | 92 | ||||
| -rw-r--r-- | docs/narr/quickstart.rst | 297 | ||||
| -rw-r--r-- | docs/narr/totp-tutorial.rst | 772 |
6 files changed, 2055 insertions, 0 deletions
diff --git a/docs/narr/context-tutorial.rst b/docs/narr/context-tutorial.rst new file mode 100644 index 0000000..718f031 --- /dev/null +++ b/docs/narr/context-tutorial.rst @@ -0,0 +1,554 @@ +.. index:: CryptContext; overview + +.. _context-tutorial: + +.. currentmodule:: passlib.context + +=============================================== +:class:`~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. + +.. rst-class:: float-center + +.. 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 + +Walkthrough Outline +=================== +* `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 collection 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 </lib/passlib.hash.sha256_crypt>`, +:doc:`md5_crypt </lib/passlib.hash.md5_crypt>`, and +:doc:`des_crypt </lib/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 </lib/passlib.hash.sha256_crypt>` +algorithm supports a ``rounds`` parameter which defaults to 80000, +and the :class:`ldap_salted_md5 </lib/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. + +Undocumented Features +===================== + +.. todo:: Document usage of the :ref:`harden_verify <context-harden-verify-option>` option. +.. todo:: Document usage of the :ref:`context-disabled-hashes` options. + +.. rst-class:: html-toggle + +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/narr/hash-tutorial.rst b/docs/narr/hash-tutorial.rst new file mode 100644 index 0000000..2407e63 --- /dev/null +++ b/docs/narr/hash-tutorial.rst @@ -0,0 +1,310 @@ +.. index:: + single: PasswordHash interface + single: custom hash handler; requirements + +.. _hash-tutorial: + +.. currentmodule:: passlib.ifc + +=========================================== +:class:`~passlib.ifc.PasswordHash` Tutorial +=========================================== + +Overview +======== +Passlib supports a large number of hash algorithms, +all of which can be imported from the :mod:`passlib.hash` module. +While the exact options and behavior will vary between each algorithm, +all of the hashes provided by Passlib use the same interface, +defined by the :class:`passlib.ifc.PasswordHash` abstract class. + +The :class:`!PasswordHash` class provides a generic interface for interacting +individually with the various hashing algorithms. +It offers methods and attributes for a number of use-cases, +which fall into three general categories: + + * Creating & verifying hashes + + * Examining the configuration of a hasher, + and customizing the defaults. + + * Assorting supplementary methods. + +.. seealso:: + + * :mod:`passlib.ifc` -- API reference of all the methods and attributes + of the :class:`!PasswordHash` class. + + * :ref:`passlib.context.CryptContext <context-tutorial>` -- + For working with multiple hash formats at once + (such a user account table with multiple existing hash formats). + +.. _hash-verifying: +.. _password-hash-examples: + +Hashing & Verifying +=================== +.. rst-class:: float-right without-title + +.. caution:: + + **Changed in 1.7:** + + This section has changed under Passlib 1.7. Prior releases used + :meth:`PasswordHash.encrypt`, which has now been renamed + to :meth:`PasswordHash.hash`. A legacy alias is present in 1.7, + but will be removed in Passlib 2.0. + +While all the hashers in :mod:`passlib.hash` offer a range of methods and attributes, +the main activities applications will need to perform is hashing and verifying passwords. + +This can be done with the :meth:`PasswordHash.hash` and :meth:`PasswordHash.verify` methods. + +Hashing +------- +First, import the desired hash. The following example uses the :class:`~passlib.hash.pbkdf2_sha256` class +(which derives from :class:`!PasswordHash`):: + + >>> # import the desired hasher + >>> from passlib.hash import pbkdf2_sha256 + +Use :meth:`PasswordHash.hash` to hash a password. It takes care of unicode encoding, +picking default rounds values:: + + >>> hash = pbkdf2_sha256.hash("password") + >>> hash + '$pbkdf2-sha256$29000$9t7be09prfXee2/NOUeotQ$Y.RDnnq8vsezSZSKy1QNy6xhKPdoBIwc.0XDdRm9sJ8' + +Note that each call generates a new salt, and thus the contents of the resulting +hash will differ, despite using the same password:: + + >>> hash2 = pbkdf2_sha256.hash("password") + >>> hash2 + '$pbkdf2-sha256$29000$V0rJeS.FcO4dw/h/D6E0Bg$FyLs7omUppxzXkARJQSl.ozcEOhgp3tNgNsKIAhKmp8' + ^^^^^^^^^^^^^^^^^^^^^^ + +Verifying +--------- +Subsequently, you can call :meth:`PasswordHash.verify` to check user input +against an existing hash:: + + >>> pbkdf2_sha256.verify("password", hash) + True + + >>> pbkdf2_sha256.verify("joshua", hash) + False + +.. _hash-unicode-behavior: + +Unicode & non-ASCII Characters +------------------------------ +Sidenote regarding unicode passwords & non-ASCII characters: + +For the majority of hash algorithms and use-cases, passwords should +be provided as either :class:`!unicode` (or ``utf-8``-encoded :class:`!bytes`). + +One major exception legacy hashes that were generated +using a different character encoding. In this case, passwords should be +encoded using the correct encoding before they are passed to :meth:`!verify`; +otherwise users may not be able to log in successfully. + +.. _hash-configuring: + +Customizing the Configuration +============================= +.. rst-class:: float-right without-title + +.. caution:: + + **Changed in 1.7:** + + This section has changed under Passlib 1.7. Prior releases required you + to pass configuration options to each call of :meth:`PasswordHash.hash` + That pattern is deprecated, and will be removed in Passlib 2.0; + code should be switched to use :meth:`PasswordHash.using`... + +Each hasher contains a number of :ref:`informational attributes <informational-attributes>`, +many of which can be customized to change the properties of the hashes +generated by :meth:`PasswordHash.hash`. + +Instead of modifying the hasher class directly, or having to pass in +the options to each call to :meth:`!PasswordHash.hash`, +all the hashes offer a :meth:`PasswordHash.using` method. + +This is a powerful method which accepts most hash informational attributes, +as well as some other hash-specific configuration keywords; and returns +a subclass of the original hasher (or an equivalent workalike). This object +inherits the defaults from it's parent, but integrates any values you +choose to override. + +As an example, if the hasher you select supports a variable number of iterations +(such as :class:`~passlib.hash.pbkdf2_sha256`), you can specify a custom value +using the ``rounds`` keyword. + +Here, the default class uses 29000 rounds:: + + >>> from passlib.hash import pbkdf2_sha256 + + >>> pbkdf2_sha256.default_rounds + 29000 + + >>> pbkdf2_sha256.hash("password") + '$pbkdf2-sha256$29000$V0rJeS.FcO4dw/h/D6E0Bg$FyLs7omUppxzXkARJQSl.ozcEOhgp3tNgNsKIAhKmp8' + ^^^^^ + +But if we call :meth:`PasswordHash.using`, we can override this value:: + + >>> custom_pbkdf2 = pbkdf2_sha256.using(rounds=123456) + >>> custom_pbkdf2.default_rounds + 123456 + + >>> custom_pbkdf2.hash("password") + '$pbkdf2-sha256$123456$QwjBmJPSOsf4HyNE6L239g$8m1pnP69EYeOiKKb5sNSiYw9M8pJMyeW.CSm0KKO.GI' + ^^^^^^ + +While hashes frequently have additional keywords supported by using, +the basic set of settings you can customize can be found by inspecting +the :attr:`PasswordHash.setting_kwds` attribute:: + + >>> pbkdf2_sha256.settings_kwds + ("salt", "salt_size", "rounds") + +This method is additionally used internally by the :ref:`CryptContext <context-tutorial>` +class it order to create a custom hasher configured based on the CryptContext policy +it was provided. + +.. seealso:: + + * :meth:`PasswordHash.using` -- API reference + +Context Keywords +================ +While the :meth:`PasswordHash.hash` example above works for most hashes, +a small number of algorithms require you provide external data +(such as a username) every time a hash is calculated. + +An example of this is the :class:`~passlib.hash.oracle10` hash, +where hashing requires a username:: + + >>> from passlib.hash import oracle10 + >>> hash = oracle10.hash("secret", user="admin") + 'B858CE295C95193F' + +The difference between this and specifying something like a rounds setting +(see :ref:`hash-configuring` above) is that a configuration option +only needs to be specified once, and is then encoded into the hash string itself... +Whereas a context keyword represents something that isn't stored in the hash string, +and needs to be specified every time you call :meth:`PasswordHash.hash` **or** +:meth:`PasswordHash.verify`:: + + >>> oracle10.verify("secret", hash, user="admin") + True + +In this example, if either the username OR password is wrong, +verify() will fail:: + + >>> oracle10.verify("secret", hash, user="wronguser") + False + + >>> oracle10.verify("wrongpassword", hash, user="admin") + False + +Forgetting to include a context keywords when it's required will cause a TypeError:: + + >>> hash = oracle10.hash("password") + Traceback (most recent call last): + <traceback omitted> + TypeError: user must be unicode or bytes, not None + +Whether a hash requires external parameters (such as ``user``) +can be determined from its documentation page; but also programmatically from +its :attr:`PasswordHash.context_kwds` attribute:: + + >>> oracle10.context_kwds + ("user",) + + >>> pbkdf2_sha256.context_kwds + () + +Identifying Hashes +================== +One of the rarer use-cases is the need to identify whether a string +recognizably belongs to a given hasher class. This can be important +in some cases, because attempting to call :meth:`PasswordHash.verify` +with another algorithm's hash will result in a ValueError:: + + >>> from passlib.hash import pbkdf2_sha256, md5_crypt + + >>> other_hash = md5_crypt.hash("password") + + >>> pbkdf2_sha256.verify("password", other_hash) + Traceback (most recent call last): + <traceback omitted> + ValueError: not a valid pbkdf2_sha256 hash + +This can be prevented by using the identify method, +which determines whether a hash belongs to a given algorithm:: + + >>> hash = pbkdf2_sha256.hash("password") + >>> pbkdf2_sha256.identify(hash) + True + + >>> pbkdf2_sha256.identify(other_hash) + False + +Note that most cases where an application will need to use this to +sort out multiple hash formats, it will be more useful to switch to +a :ref:`CryptContext <context-tutorial>` object, which handles this +(and many similar tasks) automatically. + +.. todo:: + + Document usage of :meth:`PasswordHash.needs_update`, + and how it ties into :meth:`PasswordHash.using`. + +.. index:: rounds; choosing the right value + +.. _rounds-selection-guidelines: + +Choosing the right rounds value +=============================== +For hash algorithms with a variable time-cost, +Passlib's :attr:`PasswordHash.default_rounds` values attempt to be secure enough for +the average [#avgsys]_ system. But the "right" value for a given hash +is dependant on the server, its cpu, its expected load, and its users. +Since larger values mean increased work for an attacker... + +.. centered:: + The right ``rounds`` value for a given hash & server should be the largest + possible value that doesn't cause intolerable delay for your users. + +For most public facing services, you can generally have signin +take upwards of 250ms - 400ms before users start getting annoyed. +For superuser accounts, it should take as much time as the admin can stand +(usually ~4x more delay than a regular account). + +Passlib's :attr:`!default_rounds` values are retuned periodically, +starting with a rough estimate of what an "average" system is capable of, +and then setting all :samp:`{hash}.default_rounds` values to take ~300ms on such a system. +However, some older algorithms (e.g. :class:`~passlib.hash.bsdi_crypt`) are weak enough that +a tradeoff must be made, choosing "more secure but intolerably slow" over "fast but unacceptably insecure". + +For this reason, it is strongly recommended to not use a value much lower than Passlib's default, +and to use one of :ref:`recommended hashes <recommended-hashes>`, as one of their chief qualifying +features is the mere *existence* of rounds values which take a short enough amount of time, +and yet are still considered secure. + +.. todo:: + + Expand this section into a full document, including + information from the following posts: + + * http://stackoverflow.com/questions/13545677/python-passlib-what-is-the-best-value-for-rounds + * http://stackoverflow.com/questions/11829602/pbkdf2-and-hash-comparison + + As well as maybe JS-interactive calculation helper. + + +.. [#avgsys] For Passlib 1.6.3, all hashes were retuned to take ~300ms on a + system with a 3.0 ghz 64 bit CPU. + diff --git a/docs/narr/index.rst b/docs/narr/index.rst new file mode 100644 index 0000000..1c5bb0e --- /dev/null +++ b/docs/narr/index.rst @@ -0,0 +1,30 @@ +======================= +Walkthrough & Tutorials +======================= + +.. + xxx: 'introductory materials' etc aren't proper sections + so that sphinx TOC in sidebar will show all walkthroughs + no matter which of them user is currently in + +**Introductory Materials** + + .. rst-class:: html-highlight-pages space-pages + + .. toctree:: + :maxdepth: 2 + + /install + overview + quickstart + +**Tutorials** + + .. rst-class:: html-highlight-pages space-pages + + .. toctree:: + :maxdepth: 2 + + hash-tutorial + context-tutorial + totp-tutorial diff --git a/docs/narr/overview.rst b/docs/narr/overview.rst new file mode 100644 index 0000000..6aa73ec --- /dev/null +++ b/docs/narr/overview.rst @@ -0,0 +1,92 @@ +================ +Library Overview +================ + +Passlib is a collection of routines for managing password hashes +such as found in unix "shadow" files, as returned by stdlib's :func:`crypt.crypt`, +as stored in mysql and postgres, and various other places. +Passlib's contents can be roughly grouped into four categories: +password hashes, password contexts, two-factor authentication, +and other utility functions. + +Password Hashes +=============== +All of the hashes supported by Passlib are implemented +as "hasher" classes which can be imported from the :mod:`passlib.hash` module. +In turn, all of the hashers have a uniform interface, +which is documented in the :ref:`hash-tutorial`. + +*A word of warning:* the hashes in this library marked as "insecure" +are provided for historical purposes only. Still others are specialized in ways that are not generally useful. +If you are creating a new application and need to choose a password hash, +see the :doc:`quickstart`. + +.. rst-class:: float-center + +.. seealso:: + + - :ref:`hash-tutorial` -- walkthrough of using a hasher class. + - :doc:`quickstart` -- if you need to choose a hash. + - :mod:`passlib.ifc` -- PasswordHash API reference + - :mod:`passlib.hash` -- list of all hashes in Passlib. + +Password Contexts +================= +Mature applications frequently have to deal with tables of existing password hashes. +Over time, they have to support a number of tasks: + +* Add support for new algorithms, and deprecate old ones. +* Raise the time-cost settings for existing algorithms as computing power increases. +* Perform rolling upgrades of existing hashes to comply with these changes. +* Eventually, these policies must be hardcoded in the source, + or time must be spent implementing a configuration language to encode them. + +In these situations, loading and handling multiple hash algorithms becomes +complicated and tedious. The :mod:`passlib.context` module provides a single class, +:class:`!CryptContext`, which attempts to solve all of these problems... +or at least relieve applications developers of (most of) the burden. + +This class handles managing multiple password hash schemes, +deprecation & migration of old hashes, and supports a simple configuration +language that can be serialized to an INI file. + +.. rst-class:: float-center + +.. seealso:: + + * :ref:`context-tutorial` -- walkthrough of the CryptContext class + * :mod:`passlib.context` -- API reference + +Two-Factor Authentication +========================= +While not strictly connected to password hashing, modern applications frequently +need to perform the related task of two-factor authentication. One of the most +common protocols for doing this is TOTP (:rfc:`6238`). +To help get TOTP in place, the :mod:`passlib.totp` module provides a set of helper functions +for securely configuring, persisting, and verifying TOTP tokens. + +.. rst-class:: float-center + +.. seealso:: + + * :ref:`TOTP tutorial <totp-tutorial>` -- walkthrough of setting up TOTP integration + * :mod:`passlib.totp` -- API reference + +Application Helpers +=================== +Passlib also provides a number of pre-configured :class:`!CryptContext` instances +in order to get users started quickly: + + * :mod:`passlib.apps` -- contains pre-configured + instances for managing hashes used by Postgres, Mysql, and LDAP, and others. + + * :mod:`passlib.hosts` -- contains pre-configured + instances for managing hashes as found in the /etc/shadow files + on Linux and BSD systems. + +Passlib also contains a couple of additional modules which provide +support for certain application-specific tasks: + + * :mod:`passlib.apache` -- classes for managing htpasswd and htdigest files. + + * :mod:`passlib.ext.django` -- Django plugin which monkeypatches support for (almost) any hash in Passlib. diff --git a/docs/narr/quickstart.rst b/docs/narr/quickstart.rst new file mode 100644 index 0000000..8e2570e --- /dev/null +++ b/docs/narr/quickstart.rst @@ -0,0 +1,297 @@ +================================ +New Application Quickstart Guide +================================ + +Need to quickly get password hash support added into your new application, +and don't have time to wade through pages of documentation, +comparing and contrasting all the different schemes? Read on... + +.. + NOTE: commented this out for now, considering deprecating + the "custom_app_context", since it's hard to convey policy changes to users. + May reenable if decide this is still good route to go. + + Really Quick Start + ================== + The fastest route is to use the preconfigured + :data:`~passlib.apps.custom_app_context` object. + It supports the :class:`~passlib.hash.sha256_crypt` + and :class:`~passlib.hash.sha512_crypt` schemes, + and defaults to 40000 hash iterations for increased strength. + For applications which want to quickly add password hashing, + all they need to do is the following:: + + >>> # import the context under an app-specific name (so it can easily be replaced later) + >>> from passlib.apps import custom_app_context as pwd_context + + >>> # encrypting a password... + >>> hash = pwd_context.hash("somepass") + + >>> # verifying a password... + >>> ok = pwd_context.verify("somepass", hash) + + >>> # [optional] encrypting a password for an admin account... + >>> # the custom_app_context is preconfigured so that + >>> # if the category is set to "admin" instead of None, + >>> # it uses a stronger setting of 80000 rounds: + >>> hash = pwd_context.hash("somepass", category="admin") + + For applications which started using this preset, but whose needs + have grown beyond it, it is recommended to create your own :mod:`CryptContext <passlib.context>` + instance; see below for more... + +.. index:: Passlib; recommended hash algorithms + +.. _recommended-hashes: +.. rst-class:: toc-always-open + +Choosing a Hash +================ + +If you'd like to set up a configuration that's right for your +application, the first thing to do is choose a password hashing scheme. +Passlib contains a large number of schemes, but most of them +should only be used when a specific format is explicitly required. + +.. rst-class:: float-center without-title + +.. seealso:: + + If you already know what hash algorithm(s) you want to use, + skip to the next section: `Creating and Using a CryptContext`_. + +The Options +----------- +There are currently four good choices [#choices]_ for secure hashing: + + * :class:`~passlib.hash.argon2` + * :class:`~passlib.hash.bcrypt` + * :class:`~passlib.hash.pbkdf2_sha256` / :class:`~passlib.hash.pbkdf2_sha512` + * :class:`~passlib.hash.sha256_crypt` / :class:`~passlib.hash.sha512_crypt` + +All four hashes share the following properties: + + * No known vulnerabilities. + * Based on documented & widely reviewed algorithms. + * Public-domain or BSD-licensed reference implementations available. + * variable rounds for configuring flexible cpu cost on a per-hash basis. + * At least 96 bits of salt. + * Basic algorithm has seen heavy scrutiny and use for at least 10 years + *(except for Argon2, born around 2013)*. + * In use across a number of OSes and/or a wide variety of applications. + +While Argon2 is much younger than the others, it has seen heavy scrutiny, +and was purpose-designed for password hashing. In the near future, it stands likely to +become *the* recommended standard. + +.. rst-class:: html-toggle + +Detailed Comparison of Choices +------------------------------ + +Argon2 +...... +:class:`~passlib.hash.argon2` is the newest of the four recommended hashes. +It was selected as the winner of the `2013 Password Hashing Competition <https://password-hashing.net/>`_, +and draws on the design and lessons from BCrypt, PBKDF2, and SCrypt. Despite +being much newer than the others, it has seen heavy scrutiny. Since the Argon2 project +had the foresight to provide not just a reference implementation, but a standard +hash encoding format, these hashes should be reliably interoperatable across all implementations. + +*Issues:* In it's default configuration, Argon2 uses more memory than the other hashes. +However, this is one of it's hallmarks as a "memory hard" hashing algorithm, and contributes to it's security. +Furthermore the exact amount used is configurable. It's only main drawback is that as of 2016-6-20 +it's only 3 years old. It's seen only a few minor adjustments since 2013, +but as it is just now gaining widespread use, the next few years are the period in which it will +likely either prove itself, or be found wanting. It's for this reason, +any cryptographic algorithm less than a decade old is generally considered "young" :) + +BCrypt +...... +:class:`~passlib.hash.bcrypt` +is `based <http://www.usenix.org/event/usenix99/provos/provos_html/>`_ +on the well-tested Blowfish cipher. In use since 1999, +it's the default hash on all BSD variants. If you want your application's +hashes to be readable by the native BSD crypt() function, this is the hash to use. +There is also an alternative LDAP-formatted version +(:class:`~passlib.hash.ldap_bcrypt`) available. + +*Issues:* Neither the original Blowfish, +nor the modified version which BCrypt uses, have been NIST approved; +this matter of concern is what motivated the development of SHA512-Crypt. +As well, its rounds parameter is logarithmically scaled, +making it hard to fine-tune the amount of time taken to verify passwords; +which can be an issue for applications that handle a large number +of simultaneous logon attempts (e.g. web apps). Finally, BCrypt only hashes +the first 72 characters of a password, and will silently truncate longer ones +(Passlib's non-standard :class:`~passlib.hash.bcrypt_sha256` works around this last issue). + +PBKDF2 +...... +:class:`~passlib.hash.pbkdf2_sha512` is a custom hash format designed for Passlib. +However, it directly uses the +`PBKDF2 <http://tools.ietf.org/html/rfc2898#section-5.2>`_ +key derivation function, which was standardized in 2000, and found across a +`wide variety <http://en.wikipedia.org/wiki/PBKDF2#Systems_that_use_PBKDF2>`_ +of applications and platforms. Unlike the previous two hashes, +PBKDF2 has a simple and portable design, +which is resistant (but not immune) to collision and preimage attacks +on the underlying message digest. +There is also :class:`~passlib.hash.pbkdf2_sha256`, which may be faster +on 32 bit processors; as well as LDAP-formatted versions of these ( +:class:`~passlib.hash.ldap_pbkdf2_sha512` and +:class:`~passlib.hash.ldap_pbkdf2_sha256`). + +*Issues:* PBKDF2 has no major security or portability issues, +and compares favorably against bcrypt. However, bcrypt has proven slightly +more resistant to modern GPU-based cracking techniques. + +SHA512-Crypt +............ +:class:`~passlib.hash.sha512_crypt` is +based on the well-tested :class:`~passlib.hash.md5_crypt` +algorithm. In use since 2008, it's the default hash on most Linux systems; +its direct ancestor :class:`!md5_crypt` has been in use since 1994 on most Unix systems. +If you want your application's hashes to be readable by the +native Linux crypt() function, this is the hash to use. +There is also :class:`~passlib.hash.sha256_crypt`, which may be faster +on 32 bit processors; as well as LDAP-formatted versions of these ( +:class:`~passlib.hash.ldap_sha512_crypt` and +:class:`~passlib.hash.ldap_sha256_crypt`). + +*Issues:* Like :class:`~passlib.hash.md5_crypt`, its algorithm +composes the underlying message digest hash in a baroque +and somewhat arbitrary set of combinations. +So far this "kitchen sink" design has been successful in its +primary purpose: to prevent any attempts to create an optimized +version for use in a pre-computed or brute-force search. +However, this design also hampers analysis of the algorithm +for future flaws. + +While this algorithm is still considered secure, it has fallen out of favor +in comparison to bcrypt & pbkdf2, due to it's non-standard construction. + +Furthermore, when compared to Argon2 and BCrypt, +SHA512-Crypt and PBKDF2 have proven more susceptible to cracking using modern GPU-based techniques. + +.. index:: Google App Engine; recommended hash algorithm + +:class:`~passlib.hash.sha512_crypt` is probably the best choice for Google App Engine, +as Google's production servers appear to provide native support +via :mod:`crypt`, which will be used by Passlib. + +.. note:: + + References to this algorithm are frequently confused with a raw SHA-512 hash. + While :class:`!sha512_crypt` uses the SHA-512 hash as a cryptographic primitive, + the algorithm's resulting password hash is far more secure. + +Making a Decision +----------------- +For new applications, this decision comes down to a couple of questions: + +1. Does the hash need to be natively supported by your operating system's :func:`!crypt` api, + in order to allow inter-operation with third-party applications on the host? + + * If yes, the right choice is either :class:`~passlib.hash.bcrypt` for BSD variants, + or :class:`~passlib.hash.sha512_crypt` for Linux; since these are natively supported. + + * If no, continue... + +2. Does your hosting provider allow you to install C extensions? + + * If no, you probably want to use :class:`~passlib.hash.pbkdf2_sha256`, + as this currently has the fastest pure-python backend. + + * If they allow C extensions, continue... + +3. Do you want to use the latest & greatest, and don't mind increased memory usage + when hashing? + + * :class:`~passlib.hash.argon2` is a next-generation hashing algorithm, + attempting to become the new standard. It's design has been being slightly tweaked + since 2013, but will quite likely become *the* standard in the next few years. + You'll need to install the `argon2_cffi <https://pypi.python.org/pypi/argon2_cffi>`_ + support library. + + * If you want something secure, but more battle tested, continue... + +4. The top choices left are :class:`~passlib.hash.bcrypt` and :class:`~passlib.hash.pbkdf2_sha256`. + + Both have advantages, and their respective rough edges; + though currently the balance is in favor of bcrypt + (pbkdf2 can be cracked somewhat more efficiently). + + * If choosing bcrypt, we strongly recommend installing the `bcrypt <https://pypi.python.org/pypi/bcrypt>`_ + support library on non-BSD operating systems. + + * If choosing pbkdf2, especially on python2 < 2.7.8 and python 3 < 3.4, + you will probably want to install `fastpbk2 <https://pypi.python.org/pypi/fastpbkdf2>`_ + support library. + +Creating and Using a CryptContext +================================= +Once you've chosen what password hash(es) you want to use, +the next step is to define a :class:`~passlib.context.CryptContext` object +to manage your hashes and related policy configuration. +Insert the following code into your application:: + + # + # import the CryptContext class, used to handle all hashing... + # + from passlib.context import CryptContext + + # + # create a single global instance for your app... + # + pwd_context = CryptContext( + # Replace this list with the hash(es) you wish to support. + # this example sets pbkdf2_sha256 as the default, + # with additional support for reading legacy des_crypt hashes. + schemes=["pbkdf2_sha256", "des_crypt"], + + # Automatically mark all but first hasher in list as deprecated. + # (this will be the default in Passlib 2.0) + deprecated="auto", + + # Optionally, set the number of rounds that should be used. + # Appropriate values may vary for different schemes, + # and the amount of time you wish it to take. + # Leaving this alone is usually safe, and will use passlib's defaults. + ## pbkdf2_sha256__rounds = 29000, + ) + +To start using your CryptContext, import the context you created wherever it's needed:: + + >>> # import context from where you defined it... + >>> from myapp.model.security import pwd_context + + >>> # encrypting a password... + >>> hash = pwd_context.hash("somepass") + >>> hash + '$pbkdf2-sha256$29000$BSBkLEXIeS9FKMW4F.I85w$SJMzqVU7fw49NDOJZHt2o9vKIfDUVM4cKlAD4MxIgD0' + + >>> # verifying a password... + >>> pwd_context.verify("somepass", hash) + True + >>> pwd_context.verify("wrongpass", hash) + False + +There's many more features packed into the context objects, read +the walkthrough for more... + +.. rst-class:: float-center + +.. seealso:: + + * :ref:`context-tutorial` -- full details of using the CryptContext class + * :mod:`passlib.context` -- CryptContext API reference + * :mod:`passlib.hash` -- list of all hashes supported by Passlib. + +.. rubric:: Footnotes + +.. [#choices] As of June 2016, the most commonly used password hashes are BCrypt and PBKDF2, + followed by SHA512-Crypt, with Argon2 rapidly moving up the ranks. + You should make sure you are reading a current + copy of the Passlib documentation, in case the state + of things has changed. diff --git a/docs/narr/totp-tutorial.rst b/docs/narr/totp-tutorial.rst new file mode 100644 index 0000000..f299d1d --- /dev/null +++ b/docs/narr/totp-tutorial.rst @@ -0,0 +1,772 @@ +.. index:: TOTP; overview +.. index:: TOTP; usage examples +.. _totp-tutorial: + +.. currentmodule:: passlib.totp + +==================================== +:class:`~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. |
