passlib 1.9.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. passlib/__init__.py +3 -0
  2. passlib/_data/wordsets/bip39.txt +2049 -0
  3. passlib/_data/wordsets/eff_long.txt +7776 -0
  4. passlib/_data/wordsets/eff_prefixed.txt +1296 -0
  5. passlib/_data/wordsets/eff_short.txt +1296 -0
  6. passlib/_logging.py +3 -0
  7. passlib/_protocols.py +33 -0
  8. passlib/apache.py +1106 -0
  9. passlib/apps.py +215 -0
  10. passlib/context.py +1944 -0
  11. passlib/crypto/__init__.py +1 -0
  12. passlib/crypto/_blowfish/__init__.py +153 -0
  13. passlib/crypto/_blowfish/_gen_files.py +238 -0
  14. passlib/crypto/_blowfish/base.py +1212 -0
  15. passlib/crypto/_blowfish/unrolled.py +1664 -0
  16. passlib/crypto/_md4.py +229 -0
  17. passlib/crypto/des.py +2250 -0
  18. passlib/crypto/digest.py +760 -0
  19. passlib/crypto/scrypt/__init__.py +273 -0
  20. passlib/crypto/scrypt/_builtin.py +220 -0
  21. passlib/crypto/scrypt/_gen_files.py +142 -0
  22. passlib/crypto/scrypt/_salsa.py +180 -0
  23. passlib/exc.py +409 -0
  24. passlib/ext/__init__.py +1 -0
  25. passlib/ext/django/__init__.py +6 -0
  26. passlib/ext/django/models.py +21 -0
  27. passlib/ext/django/utils.py +1181 -0
  28. passlib/handlers/__init__.py +1 -0
  29. passlib/handlers/argon2.py +999 -0
  30. passlib/handlers/bcrypt.py +996 -0
  31. passlib/handlers/cisco.py +396 -0
  32. passlib/handlers/des_crypt.py +504 -0
  33. passlib/handlers/digests.py +149 -0
  34. passlib/handlers/django.py +510 -0
  35. passlib/handlers/fshp.py +185 -0
  36. passlib/handlers/ldap_digests.py +356 -0
  37. passlib/handlers/md5_crypt.py +286 -0
  38. passlib/handlers/misc.py +201 -0
  39. passlib/handlers/mssql.py +217 -0
  40. passlib/handlers/mysql.py +92 -0
  41. passlib/handlers/oracle.py +137 -0
  42. passlib/handlers/pbkdf2.py +454 -0
  43. passlib/handlers/phpass.py +110 -0
  44. passlib/handlers/postgres.py +34 -0
  45. passlib/handlers/roundup.py +18 -0
  46. passlib/handlers/scram.py +532 -0
  47. passlib/handlers/scrypt.py +357 -0
  48. passlib/handlers/sha1_crypt.py +121 -0
  49. passlib/handlers/sha2_crypt.py +562 -0
  50. passlib/handlers/sun_md5_crypt.py +334 -0
  51. passlib/handlers/windows.py +299 -0
  52. passlib/hash.py +106 -0
  53. passlib/hosts.py +85 -0
  54. passlib/ifc.py +307 -0
  55. passlib/pwd.py +709 -0
  56. passlib/registry.py +547 -0
  57. passlib/totp.py +1852 -0
  58. passlib/utils/__init__.py +901 -0
  59. passlib/utils/binary.py +852 -0
  60. passlib/utils/compat/__init__.py +141 -0
  61. passlib/utils/decor.py +220 -0
  62. passlib/utils/des.py +31 -0
  63. passlib/utils/handlers.py +2616 -0
  64. passlib/utils/md4.py +25 -0
  65. passlib/utils/pbkdf2.py +172 -0
  66. passlib-1.9.5.dist-info/METADATA +90 -0
  67. passlib-1.9.5.dist-info/RECORD +69 -0
  68. passlib-1.9.5.dist-info/WHEEL +4 -0
  69. passlib-1.9.5.dist-info/licenses/LICENSE +116 -0
