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