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/context.py ADDED
@@ -0,0 +1,1944 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from configparser import ConfigParser
5
+ from io import StringIO
6
+ from warnings import warn
7
+
8
+ from passlib import exc
9
+ from passlib.exc import ExpectedStringError, ExpectedTypeError, PasslibConfigWarning
10
+ from passlib.registry import _validate_handler_name, get_crypt_handler
11
+ from passlib.utils import (
12
+ handlers as uh,
13
+ )
14
+ from passlib.utils import (
15
+ splitcomma,
16
+ to_unicode,
17
+ )
18
+ from passlib.utils.compat import (
19
+ numeric_types,
20
+ unicode_or_bytes,
21
+ )
22
+ from passlib.utils.decor import deprecated_method, memoized_property
23
+
24
+ # local
25
+ __all__ = [
26
+ "CryptContext",
27
+ "LazyCryptContext",
28
+ ]
29
+
30
+
31
+ # private object to detect unset params
32
+ _UNSET = object()
33
+
34
+
35
+ def _coerce_vary_rounds(value: str) -> float | int:
36
+ """parse vary_rounds string to percent as [0,1) float, or integer"""
37
+ if value.endswith("%"):
38
+ # XXX: deprecate this in favor of raw float?
39
+ return float(value.rstrip("%")) * 0.01
40
+ try:
41
+ return int(value)
42
+ except ValueError:
43
+ return float(value)
44
+
45
+
46
+ # set of options which aren't allowed to be set via policy
47
+ _forbidden_scheme_options = set(["salt"])
48
+ # 'salt' - not allowed since a fixed salt would defeat the purpose.
49
+
50
+ # dict containing funcs used to coerce strings to correct type for scheme option keys.
51
+ # NOTE: this isn't really needed any longer, since Handler.using() handles the actual parsing.
52
+ # keeping this around for now, though, since it makes context.to_dict() output cleaner.
53
+ _coerce_scheme_options = dict(
54
+ min_rounds=int,
55
+ max_rounds=int,
56
+ default_rounds=int,
57
+ vary_rounds=_coerce_vary_rounds,
58
+ salt_size=int,
59
+ )
60
+
61
+
62
+ def _is_handler_registered(handler):
63
+ """detect if handler is registered or a custom handler"""
64
+ return get_crypt_handler(handler.name, None) is handler
65
+
66
+
67
+ #: list of keys allowed under wildcard "all" scheme w/o a security warning.
68
+ _global_settings = set(["truncate_error", "vary_rounds"])
69
+
70
+
71
+ class _CryptConfig:
72
+ """parses, validates, and stores CryptContext config
73
+
74
+ this is a helper used internally by CryptContext to handle
75
+ parsing, validation, and serialization of its config options.
76
+ split out from the main class, but not made public since
77
+ that just complicates interface too much (c.f. CryptPolicy)
78
+
79
+ :arg source: config as dict mapping ``(cat,scheme,option) -> value``
80
+ """
81
+
82
+ # triple-nested dict which maps scheme -> category -> key -> value,
83
+ # storing all hash-specific options
84
+ _scheme_options = None
85
+
86
+ # double-nested dict which maps key -> category -> value
87
+ # storing all CryptContext options
88
+ _context_options = None
89
+
90
+ # tuple of handler objects
91
+ handlers = None
92
+
93
+ # tuple of scheme objects in same order as handlers
94
+ schemes = None
95
+
96
+ # tuple of categories in alphabetical order (not including None)
97
+ categories = None
98
+
99
+ # set of all context keywords used by active schemes
100
+ context_kwds = None
101
+
102
+ # dict mapping category -> default scheme
103
+ _default_schemes = None
104
+
105
+ # dict mapping (scheme, category) -> custom handler
106
+ _records = None
107
+
108
+ # dict mapping category -> list of custom handler instances for that category,
109
+ # in order of schemes(). populated on demand by _get_record_list()
110
+ _record_lists = None
111
+
112
+ def __init__(self, source):
113
+ self._init_scheme_list(source.get((None, None, "schemes")))
114
+ self._init_options(source)
115
+ self._init_default_schemes()
116
+ self._init_records()
117
+
118
+ def _init_scheme_list(self, data):
119
+ """initialize .handlers and .schemes attributes"""
120
+ handlers = []
121
+ schemes = []
122
+ if isinstance(data, str):
123
+ data = splitcomma(data)
124
+ for elem in data or ():
125
+ # resolve elem -> handler & scheme
126
+ if hasattr(elem, "name"):
127
+ handler = elem
128
+ scheme = handler.name
129
+ _validate_handler_name(scheme)
130
+ elif isinstance(elem, str):
131
+ handler = get_crypt_handler(elem)
132
+ scheme = handler.name
133
+ else:
134
+ raise TypeError(
135
+ f"scheme must be name or CryptHandler, not {type(elem)!r}"
136
+ )
137
+
138
+ # check scheme name isn't already in use
139
+ if scheme in schemes:
140
+ raise KeyError(f"multiple handlers with same name: {scheme!r}")
141
+
142
+ # add to handler list
143
+ handlers.append(handler)
144
+ schemes.append(scheme)
145
+
146
+ self.handlers = tuple(handlers)
147
+ self.schemes = tuple(schemes)
148
+
149
+ def _init_options(self, source):
150
+ """load config dict into internal representation,
151
+ and init .categories attr
152
+ """
153
+ # prepare dicts & locals
154
+ norm_scheme_option = self._norm_scheme_option
155
+ norm_context_option = self._norm_context_option
156
+ self._scheme_options = scheme_options = {}
157
+ self._context_options = context_options = {}
158
+ categories = set()
159
+
160
+ # load source config into internal storage
161
+ for (cat, scheme, key), value in source.items():
162
+ categories.add(cat)
163
+ explicit_scheme = scheme
164
+ if not cat and not scheme and key in _global_settings:
165
+ # going forward, not using "<cat>__all__<key>" format. instead...
166
+ # whitelisting set of keys which should be passed to (all) schemes,
167
+ # rather than passed to the CryptContext itself
168
+ scheme = "all"
169
+ if scheme:
170
+ # normalize scheme option
171
+ key, value = norm_scheme_option(key, value)
172
+
173
+ # e.g. things like "min_rounds" should never be set cross-scheme
174
+ # this will be fatal under 2.0.
175
+ if scheme == "all" and key not in _global_settings:
176
+ warn(
177
+ f"The '{key}' option should be configured per-algorithm, and not set "
178
+ "globally in the context; This will be an error in Passlib 2.0",
179
+ PasslibConfigWarning,
180
+ )
181
+
182
+ # this scheme is going away in 2.0;
183
+ # but most keys deserve an extra warning since it impacts security.
184
+ if explicit_scheme == "all":
185
+ warn(
186
+ "The 'all' scheme is deprecated as of Passlib 1.7, "
187
+ "and will be removed in Passlib 2.0; Please configure "
188
+ "options on a per-algorithm basis.",
189
+ DeprecationWarning,
190
+ )
191
+
192
+ # store in scheme_options
193
+ # map structure: scheme_options[scheme][category][key] = value
194
+ try:
195
+ category_map = scheme_options[scheme]
196
+ except KeyError:
197
+ scheme_options[scheme] = {cat: {key: value}}
198
+ else:
199
+ try:
200
+ option_map = category_map[cat]
201
+ except KeyError:
202
+ category_map[cat] = {key: value}
203
+ else:
204
+ option_map[key] = value
205
+ else:
206
+ # normalize context option
207
+ if cat and key == "schemes":
208
+ raise KeyError(
209
+ "'schemes' context option is not allowed per category"
210
+ )
211
+ key, value = norm_context_option(cat, key, value)
212
+
213
+ # store in context_options
214
+ # map structure: context_options[key][category] = value
215
+ try:
216
+ category_map = context_options[key]
217
+ except KeyError:
218
+ context_options[key] = {cat: value}
219
+ else:
220
+ category_map[cat] = value
221
+
222
+ # store list of configured categories
223
+ categories.discard(None)
224
+ self.categories = tuple(sorted(categories))
225
+
226
+ def _norm_scheme_option(self, key, value):
227
+ # check for invalid options
228
+ if key in _forbidden_scheme_options:
229
+ raise KeyError(f"{key!r} option not allowed in CryptContext configuration")
230
+ # coerce strings for certain fields (e.g. min_rounds uses ints)
231
+ if isinstance(value, str):
232
+ func = _coerce_scheme_options.get(key)
233
+ if func:
234
+ value = func(value)
235
+ return key, value
236
+
237
+ def _norm_context_option(self, cat, key, value):
238
+ schemes = self.schemes
239
+ if key == "default":
240
+ if hasattr(value, "name"):
241
+ value = value.name
242
+ elif not isinstance(value, str):
243
+ raise ExpectedTypeError(value, "str", "default")
244
+ if schemes and value not in schemes:
245
+ raise KeyError("default scheme not found in policy")
246
+ elif key == "deprecated":
247
+ if isinstance(value, str):
248
+ value = splitcomma(value)
249
+ elif not isinstance(value, (list, tuple)):
250
+ raise ExpectedTypeError(value, "str or seq", "deprecated")
251
+ if "auto" in value:
252
+ # XXX: have any statements been made about when this is default?
253
+ # should do it in 1.8 at latest.
254
+ if len(value) > 1:
255
+ raise ValueError(
256
+ "cannot list other schemes if ``deprecated=['auto']`` is used"
257
+ )
258
+ elif schemes:
259
+ # make sure list of deprecated schemes is subset of configured schemes
260
+ for scheme in value:
261
+ if not isinstance(scheme, str):
262
+ raise ExpectedTypeError(value, "str", "deprecated element")
263
+ if scheme not in schemes:
264
+ raise KeyError(
265
+ f"deprecated scheme not found in policy: {scheme!r}"
266
+ )
267
+ elif key != "schemes":
268
+ raise KeyError(f"unknown CryptContext keyword: {key!r}")
269
+ return key, value
270
+
271
+ # ---------------------------------------------------------------
272
+ # reading context options
273
+ # ---------------------------------------------------------------
274
+ def get_context_optionmap(self, key, _default={}):
275
+ """return dict mapping category->value for specific context option.
276
+
277
+ .. warning:: treat return value as readonly!
278
+ """
279
+ return self._context_options.get(key, _default)
280
+
281
+ def get_context_option_with_flag(self, category, key):
282
+ """return value of specific option, handling category inheritance.
283
+ also returns flag indicating whether value is category-specific.
284
+ """
285
+ try:
286
+ category_map = self._context_options[key]
287
+ except KeyError:
288
+ return None, False
289
+ value = category_map.get(None)
290
+ if category:
291
+ try:
292
+ alt = category_map[category]
293
+ except KeyError:
294
+ pass
295
+ else:
296
+ if value is None or alt != value:
297
+ return alt, True
298
+ return value, False
299
+
300
+ # ---------------------------------------------------------------
301
+ # reading scheme options
302
+ # ---------------------------------------------------------------
303
+ def _get_scheme_optionmap(self, scheme, category, default={}):
304
+ """return all options for (scheme,category) combination
305
+
306
+ .. warning:: treat return value as readonly!
307
+ """
308
+ try:
309
+ return self._scheme_options[scheme][category]
310
+ except KeyError:
311
+ return default
312
+
313
+ def get_base_handler(self, scheme):
314
+ return self.handlers[self.schemes.index(scheme)]
315
+
316
+ @staticmethod
317
+ def expand_settings(handler):
318
+ setting_kwds = handler.setting_kwds
319
+ if "rounds" in handler.setting_kwds:
320
+ # XXX: historically this extras won't be listed in setting_kwds
321
+ setting_kwds += uh.HasRounds.using_rounds_kwds
322
+ return setting_kwds
323
+
324
+ # NOTE: this is only used by _get_record_options_with_flag()...
325
+ def get_scheme_options_with_flag(self, scheme, category):
326
+ """return composite dict of all options set for scheme.
327
+ includes options inherited from 'all' and from default category.
328
+ result can be modified.
329
+ returns (kwds, has_cat_specific_options)
330
+ """
331
+ # start out with copy of global options
332
+ get_optionmap = self._get_scheme_optionmap
333
+ kwds = get_optionmap("all", None).copy()
334
+ has_cat_options = False
335
+
336
+ # add in category-specific global options
337
+ if category:
338
+ defkwds = kwds.copy() # <-- used to detect category-specific options
339
+ kwds.update(get_optionmap("all", category))
340
+
341
+ # filter out global settings not supported by handler
342
+ allowed_settings = self.expand_settings(self.get_base_handler(scheme))
343
+ for key in set(kwds).difference(allowed_settings):
344
+ kwds.pop(key)
345
+ if category:
346
+ for key in set(defkwds).difference(allowed_settings):
347
+ defkwds.pop(key)
348
+
349
+ # add in default options for scheme
350
+ other = get_optionmap(scheme, None)
351
+ kwds.update(other)
352
+
353
+ # load category-specific options for scheme
354
+ if category:
355
+ defkwds.update(other)
356
+ kwds.update(get_optionmap(scheme, category))
357
+
358
+ # compare default category options to see if there's anything
359
+ # category-specific
360
+ if kwds != defkwds:
361
+ has_cat_options = True
362
+
363
+ return kwds, has_cat_options
364
+
365
+ def _init_default_schemes(self):
366
+ """initialize maps containing default scheme for each category.
367
+
368
+ have to do this after _init_options(), since the default scheme
369
+ is affected by the list of deprecated schemes.
370
+ """
371
+ # init maps & locals
372
+ get_optionmap = self.get_context_optionmap
373
+ default_map = self._default_schemes = get_optionmap("default").copy()
374
+ dep_map = get_optionmap("deprecated")
375
+ schemes = self.schemes
376
+ if not schemes:
377
+ return
378
+
379
+ # figure out default scheme
380
+ deps = dep_map.get(None) or ()
381
+ default = default_map.get(None)
382
+ if not default:
383
+ for scheme in schemes:
384
+ if scheme not in deps:
385
+ default_map[None] = scheme
386
+ break
387
+ else:
388
+ raise ValueError("must have at least one non-deprecated scheme")
389
+ elif default in deps:
390
+ raise ValueError("default scheme cannot be deprecated")
391
+
392
+ # figure out per-category default schemes,
393
+ for cat in self.categories:
394
+ cdeps = dep_map.get(cat, deps)
395
+ cdefault = default_map.get(cat, default)
396
+ if not cdefault:
397
+ for scheme in schemes:
398
+ if scheme not in cdeps:
399
+ default_map[cat] = scheme
400
+ break
401
+ else:
402
+ raise ValueError(
403
+ "must have at least one non-deprecated "
404
+ f"scheme for {cat!r} category"
405
+ )
406
+ elif cdefault in cdeps:
407
+ raise ValueError(
408
+ f"default scheme for {cat!r} category cannot be deprecated"
409
+ )
410
+
411
+ def default_scheme(self, category):
412
+ """return default scheme for specific category"""
413
+ defaults = self._default_schemes
414
+ try:
415
+ return defaults[category]
416
+ except KeyError:
417
+ pass
418
+ if not self.schemes:
419
+ raise KeyError("no hash schemes configured for this CryptContext instance")
420
+ return defaults[None]
421
+
422
+ def is_deprecated_with_flag(self, scheme, category):
423
+ """is scheme deprecated under particular category?"""
424
+ depmap = self.get_context_optionmap("deprecated")
425
+
426
+ def test(cat):
427
+ source = depmap.get(cat, depmap.get(None))
428
+ if source is None:
429
+ return None
430
+ if "auto" in source:
431
+ return scheme != self.default_scheme(cat)
432
+ return scheme in source
433
+
434
+ value = test(None) or False
435
+ if category:
436
+ alt = test(category)
437
+ if alt is not None and value != alt:
438
+ return alt, True
439
+ return value, False
440
+
441
+ def _init_records(self):
442
+ # NOTE: this step handles final validation of settings,
443
+ # checking for violations against handler's internal invariants.
444
+ # this is why we create all the records now,
445
+ # so CryptContext throws error immediately rather than later.
446
+ self._record_lists = {}
447
+ records = self._records = {}
448
+ all_context_kwds = self.context_kwds = set()
449
+ get_options = self._get_record_options_with_flag
450
+ categories = (None,) + self.categories
451
+ for handler in self.handlers:
452
+ scheme = handler.name
453
+ all_context_kwds.update(handler.context_kwds)
454
+ for cat in categories:
455
+ kwds, has_cat_options = get_options(scheme, cat)
456
+ if cat is None or has_cat_options:
457
+ records[scheme, cat] = self._create_record(handler, cat, **kwds)
458
+ # NOTE: if handler has no category-specific opts, get_record()
459
+ # will automatically use the default category's record.
460
+ # NOTE: default records for specific category stored under the
461
+ # key (None,category); these are populated on-demand by get_record().
462
+
463
+ @staticmethod
464
+ def _create_record(handler, category=None, deprecated=False, **settings):
465
+ # create custom handler if needed.
466
+ try:
467
+ # XXX: relaxed=True is mostly here to retain backwards-compat behavior.
468
+ # could make this optional flag in future.
469
+ subcls = handler.using(relaxed=True, **settings)
470
+ except TypeError as err:
471
+ m = re.match(r".* unexpected keyword argument '(.*)'$", str(err))
472
+ if m and m.group(1) in settings:
473
+ # translate into KeyError, for backwards compat.
474
+ # XXX: push this down to GenericHandler.using() implementation?
475
+ key = m.group(1)
476
+ raise KeyError(
477
+ f"keyword not supported by {handler.name} handler: {key!r}"
478
+ )
479
+ raise
480
+
481
+ # using private attrs to store some extra metadata in custom handler
482
+ assert subcls is not handler, "expected unique variant of handler"
483
+ ##subcls._Context__category = category
484
+ subcls._Context__orig_handler = handler
485
+ subcls.deprecated = deprecated # attr reserved for this purpose
486
+ return subcls
487
+
488
+ def _get_record_options_with_flag(self, scheme, category):
489
+ """return composite dict of options for given scheme + category.
490
+
491
+ this is currently a private method, though some variant
492
+ of its output may eventually be made public.
493
+
494
+ given a scheme & category, it returns two things:
495
+ a set of all the keyword options to pass to :meth:`_create_record`,
496
+ and a bool flag indicating whether any of these options
497
+ were specific to the named category. if this flag is false,
498
+ the options are identical to the options for the default category.
499
+
500
+ the options dict includes all the scheme-specific settings,
501
+ as well as optional *deprecated* keyword.
502
+ """
503
+ # get scheme options
504
+ kwds, has_cat_options = self.get_scheme_options_with_flag(scheme, category)
505
+
506
+ # throw in deprecated flag
507
+ value, not_inherited = self.is_deprecated_with_flag(scheme, category)
508
+ if value:
509
+ kwds["deprecated"] = True
510
+ if not_inherited:
511
+ has_cat_options = True
512
+
513
+ return kwds, has_cat_options
514
+
515
+ def get_record(self, scheme, category):
516
+ """return record for specific scheme & category (cached)"""
517
+ # NOTE: this is part of the critical path shared by
518
+ # all of CryptContext's PasswordHash methods,
519
+ # hence all the caching and error checking.
520
+
521
+ # quick lookup in cache
522
+ try:
523
+ return self._records[scheme, category]
524
+ except KeyError:
525
+ pass
526
+
527
+ # type check
528
+ if category is not None and not isinstance(category, str):
529
+ raise ExpectedTypeError(category, "str or None", "category")
530
+ if scheme is not None and not isinstance(scheme, str):
531
+ raise ExpectedTypeError(scheme, "str or None", "scheme")
532
+
533
+ # if scheme=None,
534
+ # use record for category's default scheme, and cache result.
535
+ if not scheme:
536
+ default = self.default_scheme(category)
537
+ assert default
538
+ record = self._records[None, category] = self.get_record(default, category)
539
+ return record
540
+
541
+ # if no record for (scheme, category),
542
+ # use record for (scheme, None), and cache result.
543
+ if category:
544
+ try:
545
+ cache = self._records
546
+ record = cache[scheme, category] = cache[scheme, None]
547
+ return record
548
+ except KeyError:
549
+ pass
550
+
551
+ # scheme not found in configuration for default category
552
+ raise KeyError(f"crypt algorithm not found in policy: {scheme!r}")
553
+
554
+ def _get_record_list(self, category=None):
555
+ """return list of records for category (cached)
556
+
557
+ this is an internal helper used only by identify_record()
558
+ """
559
+ # type check of category - handled by _get_record()
560
+ # quick lookup in cache
561
+ try:
562
+ return self._record_lists[category]
563
+ except KeyError:
564
+ pass
565
+ # cache miss - build list from scratch
566
+ value = self._record_lists[category] = [
567
+ self.get_record(scheme, category) for scheme in self.schemes
568
+ ]
569
+ return value
570
+
571
+ def identify_record(self, hash, category, required=True):
572
+ """internal helper to identify appropriate custom handler for hash"""
573
+ # NOTE: this is part of the critical path shared by
574
+ # all of CryptContext's PasswordHash methods,
575
+ # hence all the caching and error checking.
576
+ # FIXME: if multiple hashes could match (e.g. lmhash vs nthash)
577
+ # this will only return first match. might want to do something
578
+ # about this in future, but for now only hashes with
579
+ # unique identifiers will work properly in a CryptContext.
580
+ # XXX: if all handlers have a unique prefix (e.g. all are MCF / LDAP),
581
+ # could use dict-lookup to speed up this search.
582
+ if not isinstance(hash, unicode_or_bytes):
583
+ raise ExpectedStringError(hash, "hash")
584
+ # type check of category - handled by _get_record_list()
585
+ for record in self._get_record_list(category):
586
+ if record.identify(hash):
587
+ return record
588
+ if not required:
589
+ return None
590
+ if not self.schemes:
591
+ raise KeyError("no crypt algorithms supported")
592
+ raise exc.UnknownHashError("hash could not be identified")
593
+
594
+ @memoized_property
595
+ def disabled_record(self):
596
+ for record in self._get_record_list(None):
597
+ if record.is_disabled:
598
+ return record
599
+ raise RuntimeError(
600
+ "no disabled hasher present "
601
+ "(perhaps add 'unix_disabled' to list of schemes?)"
602
+ )
603
+
604
+ def iter_config(self, resolve=False):
605
+ """regenerate original config.
606
+
607
+ this is an iterator which yields ``(cat,scheme,option),value`` items,
608
+ in the order they generally appear inside an INI file.
609
+ if interpreted as a dictionary, it should match the original
610
+ keywords passed to the CryptContext (aside from any canonization).
611
+
612
+ it's mainly used as the internal backend for most of the public
613
+ serialization methods.
614
+ """
615
+ # grab various bits of data
616
+ scheme_options = self._scheme_options
617
+ context_options = self._context_options
618
+ scheme_keys = sorted(scheme_options)
619
+ context_keys = sorted(context_options)
620
+
621
+ # write loaded schemes (may differ from 'schemes' local var)
622
+ if "schemes" in context_keys:
623
+ context_keys.remove("schemes")
624
+ value = self.handlers if resolve else self.schemes
625
+ if value:
626
+ yield (None, None, "schemes"), list(value)
627
+
628
+ # then run through config for each user category
629
+ for cat in (None,) + self.categories:
630
+ # write context options
631
+ for key in context_keys:
632
+ try:
633
+ value = context_options[key][cat]
634
+ except KeyError: # noqa: PERF203
635
+ pass
636
+ else:
637
+ if isinstance(value, list):
638
+ value = list(value)
639
+ yield (cat, None, key), value
640
+
641
+ # write per-scheme options for all schemes.
642
+ for scheme in scheme_keys:
643
+ try:
644
+ kwds = scheme_options[scheme][cat]
645
+ except KeyError: # noqa: PERF203
646
+ pass
647
+ else:
648
+ for key in sorted(kwds):
649
+ yield (cat, scheme, key), kwds[key]
650
+
651
+
652
+ class CryptContext:
653
+ """Helper for hashing & verifying passwords using multiple algorithms.
654
+
655
+ Instances of this class allow applications to choose a specific
656
+ set of hash algorithms which they wish to support, set limits and defaults
657
+ for the rounds and salt sizes those algorithms should use, flag
658
+ which algorithms should be deprecated, and automatically handle
659
+ migrating users to stronger hashes when they log in.
660
+
661
+ Basic usage::
662
+
663
+ >>> ctx = CryptContext(schemes=[...])
664
+
665
+ See the Passlib online documentation for details and full documentation.
666
+ """
667
+
668
+ # FIXME: altering the configuration of this object isn't threadsafe,
669
+ # but is generally only done during application init, so not a major
670
+ # issue (just yet).
671
+
672
+ # XXX: would like some way to restrict the categories that are allowed,
673
+ # to restrict what the app OR the config can use.
674
+
675
+ # XXX: add wrap/unwrap callback hooks so app can mutate hash format?
676
+
677
+ # XXX: add method for detecting and warning user about schemes
678
+ # which don't have any good distinguishing marks?
679
+ # or greedy ones (unix_disabled, plaintext) which are not listed at the end?
680
+
681
+ # _CryptConfig instance holding current parsed config
682
+ _config = None
683
+
684
+ # copy of _config methods, stored in CryptContext instance for speed.
685
+ _get_record = None
686
+ _identify_record = None
687
+
688
+ @classmethod
689
+ def _norm_source(cls, source):
690
+ """internal helper - accepts string, dict, or context"""
691
+ if isinstance(source, dict):
692
+ return cls(**source)
693
+ if isinstance(source, cls):
694
+ return source
695
+ self = cls()
696
+ self.load(source)
697
+ return self
698
+
699
+ @classmethod
700
+ def from_string(cls, source, section="passlib", encoding="utf-8"):
701
+ """create new CryptContext instance from an INI-formatted string.
702
+
703
+ :type source: str or bytes
704
+ :arg source:
705
+ string containing INI-formatted content.
706
+
707
+ :type section: str
708
+ :param section:
709
+ option name of section to read from, defaults to ``"passlib"``.
710
+
711
+ :type encoding: str
712
+ :arg encoding:
713
+ optional encoding used when source is bytes, defaults to ``"utf-8"``.
714
+
715
+ :returns:
716
+ new :class:`CryptContext` instance, configured based on the
717
+ parameters in the *source* string.
718
+
719
+ Usage example::
720
+
721
+ >>> from passlib.context import CryptContext
722
+ >>> context = CryptContext.from_string('''
723
+ ... [passlib]
724
+ ... schemes = sha256_crypt, des_crypt
725
+ ... sha256_crypt__default_rounds = 30000
726
+ ... ''')
727
+
728
+ .. versionadded:: 1.6
729
+
730
+ .. seealso:: :meth:`to_string`, the inverse of this constructor.
731
+ """
732
+ if not isinstance(source, unicode_or_bytes):
733
+ raise ExpectedTypeError(source, "str or bytes", "source")
734
+ self = cls(_autoload=False)
735
+ self.load(source, section=section, encoding=encoding)
736
+ return self
737
+
738
+ @classmethod
739
+ def from_path(cls, path, section="passlib", encoding="utf-8"):
740
+ """create new CryptContext instance from an INI-formatted file.
741
+
742
+ this functions exactly the same as :meth:`from_string`,
743
+ except that it loads from a local file.
744
+
745
+ :type path: str
746
+ :arg path:
747
+ path to local file containing INI-formatted config.
748
+
749
+ :type section: str
750
+ :param section:
751
+ option name of section to read from, defaults to ``"passlib"``.
752
+
753
+ :type encoding: str
754
+ :arg encoding:
755
+ encoding used to load file, defaults to ``"utf-8"``.
756
+
757
+ :returns:
758
+ new CryptContext instance, configured based on the parameters
759
+ stored in the file *path*.
760
+
761
+ .. versionadded:: 1.6
762
+
763
+ .. seealso:: :meth:`from_string` for an equivalent usage example.
764
+ """
765
+ self = cls(_autoload=False)
766
+ self.load_path(path, section=section, encoding=encoding)
767
+ return self
768
+
769
+ def copy(self, **kwds):
770
+ """Return copy of existing CryptContext instance.
771
+
772
+ This function returns a new CryptContext instance whose configuration
773
+ is exactly the same as the original, with the exception that any keywords
774
+ passed in will take precedence over the original settings.
775
+ As an example::
776
+
777
+ >>> from passlib.context import CryptContext
778
+
779
+ >>> # given an existing context...
780
+ >>> ctx1 = CryptContext(["sha256_crypt", "md5_crypt"])
781
+
782
+ >>> # copy can be used to make a clone, and update
783
+ >>> # some of the settings at the same time...
784
+ >>> ctx2 = custom_app_context.copy(default="md5_crypt")
785
+
786
+ >>> # and the original will be unaffected by the change
787
+ >>> ctx1.default_scheme()
788
+ "sha256_crypt"
789
+ >>> ctx2.default_scheme()
790
+ "md5_crypt"
791
+
792
+ .. versionadded:: 1.6
793
+ This method was previously named :meth:`!replace`. That alias
794
+ was removed in Passlib 1.8.
795
+
796
+ .. seealso:: :meth:`update`
797
+ """
798
+ # XXX: it would be faster to store ref to self._config,
799
+ # but don't want to share config objects til sure
800
+ # can rely on them being immutable.
801
+ other = CryptContext(_autoload=False)
802
+ other.load(self)
803
+ if kwds:
804
+ other.load(kwds, update=True)
805
+ return other
806
+
807
+ def using(self, **kwds):
808
+ """
809
+ alias for :meth:`copy`, to match PasswordHash.using()
810
+ """
811
+ return self.copy(**kwds)
812
+
813
+ def __init__(
814
+ self,
815
+ schemes=None,
816
+ # keyword only...
817
+ _autoload=True,
818
+ **kwds,
819
+ ):
820
+ # XXX: add ability to make flag certain contexts as immutable,
821
+ # e.g. the builtin passlib ones?
822
+ # XXX: add a name or import path for the contexts, to help out repr?
823
+ if schemes is not None:
824
+ kwds["schemes"] = schemes
825
+ if _autoload:
826
+ self.load(kwds)
827
+ else:
828
+ assert not kwds, "_autoload=False and kwds are mutually exclusive"
829
+
830
+ # XXX: would this be useful?
831
+ ##def __str__(self):
832
+ ## return self.to_string()
833
+
834
+ def __repr__(self):
835
+ return f"<CryptContext at 0x{id(self):0x}>"
836
+
837
+ @staticmethod
838
+ def _parse_ini_stream(stream, section, filename):
839
+ """helper read INI from stream, extract passlib section as dict"""
840
+ # NOTE: this expects a unicode stream,
841
+ # and resulting dict will always use native strings.
842
+ p = ConfigParser()
843
+ p.read_file(stream, filename)
844
+ # XXX: could change load() to accept list of items,
845
+ # and skip intermediate dict creation
846
+ return dict(p.items(section))
847
+
848
+ def load_path(self, path, update=False, section="passlib", encoding="utf-8"):
849
+ """Load new configuration into CryptContext from a local file.
850
+
851
+ This function is a wrapper for :meth:`load` which
852
+ loads a configuration string from the local file *path*,
853
+ instead of an in-memory source. Its behavior and options
854
+ are otherwise identical to :meth:`!load` when provided with
855
+ an INI-formatted string.
856
+
857
+ .. versionadded:: 1.6
858
+ """
859
+ with open(path, encoding=encoding) as stream:
860
+ kwds = self._parse_ini_stream(stream, section, path)
861
+ return self.load(kwds, update=update)
862
+
863
+ def load(self, source, update=False, section="passlib", encoding="utf-8"):
864
+ """Load new configuration into CryptContext, replacing existing config.
865
+
866
+ :arg source:
867
+ source of new configuration to load.
868
+ this value can be a number of different types:
869
+
870
+ * a :class:`!dict` object, or compatible Mapping
871
+
872
+ the key/value pairs will be interpreted the same
873
+ keywords for the :class:`CryptContext` class constructor.
874
+
875
+ * a :class:`!str` or :class:`!bytes` string
876
+
877
+ this will be interpreted as an INI-formatted file,
878
+ and appropriate key/value pairs will be loaded from
879
+ the specified *section*.
880
+
881
+ * another :class:`!CryptContext` object.
882
+
883
+ this will export a snapshot of its configuration
884
+ using :meth:`to_dict`.
885
+
886
+ :type update: bool
887
+ :param update:
888
+ By default, :meth:`load` will replace the existing configuration
889
+ entirely. If ``update=True``, it will preserve any existing
890
+ configuration options that are not overridden by the new source,
891
+ much like the :meth:`update` method.
892
+
893
+ :type section: str
894
+ :param section:
895
+ When parsing an INI-formatted string, :meth:`load` will look for
896
+ a section named ``"passlib"``. This option allows an alternate
897
+ section name to be used. Ignored when loading from a dictionary.
898
+
899
+ :type encoding: str
900
+ :param encoding:
901
+ Encoding to use when **source** is bytes.
902
+ Defaults to ``"utf-8"``. Ignored when loading from a dictionary.
903
+
904
+ .. deprecated:: 1.8
905
+
906
+ This keyword, and support for bytes input, will be dropped in Passlib 2.0
907
+
908
+ :raises TypeError:
909
+ * If the source cannot be identified.
910
+ * If an unknown / malformed keyword is encountered.
911
+
912
+ :raises ValueError:
913
+ If an invalid keyword value is encountered.
914
+
915
+ .. note::
916
+
917
+ If an error occurs during a :meth:`!load` call, the :class:`!CryptContext`
918
+ instance will be restored to the configuration it was in before
919
+ the :meth:`!load` call was made; this is to ensure it is
920
+ *never* left in an inconsistent state due to a load error.
921
+
922
+ .. versionadded:: 1.6
923
+ """
924
+ # -----------------------------------------------------------
925
+ # autodetect source type, convert to dict
926
+ # -----------------------------------------------------------
927
+ parse_keys = True
928
+ if isinstance(source, unicode_or_bytes):
929
+ source = to_unicode(source, encoding, param="source")
930
+ source = self._parse_ini_stream(
931
+ StringIO(source), section, "<string passed to CryptContext.load()>"
932
+ )
933
+ elif isinstance(source, CryptContext):
934
+ # extract dict directly from config, so it can be merged later
935
+ source = dict(source._config.iter_config(resolve=True))
936
+ parse_keys = False
937
+ elif not hasattr(source, "items"):
938
+ # mappings are left alone, otherwise throw an error.
939
+ raise ExpectedTypeError(source, "string or dict", "source")
940
+
941
+ # XXX: add support for other iterable types, e.g. sequence of pairs?
942
+
943
+ # -----------------------------------------------------------
944
+ # parse dict keys into (category, scheme, option) format,
945
+ # and merge with existing configuration if needed.
946
+ # -----------------------------------------------------------
947
+ if parse_keys:
948
+ parse = self._parse_config_key
949
+ source = dict((parse(key), value) for key, value in source.items())
950
+ if update and self._config is not None:
951
+ # if updating, do nothing if source is empty,
952
+ if not source:
953
+ return
954
+ # otherwise overlay source on top of existing config
955
+ tmp = source
956
+ source = dict(self._config.iter_config(resolve=True))
957
+ source.update(tmp)
958
+
959
+ # -----------------------------------------------------------
960
+ # compile into _CryptConfig instance, and update state
961
+ # -----------------------------------------------------------
962
+ config = _CryptConfig(source)
963
+ self._config = config
964
+ self._reset_dummy_verify()
965
+ self._get_record = config.get_record
966
+ self._identify_record = config.identify_record
967
+ if config.context_kwds:
968
+ # (re-)enable method for this instance (in case ELSE clause below ran last load).
969
+ self.__dict__.pop("_strip_unused_context_kwds", None)
970
+ else:
971
+ # disable method for this instance, it's not needed.
972
+ self._strip_unused_context_kwds = None
973
+
974
+ @staticmethod
975
+ def _parse_config_key(ckey):
976
+ """helper used to parse ``cat__scheme__option`` keys into a tuple"""
977
+ # split string into 1-3 parts
978
+ assert isinstance(ckey, str)
979
+ parts = ckey.replace(".", "__").split("__")
980
+ count = len(parts)
981
+ if count == 1:
982
+ cat, scheme, key = None, None, parts[0]
983
+ elif count == 2:
984
+ cat = None
985
+ scheme, key = parts
986
+ elif count == 3:
987
+ cat, scheme, key = parts
988
+ else:
989
+ raise TypeError(f"keys must have less than 3 separators: {ckey!r}")
990
+ # validate & normalize the parts
991
+ if cat == "default":
992
+ cat = None
993
+ elif not cat and cat is not None:
994
+ raise TypeError(f"empty category: {ckey!r}")
995
+ if scheme == "context":
996
+ scheme = None
997
+ elif not scheme and scheme is not None:
998
+ raise TypeError(f"empty scheme: {ckey!r}")
999
+ if not key:
1000
+ raise TypeError(f"empty option: {ckey!r}")
1001
+ return cat, scheme, key
1002
+
1003
+ def update(self, *args, **kwds):
1004
+ """Helper for quickly changing configuration.
1005
+
1006
+ This acts much like the :meth:`!dict.update` method:
1007
+ it updates the context's configuration,
1008
+ replacing the original value(s) for the specified keys,
1009
+ and preserving the rest.
1010
+ It accepts any :ref:`keyword <context-options>`
1011
+ accepted by the :class:`!CryptContext` constructor.
1012
+
1013
+ .. versionadded:: 1.6
1014
+
1015
+ .. seealso:: :meth:`copy`
1016
+ """
1017
+ if args:
1018
+ if len(args) > 1:
1019
+ raise TypeError("expected at most one positional argument")
1020
+ if kwds:
1021
+ raise TypeError("positional arg and keywords mutually exclusive")
1022
+ self.load(args[0], update=True)
1023
+ elif kwds:
1024
+ self.load(kwds, update=True)
1025
+
1026
+ # XXX: make this public? even just as flag to load?
1027
+ # FIXME: this function suffered some bitrot in 1.6.1,
1028
+ # will need to be updated before works again.
1029
+ ##def _simplify(self):
1030
+ ## "helper to remove redundant/unused options"
1031
+ ## # don't do anything if no schemes are defined
1032
+ ## if not self._schemes:
1033
+ ## return
1034
+ ##
1035
+ ## def strip_items(target, filter):
1036
+ ## keys = [key for key,value in target.items() if filter(key,value)]
1037
+ ## for key in keys:
1038
+ ## del target[key]
1039
+ ##
1040
+ ## # remove redundant default.
1041
+ ## defaults = self._default_schemes
1042
+ ## if defaults.get(None) == self._schemes[0]:
1043
+ ## del defaults[None]
1044
+ ##
1045
+ ## # remove options for unused schemes.
1046
+ ## scheme_options = self._scheme_options
1047
+ ## schemes = self._schemes + ("all",)
1048
+ ## strip_items(scheme_options, lambda k,v: k not in schemes)
1049
+ ##
1050
+ ## # remove rendundant cat defaults.
1051
+ ## cur = self.default_scheme()
1052
+ ## strip_items(defaults, lambda k,v: k and v==cur)
1053
+ ##
1054
+ ## # remove redundant category deprecations.
1055
+ ## # TODO: this should work w/ 'auto', but needs closer inspection
1056
+ ## deprecated = self._deprecated_schemes
1057
+ ## cur = self._deprecated_schemes.get(None)
1058
+ ## strip_items(deprecated, lambda k,v: k and v==cur)
1059
+ ##
1060
+ ## # remove redundant category options.
1061
+ ## for scheme, config in scheme_options.items():
1062
+ ## if None in config:
1063
+ ## cur = config[None]
1064
+ ## strip_items(config, lambda k,v: k and v==cur)
1065
+ ##
1066
+ ## # XXX: anything else?
1067
+
1068
+ def schemes(self, resolve=False, category=None, unconfigured=False):
1069
+ """return schemes loaded into this CryptContext instance.
1070
+
1071
+ :type resolve: bool
1072
+ :arg resolve:
1073
+ if ``True``, will return a tuple of :class:`~passlib.ifc.PasswordHash`
1074
+ objects instead of their names.
1075
+
1076
+ :returns:
1077
+ returns tuple of the schemes configured for this context
1078
+ via the *schemes* option.
1079
+
1080
+ .. versionadded:: 1.6
1081
+ This was previously available as ``CryptContext().policy.schemes()``
1082
+
1083
+ .. seealso:: the :ref:`schemes <context-schemes-option>` option for usage example.
1084
+ """
1085
+ # XXX: should resolv return records rather than handlers?
1086
+ # or deprecate resolve keyword completely?
1087
+ # offering up a .hashers Mapping in v1.8 would be great.
1088
+ # NOTE: supporting 'category' and 'unconfigured' kwds as of 1.7
1089
+ # just to pass through to .handler(), but not documenting them...
1090
+ # may not need to put them to use.
1091
+ schemes = self._config.schemes
1092
+ if resolve:
1093
+ return tuple(
1094
+ self.handler(scheme, category, unconfigured=unconfigured)
1095
+ for scheme in schemes
1096
+ )
1097
+ return schemes
1098
+
1099
+ def default_scheme(self, category=None, resolve=False, unconfigured=False):
1100
+ """return name of scheme that :meth:`hash` will use by default.
1101
+
1102
+ :type resolve: bool
1103
+ :arg resolve:
1104
+ if ``True``, will return a :class:`~passlib.ifc.PasswordHash`
1105
+ object instead of the name.
1106
+
1107
+ :type category: str or None
1108
+ :param category:
1109
+ Optional :ref:`user category <user-categories>`.
1110
+ If specified, this will return the catgory-specific default scheme instead.
1111
+
1112
+ :returns:
1113
+ name of the default scheme.
1114
+
1115
+ .. seealso:: the :ref:`default <context-default-option>` option for usage example.
1116
+
1117
+ .. versionadded:: 1.6
1118
+
1119
+ .. versionchanged:: 1.7
1120
+
1121
+ This now returns a hasher configured with any CryptContext-specific
1122
+ options (custom rounds settings, etc). Previously this returned
1123
+ the base hasher from :mod:`passlib.hash`.
1124
+ """
1125
+ # XXX: deprecate this in favor of .handler() or whatever it's replaced with?
1126
+ # NOTE: supporting 'unconfigured' kwds as of 1.7
1127
+ # just to pass through to .handler(), but not documenting them...
1128
+ # may not need to put them to use.
1129
+ hasher = self.handler(None, category, unconfigured=unconfigured)
1130
+ return hasher if resolve else hasher.name
1131
+
1132
+ # XXX: need to decide if exposing this would be useful in any way
1133
+ ##def categories(self):
1134
+ ## """return user-categories with algorithm-specific options in this CryptContext.
1135
+ ##
1136
+ ## this will always return a tuple.
1137
+ ## if no categories besides the default category have been configured,
1138
+ ## the tuple will be empty.
1139
+ ## """
1140
+ ## return self._config.categories
1141
+
1142
+ # XXX: need to decide if exposing this would be useful to applications
1143
+ # in any meaningful way that isn't already served by to_dict()
1144
+ ##def options(self, scheme, category=None):
1145
+ ## kwds, percat = self._config.get_options(scheme, category)
1146
+ ## return kwds
1147
+
1148
+ def handler(self, scheme=None, category=None, unconfigured=False):
1149
+ """helper to resolve name of scheme -> :class:`~passlib.ifc.PasswordHash` object used by scheme.
1150
+
1151
+ :arg scheme:
1152
+ This should identify the scheme to lookup.
1153
+ If omitted or set to ``None``, this will return the handler
1154
+ for the default scheme.
1155
+
1156
+ :arg category:
1157
+ If a user category is specified, and no scheme is provided,
1158
+ it will use the default for that category.
1159
+ Otherwise this parameter is ignored.
1160
+
1161
+ :param unconfigured:
1162
+
1163
+ By default, this returns a handler object whose .hash()
1164
+ and .needs_update() methods will honor the configured
1165
+ provided by CryptContext. See ``unconfigured=True``
1166
+ to get the underlying handler from before any context-specific
1167
+ configuration was applied.
1168
+
1169
+ :raises KeyError:
1170
+ If the scheme does not exist OR is not being used within this context.
1171
+
1172
+ :returns:
1173
+ :class:`~passlib.ifc.PasswordHash` object used to implement
1174
+ the named scheme within this context (this will usually
1175
+ be one of the objects from :mod:`passlib.hash`)
1176
+
1177
+ .. versionadded:: 1.6
1178
+ This was previously available as ``CryptContext().policy.get_handler()``
1179
+
1180
+ .. versionchanged:: 1.7
1181
+
1182
+ This now returns a hasher configured with any CryptContext-specific
1183
+ options (custom rounds settings, etc). Previously this returned
1184
+ the base hasher from :mod:`passlib.hash`.
1185
+ """
1186
+ try:
1187
+ hasher = self._get_record(scheme, category)
1188
+ if unconfigured:
1189
+ return hasher._Context__orig_handler
1190
+ return hasher
1191
+ except KeyError:
1192
+ pass
1193
+ if self._config.handlers:
1194
+ raise KeyError(
1195
+ f"crypt algorithm not found in this CryptContext instance: {scheme!r}"
1196
+ )
1197
+ raise KeyError("no crypt algorithms loaded in this CryptContext instance")
1198
+
1199
+ def _get_unregistered_handlers(self):
1200
+ """check if any handlers in this context aren't in the global registry"""
1201
+ return tuple(
1202
+ handler
1203
+ for handler in self._config.handlers
1204
+ if not _is_handler_registered(handler)
1205
+ )
1206
+
1207
+ @property
1208
+ def context_kwds(self):
1209
+ """
1210
+ return :class:`!set` containing union of all :ref:`contextual keywords <context-keywords>`
1211
+ supported by the handlers in this context.
1212
+
1213
+ .. versionadded:: 1.6.6
1214
+ """
1215
+ return self._config.context_kwds
1216
+
1217
+ @staticmethod
1218
+ def _render_config_key(key):
1219
+ """convert 3-part config key to single string"""
1220
+ cat, scheme, option = key
1221
+ if cat:
1222
+ return "{}__{}__{}".format(cat, scheme or "context", option)
1223
+ if scheme:
1224
+ return f"{scheme}__{option}"
1225
+ return option
1226
+
1227
+ @staticmethod
1228
+ def _render_ini_value(key, value):
1229
+ """render value to string suitable for INI file"""
1230
+ # convert lists to comma separated lists
1231
+ # (mainly 'schemes' & 'deprecated')
1232
+ if isinstance(value, (list, tuple)):
1233
+ value = ", ".join(value)
1234
+
1235
+ # convert numbers to strings
1236
+ elif isinstance(value, numeric_types):
1237
+ if isinstance(value, float) and key[2] == "vary_rounds":
1238
+ value = (f"{value:.2f}").rstrip("0") if value else "0"
1239
+ else:
1240
+ value = str(value)
1241
+
1242
+ assert isinstance(value, str), f"expected string for key: {key!r} {value!r}"
1243
+
1244
+ # escape any percent signs.
1245
+ return value.replace("%", "%%")
1246
+
1247
+ def to_dict(self, resolve=False):
1248
+ """Return current configuration as a dictionary.
1249
+
1250
+ :type resolve: bool
1251
+ :arg resolve:
1252
+ if ``True``, the ``schemes`` key will contain a list of
1253
+ a :class:`~passlib.ifc.PasswordHash` objects instead of just
1254
+ their names.
1255
+
1256
+ This method dumps the current configuration of the CryptContext
1257
+ instance. The key/value pairs should be in the format accepted
1258
+ by the :class:`!CryptContext` class constructor, in fact
1259
+ ``CryptContext(**myctx.to_dict())`` will create an exact copy of ``myctx``.
1260
+ As an example::
1261
+
1262
+ >>> # you can dump the configuration of any crypt context...
1263
+ >>> from passlib.apps import ldap_nocrypt_context
1264
+ >>> ldap_nocrypt_context.to_dict()
1265
+ {'schemes': ['ldap_salted_sha1',
1266
+ 'ldap_salted_md5',
1267
+ 'ldap_sha1',
1268
+ 'ldap_md5',
1269
+ 'ldap_plaintext']}
1270
+
1271
+ .. versionadded:: 1.6
1272
+ This was previously available as ``CryptContext().policy.to_dict()``
1273
+
1274
+ .. seealso:: the :ref:`context-serialization-example` example in the tutorial.
1275
+ """
1276
+ # XXX: should resolve default to conditional behavior
1277
+ # based on presence of unregistered handlers?
1278
+ render_key = self._render_config_key
1279
+ return dict(
1280
+ (render_key(key), value) for key, value in self._config.iter_config(resolve)
1281
+ )
1282
+
1283
+ def _write_to_parser(self, parser: ConfigParser, section: str) -> None:
1284
+ """helper to write to ConfigParser instance"""
1285
+ parser.add_section(section)
1286
+ for key, value in self._config.iter_config(): # type: ignore[attr-defined]
1287
+ parser.set(
1288
+ section=section,
1289
+ option=self._render_config_key(key),
1290
+ value=self._render_ini_value(key, value),
1291
+ )
1292
+
1293
+ def to_string(self, section="passlib") -> str:
1294
+ """serialize to INI format and return as unicode string.
1295
+
1296
+ :param section:
1297
+ name of INI section to output, defaults to ``"passlib"``.
1298
+
1299
+ :returns:
1300
+ CryptContext configuration, serialized to a INI unicode string.
1301
+
1302
+ This function acts exactly like :meth:`to_dict`, except that it
1303
+ serializes all the contents into a single human-readable string,
1304
+ which can be hand edited, and/or stored in a file. The
1305
+ output of this method is accepted by :meth:`from_string`,
1306
+ :meth:`from_path`, and :meth:`load`. As an example::
1307
+
1308
+ >>> # you can dump the configuration of any crypt context...
1309
+ >>> from passlib.apps import ldap_nocrypt_context
1310
+ >>> print ldap_nocrypt_context.to_string()
1311
+ [passlib]
1312
+ schemes = ldap_salted_sha1, ldap_salted_md5, ldap_sha1, ldap_md5, ldap_plaintext
1313
+
1314
+ .. versionadded:: 1.6
1315
+ This was previously available as ``CryptContext().policy.to_string()``
1316
+
1317
+ .. seealso:: the :ref:`context-serialization-example` example in the tutorial.
1318
+ """
1319
+ parser = ConfigParser()
1320
+ self._write_to_parser(parser, section)
1321
+ buf = StringIO()
1322
+ parser.write(buf)
1323
+ unregistered = self._get_unregistered_handlers()
1324
+ if unregistered:
1325
+ buf.write(
1326
+ (
1327
+ "# NOTE: the {} handler(s) are not registered with Passlib,\n"
1328
+ "# this string may not correctly reproduce the current configuration.\n\n"
1329
+ ).format(", ".join(repr(handler.name) for handler in unregistered))
1330
+ )
1331
+ return buf.getvalue()
1332
+
1333
+ # XXX: is this useful enough to enable?
1334
+ ##def write_to_path(self, path, section="passlib", update=False):
1335
+ ## "write to INI file"
1336
+ ## parser = ConfigParser()
1337
+ ## if update and os.path.exists(path):
1338
+ ## if not parser.read([path]):
1339
+ ## raise EnvironmentError("failed to read existing file")
1340
+ ## parser.remove_section(section)
1341
+ ## self._write_to_parser(parser, section)
1342
+ ## fh = file(path, "w")
1343
+ ## parser.write(fh)
1344
+ ## fh.close()
1345
+
1346
+ # NOTE: all the following methods do is look up the appropriate
1347
+ # custom handler for a given (scheme,category) combination,
1348
+ # and hand off the real work to the handler itself,
1349
+ # which is optimized for the specific (scheme,category) configuration.
1350
+ #
1351
+ # The custom handlers are cached inside the _CryptConfig
1352
+ # instance stored in self._config, and are retrieved
1353
+ # via get_record() and identify_record().
1354
+ #
1355
+ # _get_record() and _identify_record() are references
1356
+ # to _config methods of the same name,
1357
+ # stored in CryptContext for speed.
1358
+
1359
+ def _get_or_identify_record(self, hash, scheme=None, category=None):
1360
+ """return record based on scheme, or failing that, by identifying hash"""
1361
+ if scheme:
1362
+ if not isinstance(hash, unicode_or_bytes):
1363
+ raise ExpectedStringError(hash, "hash")
1364
+ return self._get_record(scheme, category)
1365
+ # hash typecheck handled by identify_record()
1366
+ return self._identify_record(hash, category)
1367
+
1368
+ def _strip_unused_context_kwds(self, kwds, record):
1369
+ """
1370
+ helper which removes any context keywords from **kwds**
1371
+ that are known to be used by another scheme in this context,
1372
+ but are NOT supported by handler specified by **record**.
1373
+
1374
+ .. note::
1375
+ as optimization, load() will set this method to None on a per-instance basis
1376
+ if there are no context kwds.
1377
+ """
1378
+ if not kwds:
1379
+ return
1380
+ unused_kwds = self._config.context_kwds.difference(record.context_kwds)
1381
+ for key in unused_kwds:
1382
+ kwds.pop(key, None)
1383
+
1384
+ def needs_update(self, hash, scheme=None, category=None, secret=None):
1385
+ """Check if hash needs to be replaced for some reason,
1386
+ in which case the secret should be re-hashed.
1387
+
1388
+ This function is the core of CryptContext's support for hash migration:
1389
+ This function takes in a hash string, and checks the scheme,
1390
+ number of rounds, and other properties against the current policy.
1391
+ It returns ``True`` if the hash is using a deprecated scheme,
1392
+ or is otherwise outside of the bounds specified by the policy
1393
+ (e.g. the number of rounds is lower than :ref:`min_rounds <context-min-rounds-option>`
1394
+ configuration for that algorithm).
1395
+ If so, the password should be re-hashed using :meth:`hash`
1396
+ Otherwise, it will return ``False``.
1397
+
1398
+ :type hash: str or bytes
1399
+ :arg hash:
1400
+ The hash string to examine.
1401
+
1402
+ :type scheme: str or None
1403
+ :param scheme:
1404
+
1405
+ Optional scheme to use. Scheme must be one of the ones
1406
+ configured for this context (see the
1407
+ :ref:`schemes <context-schemes-option>` option).
1408
+ If no scheme is specified, it will be identified
1409
+ based on the value of *hash*.
1410
+
1411
+ .. deprecated:: 1.7
1412
+
1413
+ Support for this keyword is deprecated, and will be removed in Passlib 2.0.
1414
+
1415
+ :type category: str or None
1416
+ :param category:
1417
+ Optional :ref:`user category <user-categories>`.
1418
+ If specified, this will cause any category-specific defaults to
1419
+ be used when determining if the hash needs to be updated
1420
+ (e.g. is below the minimum rounds).
1421
+
1422
+ :type secret: str, bytes, or None
1423
+ :param secret:
1424
+ Optional secret associated with the provided ``hash``.
1425
+ This is not required, or even currently used for anything...
1426
+ it's for forward-compatibility with any future
1427
+ update checks that might need this information.
1428
+ If provided, Passlib assumes the secret has already been
1429
+ verified successfully against the hash.
1430
+
1431
+ .. versionadded:: 1.6
1432
+
1433
+ :returns: ``True`` if hash should be replaced, otherwise ``False``.
1434
+
1435
+ :raises ValueError:
1436
+ If the hash did not match any of the configured :meth:`schemes`.
1437
+
1438
+ .. versionadded:: 1.6
1439
+ This method was previously named :meth:`hash_needs_update`.
1440
+
1441
+ .. seealso:: the :ref:`context-migration-example` example in the tutorial.
1442
+ """
1443
+ if scheme is not None:
1444
+ # TODO: offer replacement alternative.
1445
+ # ``context.handler(scheme).needs_update()`` would work,
1446
+ # but may deprecate .handler() in passlib 1.8.
1447
+ warn(
1448
+ "CryptContext.needs_update(): 'scheme' keyword is deprecated as of "
1449
+ "Passlib 1.7, and will be removed in Passlib 2.0",
1450
+ DeprecationWarning,
1451
+ )
1452
+ record = self._get_or_identify_record(hash, scheme, category)
1453
+ return record.deprecated or record.needs_update(hash, secret=secret)
1454
+
1455
+ @deprecated_method(
1456
+ deprecated="1.6", removed="2.0", replacement="CryptContext.needs_update()"
1457
+ )
1458
+ def hash_needs_update(self, hash, scheme=None, category=None):
1459
+ """Legacy alias for :meth:`needs_update`.
1460
+
1461
+ .. deprecated:: 1.6
1462
+ This method was renamed to :meth:`!needs_update` in version 1.6.
1463
+ This alias will be removed in version 2.0, and should only
1464
+ be used for compatibility with Passlib 1.3 - 1.5.
1465
+ """
1466
+ return self.needs_update(hash, scheme, category)
1467
+
1468
+ @deprecated_method(deprecated="1.7", removed="2.0")
1469
+ def genconfig(self, scheme=None, category=None, **settings):
1470
+ """Generate a config string for specified scheme.
1471
+
1472
+ .. deprecated:: 1.7
1473
+
1474
+ This method will be removed in version 2.0, and should only
1475
+ be used for compatibility with Passlib 1.3 - 1.6.
1476
+ """
1477
+ record = self._get_record(scheme, category)
1478
+ strip_unused = self._strip_unused_context_kwds
1479
+ if strip_unused:
1480
+ strip_unused(settings, record)
1481
+ return record.genconfig(**settings)
1482
+
1483
+ @deprecated_method(deprecated="1.7", removed="2.0")
1484
+ def genhash(self, secret, config, scheme=None, category=None, **kwds):
1485
+ """Generate hash for the specified secret using another hash.
1486
+
1487
+ .. deprecated:: 1.7
1488
+
1489
+ This method will be removed in version 2.0, and should only
1490
+ be used for compatibility with Passlib 1.3 - 1.6.
1491
+ """
1492
+ record = self._get_or_identify_record(config, scheme, category)
1493
+ strip_unused = self._strip_unused_context_kwds
1494
+ if strip_unused:
1495
+ strip_unused(kwds, record)
1496
+ return record.genhash(secret, config, **kwds)
1497
+
1498
+ def identify(
1499
+ self, hash, category=None, resolve=False, required=False, unconfigured=False
1500
+ ):
1501
+ """Attempt to identify which algorithm the hash belongs to.
1502
+
1503
+ Note that this will only consider the algorithms
1504
+ currently configured for this context
1505
+ (see the :ref:`schemes <context-schemes-option>` option).
1506
+ All registered algorithms will be checked, from first to last,
1507
+ and whichever one positively identifies the hash first will be returned.
1508
+
1509
+ :type hash: str or bytes
1510
+ :arg hash:
1511
+ The hash string to test.
1512
+
1513
+ :type category: str or None
1514
+ :param category:
1515
+ Optional :ref:`user category <user-categories>`.
1516
+ Ignored by this function, this parameter
1517
+ is provided for symmetry with the other methods.
1518
+
1519
+ :type resolve: bool
1520
+ :param resolve:
1521
+ If ``True``, returns the hash handler itself,
1522
+ instead of the name of the hash.
1523
+
1524
+ :type required: bool
1525
+ :param required:
1526
+ If ``True``, this will raise a ValueError if the hash
1527
+ cannot be identified, instead of returning ``None``.
1528
+
1529
+ :returns:
1530
+ The handler which first identifies the hash,
1531
+ or ``None`` if none of the algorithms identify the hash.
1532
+ """
1533
+ record = self._identify_record(hash, category, required)
1534
+ if record is None:
1535
+ return None
1536
+ if resolve:
1537
+ if unconfigured:
1538
+ return record._Context__orig_handler
1539
+ return record
1540
+ return record.name
1541
+
1542
+ def hash(self, secret, scheme=None, category=None, **kwds):
1543
+ """run secret through selected algorithm, returning resulting hash.
1544
+
1545
+ :type secret: str or bytes
1546
+ :arg secret:
1547
+ the password to hash.
1548
+
1549
+ :type scheme: str or None
1550
+ :param scheme:
1551
+
1552
+ Optional scheme to use. Scheme must be one of the ones
1553
+ configured for this context (see the
1554
+ :ref:`schemes <context-schemes-option>` option).
1555
+ If no scheme is specified, the configured default
1556
+ will be used.
1557
+
1558
+ .. deprecated:: 1.7
1559
+
1560
+ Support for this keyword is deprecated, and will be removed in Passlib 2.0.
1561
+
1562
+ :type category: str or None
1563
+ :param category:
1564
+ Optional :ref:`user category <user-categories>`.
1565
+ If specified, this will cause any category-specific defaults to
1566
+ be used when hashing the password (e.g. different default scheme,
1567
+ different default rounds values, etc).
1568
+
1569
+ :param \\*\\*kwds:
1570
+ All other keyword options are passed to the selected algorithm's
1571
+ :meth:`PasswordHash.hash() <passlib.ifc.PasswordHash.hash>` method.
1572
+
1573
+ :returns:
1574
+ The secret as encoded by the specified algorithm and options.
1575
+ The return value will always be a :class:`!str`.
1576
+
1577
+ :raises TypeError, ValueError:
1578
+ * If any of the arguments have an invalid type or value.
1579
+ This includes any keywords passed to the underlying hash's
1580
+ :meth:`PasswordHash.hash() <passlib.ifc.PasswordHash.hash>` method.
1581
+
1582
+ .. seealso:: the :ref:`context-basic-example` example in the tutorial
1583
+ """
1584
+ # XXX: could insert normalization to preferred str encoding here
1585
+ if scheme is not None:
1586
+ # TODO: offer replacement alternative.
1587
+ # ``context.handler(scheme).hash()`` would work,
1588
+ # but may deprecate .handler() in passlib 1.8.
1589
+ warn(
1590
+ "CryptContext.hash(): 'scheme' keyword is deprecated as of "
1591
+ "Passlib 1.7, and will be removed in Passlib 2.0",
1592
+ DeprecationWarning,
1593
+ )
1594
+ record = self._get_record(scheme, category)
1595
+ strip_unused = self._strip_unused_context_kwds
1596
+ if strip_unused:
1597
+ strip_unused(kwds, record)
1598
+ return record.hash(secret, **kwds)
1599
+
1600
+ @deprecated_method(
1601
+ deprecated="1.7", removed="2.0", replacement="CryptContext.hash()"
1602
+ )
1603
+ def encrypt(self, *args, **kwds):
1604
+ """
1605
+ Legacy alias for :meth:`hash`.
1606
+
1607
+ .. deprecated:: 1.7
1608
+ This method was renamed to :meth:`!hash` in version 1.7.
1609
+ This alias will be removed in version 2.0, and should only
1610
+ be used for compatibility with Passlib 1.3 - 1.6.
1611
+ """
1612
+ return self.hash(*args, **kwds)
1613
+
1614
+ def verify(self, secret, hash, scheme=None, category=None, **kwds):
1615
+ """verify secret against an existing hash.
1616
+
1617
+ If no scheme is specified, this will attempt to identify
1618
+ the scheme based on the contents of the provided hash
1619
+ (limited to the schemes configured for this context).
1620
+ It will then check whether the password verifies against the hash.
1621
+
1622
+ :type secret: str or bytes
1623
+ :arg secret:
1624
+ the secret to verify
1625
+
1626
+ :type hash: str or bytes
1627
+ :arg hash:
1628
+ hash string to compare to
1629
+
1630
+ if ``None`` is passed in, this will be treated as "never verifying"
1631
+
1632
+ :type scheme: str
1633
+ :param scheme:
1634
+ Optionally force context to use specific scheme.
1635
+ This is usually not needed, as most hashes can be unambiguously
1636
+ identified. Scheme must be one of the ones configured
1637
+ for this context
1638
+ (see the :ref:`schemes <context-schemes-option>` option).
1639
+
1640
+ .. deprecated:: 1.7
1641
+
1642
+ Support for this keyword is deprecated, and will be removed in Passlib 2.0.
1643
+
1644
+ :type category: str or None
1645
+ :param category:
1646
+ Optional :ref:`user category <user-categories>` string.
1647
+ This is mainly used when generating new hashes, it has little
1648
+ effect when verifying; this keyword is mainly provided for symmetry.
1649
+
1650
+ :param \\*\\*kwds:
1651
+ All additional keywords are passed to the appropriate handler,
1652
+ and should match its :attr:`~passlib.ifc.PasswordHash.context_kwds`.
1653
+
1654
+ :returns:
1655
+ ``True`` if the password matched the hash, else ``False``.
1656
+
1657
+ :raises ValueError:
1658
+ * if the hash did not match any of the configured :meth:`schemes`.
1659
+
1660
+ * if any of the arguments have an invalid value (this includes
1661
+ any keywords passed to the underlying hash's
1662
+ :meth:`PasswordHash.verify() <passlib.ifc.PasswordHash.verify>` method).
1663
+
1664
+ :raises TypeError:
1665
+ * if any of the arguments have an invalid type (this includes
1666
+ any keywords passed to the underlying hash's
1667
+ :meth:`PasswordHash.verify() <passlib.ifc.PasswordHash.verify>` method).
1668
+
1669
+ .. seealso:: the :ref:`context-basic-example` example in the tutorial
1670
+ """
1671
+ # XXX: could insert normalization to preferred unicode encoding here
1672
+ # XXX: what about supporting a setter() callback ala django 1.4 ?
1673
+ if scheme is not None:
1674
+ # TODO: offer replacement alternative.
1675
+ # ``context.handler(scheme).verify()`` would work,
1676
+ # but may deprecate .handler() in passlib 1.8.
1677
+ warn(
1678
+ "CryptContext.verify(): 'scheme' keyword is deprecated as of "
1679
+ "Passlib 1.7, and will be removed in Passlib 2.0",
1680
+ DeprecationWarning,
1681
+ )
1682
+ if hash is None:
1683
+ # convenience feature -- let apps pass in hash=None when user
1684
+ # isn't found / has no hash; useful because it invokes dummy_verify()
1685
+ self.dummy_verify()
1686
+ return False
1687
+ record = self._get_or_identify_record(hash, scheme, category)
1688
+ strip_unused = self._strip_unused_context_kwds
1689
+ if strip_unused:
1690
+ strip_unused(kwds, record)
1691
+ return record.verify(secret, hash, **kwds)
1692
+
1693
+ def verify_and_update(self, secret, hash, scheme=None, category=None, **kwds):
1694
+ """verify password and re-hash the password if needed, all in a single call.
1695
+
1696
+ This is a convenience method which takes care of all the following:
1697
+ first it verifies the password (:meth:`~CryptContext.verify`), if this is successfull
1698
+ it checks if the hash needs updating (:meth:`~CryptContext.needs_update`), and if so,
1699
+ re-hashes the password (:meth:`~CryptContext.hash`), returning the replacement hash.
1700
+ This series of steps is a very common task for applications
1701
+ which wish to update deprecated hashes, and this call takes
1702
+ care of all 3 steps efficiently.
1703
+
1704
+ :type secret: str or bytes
1705
+ :arg secret:
1706
+ the secret to verify
1707
+
1708
+ :type secret: str or bytes
1709
+ :arg hash:
1710
+ hash string to compare to.
1711
+
1712
+ if ``None`` is passed in, this will be treated as "never verifying"
1713
+
1714
+ :type scheme: str
1715
+ :param scheme:
1716
+ Optionally force context to use specific scheme.
1717
+ This is usually not needed, as most hashes can be unambiguously
1718
+ identified. Scheme must be one of the ones configured
1719
+ for this context
1720
+ (see the :ref:`schemes <context-schemes-option>` option).
1721
+
1722
+ .. deprecated:: 1.7
1723
+
1724
+ Support for this keyword is deprecated, and will be removed in Passlib 2.0.
1725
+
1726
+ :type category: str or None
1727
+ :param category:
1728
+ Optional :ref:`user category <user-categories>`.
1729
+ If specified, this will cause any category-specific defaults to
1730
+ be used if the password has to be re-hashed.
1731
+
1732
+ :param \\*\\*kwds:
1733
+ all additional keywords are passed to the appropriate handler,
1734
+ and should match that hash's
1735
+ :attr:`PasswordHash.context_kwds <passlib.ifc.PasswordHash.context_kwds>`.
1736
+
1737
+ :returns:
1738
+ This function returns a tuple containing two elements:
1739
+ ``(verified, replacement_hash)``. The first is a boolean
1740
+ flag indicating whether the password verified,
1741
+ and the second an optional replacement hash.
1742
+ The tuple will always match one of the following 3 cases:
1743
+
1744
+ * ``(False, None)`` indicates the secret failed to verify.
1745
+ * ``(True, None)`` indicates the secret verified correctly,
1746
+ and the hash does not need updating.
1747
+ * ``(True, str)`` indicates the secret verified correctly,
1748
+ but the current hash needs to be updated. The :class:`!str`
1749
+ will be the freshly generated hash, to replace the old one.
1750
+
1751
+ :raises TypeError, ValueError:
1752
+ For the same reasons as :meth:`verify`.
1753
+
1754
+ .. seealso:: the :ref:`context-migration-example` example in the tutorial.
1755
+ """
1756
+ # XXX: could insert normalization to preferred unicode encoding here.
1757
+ if scheme is not None:
1758
+ warn(
1759
+ "CryptContext.verify(): 'scheme' keyword is deprecated as of "
1760
+ "Passlib 1.7, and will be removed in Passlib 2.0",
1761
+ DeprecationWarning,
1762
+ )
1763
+ if hash is None:
1764
+ # convenience feature -- let apps pass in hash=None when user
1765
+ # isn't found / has no hash; useful because it invokes dummy_verify()
1766
+ self.dummy_verify()
1767
+ return False, None
1768
+ record = self._get_or_identify_record(hash, scheme, category)
1769
+ strip_unused = self._strip_unused_context_kwds
1770
+ if strip_unused and kwds:
1771
+ clean_kwds = kwds.copy()
1772
+ strip_unused(clean_kwds, record)
1773
+ else:
1774
+ clean_kwds = kwds
1775
+ # XXX: if record is default scheme, could extend PasswordHash
1776
+ # api to combine verify & needs_update to single call,
1777
+ # potentially saving some round-trip parsing.
1778
+ # but might make these codepaths more complex...
1779
+ if not record.verify(secret, hash, **clean_kwds):
1780
+ return False, None
1781
+ if record.deprecated or record.needs_update(hash, secret=secret):
1782
+ # NOTE: we re-hash with default scheme, not current one.
1783
+ return True, self.hash(secret, category=category, **kwds)
1784
+ return True, None
1785
+
1786
+ #: secret used for dummy_verify()
1787
+ _dummy_secret = "too many secrets"
1788
+
1789
+ @memoized_property
1790
+ def _dummy_hash(self):
1791
+ """
1792
+ precalculated hash for dummy_verify() to use
1793
+ """
1794
+ return self.hash(self._dummy_secret)
1795
+
1796
+ def _reset_dummy_verify(self):
1797
+ """
1798
+ flush memoized values used by dummy_verify()
1799
+ """
1800
+ type(self)._dummy_hash.clear_cache(self)
1801
+
1802
+ def dummy_verify(self):
1803
+ """
1804
+ Helper that applications can call when user wasn't found,
1805
+ in order to simulate time it would take to hash a password.
1806
+
1807
+ Runs verify() against a dummy hash, to simulate verification
1808
+ of a real account password.
1809
+
1810
+ .. versionadded:: 1.7
1811
+ """
1812
+ self.verify(self._dummy_secret, self._dummy_hash)
1813
+ return False
1814
+
1815
+ def is_enabled(self, hash):
1816
+ """
1817
+ test if hash represents a usuable password --
1818
+ i.e. does not represent an unusuable password such as ``"!"``,
1819
+ which is recognized by the :class:`~passlib.hash.unix_disabled` hash.
1820
+
1821
+ :raises ValueError:
1822
+ if the hash is not recognized
1823
+ (typically solved by adding ``unix_disabled`` to the list of schemes).
1824
+ """
1825
+ return not self._identify_record(hash, None).is_disabled
1826
+
1827
+ def disable(self, hash=None):
1828
+ """
1829
+ return a string to disable logins for user,
1830
+ usually by returning a non-verifying string such as ``"!"``.
1831
+
1832
+ :param hash:
1833
+ Callers can optionally provide the account's existing hash.
1834
+ Some disabled handlers (such as :class:`!unix_disabled`)
1835
+ will encode this into the returned value,
1836
+ so that it can be recovered via :meth:`enable`.
1837
+
1838
+ :raises RuntimeError:
1839
+ if this function is called w/o a disabled hasher
1840
+ (such as :class:`~passlib.hash.unix_disabled`) included
1841
+ in the list of schemes.
1842
+
1843
+ :returns:
1844
+ hash string which will be recognized as valid by the context,
1845
+ but is guaranteed to not validate against *any* password.
1846
+ """
1847
+ record = self._config.disabled_record
1848
+ assert record.is_disabled
1849
+ return record.disable(hash)
1850
+
1851
+ def enable(self, hash):
1852
+ """
1853
+ inverse of :meth:`disable` --
1854
+ attempts to recover original hash which was converted
1855
+ by a :meth:`!disable` call into a disabled hash --
1856
+ thus restoring the user's original password.
1857
+
1858
+ :raises ValueError:
1859
+ if original hash not present, or if the disabled handler doesn't
1860
+ support encoding the original hash (e.g. ``django_disabled``)
1861
+
1862
+ :returns:
1863
+ the original hash.
1864
+ """
1865
+ record = self._identify_record(hash, None)
1866
+ if record.is_disabled:
1867
+ # XXX: should we throw error if result can't be identified by context?
1868
+ return record.enable(hash)
1869
+ # hash wasn't a disabled hash, so return unchanged
1870
+ return hash
1871
+
1872
+
1873
+ class LazyCryptContext(CryptContext):
1874
+ """CryptContext subclass which doesn't load handlers until needed.
1875
+
1876
+ This is a subclass of CryptContext which takes in a set of arguments
1877
+ exactly like CryptContext, but won't import any handlers
1878
+ (or even parse its arguments) until
1879
+ the first time one of its methods is accessed.
1880
+
1881
+ :arg schemes:
1882
+ The first positional argument can be a list of schemes, or omitted,
1883
+ just like CryptContext.
1884
+
1885
+ :param onload:
1886
+
1887
+ If a callable is passed in via this keyword,
1888
+ it will be invoked at lazy-load time
1889
+ with the following signature:
1890
+ ``onload(**kwds) -> kwds``;
1891
+ where ``kwds`` is all the additional kwds passed to LazyCryptContext.
1892
+ It should perform any additional deferred initialization,
1893
+ and return the final dict of options to be passed to CryptContext.
1894
+
1895
+ .. versionadded:: 1.6
1896
+
1897
+ :param kwds:
1898
+
1899
+ All additional keywords are passed to CryptContext;
1900
+ or to the *onload* function (if provided).
1901
+
1902
+ This is mainly used internally by modules such as :mod:`passlib.apps`,
1903
+ which define a large number of contexts, but only a few of them will be needed
1904
+ at any one time. Use of this class saves the memory needed to import
1905
+ the specified handlers until the context instance is actually accessed.
1906
+ As well, it allows constructing a context at *module-init* time,
1907
+ but using :func:`!onload()` to provide dynamic configuration
1908
+ at *application-run* time.
1909
+
1910
+ .. note::
1911
+ This class is only useful if you're referencing handler objects by name,
1912
+ and don't want them imported until runtime. If you want to have the config
1913
+ validated before your application runs, or are passing in already-imported
1914
+ handler instances, you should use :class:`CryptContext` instead.
1915
+
1916
+ .. versionadded:: 1.4
1917
+ """
1918
+
1919
+ _lazy_kwds = None
1920
+
1921
+ # NOTE: the way this class works is that whenever any of the public
1922
+ # attributes are accessed, _lazy_init() is invoked, the class itself is changed
1923
+ # to a regular CryptContext (to remove the overhead once it's unneeded)
1924
+
1925
+ def __init__(self, schemes=None, **kwds):
1926
+ if schemes is not None:
1927
+ kwds["schemes"] = schemes
1928
+ self._lazy_kwds = kwds
1929
+
1930
+ def _lazy_init(self):
1931
+ kwds = self._lazy_kwds
1932
+ if "onload" in kwds:
1933
+ onload = kwds.pop("onload")
1934
+ kwds = onload(**kwds)
1935
+ del self._lazy_kwds
1936
+ super().__init__(**kwds)
1937
+ self.__class__ = CryptContext
1938
+
1939
+ def __getattribute__(self, attr):
1940
+ if (
1941
+ not attr.startswith("_") or attr.startswith("__")
1942
+ ) and self._lazy_kwds is not None:
1943
+ self._lazy_init()
1944
+ return object.__getattribute__(self, attr)