passlib/totp.py ADDED
@@ -0,0 +1,1852 @@
1
+ """passlib.totp -- TOTP / RFC6238 / Google Authenticator utilities."""
2
+
3
+ # core
4
+ import base64
5
+ import calendar
6
+ import json
7
+ import math
8
+ import re
9
+ import struct
10
+ import time as _time
11
+ from urllib.parse import parse_qsl, quote, unquote, urlparse
12
+ from warnings import warn
13
+
14
+ from passlib._logging import logger
15
+
16
+ # site
17
+ try:
18
+ # TOTP encrypted keys only supported if cryptography (https://cryptography.io) is installed
19
+ import cryptography.hazmat.primitives.ciphers.algorithms
20
+ import cryptography.hazmat.primitives.ciphers.modes
21
+ from cryptography.hazmat.backends import default_backend as _cg_default_backend
22
+ from cryptography.hazmat.primitives import ciphers as _cg_ciphers
23
+
24
+ del cryptography
25
+ except ImportError:
26
+ logger.debug("can't import 'cryptography' package, totp encryption disabled")
27
+ _cg_ciphers = _cg_default_backend = None # type: ignore[assignment]
28
+ # pkg
29
+ from passlib import exc
30
+ from passlib.crypto.digest import compile_hmac, lookup_hash, pbkdf2_hmac
31
+ from passlib.exc import (
32
+ InvalidTokenError,
33
+ MalformedTokenError,
34
+ TokenError,
35
+ UsedTokenError,
36
+ )
37
+ from passlib.utils import (
38
+ SequenceMixin,
39
+ consteq,
40
+ getrandbytes,
41
+ getrandstr,
42
+ rng,
43
+ to_bytes,
44
+ to_unicode,
45
+ )
46
+ from passlib.utils.binary import BASE64_CHARS, b32decode, b32encode
47
+ from passlib.utils.compat import bascii_to_str, numeric_types
48
+ from passlib.utils.decor import hybrid_method, memoized_property
49
+
50
+ # local
51
+ __all__ = [
52
+ # frontend classes
53
+ "AppWallet",
54
+ "TOTP",
55
+ # errors (defined in passlib.exc, but exposed here for convenience)
56
+ "TokenError",
57
+ "MalformedTokenError",
58
+ "InvalidTokenError",
59
+ "UsedTokenError",
60
+ # internal helper classes
61
+ "TotpToken",
62
+ "TotpMatch",
63
+ ]
64
+
65
+
66
+ # -----------------------------------------------------------------------------
67
+ # token parsing / rendering helpers
68
+ # -----------------------------------------------------------------------------
69
+
70
+ #: regex used to clean whitespace from tokens & keys
71
+ _clean_re = re.compile(r"\s|[-=]", re.UNICODE)
72
+
73
+ _chunk_sizes = [4, 6, 5]
74
+
75
+
76
+ def _get_group_size(klen):
77
+ """
78
+ helper for group_string() --
79
+ calculates optimal size of group for given string size.
80
+ """
81
+ # look for exact divisor
82
+ for size in _chunk_sizes:
83
+ if not klen % size:
84
+ return size
85
+ # fallback to divisor with largest remainder
86
+ # (so chunks are as close to even as possible)
87
+ best = _chunk_sizes[0]
88
+ rem = 0
89
+ for size in _chunk_sizes:
90
+ if klen % size > rem:
91
+ best = size
92
+ rem = klen % size
93
+ return best
94
+
95
+
96
+ def group_string(value, sep="-"):
97
+ """
98
+ reformat string into (roughly) evenly-sized groups, separated by **sep**.
99
+ useful for making tokens & keys easier to read by humans.
100
+ """
101
+ klen = len(value)
102
+ size = _get_group_size(klen)
103
+ return sep.join(value[o : o + size] for o in range(0, klen, size))
104
+
105
+
106
+ # -----------------------------------------------------------------------------
107
+ # encoding helpers
108
+ # -----------------------------------------------------------------------------
109
+
110
+
111
+ def _decode_bytes(key, format):
112
+ """
113
+ internal TOTP() helper --
114
+ decodes key according to specified format.
115
+ """
116
+ if format == "raw":
117
+ if not isinstance(key, bytes):
118
+ raise exc.ExpectedTypeError(key, "bytes", "key")
119
+ return key
120
+ # for encoded data, key must be either unicode or ascii-encoded bytes,
121
+ # and must contain a hex or base32 string.
122
+ key = to_unicode(key, param="key")
123
+ key = _clean_re.sub("", key).encode("utf-8") # strip whitespace & hypens
124
+ if format == "hex" or format == "base16":
125
+ return base64.b16decode(key.upper())
126
+ if format == "base32":
127
+ return b32decode(key)
128
+ # XXX: add base64 support?
129
+ raise ValueError(f"unknown byte-encoding format: {format!r}")
130
+
131
+
132
+ #: flag for detecting if encrypted totp support is present
133
+ AES_SUPPORT = bool(_cg_ciphers)
134
+
135
+ #: regex for validating secret tags
136
+ _tag_re = re.compile("(?i)^[a-z0-9][a-z0-9_.-]*$")
137
+
138
+
139
+ class AppWallet:
140
+ """
141
+ This class stores application-wide secrets that can be used
142
+ to encrypt & decrypt TOTP keys for storage.
143
+ It's mostly an internal detail, applications usually just need
144
+ to pass ``secrets`` or ``secrets_path`` to :meth:`TOTP.using`.
145
+
146
+ .. seealso::
147
+
148
+ :ref:`totp-storing-instances` for more details on this workflow.
149
+
150
+ Arguments
151
+ =========
152
+ :param secrets:
153
+ Dict of application secrets to use when encrypting/decrypting
154
+ stored TOTP keys. This should include a secret to use when encrypting
155
+ new keys, but may contain additional older secrets to decrypt
156
+ existing stored keys.
157
+
158
+ The dict should map tags -> secrets, so that each secret is identified
159
+ by a unique tag. This tag will be stored along with the encrypted
160
+ key in order to determine which secret should be used for decryption.
161
+ Tag should be string that starts with regex range ``[a-z0-9]``,
162
+ and the remaining characters must be in ``[a-z0-9_.-]``.
163
+
164
+ It is recommended to use something like a incremental counter
165
+ ("1", "2", ...), an ISO date ("2016-01-01", "2016-05-16", ...),
166
+ or a timestamp ("19803495", "19813495", ...) when assigning tags.
167
+
168
+ This mapping be provided in three formats:
169
+
170
+ * A python dict mapping tag -> secret
171
+ * A JSON-formatted string containing the dict
172
+ * A multiline string with the format ``"tag: value\\ntag: value\\n..."``
173
+
174
+ (This last format is mainly useful when loading from a text file via **secrets_path**)
175
+
176
+ .. seealso:: :func:`generate_secret` to create a secret with sufficient entropy
177
+
178
+ :param secrets_path:
179
+ Alternately, callers can specify a separate file where the
180
+ application-wide secrets are stored, using either of the string
181
+ formats described in **secrets**.
182
+
183
+ :param default_tag:
184
+ Specifies which tag in **secrets** should be used as the default
185
+ for encrypting new keys. If omitted, the tags will be sorted,
186
+ and the largest tag used as the default.
187
+
188
+ if all tags are numeric, they will be sorted numerically;
189
+ otherwise they will be sorted alphabetically.
190
+ this permits tags to be assigned numerically,
191
+ or e.g. using ``YYYY-MM-DD`` dates.
192
+
193
+ :param encrypt_cost:
194
+ Optional time-cost factor for key encryption.
195
+ This value corresponds to log2() of the number of PBKDF2
196
+ rounds used.
197
+
198
+ !!! warning
199
+ The application secret(s) should be stored in a secure location by
200
+ your application, and each secret should contain a large amount
201
+ of entropy (to prevent brute-force attacks if the encrypted keys
202
+ are leaked).
203
+
204
+ :func:`generate_secret` is provided as a convenience helper
205
+ to generate a new application secret of suitable size.
206
+
207
+ Best practice is to load these values from a file via **secrets_path**,
208
+ and then have your application give up permission to read this file
209
+ once it's running.
210
+
211
+ Public Methods
212
+ ==============
213
+ .. autoattribute:: has_secrets
214
+ .. autoattribute:: default_tag
215
+
216
+ Semi-Private Methods
217
+ ====================
218
+ The following methods are used internally by the :class:`TOTP`
219
+ class in order to encrypt & decrypt keys using the provided application
220
+ secrets. They will generally not be publically useful, and may have their
221
+ API changed periodically.
222
+ """
223
+
224
+ #: default salt size for encrypt_key() output
225
+ salt_size = 12
226
+
227
+ #: default cost (log2 of pbkdf2 rounds) for encrypt_key() output
228
+ #: NOTE: this is relatively low, since the majority of the security
229
+ #: relies on a high entropy secret to pass to AES.
230
+ encrypt_cost = 14
231
+
232
+ #: map of secret tag -> secret bytes
233
+ _secrets = None
234
+
235
+ #: tag for default secret
236
+ default_tag = None
237
+
238
+ def __init__(
239
+ self, secrets=None, default_tag=None, encrypt_cost=None, secrets_path=None
240
+ ):
241
+ # TODO: allow a lot more things to be customized from here,
242
+ # e.g. setting default TOTP constructor options.
243
+
244
+ #
245
+ # init cost
246
+ #
247
+ if encrypt_cost is not None:
248
+ if isinstance(encrypt_cost, str):
249
+ encrypt_cost = int(encrypt_cost)
250
+ assert encrypt_cost >= 0
251
+ self.encrypt_cost = encrypt_cost
252
+
253
+ #
254
+ # init secrets map
255
+ #
256
+
257
+ # load secrets from file (if needed)
258
+ if secrets_path is not None:
259
+ if secrets is not None:
260
+ raise TypeError("'secrets' and 'secrets_path' are mutually exclusive")
261
+ with open(secrets_path) as f:
262
+ secrets = f.read()
263
+
264
+ # parse & store secrets
265
+ secrets = self._secrets = self._parse_secrets(secrets)
266
+
267
+ #
268
+ # init default tag/secret
269
+ #
270
+ if secrets:
271
+ if default_tag is not None:
272
+ # verify that tag is present in map
273
+ self.get_secret(default_tag)
274
+ elif all(tag.isdigit() for tag in secrets):
275
+ default_tag = max(secrets, key=int)
276
+ else:
277
+ default_tag = max(secrets)
278
+ self.default_tag = default_tag
279
+
280
+ def _parse_secrets(self, source):
281
+ """
282
+ parse 'secrets' parameter
283
+
284
+ :returns:
285
+ Dict[tag:str, secret:bytes]
286
+ """
287
+ # parse string formats
288
+ # to make this easy to pass in configuration from a separate file,
289
+ # 'secrets' can be string using two formats -- json & "tag:value\n"
290
+ check_type = True
291
+ if isinstance(source, str):
292
+ if source.lstrip().startswith(("[", "{")):
293
+ # json list / dict
294
+ source = json.loads(source)
295
+ elif "\n" in source and ":" in source:
296
+ # multiline string containing series of "tag: value\n" rows;
297
+ # empty and "#\n" rows are ignored
298
+ def iter_pairs(source):
299
+ for line in source.splitlines():
300
+ line = line.strip()
301
+ if line and not line.startswith("#"):
302
+ tag, secret = line.split(":", 1)
303
+ yield tag.strip(), secret.strip()
304
+
305
+ source = iter_pairs(source)
306
+ check_type = False
307
+ else:
308
+ raise ValueError("unrecognized secrets string format")
309
+
310
+ # ensure we have iterable of (tag, value) pairs
311
+ if source is None:
312
+ return {}
313
+ if isinstance(source, dict):
314
+ source = source.items()
315
+ # XXX: could support iterable of (tag,value) pairs, but not yet needed...
316
+ # elif check_type and (isinstance(source, str) or not isinstance(source, Iterable)):
317
+ elif check_type:
318
+ raise TypeError("'secrets' must be mapping, or list of items")
319
+
320
+ # parse into final dict, normalizing contents
321
+ return dict(self._parse_secret_pair(tag, value) for tag, value in source)
322
+
323
+ def _parse_secret_pair(self, tag, value):
324
+ if isinstance(tag, str):
325
+ pass
326
+ elif isinstance(tag, int):
327
+ tag = str(tag)
328
+ else:
329
+ raise TypeError(f"tag must be string: {tag!r}")
330
+ if not _tag_re.match(tag):
331
+ raise ValueError(f"tag contains invalid characters: {tag!r}")
332
+ if not isinstance(value, bytes):
333
+ value = to_bytes(value, param=f"secret {tag!r}")
334
+ if not value:
335
+ raise ValueError(f"tag contains empty secret: {tag!r}")
336
+ return tag, value
337
+
338
+ @property
339
+ def has_secrets(self):
340
+ """whether at least one application secret is present"""
341
+ return self.default_tag is not None
342
+
343
+ def get_secret(self, tag):
344
+ """
345
+ resolve a secret tag to the secret (as bytes).
346
+ throws a KeyError if not found.
347
+ """
348
+ secrets = self._secrets
349
+ if not secrets:
350
+ raise KeyError("no application secrets configured")
351
+ try:
352
+ return secrets[tag]
353
+ except KeyError:
354
+ raise KeyError(f"unknown secret tag: {tag!r}") from None
355
+
356
+ @staticmethod
357
+ def _cipher_aes_key(value, secret, salt, cost, decrypt=False):
358
+ """
359
+ Internal helper for :meth:`encrypt_key` --
360
+ handles lowlevel encryption/decryption.
361
+
362
+ Algorithm details:
363
+
364
+ This function uses PBKDF2-HMAC-SHA256 to generate a 32-byte AES key
365
+ and a 16-byte IV from the application secret & random salt.
366
+ It then uses AES-256-CTR to encrypt/decrypt the TOTP key.
367
+
368
+ CTR mode was chosen over CBC because the main attack scenario here
369
+ is that the attacker has stolen the database, and is trying to decrypt a TOTP key
370
+ (the plaintext value here). To make it hard for them, we want every password
371
+ to decrypt to a potentially valid key -- thus need to avoid any authentication
372
+ or padding oracle attacks. While some random padding construction could be devised
373
+ to make this work for CBC mode, a stream cipher mode is just plain simpler.
374
+ OFB/CFB modes would also work here, but seeing as they have malleability
375
+ and cyclic issues (though remote and barely relevant here),
376
+ CTR was picked as the best overall choice.
377
+ """
378
+ # make sure backend AES support is available
379
+ if _cg_ciphers is None:
380
+ raise RuntimeError(
381
+ "TOTP encryption requires 'cryptography' package "
382
+ "(https://cryptography.io)"
383
+ )
384
+
385
+ # use pbkdf2 to derive both key (32 bytes) & iv (16 bytes)
386
+ # NOTE: this requires 2 sha256 blocks to be calculated.
387
+ keyiv = pbkdf2_hmac("sha256", secret, salt=salt, rounds=(1 << cost), keylen=48)
388
+
389
+ # use AES-256-CTR to encrypt/decrypt input value
390
+ cipher = _cg_ciphers.Cipher(
391
+ _cg_ciphers.algorithms.AES(keyiv[:32]),
392
+ _cg_ciphers.modes.CTR(keyiv[32:]),
393
+ _cg_default_backend(),
394
+ )
395
+ ctx = cipher.decryptor() if decrypt else cipher.encryptor()
396
+ return ctx.update(value) + ctx.finalize()
397
+
398
+ def encrypt_key(self, key):
399
+ """
400
+ Helper used to encrypt TOTP keys for storage.
401
+
402
+ :param key:
403
+ TOTP key to encrypt, as raw bytes.
404
+
405
+ :returns:
406
+ dict containing encrypted TOTP key & configuration parameters.
407
+ this format should be treated as opaque, and potentially subject
408
+ to change, though it is designed to be easily serialized/deserialized
409
+ (e.g. via JSON).
410
+
411
+ .. note::
412
+
413
+ This function requires installation of the external
414
+ `cryptography <https://cryptography.io>`_ package.
415
+
416
+ To give some algorithm details: This function uses AES-256-CTR to encrypt
417
+ the provided data. It takes the application secret and randomly generated salt,
418
+ and uses PBKDF2-HMAC-SHA256 to combine them and generate the AES key & IV.
419
+ """
420
+ if not key:
421
+ raise ValueError("no key provided")
422
+ salt = getrandbytes(rng, self.salt_size)
423
+ cost = self.encrypt_cost
424
+ tag = self.default_tag
425
+ if not tag:
426
+ raise TypeError("no application secrets configured, can't encrypt OTP key")
427
+ ckey = self._cipher_aes_key(key, self.get_secret(tag), salt, cost)
428
+ # XXX: switch to base64?
429
+ return dict(v=1, c=cost, t=tag, s=b32encode(salt), k=b32encode(ckey))
430
+
431
+ def decrypt_key(self, enckey):
432
+ """
433
+ Helper used to decrypt TOTP keys from storage format.
434
+ Consults configured secrets to decrypt key.
435
+
436
+ :param source:
437
+ source object, as returned by :meth:`encrypt_key`.
438
+
439
+ :returns:
440
+ ``(key, needs_recrypt)`` --
441
+
442
+ **key** will be the decrypted key, as bytes.
443
+
444
+ **needs_recrypt** will be a boolean flag indicating
445
+ whether encryption cost or default tag is too old,
446
+ and henace that key needs re-encrypting before storing.
447
+
448
+ .. note::
449
+
450
+ This function requires installation of the external
451
+ `cryptography <https://cryptography.io>`_ package.
452
+ """
453
+ if not isinstance(enckey, dict):
454
+ raise TypeError("'enckey' must be dictionary")
455
+ version = enckey.get("v", None)
456
+ needs_recrypt = False
457
+ if version == 1:
458
+ _cipher_key = self._cipher_aes_key
459
+ else:
460
+ raise ValueError(f"missing / unrecognized 'enckey' version: {version!r}")
461
+ tag = enckey["t"]
462
+ cost = enckey["c"]
463
+ key = _cipher_key(
464
+ value=b32decode(enckey["k"]),
465
+ secret=self.get_secret(tag),
466
+ salt=b32decode(enckey["s"]),
467
+ cost=cost,
468
+ )
469
+ if cost != self.encrypt_cost or tag != self.default_tag:
470
+ needs_recrypt = True
471
+ return key, needs_recrypt
472
+
473
+
474
+ #: helper to convert HOTP counter to bytes
475
+ _pack_uint64 = struct.Struct(">Q").pack
476
+
477
+ #: helper to extract value from HOTP digest
478
+ _unpack_uint32 = struct.Struct(">I").unpack
479
+
480
+ #: dummy bytes used as temp key for .using() method
481
+ _DUMMY_KEY = b"\x00" * 16
482
+
483
+
484
+ class TOTP:
485
+ """
486
+ Helper for generating and verifying TOTP codes.
487
+
488
+ Given a secret key and set of configuration options, this object
489
+ offers methods for token generation, token validation, and serialization.
490
+ It can also be used to track important persistent TOTP state,
491
+ such as the last counter used.
492
+
493
+ This class accepts the following options
494
+ (only **key** and **format** may be specified as positional arguments).
495
+
496
+ :arg str key:
497
+ The secret key to use. By default, should be encoded as
498
+ a base32 string (see **format** for other encodings).
499
+
500
+ Exactly one of **key** or ``new=True`` must be specified.
501
+
502
+ :arg str format:
503
+ The encoding used by the **key** parameter. May be one of:
504
+ ``"base32"`` (base32-encoded string),
505
+ ``"hex"`` (hexadecimal string), or ``"raw"`` (raw bytes).
506
+ Defaults to ``"base32"``.
507
+
508
+ :param bool new:
509
+ If ``True``, a new key will be generated using :class:`random.SystemRandom`.
510
+
511
+ Exactly one ``new=True`` or **key** must be specified.
512
+
513
+ :param str label:
514
+ Label to associate with this token when generating a URI.
515
+ Displayed to user by most OTP client applications (e.g. Google Authenticator),
516
+ and typically has format such as ``"John Smith"`` or ``"jsmith@webservice.example.org"``.
517
+ Defaults to ``None``.
518
+ See :meth:`to_uri` for details.
519
+
520
+ :param str issuer:
521
+ String identifying the token issuer (e.g. the domain name of your service).
522
+ Used internally by some OTP client applications (e.g. Google Authenticator) to distinguish entries
523
+ which otherwise have the same label.
524
+ Optional but strongly recommended if you're rendering to a URI.
525
+ Defaults to ``None``.
526
+ See :meth:`to_uri` for details.
527
+
528
+ :param int size:
529
+ Number of bytes when generating new keys. Defaults to size of hash algorithm (e.g. 20 for SHA1).
530
+
531
+ .. warning::
532
+
533
+ Overriding the default values for ``digits``, ``period``, or ``alg`` may
534
+ cause problems with some OTP client programs (such as Google Authenticator),
535
+ which may have these defaults hardcoded.
536
+
537
+ :param int digits:
538
+ The number of digits in the generated / accepted tokens. Defaults to ``6``.
539
+ Must be in range [6 .. 10].
540
+
541
+ .. rst-class:: inline-title
542
+ .. caution::
543
+ Due to a limitation of the HOTP algorithm, the 10th digit can only take on values 0 .. 2,
544
+ and thus offers very little extra security.
545
+
546
+ :param str alg:
547
+ Name of hash algorithm to use. Defaults to ``"sha1"``.
548
+ ``"sha256"`` and ``"sha512"`` are also accepted, per :rfc:`6238`.
549
+
550
+ :param int period:
551
+ The time-step period to use, in integer seconds. Defaults to ``30``.
552
+
553
+ ..
554
+ See the passlib documentation for a full list of attributes & methods.
555
+ """
556
+
557
+ #: minimum number of bytes to allow in key, enforced by passlib.
558
+ # XXX: see if spec says anything relevant to this.
559
+ _min_key_size = 10
560
+
561
+ #: minimum & current serialization version (may be set independently by subclasses)
562
+ min_json_version = json_version = 1
563
+
564
+ #: AppWallet that this class will use for encrypting/decrypting keys.
565
+ #: (can be overwritten via the :meth:`TOTP.using()` constructor)
566
+ wallet = None
567
+
568
+ #: function to get system time in seconds, as needed by :meth:`generate` and :meth:`verify`.
569
+ #: defaults to :func:`time.time`, but can be overridden on a per-instance basis.
570
+ now = _time.time
571
+
572
+ # ---------------------------------------------------------------------------
573
+ # configuration attrs
574
+ # ---------------------------------------------------------------------------
575
+
576
+ #: [private] secret key as raw :class:`!bytes`
577
+ #: see .key property for public access.
578
+ _key = None
579
+
580
+ #: [private] cached copy of encrypted secret,
581
+ #: so .to_json() doesn't have to re-encrypt on each call.
582
+ _encrypted_key = None
583
+
584
+ #: [private] cached copy of keyed HMAC function,
585
+ #: so ._generate() doesn't have to rebuild this each time
586
+ #: ._find_match() invokes it.
587
+ _keyed_hmac = None
588
+
589
+ #: number of digits in the generated tokens.
590
+ digits = 6
591
+
592
+ #: name of hash algorithm in use (e.g. ``"sha1"``)
593
+ alg = "sha1"
594
+
595
+ #: default label for :meth:`to_uri`
596
+ label = None
597
+
598
+ #: default issuer for :meth:`to_uri`
599
+ issuer = None
600
+
601
+ #: number of seconds per counter step.
602
+ #: *(TOTP uses an internal time-derived counter which
603
+ #: increments by 1 every* :attr:`!period` *seconds)*.
604
+ period = 30
605
+
606
+ # ---------------------------------------------------------------------------
607
+ # state attrs
608
+ # ---------------------------------------------------------------------------
609
+
610
+ #: Flag set by deserialization methods to indicate the object needs to be re-serialized.
611
+ #: This can be for a number of reasons -- encoded using deprecated format,
612
+ #: or encrypted using a deprecated key or too few rounds.
613
+ changed = False
614
+
615
+ @classmethod
616
+ def using(
617
+ cls,
618
+ digits=None,
619
+ alg=None,
620
+ period=None,
621
+ issuer=None,
622
+ wallet=None,
623
+ now=None,
624
+ **kwds,
625
+ ):
626
+ """
627
+ Dynamically create subtype of :class:`!TOTP` class
628
+ which has the specified defaults set.
629
+
630
+ :parameters: **digits, alg, period, issuer**:
631
+
632
+ All these options are the same as in the :class:`TOTP` constructor,
633
+ and the resulting class will use any values you specify here
634
+ as the default for all TOTP instances it creates.
635
+
636
+ :param wallet:
637
+ Optional :class:`AppWallet` that will be used for encrypting/decrypting keys.
638
+
639
+ :param secrets, secrets_path, encrypt_cost:
640
+
641
+ If specified, these options will be passed to the :class:`AppWallet` constructor,
642
+ allowing you to directly specify the secret keys that should be used
643
+ to encrypt & decrypt stored keys.
644
+
645
+ :returns:
646
+ subclass of :class:`!TOTP`.
647
+
648
+ This method is useful for creating a TOTP class configured
649
+ to use your application's secrets for encrypting & decrypting
650
+ keys, as well as create new keys using it's desired configuration defaults.
651
+
652
+ As an example::
653
+
654
+ >>> # your application can create a custom class when it initializes
655
+ >>> from passlib.totp import TOTP, generate_secret
656
+ >>> TotpFactory = TOTP.using(secrets={"1": generate_secret()})
657
+
658
+ >>> # subsequent TOTP objects created from this factory
659
+ >>> # will use the specified secrets to encrypt their keys...
660
+ >>> totp = TotpFactory.new()
661
+ >>> totp.to_dict()
662
+ {'enckey': {'c': 14,
663
+ 'k': 'H77SYXWORDPGVOQTFRR2HFUB3C45XXI7',
664
+ 's': 'G5DOQPIHIBUM2OOHHADQ',
665
+ 't': '1',
666
+ 'v': 1},
667
+ 'type': 'totp',
668
+ 'v': 1}
669
+
670
+ .. seealso:: :ref:`totp-creation` and :ref:`totp-storing-instances` tutorials for a usage example
671
+ """
672
+ # XXX: could add support for setting default match 'window' and 'reuse' policy
673
+
674
+ # :param now:
675
+ # Optional callable that should return current time for generator to use.
676
+ # Default to :func:`time.time`. This optional is generally not needed,
677
+ # and is mainly present for examples & unit-testing.
678
+
679
+ subcls = type("TOTP", (cls,), {})
680
+
681
+ def norm_param(attr, value):
682
+ """
683
+ helper which uses constructor to validate parameter value.
684
+ it returns corresponding attribute, so we use normalized value.
685
+ """
686
+ # NOTE: this creates *subclass* instance,
687
+ # so normalization takes into account any custom params
688
+ # already stored.
689
+ kwds = dict(key=_DUMMY_KEY, format="raw")
690
+ kwds[attr] = value
691
+ obj = subcls(**kwds)
692
+ return getattr(obj, attr)
693
+
694
+ if digits is not None:
695
+ subcls.digits = norm_param("digits", digits)
696
+
697
+ if alg is not None:
698
+ subcls.alg = norm_param("alg", alg)
699
+
700
+ if period is not None:
701
+ subcls.period = norm_param("period", period)
702
+
703
+ # XXX: add default size as configurable parameter?
704
+
705
+ if issuer is not None:
706
+ subcls.issuer = norm_param("issuer", issuer)
707
+
708
+ if kwds:
709
+ subcls.wallet = AppWallet(**kwds)
710
+ if wallet:
711
+ raise TypeError(
712
+ "'wallet' and 'secrets' keywords are mutually exclusive"
713
+ )
714
+ elif wallet is not None:
715
+ if not isinstance(wallet, AppWallet):
716
+ raise exc.ExpectedTypeError(wallet, AppWallet, "wallet")
717
+ subcls.wallet = wallet
718
+
719
+ if now is not None:
720
+ err_msg = "now() function must return non-negative int/float"
721
+ assert isinstance(now(), numeric_types), err_msg
722
+ assert now() >= 0, err_msg
723
+ subcls.now = staticmethod(now)
724
+
725
+ return subcls
726
+
727
+ @classmethod
728
+ def new(cls, **kwds):
729
+ """
730
+ convenience alias for creating new TOTP key, same as ``TOTP(new=True)``
731
+ """
732
+ return cls(new=True, **kwds)
733
+
734
+ def __init__(
735
+ self,
736
+ key=None,
737
+ format="base32",
738
+ # keyword only...
739
+ new=False,
740
+ digits=None,
741
+ alg=None,
742
+ size=None,
743
+ period=None,
744
+ label=None,
745
+ issuer=None,
746
+ changed=False,
747
+ **kwds,
748
+ ):
749
+ super().__init__(**kwds)
750
+ if changed:
751
+ self.changed = changed
752
+
753
+ # validate & normalize alg
754
+ info = lookup_hash(alg or self.alg)
755
+ self.alg = info.name
756
+ digest_size = info.digest_size
757
+ if digest_size < 4:
758
+ raise RuntimeError(f"{alg!r} hash digest too small")
759
+
760
+ # parse or generate new key
761
+ if new:
762
+ # generate new key
763
+ if key:
764
+ raise TypeError("'key' and 'new=True' are mutually exclusive")
765
+ if size is None:
766
+ # default to digest size, per RFC 6238 Section 5.1
767
+ size = digest_size
768
+ elif size > digest_size:
769
+ # not forbidden by spec, but would just be wasted bytes.
770
+ # maybe just warn about this?
771
+ raise ValueError(
772
+ "'size' should be less than digest size (%d)" % digest_size
773
+ )
774
+ self.key = getrandbytes(rng, size)
775
+ elif not key:
776
+ raise TypeError("must specify either an existing 'key', or 'new=True'")
777
+ elif format == "encrypted":
778
+ # NOTE: this handles decrypting & setting '.key'
779
+ self.encrypted_key = key
780
+ elif key:
781
+ # use existing key, encoded using specified <format>
782
+ self.key = _decode_bytes(key, format)
783
+
784
+ # enforce min key size
785
+ if len(self.key) < self._min_key_size:
786
+ # only making this fatal for new=True,
787
+ # so that existing (but ridiculously small) keys can still be used.
788
+ msg = (
789
+ "for security purposes, secret key must be >= %d bytes"
790
+ % self._min_key_size
791
+ )
792
+ if new:
793
+ raise ValueError(msg)
794
+ warn(msg, exc.PasslibSecurityWarning, stacklevel=1)
795
+
796
+ # validate digits
797
+ if digits is None:
798
+ digits = self.digits
799
+ if not isinstance(digits, int):
800
+ raise TypeError(f"digits must be an integer, not a {type(digits)!r}")
801
+ if digits < 6 or digits > 10:
802
+ raise ValueError("digits must in range(6,11)")
803
+ self.digits = digits
804
+
805
+ # validate label
806
+ if label:
807
+ self._check_label(label)
808
+ self.label = label
809
+
810
+ # validate issuer
811
+ if issuer:
812
+ self._check_issuer(issuer)
813
+ self.issuer = issuer
814
+
815
+ # init period
816
+ if period is not None:
817
+ self._check_serial(period, "period", minval=1)
818
+ self.period = period
819
+
820
+ @staticmethod
821
+ def _check_serial(value, param, minval=0):
822
+ """
823
+ check that serial value (e.g. 'counter') is non-negative integer
824
+ """
825
+ if not isinstance(value, int):
826
+ raise exc.ExpectedTypeError(value, "int", param)
827
+ if value < minval:
828
+ raise ValueError("%s must be >= %d" % (param, minval))
829
+
830
+ @staticmethod
831
+ def _check_label(label):
832
+ """
833
+ check that label doesn't contain chars forbidden by KeyURI spec
834
+ """
835
+ if label and ":" in label:
836
+ raise ValueError("label may not contain ':'")
837
+
838
+ @staticmethod
839
+ def _check_issuer(issuer):
840
+ """
841
+ check that issuer doesn't contain chars forbidden by KeyURI spec
842
+ """
843
+ if issuer and ":" in issuer:
844
+ raise ValueError("issuer may not contain ':'")
845
+
846
+ @property
847
+ def key(self):
848
+ """
849
+ secret key as raw bytes
850
+ """
851
+ return self._key
852
+
853
+ @key.setter
854
+ def key(self, value):
855
+ # set key
856
+ if not isinstance(value, bytes):
857
+ raise exc.ExpectedTypeError(value, bytes, "key")
858
+ self._key = value
859
+
860
+ # clear cached properties derived from key
861
+ self._encrypted_key = self._keyed_hmac = None
862
+
863
+ # ------------------------------------------------------------------
864
+ # encrypted key
865
+ # ------------------------------------------------------------------
866
+ @property
867
+ def encrypted_key(self):
868
+ """
869
+ secret key, encrypted using application secret.
870
+ this match the output of :meth:`AppWallet.encrypt_key`,
871
+ and should be treated as an opaque json serializable object.
872
+ """
873
+ enckey = self._encrypted_key
874
+ if enckey is None:
875
+ wallet = self.wallet
876
+ if not wallet:
877
+ raise TypeError(
878
+ "no application secrets present, can't encrypt TOTP key"
879
+ )
880
+ enckey = self._encrypted_key = wallet.encrypt_key(self.key)
881
+ return enckey
882
+
883
+ @encrypted_key.setter
884
+ def encrypted_key(self, value):
885
+ wallet = self.wallet
886
+ if not wallet:
887
+ raise TypeError("no application secrets present, can't decrypt TOTP key")
888
+ self.key, needs_recrypt = wallet.decrypt_key(value)
889
+ if needs_recrypt:
890
+ # mark as changed so it gets re-encrypted & written to db
891
+ self.changed = True
892
+ else:
893
+ # cache encrypted key for re-use
894
+ self._encrypted_key = value
895
+
896
+ # ------------------------------------------------------------------
897
+ # pretty-printed / encoded key helpers
898
+ # ------------------------------------------------------------------
899
+
900
+ @property
901
+ def hex_key(self):
902
+ """
903
+ secret key encoded as hexadecimal string
904
+ """
905
+ return bascii_to_str(base64.b16encode(self.key)).lower()
906
+
907
+ @property
908
+ def base32_key(self):
909
+ """
910
+ secret key encoded as base32 string
911
+ """
912
+ return b32encode(self.key)
913
+
914
+ def pretty_key(self, format="base32", sep="-"):
915
+ """
916
+ pretty-print the secret key.
917
+
918
+ This is mainly useful for situations where the user cannot get the qrcode to work,
919
+ and must enter the key manually into their TOTP client. It tries to format
920
+ the key in a manner that is easier for humans to read.
921
+
922
+ :param format:
923
+ format to output secret key. ``"hex"`` and ``"base32"`` are both accepted.
924
+
925
+ :param sep:
926
+ separator to insert to break up key visually.
927
+ can be any of ``"-"`` (the default), ``" "``, or ``False`` (no separator).
928
+
929
+ :return:
930
+ key as native string.
931
+
932
+ Usage example::
933
+
934
+ >>> t = TOTP('s3jdvb7qd2r7jpxx')
935
+ >>> t.pretty_key()
936
+ 'S3JD-VB7Q-D2R7-JPXX'
937
+ """
938
+ if format == "hex" or format == "base16":
939
+ key = self.hex_key
940
+ elif format == "base32":
941
+ key = self.base32_key
942
+ else:
943
+ raise ValueError(f"unknown byte-encoding format: {format!r}")
944
+ if sep:
945
+ key = group_string(key, sep)
946
+ return key
947
+
948
+ @classmethod
949
+ def normalize_time(cls, time):
950
+ """
951
+ Normalize time value to unix epoch seconds.
952
+
953
+ :arg time:
954
+ Can be ``None``, :class:`!datetime`,
955
+ or unix epoch timestamp as :class:`!float` or :class:`!int`.
956
+ If ``None``, uses current system time.
957
+ Naive datetimes are treated as UTC.
958
+
959
+ :returns:
960
+ unix epoch timestamp as :class:`int`.
961
+ """
962
+ if isinstance(time, int):
963
+ return time
964
+ if isinstance(time, float):
965
+ return int(time)
966
+ if time is None:
967
+ return int(cls.now())
968
+ if hasattr(time, "utctimetuple"):
969
+ # coerce datetime to UTC timestamp
970
+ # NOTE: utctimetuple() assumes naive datetimes are in UTC
971
+ # NOTE: we explicitly *don't* want microseconds.
972
+ return calendar.timegm(time.utctimetuple())
973
+ raise exc.ExpectedTypeError(time, "int, float, or datetime", "time")
974
+
975
+ def _time_to_counter(self, time):
976
+ """
977
+ convert timestamp to HOTP counter using :attr:`period`.
978
+ """
979
+ return time // self.period
980
+
981
+ def _counter_to_time(self, counter):
982
+ """
983
+ convert HOTP counter to timestamp using :attr:`period`.
984
+ """
985
+ return counter * self.period
986
+
987
+ @hybrid_method
988
+ def normalize_token(self_or_cls, token):
989
+ """
990
+ Normalize OTP token representation:
991
+ strips whitespace, converts integers to a zero-padded string,
992
+ validates token content & number of digits.
993
+
994
+ This is a hybrid method -- it can be called at the class level,
995
+ as ``TOTP.normalize_token()``, or the instance level as ``TOTP().normalize_token()``.
996
+ It will normalize to the instance-specific number of :attr:`~TOTP.digits`,
997
+ or use the class default.
998
+
999
+ :arg token:
1000
+ token as ascii bytes, str, or an integer.
1001
+
1002
+ :raises ValueError:
1003
+ if token has wrong number of digits, or contains non-numeric characters.
1004
+
1005
+ :returns:
1006
+ token as :class:`!str`, containing only digits 0-9.
1007
+ """
1008
+ digits = self_or_cls.digits
1009
+ if isinstance(token, int):
1010
+ token = "%0*d" % (digits, token)
1011
+ else:
1012
+ token = to_unicode(token, param="token")
1013
+ token = _clean_re.sub("", token)
1014
+ if not token.isdigit():
1015
+ raise MalformedTokenError("Token must contain only the digits 0-9")
1016
+ if len(token) != digits:
1017
+ raise MalformedTokenError("Token must have exactly %d digits" % digits)
1018
+ return token
1019
+
1020
+ # # debug helper
1021
+ # def generate_range(self, size, time=None):
1022
+ # counter = self._time_to_counter(time) - (size + 1) // 2
1023
+ # end = counter + size
1024
+ # while counter <= end:
1025
+ # token = self._generate(counter)
1026
+ # yield TotpToken(self, token, counter)
1027
+ # counter += 1
1028
+
1029
+ def generate(self, time=None):
1030
+ """
1031
+ Generate token for specified time
1032
+ (uses current time if none specified).
1033
+
1034
+ :arg time:
1035
+ Can be ``None``, a :class:`!datetime`,
1036
+ or class:`!float` / :class:`!int` unix epoch timestamp.
1037
+ If ``None`` (the default), uses current system time.
1038
+ Naive datetimes are treated as UTC.
1039
+
1040
+ :returns:
1041
+
1042
+ A :class:`TotpToken` instance, which can be treated
1043
+ as a sequence of ``(token, expire_time)`` -- see that class
1044
+ for more details.
1045
+
1046
+ Usage example::
1047
+
1048
+ >>> # generate a new token, wrapped in a TotpToken instance...
1049
+ >>> otp = TOTP('s3jdvb7qd2r7jpxx')
1050
+ >>> otp.generate(1419622739)
1051
+ <TotpToken token='897212' expire_time=1419622740>
1052
+
1053
+ >>> # when you just need the token...
1054
+ >>> otp.generate(1419622739).token
1055
+ '897212'
1056
+ """
1057
+ time = self.normalize_time(time)
1058
+ counter = self._time_to_counter(time)
1059
+ if counter < 0:
1060
+ raise ValueError("timestamp must be >= 0")
1061
+ token = self._generate(counter)
1062
+ return TotpToken(self, token, counter)
1063
+
1064
+ def _generate(self, counter):
1065
+ """
1066
+ base implementation of HOTP token generation algorithm.
1067
+
1068
+ :arg counter: HOTP counter, as non-negative integer
1069
+ :returns: token as unicode string
1070
+ """
1071
+ # generate digest
1072
+ assert isinstance(counter, int), "counter must be integer"
1073
+ assert counter >= 0, "counter must be non-negative"
1074
+ keyed_hmac = self._keyed_hmac
1075
+ if keyed_hmac is None:
1076
+ keyed_hmac = self._keyed_hmac = compile_hmac(self.alg, self.key)
1077
+ digest = keyed_hmac(_pack_uint64(counter))
1078
+ digest_size = keyed_hmac.digest_info.digest_size
1079
+ assert len(digest) == digest_size, "digest_size: sanity check failed"
1080
+
1081
+ # derive 31-bit token value
1082
+ # assert isinstance(digest, bytes)
1083
+ assert digest_size >= 20, (
1084
+ "digest_size: sanity check 2 failed"
1085
+ ) # otherwise 0xF+4 will run off end of hash.
1086
+ offset = digest[-1] & 0xF
1087
+ value = _unpack_uint32(digest[offset : offset + 4])[0] & 0x7FFFFFFF
1088
+
1089
+ # render to decimal string, return last <digits> chars
1090
+ # NOTE: the 10'th digit is not as secure, as it can only take on values 0-2, not 0-9,
1091
+ # due to 31-bit mask on int ">I". But some servers / clients use it :|
1092
+ # if 31-bit mask removed (which breaks spec), would only get values 0-4.
1093
+ digits = self.digits
1094
+ assert 0 < digits < 11, "digits: sanity check failed"
1095
+ return ("%0*d" % (digits, value))[-digits:]
1096
+
1097
+ @classmethod
1098
+ def verify(cls, token, source, **kwds):
1099
+ r"""
1100
+ Convenience wrapper around :meth:`TOTP.from_source` and :meth:`TOTP.match`.
1101
+
1102
+ This parses a TOTP key & configuration from the specified source,
1103
+ and tries and match the token.
1104
+ It's designed to parallel the :meth:`passlib.ifc.PasswordHash.verify` method.
1105
+
1106
+ :param token:
1107
+ Token string to match.
1108
+
1109
+ :param source:
1110
+ Serialized TOTP key.
1111
+ Can be anything accepted by :meth:`TOTP.from_source`.
1112
+
1113
+ :param \\*\\*kwds:
1114
+ All additional keywords passed to :meth:`TOTP.match`.
1115
+
1116
+ :return:
1117
+ A :class:`TotpMatch` instance, or raises a :exc:`TokenError`.
1118
+ """
1119
+ return cls.from_source(source).match(token, **kwds)
1120
+
1121
+ def match(self, token, time=None, window=30, skew=0, last_counter=None):
1122
+ """
1123
+ Match TOTP token against specified timestamp.
1124
+ Searches within a window before & after the provided time,
1125
+ in order to account for transmission delay and small amounts of skew in the client's clock.
1126
+
1127
+ :arg token:
1128
+ Token to validate.
1129
+ may be integer or string (whitespace and hyphens are ignored).
1130
+
1131
+ :param time:
1132
+ Unix epoch timestamp, can be any of :class:`!float`, :class:`!int`, or :class:`!datetime`.
1133
+ if ``None`` (the default), uses current system time.
1134
+ *this should correspond to the time the token was received from the client*.
1135
+
1136
+ :param int window:
1137
+ How far backward and forward in time to search for a match.
1138
+ Measured in seconds. Defaults to ``30``. Typically only useful if set
1139
+ to multiples of :attr:`period`.
1140
+
1141
+ :param int skew:
1142
+ Adjust timestamp by specified value, to account for excessive
1143
+ client clock skew. Measured in seconds. Defaults to ``0``.
1144
+
1145
+ Negative skew (the common case) indicates transmission delay,
1146
+ and/or that the client clock is running behind the server.
1147
+
1148
+ Positive skew indicates the client clock is running ahead of the server
1149
+ (and by enough that it cancels out any negative skew added by
1150
+ the transmission delay).
1151
+
1152
+ You should ensure the server clock uses a reliable time source such as NTP,
1153
+ so that only the client clock's inaccuracy needs to be accounted for.
1154
+
1155
+ This is an advanced parameter that should usually be left at ``0``;
1156
+ The **window** parameter is usually enough to account
1157
+ for any observed transmission delay.
1158
+
1159
+ :param last_counter:
1160
+ Optional value of last counter value that was successfully used.
1161
+ If specified, verify will never search earlier counters,
1162
+ no matter how large the window is.
1163
+
1164
+ Useful when client has previously authenticated,
1165
+ and thus should never provide a token older than previously
1166
+ verified value.
1167
+
1168
+ :raises ~passlib.exc.TokenError:
1169
+
1170
+ If the token is malformed, fails to match, or has already been used.
1171
+
1172
+ :returns TotpMatch:
1173
+
1174
+ Returns a :class:`TotpMatch` instance on successful match.
1175
+ Can be treated as tuple of ``(counter, time)``.
1176
+ Raises error if token is malformed / can't be verified.
1177
+
1178
+ Usage example::
1179
+
1180
+ >>> totp = TOTP('s3jdvb7qd2r7jpxx')
1181
+
1182
+ >>> # valid token for this time period
1183
+ >>> totp.match('897212', 1419622729)
1184
+ <TotpMatch counter=47320757 time=1419622729 cache_seconds=60>
1185
+
1186
+ >>> # token from counter step 30 sec ago (within allowed window)
1187
+ >>> totp.match('000492', 1419622729)
1188
+ <TotpMatch counter=47320756 time=1419622729 cache_seconds=60>
1189
+
1190
+ >>> # invalid token -- token from 60 sec ago (outside of window)
1191
+ >>> totp.match('760389', 1419622729)
1192
+ Traceback:
1193
+ ...
1194
+ InvalidTokenError: Token did not match
1195
+ """
1196
+ time = self.normalize_time(time)
1197
+ self._check_serial(window, "window")
1198
+
1199
+ client_time = time + skew
1200
+ if last_counter is None:
1201
+ last_counter = -1
1202
+ start = max(last_counter, self._time_to_counter(client_time - window))
1203
+ end = self._time_to_counter(client_time + window) + 1
1204
+ # XXX: could pass 'expected = _time_to_counter(client_time + TRANSMISSION_DELAY)'
1205
+ # to the _find_match() method, would help if window set to very large value.
1206
+
1207
+ counter = self._find_match(token, start, end)
1208
+ assert counter >= last_counter, "sanity check failed: counter went backward"
1209
+
1210
+ if counter == last_counter:
1211
+ raise UsedTokenError(expire_time=(last_counter + 1) * self.period)
1212
+
1213
+ # NOTE: By returning match tied to <time>, not <client_time>, we're
1214
+ # causing .skipped to reflect the observed skew, independent of
1215
+ # the 'skew' param. This is deliberately done so that caller
1216
+ # can use historical .skipped values to estimate future skew.
1217
+ return TotpMatch(self, counter, time, window)
1218
+
1219
+ def _find_match(self, token, start, end, expected=None):
1220
+ """
1221
+ helper for verify() --
1222
+ returns counter value within specified range that matches token.
1223
+
1224
+ :arg token:
1225
+ token value to match (will be normalized internally)
1226
+
1227
+ :arg start:
1228
+ starting counter value to check
1229
+
1230
+ :arg end:
1231
+ check up to (but not including) this counter value
1232
+
1233
+ :arg expected:
1234
+ optional expected value where search should start,
1235
+ to help speed up searches.
1236
+
1237
+ :raises ~passlib.exc.TokenError:
1238
+ If the token is malformed, or fails to verify.
1239
+
1240
+ :returns:
1241
+ counter value that matched
1242
+ """
1243
+ token = self.normalize_token(token)
1244
+ start = max(start, 0)
1245
+ if end <= start:
1246
+ raise InvalidTokenError
1247
+ generate = self._generate
1248
+ if not (expected is None or expected < start) and consteq(
1249
+ token, generate(expected)
1250
+ ):
1251
+ return expected
1252
+ # XXX: if (end - start) is very large (e.g. for resync purposes),
1253
+ # could start with expected value, and work outward from there,
1254
+ # alternately checking before & after it until match is found.
1255
+ # TODO: replace counter loop with "for counter in range(start, end)";
1256
+ # think this was holding from PY2+win32 issue with values > 32 bit (e.g. 'end').
1257
+ counter = start
1258
+ while counter < end:
1259
+ if consteq(token, generate(counter)):
1260
+ return counter
1261
+ counter += 1
1262
+ raise InvalidTokenError
1263
+
1264
+ # -------------------------------------------------------------------------
1265
+ # TODO: resync(self, tokens, time=None, min_tokens=10, window=100)
1266
+ # helper to re-synchronize using series of sequential tokens,
1267
+ # all of which must validate; per RFC recommendation.
1268
+ # NOTE: need to make sure this function is constant time
1269
+ # (i.e. scans ALL tokens, and doesn't short-circuit after first mismatch)
1270
+ # -------------------------------------------------------------------------
1271
+
1272
+ @classmethod
1273
+ def from_source(cls, source):
1274
+ """
1275
+ Load / create a TOTP object from a serialized source.
1276
+ This acts as a wrapper for the various deserialization methods:
1277
+
1278
+ * TOTP URIs are handed off to :meth:`from_uri`
1279
+ * Any other strings are handed off to :meth:`from_json`
1280
+ * Dicts are handed off to :meth:`from_dict`
1281
+
1282
+ :param source:
1283
+ Serialized TOTP object.
1284
+
1285
+ :raises ValueError:
1286
+ If the key has been encrypted, but the application secret isn't available;
1287
+ or if the string cannot be recognized, parsed, or decoded.
1288
+
1289
+ See :meth:`TOTP.using()` for how to configure application secrets.
1290
+
1291
+ :returns:
1292
+ a :class:`TOTP` instance.
1293
+ """
1294
+ if isinstance(source, TOTP):
1295
+ # return object unchanged if they share same wallet.
1296
+ # otherwise make a new one that's bound to expected wallet.
1297
+ if cls.wallet == source.wallet:
1298
+ return source
1299
+ source = source.to_dict(encrypt=False)
1300
+ if isinstance(source, dict):
1301
+ return cls.from_dict(source)
1302
+ # NOTE: letting to_unicode() raise TypeError in this case
1303
+ source = to_unicode(source, param="totp source")
1304
+ if source.startswith("otpauth://"):
1305
+ return cls.from_uri(source)
1306
+ return cls.from_json(source)
1307
+
1308
+ @classmethod
1309
+ def from_uri(cls, uri):
1310
+ """
1311
+ create an OTP instance from a URI (such as returned by :meth:`to_uri`).
1312
+
1313
+ :returns:
1314
+ :class:`TOTP` instance.
1315
+
1316
+ :raises ValueError:
1317
+ if the uri cannot be parsed or contains errors.
1318
+
1319
+ .. seealso:: :ref:`totp-configuring-clients` tutorial for a usage example
1320
+ """
1321
+ # check for valid uri
1322
+ uri = to_unicode(uri, param="uri").strip()
1323
+ result = urlparse(uri)
1324
+ if result.scheme != "otpauth":
1325
+ raise cls._uri_parse_error("wrong uri scheme")
1326
+
1327
+ # validate netloc, and hand off to helper
1328
+ cls._check_otp_type(result.netloc)
1329
+ return cls._from_parsed_uri(result)
1330
+
1331
+ @classmethod
1332
+ def _check_otp_type(cls, type):
1333
+ """
1334
+ validate otp URI type is supported.
1335
+ returns True or raises appropriate error.
1336
+ """
1337
+ if type == "totp":
1338
+ return True
1339
+ if type == "hotp":
1340
+ raise NotImplementedError("HOTP not supported")
1341
+ raise ValueError(f"unknown otp type: {type!r}")
1342
+
1343
+ @classmethod
1344
+ def _from_parsed_uri(cls, result):
1345
+ """
1346
+ internal from_uri() helper --
1347
+ handles parsing a validated TOTP URI
1348
+
1349
+ :param result:
1350
+ a urlparse() instance
1351
+
1352
+ :returns:
1353
+ cls instance
1354
+ """
1355
+
1356
+ # decode label from uri path
1357
+ label = result.path
1358
+ if label.startswith("/") and len(label) > 1:
1359
+ label = unquote(label[1:])
1360
+ else:
1361
+ raise cls._uri_parse_error("missing label")
1362
+
1363
+ # extract old-style issuer prefix
1364
+ if ":" in label:
1365
+ try:
1366
+ issuer, label = label.split(":")
1367
+ except ValueError: # too many ":"
1368
+ raise cls._uri_parse_error("malformed label")
1369
+ else:
1370
+ issuer = None
1371
+ if label:
1372
+ # NOTE: KeyURI spec says there may be leading spaces
1373
+ label = label.strip() or None
1374
+
1375
+ # parse query params
1376
+ params = dict(label=label)
1377
+ for k, v in parse_qsl(result.query):
1378
+ if k in params:
1379
+ raise cls._uri_parse_error(f"duplicate parameter ({k!r})")
1380
+ params[k] = v
1381
+
1382
+ # synchronize issuer prefix w/ issuer param
1383
+ if issuer:
1384
+ if "issuer" not in params:
1385
+ params["issuer"] = issuer
1386
+ elif params["issuer"] != issuer:
1387
+ raise cls._uri_parse_error("conflicting issuer identifiers")
1388
+
1389
+ # convert query params to constructor kwds, and call constructor
1390
+ return cls(**cls._adapt_uri_params(**params))
1391
+
1392
+ @classmethod
1393
+ def _adapt_uri_params(
1394
+ cls,
1395
+ label=None,
1396
+ secret=None,
1397
+ issuer=None,
1398
+ digits=None,
1399
+ algorithm=None,
1400
+ period=None,
1401
+ **extra,
1402
+ ):
1403
+ """
1404
+ from_uri() helper --
1405
+ converts uri params into constructor args.
1406
+ """
1407
+ assert label, "from_uri() failed to provide label"
1408
+ if not secret:
1409
+ raise cls._uri_parse_error("missing 'secret' parameter")
1410
+ kwds = dict(label=label, issuer=issuer, key=secret, format="base32")
1411
+ if digits:
1412
+ kwds["digits"] = cls._uri_parse_int(digits, "digits")
1413
+ if algorithm:
1414
+ kwds["alg"] = algorithm
1415
+ if period:
1416
+ kwds["period"] = cls._uri_parse_int(period, "period")
1417
+ if extra:
1418
+ # malicious uri, deviation from spec, or newer revision of spec?
1419
+ # in either case, we issue warning and ignore extra params.
1420
+ warn(
1421
+ f"{cls}: unexpected parameters encountered in otp uri: {extra!r}",
1422
+ exc.PasslibRuntimeWarning,
1423
+ )
1424
+ return kwds
1425
+
1426
+ @staticmethod
1427
+ def _uri_parse_error(reason):
1428
+ """uri parsing helper -- creates preformatted error message"""
1429
+ return ValueError(f"Invalid otpauth uri: {reason}")
1430
+
1431
+ @classmethod
1432
+ def _uri_parse_int(cls, source, param):
1433
+ """uri parsing helper -- int() wrapper"""
1434
+ try:
1435
+ return int(source)
1436
+ except ValueError:
1437
+ raise cls._uri_parse_error(f"Malformed {param!r} parameter")
1438
+
1439
+ def to_uri(self, label=None, issuer=None):
1440
+ """
1441
+ Serialize key and configuration into a URI, per
1442
+ Google Auth's `KeyUriFormat <http://code.google.com/p/google-authenticator/wiki/KeyUriFormat>`_.
1443
+
1444
+ :param str label:
1445
+ Label to associate with this token when generating a URI.
1446
+ Displayed to user by most OTP client applications (e.g. Google Authenticator),
1447
+ and typically has format such as ``"John Smith"`` or ``"jsmith@webservice.example.org"``.
1448
+
1449
+ Defaults to **label** constructor argument. Must be provided in one or the other location.
1450
+ May not contain ``:``.
1451
+
1452
+ :param str issuer:
1453
+ String identifying the token issuer (e.g. the domain or canonical name of your service).
1454
+ Optional but strongly recommended if you're rendering to a URI.
1455
+ Used internally by some OTP client applications (e.g. Google Authenticator) to distinguish entries
1456
+ which otherwise have the same label.
1457
+
1458
+ Defaults to **issuer** constructor argument, or ``None``.
1459
+ May not contain ``:``.
1460
+
1461
+ :raises ValueError:
1462
+ * if a label was not provided either as an argument, or in the constructor.
1463
+ * if the label or issuer contains invalid characters.
1464
+
1465
+ :returns:
1466
+ all the configuration information for this OTP token generator,
1467
+ encoded into a URI.
1468
+
1469
+ These URIs are frequently converted to a QRCode for transferring
1470
+ to a TOTP client application such as Google Auth.
1471
+ Usage example::
1472
+
1473
+ >>> from passlib.totp import TOTP
1474
+ >>> tp = TOTP('s3jdvb7qd2r7jpxx')
1475
+ >>> uri = tp.to_uri("user@example.org", "myservice.another-example.org")
1476
+ >>> uri
1477
+ 'otpauth://totp/user@example.org?secret=S3JDVB7QD2R7JPXX&issuer=myservice.another-example.org'
1478
+
1479
+ .. versionchanged:: 1.7.2
1480
+
1481
+ This method now prepends the issuer URI label. This is recommended by the KeyURI
1482
+ specification, for compatibility with older clients.
1483
+ """
1484
+ # encode label
1485
+ if label is None:
1486
+ label = self.label
1487
+ if not label:
1488
+ raise ValueError(
1489
+ "a label must be specified as argument, or in the constructor"
1490
+ )
1491
+ self._check_label(label)
1492
+ # NOTE: reference examples in spec seem to indicate the '@' in a label
1493
+ # shouldn't be escaped, though spec doesn't explicitly address this.
1494
+ # XXX: is '/' ok to leave unencoded?
1495
+ label = quote(label, "@")
1496
+
1497
+ # encode query parameters
1498
+ params = self._to_uri_params()
1499
+ if issuer is None:
1500
+ issuer = self.issuer
1501
+ if issuer:
1502
+ self._check_issuer(issuer)
1503
+ # NOTE: per KeyURI spec, including issuer as part of label is deprecated,
1504
+ # in favor of adding it to query params. however, some QRCode clients
1505
+ # don't recognize the 'issuer' query parameter, so spec recommends (as of 2018-7)
1506
+ # to include both.
1507
+ label = "{}:{}".format(quote(issuer, "@"), label)
1508
+ params.append(("issuer", issuer))
1509
+ # NOTE: not using urllib.urlencode() because it encodes ' ' as '+';
1510
+ # but spec says to use '%20', and not sure how fragile
1511
+ # the various totp clients' parsers are.
1512
+ param_str = "&".join(
1513
+ "{}={}".format(key, quote(value, "")) for key, value in params
1514
+ )
1515
+ assert param_str, "param_str should never be empty"
1516
+
1517
+ # render uri
1518
+ return f"otpauth://totp/{label}?{param_str}"
1519
+
1520
+ def _to_uri_params(self):
1521
+ """return list of (key, param) entries for URI"""
1522
+ args = [("secret", self.base32_key)]
1523
+ if self.alg != "sha1":
1524
+ args.append(("algorithm", self.alg.upper()))
1525
+ if self.digits != 6:
1526
+ args.append(("digits", str(self.digits)))
1527
+ if self.period != 30:
1528
+ args.append(("period", str(self.period)))
1529
+ return args
1530
+
1531
+ @classmethod
1532
+ def from_json(cls, source):
1533
+ """
1534
+ Load / create an OTP object from a serialized json string
1535
+ (as generated by :meth:`to_json`).
1536
+
1537
+ :arg json:
1538
+ Serialized output from :meth:`to_json`, as str or ascii bytes.
1539
+
1540
+ :raises ValueError:
1541
+ If the key has been encrypted, but the application secret isn't available;
1542
+ or if the string cannot be recognized, parsed, or decoded.
1543
+
1544
+ See :meth:`TOTP.using()` for how to configure application secrets.
1545
+
1546
+ :returns:
1547
+ a :class:`TOTP` instance.
1548
+
1549
+ .. seealso:: :ref:`totp-storing-instances` tutorial for a usage example
1550
+ """
1551
+ source = to_unicode(source, param="json source")
1552
+ return cls.from_dict(json.loads(source))
1553
+
1554
+ def to_json(self, encrypt=None):
1555
+ """
1556
+ Serialize configuration & internal state to a json string,
1557
+ mainly useful for persisting client-specific state in a database.
1558
+ All keywords passed to :meth:`to_dict`.
1559
+
1560
+ :returns:
1561
+ json string containing serializes configuration & state.
1562
+ """
1563
+ state = self.to_dict(encrypt=encrypt)
1564
+ return json.dumps(state, sort_keys=True, separators=(",", ":"))
1565
+
1566
+ @classmethod
1567
+ def from_dict(cls, source):
1568
+ """
1569
+ Load / create a TOTP object from a dictionary
1570
+ (as generated by :meth:`to_dict`)
1571
+
1572
+ :param source:
1573
+ dict containing serialized TOTP key & configuration.
1574
+
1575
+ :raises ValueError:
1576
+ If the key has been encrypted, but the application secret isn't available;
1577
+ or if the dict cannot be recognized, parsed, or decoded.
1578
+
1579
+ See :meth:`TOTP.using()` for how to configure application secrets.
1580
+
1581
+ :returns:
1582
+ A :class:`TOTP` instance.
1583
+
1584
+ .. seealso:: :ref:`totp-storing-instances` tutorial for a usage example
1585
+ """
1586
+ if not isinstance(source, dict) or "type" not in source:
1587
+ raise cls._dict_parse_error("unrecognized format")
1588
+ return cls(**cls._adapt_dict_kwds(**source))
1589
+
1590
+ @classmethod
1591
+ def _adapt_dict_kwds(cls, type, **kwds):
1592
+ """
1593
+ Internal helper for .from_json() --
1594
+ Adapts serialized json dict into constructor keywords.
1595
+ """
1596
+ # default json format is just serialization of constructor kwds.
1597
+ # XXX: just pass all this through to _from_json / constructor?
1598
+ # go ahead and mark as changed (needs re-saving) if the version is too old
1599
+ assert cls._check_otp_type(type)
1600
+ ver = kwds.pop("v", None)
1601
+ if not ver or ver < cls.min_json_version or ver > cls.json_version:
1602
+ raise cls._dict_parse_error(f"missing/unsupported version ({ver!r})")
1603
+ if ver != cls.json_version:
1604
+ # mark older version as needing re-serializing
1605
+ kwds["changed"] = True
1606
+ if "enckey" in kwds:
1607
+ # handing encrypted key off to constructor, which handles the
1608
+ # decryption. this lets it get ahold of (and store) the original
1609
+ # encrypted key, so if to_json() is called again, the encrypted
1610
+ # key can be re-used.
1611
+ # XXX: wallet is known at this point, could decrypt key here.
1612
+ assert "key" not in kwds # shouldn't be present w/ enckey
1613
+ kwds.update(key=kwds.pop("enckey"), format="encrypted")
1614
+ elif "key" not in kwds:
1615
+ raise cls._dict_parse_error("missing 'enckey' / 'key'")
1616
+ # XXX: could should set changed=True if active wallet is available,
1617
+ # and source wasn't encrypted.
1618
+ kwds.pop("last_counter", None) # extract legacy counter parameter
1619
+ return kwds
1620
+
1621
+ @staticmethod
1622
+ def _dict_parse_error(reason):
1623
+ """dict parsing helper -- creates preformatted error message"""
1624
+ return ValueError(f"Invalid totp data: {reason}")
1625
+
1626
+ def to_dict(self, encrypt=None):
1627
+ """
1628
+ Serialize configuration & internal state to a dict,
1629
+ mainly useful for persisting client-specific state in a database.
1630
+
1631
+ :param encrypt:
1632
+ Whether to output should be encrypted.
1633
+
1634
+ * ``None`` (the default) -- uses encrypted key if application
1635
+ secrets are available, otherwise uses plaintext key.
1636
+ * ``True`` -- uses encrypted key, or raises TypeError
1637
+ if application secret wasn't provided to OTP constructor.
1638
+ * ``False`` -- uses raw key.
1639
+
1640
+ :returns:
1641
+ dictionary, containing basic (json serializable) datatypes.
1642
+ """
1643
+ # NOTE: 'type' may seem redundant, but using it so code can try to
1644
+ # detect that this *is* a TOTP json string / dict.
1645
+ state = dict(v=self.json_version, type="totp")
1646
+ if self.alg != "sha1":
1647
+ state["alg"] = self.alg
1648
+ if self.digits != 6:
1649
+ state["digits"] = self.digits
1650
+ if self.period != 30:
1651
+ state["period"] = self.period
1652
+ # XXX: should we include label as part of json format?
1653
+ if self.label:
1654
+ state["label"] = self.label
1655
+ issuer = self.issuer
1656
+ if issuer and issuer != type(self).issuer:
1657
+ # (omit issuer if it matches class default)
1658
+ state["issuer"] = issuer
1659
+ if encrypt is None:
1660
+ wallet = self.wallet
1661
+ encrypt = wallet and wallet.has_secrets
1662
+ if encrypt:
1663
+ state["enckey"] = self.encrypted_key
1664
+ else:
1665
+ state["key"] = self.base32_key
1666
+ # NOTE: in the future, may add a "history" parameter
1667
+ # containing a list of (time, skipped) pairs, encoding
1668
+ # the last X successful verifications, to allow persisting
1669
+ # & estimating client clock skew over time.
1670
+ return state
1671
+
1672
+
1673
+ class TotpToken(SequenceMixin):
1674
+ """
1675
+ Object returned by :meth:`TOTP.generate`.
1676
+ It can be treated as a sequence of ``(token, expire_time)``,
1677
+ or accessed via the following attributes:
1678
+
1679
+ .. autoattribute:: token
1680
+ .. autoattribute:: expire_time
1681
+ .. autoattribute:: counter
1682
+ .. autoattribute:: remaining
1683
+ .. autoattribute:: valid
1684
+ """
1685
+
1686
+ #: TOTP object that generated this token
1687
+ totp = None
1688
+
1689
+ #: Token as decimal-encoded ascii string.
1690
+ token = None
1691
+
1692
+ #: HOTP counter value used to generate token (derived from time)
1693
+ counter = None
1694
+
1695
+ def __init__(self, totp, token, counter):
1696
+ """
1697
+ .. warning::
1698
+ the constructor signature is an internal detail, and is subject to change.
1699
+ """
1700
+ self.totp = totp
1701
+ self.token = token
1702
+ self.counter = counter
1703
+
1704
+ @memoized_property
1705
+ def start_time(self):
1706
+ """Timestamp marking beginning of period when token is valid"""
1707
+ return self.totp._counter_to_time(self.counter)
1708
+
1709
+ @memoized_property
1710
+ def expire_time(self):
1711
+ """Timestamp marking end of period when token is valid"""
1712
+ return self.totp._counter_to_time(self.counter + 1)
1713
+
1714
+ @property
1715
+ def remaining(self):
1716
+ """number of (float) seconds before token expires"""
1717
+ return max(0, self.expire_time - self.totp.now())
1718
+
1719
+ @property
1720
+ def valid(self):
1721
+ """whether token is still valid"""
1722
+ return bool(self.remaining)
1723
+
1724
+ def _as_tuple(self):
1725
+ return self.token, self.expire_time
1726
+
1727
+ def __repr__(self):
1728
+ expired = "" if self.remaining else " expired"
1729
+ return "<TotpToken token='%s' expire_time=%d%s>" % (
1730
+ self.token,
1731
+ self.expire_time,
1732
+ expired,
1733
+ )
1734
+
1735
+
1736
+ class TotpMatch(SequenceMixin):
1737
+ """
1738
+ Object returned by :meth:`TOTP.match` and :meth:`TOTP.verify` on a successful match.
1739
+
1740
+ It can be treated as a sequence of ``(counter, time)``,
1741
+ or accessed via the following attributes:
1742
+
1743
+ .. autoattribute:: counter
1744
+ :annotation: = 0
1745
+
1746
+ .. autoattribute:: time
1747
+ :annotation: = 0
1748
+
1749
+ .. autoattribute:: expected_counter
1750
+ :annotation: = 0
1751
+
1752
+ .. autoattribute:: skipped
1753
+ :annotation: = 0
1754
+
1755
+ .. autoattribute:: expire_time
1756
+ :annotation: = 0
1757
+
1758
+ .. autoattribute:: cache_seconds
1759
+ :annotation: = 60
1760
+
1761
+ .. autoattribute:: cache_time
1762
+ :annotation: = 0
1763
+
1764
+ This object will always have a ``True`` boolean value.
1765
+ """
1766
+
1767
+ #: TOTP object that generated this token
1768
+ totp = None
1769
+
1770
+ #: TOTP counter value which matched token.
1771
+ #: (Best practice is to subsequently ignore tokens matching this counter
1772
+ #: or earlier)
1773
+ counter = 0
1774
+
1775
+ #: Timestamp when verification was performed.
1776
+ time = 0
1777
+
1778
+ #: Search window used by verify() (affects cache_time)
1779
+ window = 30
1780
+
1781
+ def __init__(self, totp, counter, time, window=30):
1782
+ """
1783
+ .. warning::
1784
+ the constructor signature is an internal detail, and is subject to change.
1785
+ """
1786
+ self.totp = totp
1787
+ self.counter = counter
1788
+ self.time = time
1789
+ self.window = window
1790
+
1791
+ @memoized_property
1792
+ def expected_counter(self):
1793
+ """
1794
+ Counter value expected for timestamp.
1795
+ """
1796
+ return self.totp._time_to_counter(self.time)
1797
+
1798
+ @memoized_property
1799
+ def skipped(self):
1800
+ """
1801
+ How many steps were skipped between expected and actual matched counter
1802
+ value (may be positive, zero, or negative).
1803
+ """
1804
+ return self.counter - self.expected_counter
1805
+
1806
+ # @memoized_property
1807
+ # def start_time(self):
1808
+ # """Timestamp marking start of period when token is valid"""
1809
+ # return self.totp._counter_to_time(self.counter + 1)
1810
+
1811
+ @memoized_property
1812
+ def expire_time(self):
1813
+ """Timestamp marking end of period when token is valid"""
1814
+ return self.totp._counter_to_time(self.counter + 1)
1815
+
1816
+ @memoized_property
1817
+ def cache_seconds(self):
1818
+ """
1819
+ Number of seconds counter should be cached
1820
+ before it's guaranteed to have passed outside of verification window.
1821
+ """
1822
+ # XXX: real value is 'cache_time - now()',
1823
+ # but this is a cheaper upper bound.
1824
+ return self.totp.period + self.window
1825
+
1826
+ @memoized_property
1827
+ def cache_time(self):
1828
+ """
1829
+ Timestamp marking when counter has passed outside of verification window.
1830
+ """
1831
+ return self.expire_time + self.window
1832
+
1833
+ def _as_tuple(self):
1834
+ return self.counter, self.time
1835
+
1836
+ def __repr__(self):
1837
+ args = (self.counter, self.time, self.cache_seconds)
1838
+ return "<TotpMatch counter=%d time=%d cache_seconds=%d>" % args
1839
+
1840
+
1841
+ def generate_secret(entropy=256, charset=BASE64_CHARS[:-2]):
1842
+ """
1843
+ generate a random string suitable for use as an
1844
+ :class:`AppWallet` application secret.
1845
+
1846
+ :param entropy:
1847
+ number of bits of entropy (controls size/complexity of password).
1848
+ """
1849
+ assert entropy > 0
1850
+ assert len(charset) > 1
1851
+ count = int(math.ceil(entropy * math.log(2, len(charset))))
1852
+ return getrandstr(rng, charset, count)