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
@@ -0,0 +1,2616 @@
1
+ """passlib.handler - code for implementing handlers, and global registry for handlers"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+ import math
7
+ import threading
8
+ from typing import TYPE_CHECKING
9
+ from warnings import warn
10
+
11
+ from passlib import exc, ifc
12
+ from passlib.exc import PasslibConfigWarning, PasslibHashWarning
13
+ from passlib.ifc import PasswordHash
14
+ from passlib.registry import get_crypt_handler
15
+ from passlib.utils import (
16
+ MAX_PASSWORD_SIZE,
17
+ accepts_keyword,
18
+ as_bool,
19
+ consteq,
20
+ getrandbytes,
21
+ getrandstr,
22
+ join_unicode,
23
+ rng,
24
+ to_unicode,
25
+ update_mixin_classes,
26
+ )
27
+ from passlib.utils.binary import (
28
+ ALL_BYTE_VALUES,
29
+ BASE64_CHARS,
30
+ HASH64_CHARS,
31
+ HEX_CHARS,
32
+ LOWER_HEX_CHARS,
33
+ PADDED_BASE64_CHARS,
34
+ UPPER_HEX_CHARS,
35
+ )
36
+ from passlib.utils.compat import unicode_or_bytes
37
+ from passlib.utils.decor import classproperty, deprecated_method
38
+
39
+ if TYPE_CHECKING:
40
+ import re
41
+ from collections.abc import Mapping
42
+
43
+ # local
44
+ __all__ = [
45
+ # helpers for implementing MCF handlers
46
+ "parse_mc2",
47
+ "parse_mc3",
48
+ "render_mc2",
49
+ "render_mc3",
50
+ # framework for implementing handlers
51
+ "GenericHandler",
52
+ "StaticHandler",
53
+ "HasUserContext",
54
+ "HasRawChecksum",
55
+ "HasManyIdents",
56
+ "HasSalt",
57
+ "HasRawSalt",
58
+ "HasRounds",
59
+ "HasManyBackends",
60
+ # other helpers
61
+ "PrefixWrapper",
62
+ "HEX_CHARS",
63
+ "ifc",
64
+ # TODO: a bunch of other things are commonly assumed in this namespace
65
+ # (e.g. HEX_CHARS etc); need to audit uses and update this list.
66
+ ]
67
+
68
+
69
+ # deprecated aliases - will be removed after passlib 1.8
70
+ H64_CHARS = HASH64_CHARS
71
+ B64_CHARS = BASE64_CHARS
72
+ PADDED_B64_CHARS = PADDED_BASE64_CHARS
73
+ UC_HEX_CHARS = UPPER_HEX_CHARS
74
+ LC_HEX_CHARS = LOWER_HEX_CHARS
75
+
76
+
77
+ def _bitsize(count, chars):
78
+ """helper for bitsize() methods"""
79
+ if chars and count:
80
+ import math
81
+
82
+ return int(count * math.log2(len(chars)))
83
+ return 0
84
+
85
+
86
+ def guess_app_stacklevel(start=1):
87
+ """
88
+ try to guess stacklevel for application warning.
89
+ looks for first frame not part of passlib.
90
+ """
91
+ frame = inspect.currentframe()
92
+ count = -start
93
+ try:
94
+ while frame:
95
+ name = frame.f_globals.get("__name__", "")
96
+ if name.startswith("tests.") or not name.startswith("passlib."):
97
+ return max(1, count)
98
+ count += 1
99
+ frame = frame.f_back
100
+ return start
101
+ finally:
102
+ del frame
103
+
104
+
105
+ def warn_hash_settings_deprecation(handler, kwds):
106
+ warn(
107
+ "passing settings to {handler}.hash() is deprecated, and won't be supported in Passlib 2.0; "
108
+ "use '{handler}.using(**settings).hash(secret)' instead".format(
109
+ **dict(handler=handler.name)
110
+ ),
111
+ DeprecationWarning,
112
+ stacklevel=guess_app_stacklevel(2),
113
+ )
114
+
115
+
116
+ def extract_settings_kwds(handler, kwds):
117
+ """
118
+ helper to extract settings kwds from mix of context & settings kwds.
119
+ pops settings keys from kwds, returns them as a dict.
120
+ """
121
+ context_keys = set(handler.context_kwds)
122
+ return dict((key, kwds.pop(key)) for key in list(kwds) if key not in context_keys)
123
+
124
+
125
+ _UDOLLAR = "$"
126
+ _UZERO = "0"
127
+
128
+
129
+ def validate_secret(secret):
130
+ """ensure secret has correct type & size"""
131
+ if not isinstance(secret, unicode_or_bytes):
132
+ raise exc.ExpectedStringError(secret, "secret")
133
+ if len(secret) > MAX_PASSWORD_SIZE:
134
+ raise exc.PasswordSizeError(MAX_PASSWORD_SIZE)
135
+
136
+
137
+ def to_unicode_for_identify(hash):
138
+ """convert hash to unicode for identify method"""
139
+ if isinstance(hash, str):
140
+ return hash
141
+ if isinstance(hash, bytes):
142
+ # try as utf-8, but if it fails, use foolproof latin-1,
143
+ # since we don't really care about non-ascii chars
144
+ # when running identify.
145
+ try:
146
+ return hash.decode("utf-8")
147
+ except UnicodeDecodeError:
148
+ return hash.decode("latin-1")
149
+ else:
150
+ raise exc.ExpectedStringError(hash, "hash")
151
+
152
+
153
+ def parse_mc2(hash, prefix, sep=_UDOLLAR, handler=None):
154
+ """parse hash using 2-part modular crypt format.
155
+
156
+ this expects a hash of the format :samp:`{prefix}{salt}[${checksum}]`,
157
+ such as md5_crypt, and parses it into salt / checksum portions.
158
+
159
+ :arg hash: the hash to parse (bytes or str)
160
+ :arg prefix: the identifying prefix (str)
161
+ :param sep: field separator (unicode, defaults to ``$``).
162
+ :param handler: handler class to pass to error constructors.
163
+
164
+ :returns:
165
+ a ``(salt, chk | None)`` tuple.
166
+ """
167
+ # detect prefix
168
+ hash = to_unicode(hash, "ascii", "hash")
169
+ assert isinstance(prefix, str)
170
+ if not hash.startswith(prefix):
171
+ raise exc.InvalidHashError(handler)
172
+
173
+ # parse 2-part hash or 1-part config string
174
+ assert isinstance(sep, str)
175
+ parts = hash[len(prefix) :].split(sep)
176
+ if len(parts) == 2:
177
+ salt, chk = parts
178
+ return salt, chk or None
179
+ if len(parts) == 1:
180
+ return parts[0], None
181
+ raise exc.MalformedHashError(handler)
182
+
183
+
184
+ def parse_mc3(
185
+ hash, prefix, sep=_UDOLLAR, rounds_base=10, default_rounds=None, handler=None
186
+ ):
187
+ """parse hash using 3-part modular crypt format.
188
+
189
+ this expects a hash of the format :samp:`{prefix}[{rounds}]${salt}[${checksum}]`,
190
+ such as sha1_crypt, and parses it into rounds / salt / checksum portions.
191
+ tries to convert the rounds to an integer,
192
+ and throws error if it has zero-padding.
193
+
194
+ :arg hash: the hash to parse (bytes or unicode)
195
+ :arg prefix: the identifying prefix (unicode)
196
+ :param sep: field separator (unicode, defaults to ``$``).
197
+ :param rounds_base:
198
+ the numeric base the rounds are encoded in (defaults to base 10).
199
+ :param default_rounds:
200
+ the default rounds value to return if the rounds field was omitted.
201
+ if this is ``None`` (the default), the rounds field is *required*.
202
+ :param handler: handler class to pass to error constructors.
203
+
204
+ :returns:
205
+ a ``(rounds : int, salt, chk | None)`` tuple.
206
+ """
207
+ # detect prefix
208
+ hash = to_unicode(hash, "ascii", "hash")
209
+ assert isinstance(prefix, str)
210
+ if not hash.startswith(prefix):
211
+ raise exc.InvalidHashError(handler)
212
+
213
+ # parse 3-part hash or 2-part config string
214
+ assert isinstance(sep, str)
215
+ parts = hash[len(prefix) :].split(sep)
216
+ if len(parts) == 3:
217
+ rounds, salt, chk = parts
218
+ elif len(parts) == 2:
219
+ rounds, salt = parts
220
+ chk = None
221
+ else:
222
+ raise exc.MalformedHashError(handler)
223
+
224
+ # validate & parse rounds portion
225
+ if rounds.startswith(_UZERO) and rounds != _UZERO:
226
+ raise exc.ZeroPaddedRoundsError(handler)
227
+ if rounds:
228
+ rounds = int(rounds, rounds_base)
229
+ elif default_rounds is None:
230
+ raise exc.MalformedHashError(handler, "empty rounds field")
231
+ else:
232
+ rounds = default_rounds
233
+
234
+ # return result
235
+ return rounds, salt, chk or None
236
+
237
+
238
+ # def parse_mc3_long(hash, prefix, sep=_UDOLLAR, handler=None):
239
+ # """
240
+ # parse hash using 3-part modular crypt format,
241
+ # with complex settings string instead of simple rounds.
242
+ # otherwise works same as :func:`parse_mc3`
243
+ # """
244
+ # # detect prefix
245
+ # hash = to_unicode(hash, "ascii", "hash")
246
+ # assert isinstance(prefix, unicode)
247
+ # if not hash.startswith(prefix):
248
+ # raise exc.InvalidHashError(handler)
249
+ #
250
+ # # parse 3-part hash or 2-part config string
251
+ # assert isinstance(sep, unicode)
252
+ # parts = hash[len(prefix):].split(sep)
253
+ # if len(parts) == 3:
254
+ # return parts
255
+ # elif len(parts) == 2:
256
+ # settings, salt = parts
257
+ # return settings, salt, None
258
+ # else:
259
+ # raise exc.MalformedHashError(handler)
260
+
261
+
262
+ def parse_int(source, base=10, default=None, param="value", handler=None):
263
+ """
264
+ helper to parse an integer config field
265
+
266
+ :arg source: unicode source string
267
+ :param base: numeric base
268
+ :param default: optional default if source is empty
269
+ :param param: name of variable, for error msgs
270
+ :param handler: handler class, for error msgs
271
+ """
272
+ if source.startswith(_UZERO) and source != _UZERO:
273
+ raise exc.MalformedHashError(handler, f"zero-padded {param} field")
274
+ if source:
275
+ return int(source, base)
276
+ if default is None:
277
+ raise exc.MalformedHashError(handler, f"empty {param} field")
278
+ return default
279
+
280
+
281
+ def render_mc2(ident, salt, checksum, sep="$"):
282
+ """format hash using 2-part modular crypt format; inverse of parse_mc2()
283
+
284
+ returns native string with format :samp:`{ident}{salt}[${checksum}]`,
285
+ such as used by md5_crypt.
286
+
287
+ :arg ident: identifier prefix (unicode)
288
+ :arg salt: encoded salt (unicode)
289
+ :arg checksum: encoded checksum (unicode or None)
290
+ :param sep: separator char (unicode, defaults to ``$``)
291
+
292
+ :returns:
293
+ config or hash (native str)
294
+ """
295
+ if checksum: # noqa: SIM108
296
+ parts = [ident, salt, sep, checksum]
297
+ else:
298
+ parts = [ident, salt]
299
+ return "".join(parts)
300
+
301
+
302
+ def render_mc3(ident, rounds, salt, checksum, sep="$", rounds_base=10):
303
+ """format hash using 3-part modular crypt format; inverse of parse_mc3()
304
+
305
+ returns native string with format :samp:`{ident}[{rounds}$]{salt}[${checksum}]`,
306
+ such as used by sha1_crypt.
307
+
308
+ :arg ident: identifier prefix (unicode)
309
+ :arg rounds: rounds field (int or None)
310
+ :arg salt: encoded salt (unicode)
311
+ :arg checksum: encoded checksum (unicode or None)
312
+ :param sep: separator char (unicode, defaults to ``$``)
313
+ :param rounds_base: base to encode rounds value (defaults to base 10)
314
+
315
+ :returns:
316
+ config or hash (native str)
317
+ """
318
+ if rounds is None:
319
+ rounds = ""
320
+ elif rounds_base == 16:
321
+ rounds = f"{rounds:x}"
322
+ else:
323
+ assert rounds_base == 10
324
+ rounds = str(rounds)
325
+ if checksum:
326
+ parts = [ident, rounds, sep, salt, sep, checksum]
327
+ else:
328
+ parts = [ident, rounds, sep, salt]
329
+ return join_unicode(parts)
330
+
331
+
332
+ def mask_value(value, show=4, pct=0.125, char="*"):
333
+ """
334
+ helper to mask contents of sensitive field.
335
+
336
+ :param value:
337
+ raw value (str, bytes, etc)
338
+
339
+ :param show:
340
+ max # of characters to remain visible
341
+
342
+ :param pct:
343
+ don't show more than this % of input.
344
+
345
+ :param char:
346
+ character to use for masking
347
+
348
+ :rtype: str | None
349
+ """
350
+ if value is None:
351
+ return None
352
+ if not isinstance(value, str):
353
+ if isinstance(value, bytes):
354
+ from passlib.utils.binary import ab64_encode
355
+
356
+ value = ab64_encode(value).decode("ascii")
357
+ else:
358
+ value = str(value)
359
+ size = len(value)
360
+ show = min(show, int(size * pct))
361
+ return value[:show] + char * (size - show)
362
+
363
+
364
+ def validate_default_value(handler, default, norm, param="value"):
365
+ """
366
+ assert helper that quickly validates default value.
367
+ designed to get out of the way and reduce overhead when asserts are stripped.
368
+ """
369
+ assert default is not None, f"{handler.name} lacks default {param}"
370
+ assert norm(default) == default, (
371
+ f"{handler.name}: invalid default {param}: {default!r}"
372
+ )
373
+ return True
374
+
375
+
376
+ def norm_integer(
377
+ handler,
378
+ value,
379
+ min=1,
380
+ max=None, # *
381
+ param="value",
382
+ relaxed=False,
383
+ ):
384
+ """
385
+ helper to normalize and validate an integer value (e.g. rounds, salt_size)
386
+
387
+ :arg value: value provided to constructor
388
+ :arg default: default value if none provided. if set to ``None``, value is required.
389
+ :arg param: name of parameter (xxx: move to first arg?)
390
+ :param min: minimum value (defaults to 1)
391
+ :param max: maximum value (default ``None`` means no maximum)
392
+ :returns: validated value
393
+ """
394
+ # check type
395
+ if not isinstance(value, int):
396
+ raise exc.ExpectedTypeError(value, "integer", param)
397
+
398
+ # check minimum
399
+ if value < min:
400
+ msg = "%s: %s (%d) is too low, must be at least %d" % (
401
+ handler.name,
402
+ param,
403
+ value,
404
+ min,
405
+ )
406
+ if relaxed:
407
+ warn(msg, exc.PasslibHashWarning)
408
+ value = min
409
+ else:
410
+ raise ValueError(msg)
411
+
412
+ # check maximum
413
+ if max and value > max:
414
+ msg = "%s: %s (%d) is too large, cannot be more than %d" % (
415
+ handler.name,
416
+ param,
417
+ value,
418
+ max,
419
+ )
420
+ if relaxed:
421
+ warn(msg, exc.PasslibHashWarning)
422
+ value = max
423
+ else:
424
+ raise ValueError(msg)
425
+
426
+ return value
427
+
428
+
429
+ class MinimalHandler(PasswordHash):
430
+ """
431
+ helper class for implementing hash handlers.
432
+ provides nothing besides a base implementation of the .using() subclass constructor.
433
+ """
434
+
435
+ #: private flag used by using() constructor to detect if this is already a subclass.
436
+ _configured = False
437
+
438
+ @classmethod
439
+ def using(cls, relaxed=False):
440
+ # NOTE: this provides the base implementation, which takes care of
441
+ # creating the newly configured class. Mixins and subclasses
442
+ # should wrap this, and modify the returned class to suit their options.
443
+ # NOTE: 'relaxed' keyword is ignored here, but parsed so that subclasses
444
+ # can check for it as argument, and modify their parsing behavior accordingly.
445
+ name = cls.__name__
446
+ if not cls._configured:
447
+ # TODO: straighten out class naming, repr, and .name attr
448
+ name = f"<customized {name} hasher>"
449
+ return type(name, (cls,), dict(__module__=cls.__module__, _configured=True))
450
+
451
+
452
+ class TruncateMixin(MinimalHandler):
453
+ """
454
+ PasswordHash mixin which provides a method
455
+ that will check if secret would be truncated,
456
+ and can be configured to throw an error.
457
+
458
+ .. warning::
459
+
460
+ Hashers using this mixin will generally need to override
461
+ the default PasswordHash.truncate_error policy of "True",
462
+ and will similarly want to override .truncate_verify_reject as well.
463
+
464
+ TODO: This should be done explicitly, but for now this mixin sets
465
+ these flags implicitly.
466
+ """
467
+
468
+ truncate_error = False
469
+ truncate_verify_reject = False
470
+
471
+ @classmethod
472
+ def using(cls, truncate_error=None, **kwds):
473
+ subcls = super().using(**kwds)
474
+ if truncate_error is not None:
475
+ truncate_error = as_bool(truncate_error, param="truncate_error")
476
+ if truncate_error is not None:
477
+ subcls.truncate_error = truncate_error
478
+ return subcls
479
+
480
+ @classmethod
481
+ def _check_truncate_policy(cls, secret):
482
+ """
483
+ make sure secret won't be truncated.
484
+ NOTE: this should only be called for .hash(), not for .verify(),
485
+ which should honor the .truncate_verify_reject policy.
486
+ """
487
+ assert cls.truncate_size is not None, "truncate_size must be set by subclass"
488
+ if cls.truncate_error and len(secret) > cls.truncate_size:
489
+ raise exc.PasswordTruncateError(cls)
490
+
491
+
492
+ class GenericHandler(MinimalHandler):
493
+ """helper class for implementing hash handlers.
494
+
495
+ GenericHandler-derived classes will have (at least) the following
496
+ constructor options, though others may be added by mixins
497
+ and by the class itself:
498
+
499
+ :param checksum:
500
+ this should contain the digest portion of a
501
+ parsed hash (mainly provided when the constructor is called
502
+ by :meth:`from_string()`).
503
+ defaults to ``None``.
504
+
505
+ :param use_defaults:
506
+ If ``False`` (the default), a :exc:`TypeError` should be thrown
507
+ if any settings required by the handler were not explicitly provided.
508
+
509
+ If ``True``, the handler should attempt to provide a default for any
510
+ missing values. This means generate missing salts, fill in default
511
+ cost parameters, etc.
512
+
513
+ This is typically only set to ``True`` when the constructor
514
+ is called by :meth:`hash`, allowing user-provided values
515
+ to be handled in a more permissive manner.
516
+
517
+ :param relaxed:
518
+ If ``False`` (the default), a :exc:`ValueError` should be thrown
519
+ if any settings are out of bounds or otherwise invalid.
520
+
521
+ If ``True``, they should be corrected if possible, and a warning
522
+ issue. If not possible, only then should an error be raised.
523
+ (e.g. under ``relaxed=True``, rounds values will be clamped
524
+ to min/max rounds).
525
+
526
+ This is mainly used when parsing the config strings of certain
527
+ hashes, whose specifications implementations to be tolerant
528
+ of incorrect values in salt strings.
529
+
530
+ Class Attributes
531
+ ================
532
+
533
+ .. attribute:: ident
534
+
535
+ [optional]
536
+ If this attribute is filled in, the default :meth:`identify` method will use
537
+ it as a identifying prefix that can be used to recognize instances of this handler's
538
+ hash. Filling this out is recommended for speed.
539
+
540
+ This should be a unicode str.
541
+
542
+ .. attribute:: _hash_regex
543
+
544
+ [optional]
545
+ If this attribute is filled in, the default :meth:`identify` method
546
+ will use it to recognize instances of the hash. If :attr:`ident`
547
+ is specified, this will be ignored.
548
+
549
+ This should be a unique regex object.
550
+
551
+ .. attribute:: checksum_size
552
+
553
+ [optional]
554
+ Specifies the number of characters that should be expected in the checksum string.
555
+ If omitted, no check will be performed.
556
+
557
+ .. attribute:: checksum_chars
558
+
559
+ [optional]
560
+ A string listing all the characters allowed in the checksum string.
561
+ If omitted, no check will be performed.
562
+
563
+ This should be a unicode str.
564
+
565
+ .. attribute:: _stub_checksum
566
+
567
+ Placeholder checksum that will be used by genconfig()
568
+ in lieu of actually generating a hash for the empty string.
569
+ This should be a string of the same datatype as :attr:`checksum`.
570
+
571
+ Instance Attributes
572
+ ===================
573
+ .. attribute:: checksum
574
+
575
+ The checksum string provided to the constructor (after passing it
576
+ through :meth:`_norm_checksum`).
577
+
578
+ Required Subclass Methods
579
+ =========================
580
+ The following methods must be provided by handler subclass:
581
+
582
+ .. automethod:: from_string
583
+ .. automethod:: to_string
584
+ .. automethod:: _calc_checksum
585
+
586
+ Default Methods
587
+ ===============
588
+ The following methods have default implementations that should work for
589
+ most cases, though they may be overridden if the hash subclass needs to:
590
+
591
+ .. automethod:: _norm_checksum
592
+
593
+ .. automethod:: genconfig
594
+ .. automethod:: genhash
595
+ .. automethod:: identify
596
+ .. automethod:: hash
597
+ .. automethod:: verify
598
+ """
599
+
600
+ # this must be provided by the actual class.
601
+ setting_kwds: tuple[str, ...] | None = None
602
+
603
+ # providing default since most classes don't use this at all.
604
+ context_kwds: tuple[str, ...] = ()
605
+
606
+ # optional prefix that uniquely identifies hash
607
+ ident: str | None = None
608
+
609
+ # optional regexp for recognizing hashes,
610
+ # used by default identify() if .ident isn't specified.
611
+ _hash_regex: re.Pattern[str] | None = None
612
+
613
+ # if specified, _norm_checksum will require this length
614
+ checksum_size: int | None = None
615
+
616
+ # if specified, _norm_checksum() will validate this
617
+ checksum_chars: str | None = None
618
+
619
+ # private flag used by HasRawChecksum
620
+ _checksum_is_bytes = False
621
+ checksum = None # stores checksum
622
+
623
+ # use_defaults = False # whether _norm_xxx() funcs should fill in defaults.
624
+ # relaxed = False # when _norm_xxx() funcs should be strict about inputs
625
+ def __init__(self, checksum=None, use_defaults=False, **kwds):
626
+ self.use_defaults = use_defaults
627
+ super().__init__(**kwds)
628
+ if checksum is not None:
629
+ # XXX: do we need to set .relaxed for checksum coercion?
630
+ self.checksum = self._norm_checksum(checksum)
631
+
632
+ # NOTE: would like to make this classmethod, but fshp checksum size
633
+ # is dependant on .variant, so leaving this as instance method.
634
+ def _norm_checksum(self, checksum, relaxed=False):
635
+ """validates checksum keyword against class requirements,
636
+ returns normalized version of checksum.
637
+ """
638
+ # NOTE: by default this code assumes checksum should be unicode.
639
+ # For classes where the checksum is raw bytes, the HasRawChecksum sets
640
+ # the _checksum_is_bytes flag which alters various code paths below.
641
+
642
+ # normalize to bytes / unicode
643
+ raw = self._checksum_is_bytes
644
+ if raw:
645
+ # NOTE: no clear route to reasonably convert unicode -> raw bytes,
646
+ # so 'relaxed' does nothing here
647
+ if not isinstance(checksum, bytes):
648
+ raise exc.ExpectedTypeError(checksum, "bytes", "checksum")
649
+
650
+ elif not isinstance(checksum, str):
651
+ if isinstance(checksum, bytes) and relaxed:
652
+ warn("checksum should be unicode, not bytes", PasslibHashWarning)
653
+ checksum = checksum.decode("ascii")
654
+ else:
655
+ raise exc.ExpectedTypeError(checksum, "str", "checksum")
656
+
657
+ # check size
658
+ cc = self.checksum_size
659
+ if cc and len(checksum) != cc:
660
+ raise exc.ChecksumSizeError(self, raw=raw)
661
+
662
+ # check charset
663
+ if not raw:
664
+ cs = self.checksum_chars
665
+ if cs and any(c not in cs for c in checksum):
666
+ raise ValueError(f"invalid characters in {self.name} checksum")
667
+
668
+ return checksum
669
+
670
+ @classmethod
671
+ def identify(cls, hash):
672
+ # NOTE: subclasses may wish to use faster / simpler identify,
673
+ # and raise value errors only when an invalid (but identifiable)
674
+ # string is parsed
675
+ hash = to_unicode_for_identify(hash)
676
+ if not hash:
677
+ return False
678
+
679
+ # does class specify a known unique prefix to look for?
680
+ ident = cls.ident
681
+ if ident is not None:
682
+ return hash.startswith(ident)
683
+
684
+ # does class provide a regexp to use?
685
+ pat = cls._hash_regex
686
+ if pat is not None:
687
+ return pat.match(hash) is not None
688
+
689
+ # as fallback, try to parse hash, and see if we succeed.
690
+ # inefficient, but works for most cases.
691
+ try:
692
+ cls.from_string(hash)
693
+ return True
694
+ except ValueError:
695
+ return False
696
+
697
+ @classmethod
698
+ def from_string(cls, hash, **context): # pragma: no cover
699
+ r"""
700
+ return parsed instance from hash/configuration string
701
+
702
+ :param \\*\\*context:
703
+ context keywords to pass to constructor (if applicable).
704
+
705
+ :raises ValueError: if hash is incorrectly formatted
706
+
707
+ :returns:
708
+ hash parsed into components,
709
+ for formatting / calculating checksum.
710
+ """
711
+ raise NotImplementedError(f"{cls} must implement from_string()")
712
+
713
+ def to_string(self): # pragma: no cover
714
+ """render instance to hash or configuration string
715
+
716
+ :returns:
717
+ hash string with salt & digest included.
718
+
719
+ should return native str.
720
+ """
721
+ raise NotImplementedError(f"{self.__class__} must implement from_string()")
722
+
723
+ # NOTE: this is only used by genconfig(), and will be removed in passlib 2.0
724
+ @property
725
+ def _stub_checksum(self):
726
+ """
727
+ placeholder used by default .genconfig() so it can avoid expense of calculating digest.
728
+ """
729
+ # used fixed string if available
730
+ if self.checksum_size:
731
+ if self._checksum_is_bytes:
732
+ return b"\x00" * self.checksum_size
733
+ if self.checksum_chars:
734
+ return self.checksum_chars[0] * self.checksum_size
735
+
736
+ # hack to minimize cost of calculating real checksum
737
+ if isinstance(self, HasRounds):
738
+ orig = self.rounds
739
+ self.rounds = self.min_rounds or 1
740
+ try:
741
+ return self._calc_checksum("")
742
+ finally:
743
+ self.rounds = orig
744
+
745
+ # final fallback, generate a real checksum
746
+ return self._calc_checksum("")
747
+
748
+ def _calc_checksum(self, secret): # pragma: no cover
749
+ """given secret; calcuate and return encoded checksum portion of hash
750
+ string, taking config from object state
751
+
752
+ calc checksum implementations may assume secret is always
753
+ either str or bytes, checks are performed by verify/etc.
754
+ """
755
+ raise NotImplementedError(f"{self.__class__} must implement _calc_checksum()")
756
+
757
+ @classmethod
758
+ def hash(cls, secret, **kwds):
759
+ if kwds:
760
+ # Deprecating passing any settings keywords via .hash() as of passlib 1.7; everything
761
+ # should use .using().hash() instead. If any keywords are specified, presume they're
762
+ # context keywords by default (the common case), and extract out any settings kwds.
763
+ # Support for passing settings via .hash() will be removed in Passlib 2.0, along with
764
+ # this block of code.
765
+ settings = extract_settings_kwds(cls, kwds)
766
+ if settings:
767
+ warn_hash_settings_deprecation(cls, settings)
768
+ return cls.using(**settings).hash(secret, **kwds)
769
+ # NOTE: at this point, 'kwds' should just contain context_kwds subset
770
+ validate_secret(secret)
771
+ self = cls(use_defaults=True, **kwds)
772
+ self.checksum = self._calc_checksum(secret)
773
+ return self.to_string()
774
+
775
+ @classmethod
776
+ def verify(cls, secret, hash, **context):
777
+ # NOTE: classes with multiple checksum encodings should either
778
+ # override this method, or ensure that from_string() / _norm_checksum()
779
+ # ensures .checksum always uses a single canonical representation.
780
+ validate_secret(secret)
781
+ self = cls.from_string(hash, **context)
782
+ chk = self.checksum
783
+ if chk is None:
784
+ raise exc.MissingDigestError(cls)
785
+ return consteq(self._calc_checksum(secret), chk)
786
+
787
+ @deprecated_method(deprecated="1.7", removed="2.0")
788
+ @classmethod
789
+ def genconfig(cls, **kwds):
790
+ # NOTE: 'kwds' should generally always be settings, so after this completes, *should* be empty.
791
+ settings = extract_settings_kwds(cls, kwds)
792
+ if settings:
793
+ return cls.using(**settings).genconfig(**kwds)
794
+ # NOTE: this uses optional stub checksum to bypass potentially expensive digest generation,
795
+ # when caller just wants the config string.
796
+ self = cls(use_defaults=True, **kwds)
797
+ self.checksum = self._stub_checksum
798
+ return self.to_string()
799
+
800
+ @deprecated_method(deprecated="1.7", removed="2.0")
801
+ @classmethod
802
+ def genhash(cls, secret, config, **context):
803
+ if config is None:
804
+ raise TypeError("config must be string")
805
+ validate_secret(secret)
806
+ self = cls.from_string(config, **context)
807
+ self.checksum = self._calc_checksum(secret)
808
+ return self.to_string()
809
+
810
+ @classmethod
811
+ def needs_update(cls, hash, secret=None, **kwds):
812
+ # NOTE: subclasses should generally just wrap _calc_needs_update()
813
+ # to check their particular keywords.
814
+ self = cls.from_string(hash)
815
+ assert isinstance(self, cls)
816
+ return self._calc_needs_update(secret=secret, **kwds)
817
+
818
+ def _calc_needs_update(self, secret=None):
819
+ """
820
+ internal helper for :meth:`needs_update`.
821
+ """
822
+ # NOTE: this just provides a stub, subclasses & mixins
823
+ # should override this with their own tests.
824
+ return False
825
+
826
+ # ===================================================================
827
+ # experimental - the following methods are not finished or tested,
828
+ # but way work correctly for some hashes
829
+ # ===================================================================
830
+
831
+ #: internal helper for forcing settings to be included, even if default matches
832
+ _always_parse_settings: tuple[str, ...] = ()
833
+
834
+ #: internal helper for excluding certain setting_kwds from parsehash() result
835
+ _unparsed_settings: tuple[str, ...] = ("salt_size", "relaxed")
836
+
837
+ #: parsehash() keys that need to be sanitized
838
+ _unsafe_settings: tuple[str, ...] = ("salt", "checksum")
839
+
840
+ @classproperty
841
+ def _parsed_settings(cls):
842
+ """
843
+ helper for :meth:`parsehash` --
844
+ returns list of attributes which should be extracted by parse_hash() from hasher object.
845
+
846
+ default implementation just takes setting_kwds, and excludes _unparsed_settings
847
+ """
848
+ return tuple(
849
+ key for key in cls.setting_kwds if key not in cls._unparsed_settings
850
+ )
851
+
852
+ @classmethod
853
+ def parsehash(cls, hash, checksum=True, sanitize=False):
854
+ """[experimental method] parse hash into dictionary of settings.
855
+
856
+ this essentially acts as the inverse of :meth:`hash`: for most
857
+ cases, if ``hash = cls.hash(secret, **opts)``, then
858
+ ``cls.parsehash(hash)`` will return a dict matching the original options
859
+ (with the extra keyword *checksum*).
860
+
861
+ this method may not work correctly for all hashes,
862
+ and may not be available on some few. its interface may
863
+ change in future releases, if it's kept around at all.
864
+
865
+ :arg hash: hash to parse
866
+ :param checksum: include checksum keyword? (defaults to True)
867
+ :param sanitize: mask data for sensitive fields? (defaults to False)
868
+ """
869
+ # FIXME: this may not work for hashes with non-standard settings.
870
+ # XXX: how should this handle checksum/salt encoding?
871
+ # need to work that out for hash() anyways.
872
+ self = cls.from_string(hash)
873
+ # XXX: could split next few lines out as self._parsehash() for subclassing
874
+ # XXX: could try to resolve ident/variant to publically suitable alias.
875
+ # XXX: for v1.8, consider making "always" the default policy, and compare to class default
876
+ # only for whitelisted attrs? or make this whole method obsolete by reworking
877
+ # so "hasher" object & it's attrs are public?
878
+ UNSET = object()
879
+ always = self._always_parse_settings
880
+ kwds = dict(
881
+ (key, getattr(self, key))
882
+ for key in self._parsed_settings
883
+ if key in always or getattr(self, key) != getattr(cls, key, UNSET)
884
+ )
885
+ if checksum and self.checksum is not None:
886
+ kwds["checksum"] = self.checksum
887
+ if sanitize:
888
+ if sanitize is True:
889
+ sanitize = mask_value
890
+ for key in cls._unsafe_settings:
891
+ if key in kwds:
892
+ kwds[key] = sanitize(kwds[key])
893
+ return kwds
894
+
895
+ @classmethod
896
+ def bitsize(cls, **kwds):
897
+ """[experimental method] return info about bitsizes of hash"""
898
+ try:
899
+ info = super().bitsize(**kwds)
900
+ except AttributeError:
901
+ info = {}
902
+ cc = ALL_BYTE_VALUES if cls._checksum_is_bytes else cls.checksum_chars
903
+ if cls.checksum_size and cc:
904
+ # FIXME: this may overestimate size due to padding bits (e.g. bcrypt)
905
+ # FIXME: this will be off by 1 for case-insensitive hashes.
906
+ info["checksum"] = _bitsize(cls.checksum_size, cc)
907
+ return info
908
+
909
+
910
+ class StaticHandler(GenericHandler):
911
+ """GenericHandler mixin for classes which have no settings.
912
+
913
+ This mixin assumes the entirety of the hash ise stored in the
914
+ :attr:`checksum` attribute; that the hash has no rounds, salt,
915
+ etc. This class provides the following:
916
+
917
+ * a default :meth:`genconfig` that always returns None.
918
+ * a default :meth:`from_string` and :meth:`to_string`
919
+ that store the entire hash within :attr:`checksum`,
920
+ after optionally stripping a constant prefix.
921
+
922
+ All that is required by subclasses is an implementation of
923
+ the :meth:`_calc_checksum` method.
924
+ """
925
+
926
+ # TODO: document _norm_hash()
927
+
928
+ setting_kwds: tuple[str, ...] = ()
929
+
930
+ # optional constant prefix subclasses can specify
931
+ _hash_prefix = ""
932
+
933
+ @classmethod
934
+ def from_string(cls, hash, **context):
935
+ # default from_string() which strips optional prefix,
936
+ # and passes rest unchanged as checksum value.
937
+ hash = to_unicode(hash, "ascii", "hash")
938
+ hash = cls._norm_hash(hash)
939
+ # could enable this for extra strictness
940
+ ##pat = cls._hash_regex
941
+ ##if pat and pat.match(hash) is None:
942
+ ## raise ValueError("not a valid %s hash" % (cls.name,))
943
+ prefix = cls._hash_prefix
944
+ if prefix:
945
+ if hash.startswith(prefix):
946
+ hash = hash[len(prefix) :]
947
+ else:
948
+ raise exc.InvalidHashError(cls)
949
+ return cls(checksum=hash, **context)
950
+
951
+ @classmethod
952
+ def _norm_hash(cls, hash):
953
+ """helper for subclasses to normalize case if needed"""
954
+ return hash
955
+
956
+ def to_string(self):
957
+ return self._hash_prefix + self.checksum
958
+
959
+
960
+ class HasEncodingContext(GenericHandler):
961
+ """helper for classes which require knowledge of the encoding used"""
962
+
963
+ context_kwds = ("encoding",)
964
+ default_encoding = "utf-8"
965
+
966
+ def __init__(self, encoding=None, **kwds):
967
+ super().__init__(**kwds)
968
+ self.encoding = encoding or self.default_encoding
969
+
970
+
971
+ class HasUserContext(GenericHandler):
972
+ """helper for classes which require a user context keyword"""
973
+
974
+ context_kwds = ("user",)
975
+
976
+ def __init__(self, user=None, **kwds):
977
+ super().__init__(**kwds)
978
+ self.user = user
979
+
980
+ # XXX: would like to validate user input here, but calls to from_string()
981
+ # which lack context keywords would then fail; so leaving code per-handler.
982
+
983
+ # wrap funcs to accept 'user' as positional arg for ease of use.
984
+ @classmethod
985
+ def hash(cls, secret, user=None, **context):
986
+ return super().hash(secret, user=user, **context)
987
+
988
+ @classmethod
989
+ def verify(cls, secret, hash, user=None, **context):
990
+ return super().verify(secret, hash, user=user, **context)
991
+
992
+ @deprecated_method(deprecated="1.7", removed="2.0")
993
+ @classmethod
994
+ def genhash(cls, secret, config, user=None, **context):
995
+ return super().genhash(secret, config, user=user, **context)
996
+
997
+ # XXX: how to guess the entropy of a username?
998
+ # most of these hashes are for a system (e.g. Oracle)
999
+ # which has a few *very common* names and thus really low entropy;
1000
+ # while the rest are slightly less predictable.
1001
+ # need to find good reference about this.
1002
+ ##@classmethod
1003
+ ##def bitsize(cls, **kwds):
1004
+ ## info = super().bitsize(**kwds)
1005
+ ## info['user'] = xxx
1006
+ ## return info
1007
+
1008
+
1009
+ class HasRawChecksum(GenericHandler):
1010
+ """mixin for classes which work with decoded checksum bytes
1011
+
1012
+ .. todo::
1013
+
1014
+ document this class's usage
1015
+ """
1016
+
1017
+ # NOTE: GenericHandler.checksum_chars is ignored by this implementation.
1018
+
1019
+ # NOTE: all HasRawChecksum code is currently part of GenericHandler,
1020
+ # using private '_checksum_is_bytes' flag.
1021
+ # this arrangement may be changed in the future.
1022
+ _checksum_is_bytes = True
1023
+
1024
+
1025
+ class HasManyIdents(GenericHandler):
1026
+ """mixin for hashes which use multiple prefix identifiers
1027
+
1028
+ For the hashes which may use multiple identifier prefixes,
1029
+ this mixin adds an ``ident`` keyword to constructor.
1030
+ Any value provided is passed through the :meth:`norm_idents` method,
1031
+ which takes care of validating the identifier,
1032
+ as well as allowing aliases for easier specification
1033
+ of the identifiers by the user.
1034
+
1035
+ .. todo::
1036
+
1037
+ document this class's usage
1038
+
1039
+ Class Methods
1040
+ =============
1041
+ .. todo:: document using() and needs_update() options
1042
+ """
1043
+
1044
+ default_ident: str | None = None # should be str
1045
+ ident_values: tuple[str, ...] | None = None # should be list of unicode strings
1046
+ ident_aliases: Mapping[str, str] | None = (
1047
+ None # should be dict of unicode -> unicode
1048
+ )
1049
+ # NOTE: any aliases provided to norm_ident() as bytes
1050
+ # will have been converted to unicode before
1051
+ # comparing against this dictionary.
1052
+
1053
+ # NOTE: relying on test_06_HasManyIdents() to verify
1054
+ # these are configured correctly.
1055
+ ident = None
1056
+
1057
+ @classmethod
1058
+ def using(
1059
+ cls, # keyword only...
1060
+ default_ident=None,
1061
+ ident=None,
1062
+ **kwds,
1063
+ ):
1064
+ """
1065
+ This mixin adds support for the following :meth:`~passlib.ifc.PasswordHash.using` keywords:
1066
+
1067
+ :param default_ident:
1068
+ default identifier that will be used by resulting customized hasher.
1069
+
1070
+ :param ident:
1071
+ supported as alternate alias for **default_ident**.
1072
+ """
1073
+ # resolve aliases
1074
+ if ident is not None:
1075
+ if default_ident is not None:
1076
+ raise TypeError("'default_ident' and 'ident' are mutually exclusive")
1077
+ default_ident = ident
1078
+
1079
+ # create subclass
1080
+ subcls = super().using(**kwds)
1081
+
1082
+ # add custom default ident
1083
+ # (NOTE: creates instance to run value through _norm_ident())
1084
+ if default_ident is not None:
1085
+ subcls.default_ident = cls(ident=default_ident, use_defaults=True).ident
1086
+ return subcls
1087
+
1088
+ def __init__(self, ident=None, **kwds):
1089
+ super().__init__(**kwds)
1090
+
1091
+ # init ident
1092
+ if ident is not None:
1093
+ ident = self._norm_ident(ident)
1094
+ elif self.use_defaults:
1095
+ ident = self.default_ident
1096
+ assert validate_default_value(
1097
+ self, ident, self._norm_ident, param="default_ident"
1098
+ )
1099
+ else:
1100
+ raise TypeError("no ident specified")
1101
+ self.ident = ident
1102
+
1103
+ @classmethod
1104
+ def _norm_ident(cls, ident):
1105
+ """
1106
+ helper which normalizes & validates 'ident' value.
1107
+ """
1108
+ # handle bytes
1109
+ assert ident is not None
1110
+ if isinstance(ident, bytes):
1111
+ ident = ident.decode("ascii")
1112
+
1113
+ # check if identifier is valid
1114
+ iv = cls.ident_values
1115
+ if ident in iv:
1116
+ return ident
1117
+
1118
+ # resolve aliases, and recheck against ident_values
1119
+ ia = cls.ident_aliases
1120
+ if ia:
1121
+ try:
1122
+ value = ia[ident]
1123
+ except KeyError:
1124
+ pass
1125
+ else:
1126
+ if value in iv:
1127
+ return value
1128
+
1129
+ # failure!
1130
+ # XXX: give this it's own error type?
1131
+ raise ValueError(f"invalid ident: {ident!r}")
1132
+
1133
+ @classmethod
1134
+ def identify(cls, hash):
1135
+ hash = to_unicode_for_identify(hash)
1136
+ return hash.startswith(cls.ident_values)
1137
+
1138
+ @classmethod
1139
+ def _parse_ident(cls, hash):
1140
+ """extract ident prefix from hash, helper for subclasses' from_string()"""
1141
+ hash = to_unicode(hash, "ascii", "hash")
1142
+ for ident in cls.ident_values:
1143
+ if hash.startswith(ident):
1144
+ return ident, hash[len(ident) :]
1145
+ raise exc.InvalidHashError(cls)
1146
+
1147
+ # XXX: implement a needs_update() helper that marks everything but default_ident as deprecated?
1148
+
1149
+
1150
+ class HasSalt(GenericHandler):
1151
+ """mixin for validating salts.
1152
+
1153
+ This :class:`GenericHandler` mixin adds a ``salt`` keyword to the class constuctor;
1154
+ any value provided is passed through the :meth:`_norm_salt` method,
1155
+ which takes care of validating salt length and content,
1156
+ as well as generating new salts if one it not provided.
1157
+
1158
+ :param salt:
1159
+ optional salt string
1160
+
1161
+ :param salt_size:
1162
+ optional size of salt (only used if no salt provided);
1163
+ defaults to :attr:`default_salt_size`.
1164
+
1165
+ Class Attributes
1166
+ ================
1167
+ In order for :meth:`!_norm_salt` to do its job, the following
1168
+ attributes should be provided by the handler subclass:
1169
+
1170
+ .. attribute:: min_salt_size
1171
+
1172
+ The minimum number of characters allowed in a salt string.
1173
+ An :exc:`ValueError` will be throw if the provided salt is too small.
1174
+ Defaults to ``0``.
1175
+
1176
+ .. attribute:: max_salt_size
1177
+
1178
+ The maximum number of characters allowed in a salt string.
1179
+ By default an :exc:`ValueError` will be throw if the provided salt is
1180
+ too large; but if ``relaxed=True``, it will be clipped and a warning
1181
+ issued instead. Defaults to ``None``, for no maximum.
1182
+
1183
+ .. attribute:: default_salt_size
1184
+
1185
+ [required]
1186
+ If no salt is provided, this should specify the size of the salt
1187
+ that will be generated by :meth:`_generate_salt`. By default
1188
+ this will fall back to :attr:`max_salt_size`.
1189
+
1190
+ .. attribute:: salt_chars
1191
+
1192
+ A string containing all the characters which are allowed in the salt
1193
+ string. An :exc:`ValueError` will be throw if any other characters
1194
+ are encountered. May be set to ``None`` to skip this check (but see
1195
+ in :attr:`default_salt_chars`).
1196
+
1197
+ .. attribute:: default_salt_chars
1198
+
1199
+ [required]
1200
+ This attribute controls the set of characters use to generate
1201
+ *new* salt strings. By default, it mirrors :attr:`salt_chars`.
1202
+ If :attr:`!salt_chars` is ``None``, this attribute must be specified
1203
+ in order to generate new salts. Aside from that purpose,
1204
+ the main use of this attribute is for hashes which wish to generate
1205
+ salts from a restricted subset of :attr:`!salt_chars`; such as
1206
+ accepting all characters, but only using a-z.
1207
+
1208
+ Instance Attributes
1209
+ ===================
1210
+ .. attribute:: salt
1211
+
1212
+ This instance attribute will be filled in with the salt provided
1213
+ to the constructor (as adapted by :meth:`_norm_salt`)
1214
+
1215
+ Subclassable Methods
1216
+ ====================
1217
+ .. automethod:: _norm_salt
1218
+ .. automethod:: _generate_salt
1219
+ """
1220
+
1221
+ # TODO: document _truncate_salt()
1222
+ # XXX: allow providing raw salt to this class, and encoding it?
1223
+
1224
+ min_salt_size = 0
1225
+ max_salt_size: int | None = None
1226
+ salt_chars: str | bytes | None = None
1227
+
1228
+ @classproperty
1229
+ def default_salt_size(cls):
1230
+ """default salt size (defaults to *max_salt_size*)"""
1231
+ return cls.max_salt_size
1232
+
1233
+ @classproperty
1234
+ def default_salt_chars(cls):
1235
+ """charset used to generate new salt strings (defaults to *salt_chars*)"""
1236
+ return cls.salt_chars
1237
+
1238
+ # private helpers for HasRawSalt, shouldn't be used by subclasses
1239
+ _salt_is_bytes = False
1240
+ _salt_unit = "chars"
1241
+
1242
+ # TODO: could support using(min/max_desired_salt_size) via using() and needs_update()
1243
+ salt = None
1244
+
1245
+ @classmethod
1246
+ def using(
1247
+ cls, # keyword only...
1248
+ default_salt_size=None,
1249
+ salt_size=None, # aliases used by CryptContext
1250
+ salt=None,
1251
+ **kwds,
1252
+ ):
1253
+ # check for aliases used by CryptContext
1254
+ if salt_size is not None:
1255
+ if default_salt_size is not None:
1256
+ raise TypeError(
1257
+ "'salt_size' and 'default_salt_size' aliases are mutually exclusive"
1258
+ )
1259
+ default_salt_size = salt_size
1260
+
1261
+ # generate new subclass
1262
+ subcls = super().using(**kwds)
1263
+
1264
+ # replace default_rounds
1265
+ relaxed = kwds.get("relaxed")
1266
+ if default_salt_size is not None:
1267
+ if isinstance(default_salt_size, str):
1268
+ default_salt_size = int(default_salt_size)
1269
+ subcls.default_salt_size = subcls._clip_to_valid_salt_size(
1270
+ default_salt_size, param="salt_size", relaxed=relaxed
1271
+ )
1272
+
1273
+ # if salt specified, replace _generate_salt() with fixed output.
1274
+ # NOTE: this is mainly useful for testing / debugging.
1275
+ if salt is not None:
1276
+ salt = subcls._norm_salt(salt, relaxed=relaxed)
1277
+ subcls._generate_salt = staticmethod(lambda: salt)
1278
+
1279
+ return subcls
1280
+
1281
+ # XXX: would like to combine w/ _norm_salt() code below, but doesn't quite fit.
1282
+ @classmethod
1283
+ def _clip_to_valid_salt_size(cls, salt_size, param="salt_size", relaxed=True):
1284
+ """
1285
+ internal helper --
1286
+ clip salt size value to handler's absolute limits (min_salt_size / max_salt_size)
1287
+
1288
+ :param relaxed:
1289
+ if ``True`` (the default), issues PasslibHashWarning is rounds are outside allowed range.
1290
+ if ``False``, raises a ValueError instead.
1291
+
1292
+ :param param:
1293
+ optional name of parameter to insert into error/warning messages.
1294
+
1295
+ :returns:
1296
+ clipped rounds value
1297
+ """
1298
+ mn = cls.min_salt_size
1299
+ mx = cls.max_salt_size
1300
+
1301
+ # check if salt size is fixed
1302
+ if mn == mx:
1303
+ if salt_size != mn:
1304
+ msg = "%s: %s (%d) must be exactly %d" % (
1305
+ cls.name,
1306
+ param,
1307
+ salt_size,
1308
+ mn,
1309
+ )
1310
+ if relaxed:
1311
+ warn(msg, PasslibHashWarning)
1312
+ else:
1313
+ raise ValueError(msg)
1314
+ return mn
1315
+
1316
+ # check min size
1317
+ if salt_size < mn:
1318
+ msg = "%s: %s (%r) below min_salt_size (%d)" % (
1319
+ cls.name,
1320
+ param,
1321
+ salt_size,
1322
+ mn,
1323
+ )
1324
+ if relaxed:
1325
+ warn(msg, PasslibHashWarning)
1326
+ salt_size = mn
1327
+ else:
1328
+ raise ValueError(msg)
1329
+
1330
+ # check max size
1331
+ if mx and salt_size > mx:
1332
+ msg = "%s: %s (%r) above max_salt_size (%d)" % (
1333
+ cls.name,
1334
+ param,
1335
+ salt_size,
1336
+ mx,
1337
+ )
1338
+ if relaxed:
1339
+ warn(msg, PasslibHashWarning)
1340
+ salt_size = mx
1341
+ else:
1342
+ raise ValueError(msg)
1343
+
1344
+ return salt_size
1345
+
1346
+ def __init__(self, salt=None, **kwds):
1347
+ super().__init__(**kwds)
1348
+ if salt is not None:
1349
+ salt = self._parse_salt(salt)
1350
+ elif self.use_defaults:
1351
+ salt = self._generate_salt()
1352
+ assert self._norm_salt(salt) == salt, f"generated invalid salt: {salt!r}"
1353
+ else:
1354
+ raise TypeError("no salt specified")
1355
+ self.salt = salt
1356
+
1357
+ # NOTE: split out mainly so sha256_crypt can subclass this
1358
+ def _parse_salt(self, salt):
1359
+ return self._norm_salt(salt)
1360
+
1361
+ @classmethod
1362
+ def _norm_salt(cls, salt, relaxed=False):
1363
+ """helper to normalize & validate user-provided salt string
1364
+
1365
+ :arg salt:
1366
+ salt string
1367
+
1368
+ :raises TypeError:
1369
+ If salt not correct type.
1370
+
1371
+ :raises ValueError:
1372
+
1373
+ * if salt contains chars that aren't in :attr:`salt_chars`.
1374
+ * if salt contains less than :attr:`min_salt_size` characters.
1375
+ * if ``relaxed=False`` and salt has more than :attr:`max_salt_size`
1376
+ characters (if ``relaxed=True``, the salt is truncated
1377
+ and a warning is issued instead).
1378
+
1379
+ :returns:
1380
+ normalized salt
1381
+ """
1382
+ # check type
1383
+ if cls._salt_is_bytes:
1384
+ if not isinstance(salt, bytes):
1385
+ raise exc.ExpectedTypeError(salt, "bytes", "salt")
1386
+ else:
1387
+ if not isinstance(salt, str):
1388
+ # NOTE: allowing bytes under py2 so salt can be native str.
1389
+ if relaxed and isinstance(salt, bytes):
1390
+ salt = salt.decode("ascii")
1391
+ else:
1392
+ raise exc.ExpectedTypeError(salt, "str", "salt")
1393
+
1394
+ # check charset
1395
+ sc = cls.salt_chars
1396
+ if sc is not None and any(c not in sc for c in salt):
1397
+ raise ValueError(f"invalid characters in {cls.name} salt")
1398
+
1399
+ # check min size
1400
+ mn = cls.min_salt_size
1401
+ if mn and len(salt) < mn:
1402
+ msg = "salt too small (%s requires %s %d %s)" % (
1403
+ cls.name,
1404
+ "exactly" if mn == cls.max_salt_size else ">=",
1405
+ mn,
1406
+ cls._salt_unit,
1407
+ )
1408
+ raise ValueError(msg)
1409
+
1410
+ # check max size
1411
+ mx = cls.max_salt_size
1412
+ if mx and len(salt) > mx:
1413
+ msg = "salt too large (%s requires %s %d %s)" % (
1414
+ cls.name,
1415
+ "exactly" if mx == mn else "<=",
1416
+ mx,
1417
+ cls._salt_unit,
1418
+ )
1419
+ if relaxed:
1420
+ warn(msg, PasslibHashWarning)
1421
+ salt = cls._truncate_salt(salt, mx)
1422
+ else:
1423
+ raise ValueError(msg)
1424
+
1425
+ return salt
1426
+
1427
+ @staticmethod
1428
+ def _truncate_salt(salt, mx):
1429
+ # NOTE: some hashes (e.g. bcrypt) has structure within their
1430
+ # salt string. this provides a method to override to perform
1431
+ # the truncation properly
1432
+ return salt[:mx]
1433
+
1434
+ @classmethod
1435
+ def _generate_salt(cls):
1436
+ """
1437
+ helper method for _init_salt(); generates a new random salt string.
1438
+ """
1439
+ return getrandstr(rng, cls.default_salt_chars, cls.default_salt_size)
1440
+
1441
+ @classmethod
1442
+ def bitsize(cls, salt_size=None, **kwds):
1443
+ """[experimental method] return info about bitsizes of hash"""
1444
+ info = super().bitsize(**kwds)
1445
+ if salt_size is None:
1446
+ salt_size = cls.default_salt_size
1447
+ # FIXME: this may overestimate size due to padding bits
1448
+ # FIXME: this will be off by 1 for case-insensitive hashes.
1449
+ info["salt"] = _bitsize(salt_size, cls.default_salt_chars)
1450
+ return info
1451
+
1452
+
1453
+ class HasRawSalt(HasSalt):
1454
+ """mixin for classes which use decoded salt parameter
1455
+
1456
+ A variant of :class:`!HasSalt` which takes in decoded bytes instead of an encoded string.
1457
+
1458
+ .. todo::
1459
+
1460
+ document this class's usage
1461
+ """
1462
+
1463
+ salt_chars = ALL_BYTE_VALUES
1464
+
1465
+ # NOTE: all HasRawSalt code is currently part of HasSalt, using private
1466
+ # '_salt_is_bytes' flag. this arrangement may be changed in the future.
1467
+ _salt_is_bytes = True
1468
+ _salt_unit = "bytes"
1469
+
1470
+ @classmethod
1471
+ def _generate_salt(cls):
1472
+ assert cls.salt_chars in [None, ALL_BYTE_VALUES]
1473
+ return getrandbytes(rng, cls.default_salt_size)
1474
+
1475
+
1476
+ class HasRounds(GenericHandler):
1477
+ """mixin for validating rounds parameter
1478
+
1479
+ This :class:`GenericHandler` mixin adds a ``rounds`` keyword to the class
1480
+ constuctor; any value provided is passed through the :meth:`_norm_rounds`
1481
+ method, which takes care of validating the number of rounds.
1482
+
1483
+ :param rounds: optional number of rounds hash should use
1484
+
1485
+ Class Attributes
1486
+ ================
1487
+ In order for :meth:`!_norm_rounds` to do its job, the following
1488
+ attributes must be provided by the handler subclass:
1489
+
1490
+ .. attribute:: min_rounds
1491
+
1492
+ The minimum number of rounds allowed. A :exc:`ValueError` will be
1493
+ thrown if the rounds value is too small. Defaults to ``0``.
1494
+
1495
+ .. attribute:: max_rounds
1496
+
1497
+ The maximum number of rounds allowed. A :exc:`ValueError` will be
1498
+ thrown if the rounds value is larger than this. Defaults to ``None``
1499
+ which indicates no limit to the rounds value.
1500
+
1501
+ .. attribute:: default_rounds
1502
+
1503
+ If no rounds value is provided to constructor, this value will be used.
1504
+ If this is not specified, a rounds value *must* be specified by the
1505
+ application.
1506
+
1507
+ .. attribute:: rounds_cost
1508
+
1509
+ [required]
1510
+ The ``rounds`` parameter typically encodes a cpu-time cost
1511
+ for calculating a hash. This should be set to ``"linear"``
1512
+ (the default) or ``"log2"``, depending on how the rounds value relates
1513
+ to the actual amount of time that will be required.
1514
+
1515
+ Class Methods
1516
+ =============
1517
+ .. todo:: document using() and needs_update() options
1518
+
1519
+ Instance Attributes
1520
+ ===================
1521
+ .. attribute:: rounds
1522
+
1523
+ This instance attribute will be filled in with the rounds value provided
1524
+ to the constructor (as adapted by :meth:`_norm_rounds`)
1525
+
1526
+ Subclassable Methods
1527
+ ====================
1528
+ .. automethod:: _norm_rounds
1529
+ """
1530
+
1531
+ # -----------------
1532
+ # algorithm options -- not application configurable
1533
+ # -----------------
1534
+ # XXX: rename to min_valid_rounds / max_valid_rounds,
1535
+ # to clarify role compared to min_desired_rounds / max_desired_rounds?
1536
+ min_rounds: int = 0
1537
+ max_rounds: int | None = None
1538
+ rounds_cost: str = "linear" # default to the common case
1539
+
1540
+ # hack to pass info to _CryptRecord (will be removed in passlib 2.0)
1541
+ using_rounds_kwds = (
1542
+ "min_desired_rounds",
1543
+ "max_desired_rounds",
1544
+ "min_rounds",
1545
+ "max_rounds",
1546
+ "default_rounds",
1547
+ "vary_rounds",
1548
+ )
1549
+
1550
+ # -----------------
1551
+ # desired & default rounds -- configurable via .using() classmethod
1552
+ # -----------------
1553
+ min_desired_rounds = None
1554
+ max_desired_rounds = None
1555
+ default_rounds: int | None = None
1556
+ vary_rounds = None
1557
+ rounds = None
1558
+
1559
+ @classmethod
1560
+ def using( # type: ignore[override]
1561
+ cls,
1562
+ min_desired_rounds=None,
1563
+ max_desired_rounds=None,
1564
+ default_rounds=None,
1565
+ vary_rounds: str | float | None = None,
1566
+ min_rounds=None,
1567
+ max_rounds=None,
1568
+ rounds=None, # aliases used by CryptContext
1569
+ **kwds,
1570
+ ):
1571
+ # check for aliases used by CryptContext
1572
+ if min_rounds is not None:
1573
+ if min_desired_rounds is not None:
1574
+ raise TypeError(
1575
+ "'min_rounds' and 'min_desired_rounds' aliases are mutually exclusive"
1576
+ )
1577
+ min_desired_rounds = min_rounds
1578
+
1579
+ if max_rounds is not None:
1580
+ if max_desired_rounds is not None:
1581
+ raise TypeError(
1582
+ "'max_rounds' and 'max_desired_rounds' aliases are mutually exclusive"
1583
+ )
1584
+ max_desired_rounds = max_rounds
1585
+
1586
+ # use 'rounds' as fallback for min, max, AND default
1587
+ # XXX: would it be better to make 'default_rounds' and 'rounds'
1588
+ # aliases, and have a separate 'require_rounds' parameter for this behavior?
1589
+ if rounds is not None:
1590
+ if min_desired_rounds is None:
1591
+ min_desired_rounds = rounds
1592
+ if max_desired_rounds is None:
1593
+ max_desired_rounds = rounds
1594
+ if default_rounds is None:
1595
+ default_rounds = rounds
1596
+
1597
+ # generate new subclass
1598
+ subcls = super().using(**kwds)
1599
+
1600
+ # replace min_desired_rounds
1601
+ relaxed = kwds.get("relaxed")
1602
+ if min_desired_rounds is None:
1603
+ explicit_min_rounds = False
1604
+ min_desired_rounds = cls.min_desired_rounds
1605
+ else:
1606
+ explicit_min_rounds = True
1607
+ if isinstance(min_desired_rounds, str):
1608
+ min_desired_rounds = int(min_desired_rounds)
1609
+ subcls.min_desired_rounds = subcls._norm_rounds(
1610
+ min_desired_rounds, param="min_desired_rounds", relaxed=relaxed
1611
+ )
1612
+
1613
+ # replace max_desired_rounds
1614
+ if max_desired_rounds is None:
1615
+ max_desired_rounds = cls.max_desired_rounds
1616
+ else:
1617
+ if isinstance(max_desired_rounds, str):
1618
+ max_desired_rounds = int(max_desired_rounds)
1619
+ if min_desired_rounds and max_desired_rounds < min_desired_rounds:
1620
+ msg = f"{subcls.name}: max_desired_rounds ({max_desired_rounds!r}) below min_desired_rounds ({min_desired_rounds!r})"
1621
+ if explicit_min_rounds:
1622
+ raise ValueError(msg)
1623
+ warn(msg, PasslibConfigWarning)
1624
+ max_desired_rounds = min_desired_rounds
1625
+ subcls.max_desired_rounds = subcls._norm_rounds(
1626
+ max_desired_rounds, param="max_desired_rounds", relaxed=relaxed
1627
+ )
1628
+
1629
+ # replace default_rounds
1630
+ if default_rounds is not None:
1631
+ if isinstance(default_rounds, str):
1632
+ default_rounds = int(default_rounds)
1633
+ if min_desired_rounds and default_rounds < min_desired_rounds:
1634
+ raise ValueError(
1635
+ f"{subcls.name}: default_rounds ({default_rounds!r}) below min_desired_rounds ({min_desired_rounds!r})"
1636
+ )
1637
+ if max_desired_rounds and default_rounds > max_desired_rounds:
1638
+ raise ValueError(
1639
+ f"{subcls.name}: default_rounds ({default_rounds!r}) above max_desired_rounds ({max_desired_rounds!r})"
1640
+ )
1641
+ subcls.default_rounds = subcls._norm_rounds(
1642
+ default_rounds, param="default_rounds", relaxed=relaxed
1643
+ )
1644
+
1645
+ # clip default rounds to new limits.
1646
+ if subcls.default_rounds is not None:
1647
+ subcls.default_rounds = subcls._clip_to_desired_rounds(
1648
+ subcls.default_rounds
1649
+ )
1650
+
1651
+ # replace / set vary_rounds
1652
+ if vary_rounds is not None:
1653
+ if isinstance(vary_rounds, str):
1654
+ if vary_rounds.endswith("%"):
1655
+ vary_rounds = float(vary_rounds[:-1]) * 0.01
1656
+ elif "." in vary_rounds:
1657
+ vary_rounds = float(vary_rounds)
1658
+ else:
1659
+ vary_rounds = int(vary_rounds)
1660
+ if vary_rounds < 0:
1661
+ raise ValueError(
1662
+ f"{subcls.name}: vary_rounds ({vary_rounds!r}) below 0"
1663
+ )
1664
+ if isinstance(vary_rounds, float):
1665
+ # TODO: deprecate / disallow vary_rounds=1.0
1666
+ if vary_rounds > 1:
1667
+ raise ValueError(
1668
+ f"{subcls.name}: vary_rounds ({vary_rounds!r}) above 1.0"
1669
+ )
1670
+ elif not isinstance(vary_rounds, int):
1671
+ raise TypeError("vary_rounds must be int or float")
1672
+ if vary_rounds:
1673
+ warn(
1674
+ "The 'vary_rounds' option is deprecated as of Passlib 1.7, "
1675
+ "and will be removed in Passlib 2.0",
1676
+ PasslibConfigWarning,
1677
+ )
1678
+ subcls.vary_rounds = vary_rounds
1679
+ # XXX: could cache _calc_vary_rounds_range() here if needed,
1680
+ # but would need to handle user manually changing .default_rounds
1681
+ return subcls
1682
+
1683
+ @classmethod
1684
+ def _clip_to_desired_rounds(cls, rounds):
1685
+ """
1686
+ helper for :meth:`_generate_rounds` --
1687
+ clips rounds value to desired min/max set by class (if any)
1688
+ """
1689
+ # NOTE: min/max_desired_rounds are None if unset.
1690
+ # check minimum
1691
+ mnd = cls.min_desired_rounds or 0
1692
+ if rounds < mnd:
1693
+ return mnd
1694
+
1695
+ # check maximum
1696
+ mxd = cls.max_desired_rounds
1697
+ if mxd and rounds > mxd:
1698
+ return mxd
1699
+
1700
+ return rounds
1701
+
1702
+ @classmethod
1703
+ def _calc_vary_rounds_range(cls, default_rounds):
1704
+ """
1705
+ helper for :meth:`_generate_rounds` --
1706
+ returns range for vary rounds generation.
1707
+
1708
+ :returns:
1709
+ (lower, upper) limits suitable for random.randint()
1710
+ """
1711
+ # XXX: could precalculate output of this in using() method, and save per-hash cost.
1712
+ # but then users patching cls.vary_rounds / cls.default_rounds would get wrong value.
1713
+ assert default_rounds
1714
+ vary_rounds = cls.vary_rounds
1715
+
1716
+ # if vary_rounds specified as % of default, convert it to actual rounds
1717
+ def linear_to_native(value, upper):
1718
+ return value
1719
+
1720
+ if isinstance(vary_rounds, float):
1721
+ assert 0 <= vary_rounds <= 1 # TODO: deprecate vary_rounds==1
1722
+ if cls.rounds_cost == "log2":
1723
+ # special case -- have to convert default_rounds to linear scale,
1724
+ # apply +/- vary_rounds to that, and convert back to log scale again.
1725
+ # linear_to_native() takes care of the "convert back" step.
1726
+ default_rounds = 1 << default_rounds
1727
+
1728
+ def linear_to_native(value, upper):
1729
+ if value <= 0: # log() undefined for <= 0
1730
+ return 0
1731
+ if upper: # use smallest upper bound for start of range
1732
+ return int(math.log2(value))
1733
+ # use greatest lower bound for end of range
1734
+ return int(math.ceil(math.log2(value)))
1735
+
1736
+ # calculate integer vary rounds based on current default_rounds
1737
+ vary_rounds = int(default_rounds * vary_rounds)
1738
+
1739
+ # calculate bounds based on default_rounds +/- vary_rounds
1740
+ assert vary_rounds >= 0
1741
+ assert isinstance(vary_rounds, int)
1742
+ lower = linear_to_native(default_rounds - vary_rounds, False)
1743
+ upper = linear_to_native(default_rounds + vary_rounds, True)
1744
+ return cls._clip_to_desired_rounds(lower), cls._clip_to_desired_rounds(upper)
1745
+
1746
+ def __init__(self, rounds=None, **kwds):
1747
+ super().__init__(**kwds)
1748
+ if rounds is not None:
1749
+ rounds = self._parse_rounds(rounds)
1750
+ elif self.use_defaults:
1751
+ rounds = self._generate_rounds()
1752
+ assert self._norm_rounds(rounds) == rounds, (
1753
+ f"generated invalid rounds: {rounds!r}"
1754
+ )
1755
+ else:
1756
+ raise TypeError("no rounds specified")
1757
+ self.rounds = rounds
1758
+
1759
+ # NOTE: split out mainly so sha256_crypt & bsdi_crypt can subclass this
1760
+ def _parse_rounds(self, rounds):
1761
+ return self._norm_rounds(rounds)
1762
+
1763
+ @classmethod
1764
+ def _norm_rounds(cls, rounds, relaxed=False, param="rounds"):
1765
+ """
1766
+ helper for normalizing rounds value.
1767
+
1768
+ :arg rounds:
1769
+ an integer cost parameter.
1770
+
1771
+ :param relaxed:
1772
+ if ``True`` (the default), issues PasslibHashWarning is rounds are outside allowed range.
1773
+ if ``False``, raises a ValueError instead.
1774
+
1775
+ :param param:
1776
+ optional name of parameter to insert into error/warning messages.
1777
+
1778
+ :raises TypeError:
1779
+ * if ``use_defaults=False`` and no rounds is specified
1780
+ * if rounds is not an integer.
1781
+
1782
+ :raises ValueError:
1783
+
1784
+ * if rounds is ``None`` and class does not specify a value for
1785
+ :attr:`default_rounds`.
1786
+ * if ``relaxed=False`` and rounds is outside bounds of
1787
+ :attr:`min_rounds` and :attr:`max_rounds` (if ``relaxed=True``,
1788
+ the rounds value will be clamped, and a warning issued).
1789
+
1790
+ :returns:
1791
+ normalized rounds value
1792
+ """
1793
+ return norm_integer(
1794
+ cls, rounds, cls.min_rounds, cls.max_rounds, param=param, relaxed=relaxed
1795
+ )
1796
+
1797
+ @classmethod
1798
+ def _generate_rounds(cls):
1799
+ """
1800
+ internal helper for :meth:`_norm_rounds` --
1801
+ returns default rounds value, incorporating vary_rounds,
1802
+ and any other limitations hash may place on rounds parameter.
1803
+ """
1804
+ # load default rounds
1805
+ rounds = cls.default_rounds
1806
+ if rounds is None:
1807
+ raise TypeError(f"{cls.name} rounds value must be specified explicitly")
1808
+
1809
+ # randomly vary the rounds slightly basic on vary_rounds parameter.
1810
+ # reads default_rounds internally.
1811
+ if cls.vary_rounds:
1812
+ lower, upper = cls._calc_vary_rounds_range(rounds)
1813
+ assert lower <= rounds <= upper
1814
+ if lower < upper:
1815
+ rounds = rng.randint(lower, upper)
1816
+
1817
+ return rounds
1818
+
1819
+ def _calc_needs_update(self, **kwds):
1820
+ """
1821
+ mark hash as needing update if rounds is outside desired bounds.
1822
+ """
1823
+ min_desired_rounds = self.min_desired_rounds
1824
+ if min_desired_rounds and self.rounds < min_desired_rounds:
1825
+ return True
1826
+ max_desired_rounds = self.max_desired_rounds
1827
+ if max_desired_rounds and self.rounds > max_desired_rounds:
1828
+ return True
1829
+ return super()._calc_needs_update(**kwds)
1830
+
1831
+ @classmethod
1832
+ def bitsize(cls, rounds=None, vary_rounds=0.1, **kwds):
1833
+ """[experimental method] return info about bitsizes of hash"""
1834
+ info = super().bitsize(**kwds)
1835
+ # NOTE: this essentially estimates how many bits of "salt"
1836
+ # can be added by varying the rounds value just a little bit.
1837
+ if cls.rounds_cost != "log2":
1838
+ # assume rounds can be randomized within the range
1839
+ # rounds*(1-vary_rounds) ... rounds*(1+vary_rounds)
1840
+ # then this can be used to encode
1841
+ # log2(rounds*(1+vary_rounds)-rounds*(1-vary_rounds))
1842
+ # worth of salt-like bits. this works out to
1843
+ # 1+log2(rounds*vary_rounds)
1844
+ import math
1845
+
1846
+ if rounds is None:
1847
+ rounds = cls.default_rounds
1848
+ info["rounds"] = max(0, int(1 + math.log2(rounds * vary_rounds)))
1849
+ ## else: # log2 rounds
1850
+ # all bits of the rounds value are critical to choosing
1851
+ # the time-cost, and can't be randomized.
1852
+ return info
1853
+
1854
+
1855
+ class ParallelismMixin(GenericHandler):
1856
+ """
1857
+ mixin which provides common behavior for 'parallelism' setting
1858
+ """
1859
+
1860
+ # NOTE: subclasses should add "parallelism" to their settings_kwds
1861
+
1862
+ #: parallelism setting (class-level value used as default)
1863
+ parallelism = 1
1864
+
1865
+ @classmethod
1866
+ def using(cls, parallelism=None, **kwds):
1867
+ subcls = super().using(**kwds)
1868
+ if parallelism is not None:
1869
+ if isinstance(parallelism, str):
1870
+ parallelism = int(parallelism)
1871
+ subcls.parallelism = subcls._norm_parallelism(
1872
+ parallelism, relaxed=kwds.get("relaxed")
1873
+ )
1874
+ return subcls
1875
+
1876
+ def __init__(self, parallelism=None, **kwds):
1877
+ super().__init__(**kwds)
1878
+
1879
+ # init parallelism
1880
+ if parallelism is None:
1881
+ assert validate_default_value(
1882
+ self, self.parallelism, self._norm_parallelism, param="parallelism"
1883
+ )
1884
+ else:
1885
+ self.parallelism = self._norm_parallelism(parallelism)
1886
+
1887
+ @classmethod
1888
+ def _norm_parallelism(cls, parallelism, relaxed=False):
1889
+ return norm_integer(
1890
+ cls, parallelism, min=1, param="parallelism", relaxed=relaxed
1891
+ )
1892
+
1893
+ def _calc_needs_update(self, **kwds):
1894
+ """
1895
+ mark hash as needing update if rounds is outside desired bounds.
1896
+ """
1897
+ # XXX: for now, marking all hashes which don't have matching parallelism setting
1898
+ if self.parallelism != type(self).parallelism:
1899
+ return True
1900
+ return super()._calc_needs_update(**kwds)
1901
+
1902
+
1903
+ #: global lock that must be held when changing backends.
1904
+ #: not bothering to make this more granular, as backend switching
1905
+ #: isn't a speed-critical path. lock is needed since there is some
1906
+ #: class-level state that may be modified during a "dry run"
1907
+ _backend_lock = threading.RLock()
1908
+
1909
+
1910
+ class BackendMixin(PasswordHash):
1911
+ """
1912
+ PasswordHash mixin which provides generic framework for supporting multiple backends
1913
+ within the class.
1914
+
1915
+ Public API
1916
+ ----------
1917
+
1918
+ .. attribute:: backends
1919
+
1920
+ This attribute should be a tuple containing the names of the backends
1921
+ which are supported. Two common names are ``"os_crypt"`` (if backend
1922
+ uses :mod:`crypt`), and ``"builtin"`` (if the backend is a pure-python
1923
+ fallback).
1924
+
1925
+ .. automethod:: get_backend
1926
+ .. automethod:: set_backend
1927
+ .. automethod:: has_backend
1928
+
1929
+ .. warning::
1930
+
1931
+ :meth:`set_backend` is intended to be called during application startup --
1932
+ it affects global state, and switching backends is not guaranteed threadsafe.
1933
+
1934
+ Private API (Subclass Hooks)
1935
+ ----------------------------
1936
+ Subclasses should set the :attr:`!backends` attribute to a tuple of the backends
1937
+ they wish to support. They should also define one method:
1938
+
1939
+ .. classmethod:: _load_backend_{name}(dryrun=False)
1940
+
1941
+ One copy of this method should be defined for each :samp:`name` within :attr:`!backends`.
1942
+
1943
+ It will be called in order to load the backend, and should take care of whatever
1944
+ is needed to enable the backend. This may include importing modules, running tests,
1945
+ issuing warnings, etc.
1946
+
1947
+ :param name:
1948
+ [Optional] name of backend.
1949
+
1950
+ :param dryrun:
1951
+ [Optional] True/False if currently performing a "dry run".
1952
+
1953
+ if True, the method should perform all setup actions *except*
1954
+ switching the class over to the new backend.
1955
+
1956
+ :raises passlib.exc.PasslibSecurityError:
1957
+ if the backend is available, but cannot be loaded due to a security issue.
1958
+
1959
+ :returns:
1960
+ False if backend not available, True if backend loaded.
1961
+
1962
+ .. warning::
1963
+
1964
+ Due to the way passlib's internals are arranged,
1965
+ backends should generally store stateful data at the class level
1966
+ (not the module level), and be prepared to be called on subclasses
1967
+ which may be set to a different backend from their parent.
1968
+
1969
+ (Idempotent module-level data such as lazy imports are fine).
1970
+
1971
+ .. automethod:: _finalize_backend
1972
+
1973
+ .. versionadded:: 1.7
1974
+ """
1975
+
1976
+ #: list of backend names, provided by subclass.
1977
+ backends: tuple[str, ...] | None = None
1978
+
1979
+ #: private attr mixin uses to hold currently loaded backend (or ``None``)
1980
+ __backend = None
1981
+
1982
+ #: optional class-specific text containing suggestion about what to do
1983
+ #: when no backends are available.
1984
+ _no_backend_suggestion: str | None = None
1985
+
1986
+ #: shared attr used by set_backend() to indicate what backend it's loaded;
1987
+ #: meaningless while not in set_backend().
1988
+ _pending_backend = None
1989
+
1990
+ #: shared attr used by set_backend() to indicate if it's in "dry run" mode;
1991
+ #: meaningless while not in set_backend().
1992
+ _pending_dry_run = False
1993
+
1994
+ @classmethod
1995
+ def get_backend(cls):
1996
+ """
1997
+ Return name of currently active backend.
1998
+ if no backend has been loaded, loads and returns name of default backend.
1999
+
2000
+ :raises passlib.exc.MissingBackendError:
2001
+ if no backends are available.
2002
+
2003
+ :returns:
2004
+ name of active backend
2005
+ """
2006
+ if not cls.__backend:
2007
+ cls.set_backend()
2008
+ assert cls.__backend, "set_backend() failed to load a default backend"
2009
+ return cls.__backend
2010
+
2011
+ @classmethod
2012
+ def has_backend(cls, name="any"):
2013
+ """
2014
+ Check if support is currently available for specified backend.
2015
+
2016
+ :arg name:
2017
+ name of backend to check for.
2018
+ can be any string accepted by :meth:`set_backend`.
2019
+
2020
+ :raises ValueError:
2021
+ if backend name is unknown
2022
+
2023
+ :returns:
2024
+ * ``True`` if backend is available.
2025
+ * ``False`` if it's available / can't be loaded.
2026
+ * ``None`` if it's present, but won't load due to a security issue.
2027
+ """
2028
+ try:
2029
+ cls.set_backend(name, dryrun=True)
2030
+ return True
2031
+ except (exc.MissingBackendError, exc.PasslibSecurityError):
2032
+ return False
2033
+
2034
+ @classmethod
2035
+ def set_backend(cls, name="any", dryrun=False):
2036
+ """
2037
+ Load specified backend.
2038
+
2039
+ :arg name:
2040
+ name of backend to load, can be any of the following:
2041
+
2042
+ * ``"any"`` -- use current backend if one is loaded,
2043
+ otherwise load the first available backend.
2044
+
2045
+ * ``"default"`` -- use the first available backend.
2046
+
2047
+ * any string in :attr:`backends`, loads specified backend.
2048
+
2049
+ :param dryrun:
2050
+ If True, this perform all setup actions *except* switching over to the new backend.
2051
+ (this flag is used to implement :meth:`has_backend`).
2052
+
2053
+ .. versionadded:: 1.7
2054
+
2055
+ :raises ValueError:
2056
+ If backend name is unknown.
2057
+
2058
+ :raises passlib.exc.MissingBackendError:
2059
+ If specific backend is missing;
2060
+ or in the case of ``"any"`` / ``"default"``, if *no* backends are available.
2061
+
2062
+ :raises passlib.exc.PasslibSecurityError:
2063
+
2064
+ If ``"any"`` or ``"default"`` was specified,
2065
+ but the only backend available has a PasslibSecurityError.
2066
+ """
2067
+ # check if active backend is acceptable
2068
+ if (name == "any" and cls.__backend) or (name and name == cls.__backend):
2069
+ return cls.__backend
2070
+
2071
+ # if this isn't the final subclass, whose bases we can modify,
2072
+ # find that class, and recursively call this method for the proper class.
2073
+ owner = cls._get_backend_owner()
2074
+ if owner is not cls:
2075
+ return owner.set_backend(name, dryrun=dryrun)
2076
+
2077
+ # pick first available backend
2078
+ if name == "any" or name == "default":
2079
+ default_error = None
2080
+ for name in cls.backends:
2081
+ try:
2082
+ return cls.set_backend(name, dryrun=dryrun)
2083
+ except exc.MissingBackendError: # noqa: PERF203
2084
+ continue
2085
+ except exc.PasslibSecurityError as err:
2086
+ # backend is available, but refuses to load due to security issue.
2087
+ if default_error is None:
2088
+ default_error = err
2089
+ continue
2090
+ if default_error is None:
2091
+ msg = f"{cls.name}: no backends available"
2092
+ if cls._no_backend_suggestion:
2093
+ msg += cls._no_backend_suggestion
2094
+ default_error = exc.MissingBackendError(msg)
2095
+ raise default_error
2096
+
2097
+ # validate name
2098
+ if name not in cls.backends:
2099
+ raise exc.UnknownBackendError(cls, name)
2100
+
2101
+ # hand off to _set_backend()
2102
+ with _backend_lock:
2103
+ orig = cls._pending_backend, cls._pending_dry_run
2104
+ try:
2105
+ cls._pending_backend = name
2106
+ cls._pending_dry_run = dryrun
2107
+ cls._set_backend(name, dryrun)
2108
+ finally:
2109
+ cls._pending_backend, cls._pending_dry_run = orig
2110
+ if not dryrun:
2111
+ cls.__backend = name
2112
+ return name
2113
+
2114
+ @classmethod
2115
+ def _get_backend_owner(cls):
2116
+ """
2117
+ return class that set_backend() should actually be modifying.
2118
+ for SubclassBackendMixin, this may not always be the class that was invoked.
2119
+ """
2120
+ return cls
2121
+
2122
+ @classmethod
2123
+ def _set_backend(cls, name, dryrun):
2124
+ """
2125
+ Internal method invoked by :meth:`set_backend`.
2126
+ handles actual loading of specified backend.
2127
+
2128
+ global _backend_lock will be held for duration of this method,
2129
+ and _pending_dry_run & _pending_backend will also be set.
2130
+
2131
+ should return True / False.
2132
+ """
2133
+ loader = cls._get_backend_loader(name)
2134
+ kwds = {}
2135
+ if accepts_keyword(loader, "name"):
2136
+ kwds["name"] = name
2137
+ if accepts_keyword(loader, "dryrun"):
2138
+ kwds["dryrun"] = dryrun
2139
+ ok = loader(**kwds)
2140
+ if ok is False:
2141
+ raise exc.MissingBackendError(f"{cls.name}: backend not available: {name}")
2142
+ if ok is not True:
2143
+ raise AssertionError(f"backend loaders must return True or False: {ok!r}")
2144
+
2145
+ @classmethod
2146
+ def _get_backend_loader(cls, name):
2147
+ """
2148
+ Hook called to get the specified backend's loader.
2149
+ Should return callable which optionally takes ``"name"`` and/or
2150
+ ``"dryrun"`` keywords.
2151
+
2152
+ Callable should return True if backend initialized successfully.
2153
+
2154
+ If backend can't be loaded, callable should return False
2155
+ OR raise MissingBackendError directly.
2156
+ """
2157
+ raise NotImplementedError("implement in subclass")
2158
+
2159
+ @classmethod
2160
+ def _stub_requires_backend(cls):
2161
+ """
2162
+ helper for subclasses to create stub methods which auto-load backend.
2163
+ """
2164
+ if cls.__backend:
2165
+ raise AssertionError(
2166
+ f"{cls.name}: _finalize_backend({cls.__backend!r}) failed to replace lazy loader"
2167
+ )
2168
+ cls.set_backend()
2169
+ if not cls.__backend:
2170
+ raise AssertionError(
2171
+ f"{cls.name}: set_backend() failed to load a default backend"
2172
+ )
2173
+
2174
+
2175
+ class SubclassBackendMixin(BackendMixin):
2176
+ """
2177
+ variant of BackendMixin which allows backends to be implemented
2178
+ as separate mixin classes, and dynamically switches them out.
2179
+
2180
+ backend classes should implement a _load_backend() classmethod,
2181
+ which will be invoked with an optional 'dryrun' keyword,
2182
+ and should return True or False.
2183
+
2184
+ _load_backend() will be invoked with ``cls`` equal to the mixin,
2185
+ *not* the overall class.
2186
+
2187
+ .. versionadded:: 1.7
2188
+ """
2189
+
2190
+ # 'backends' required by BackendMixin
2191
+
2192
+ #: NON-INHERITED flag that this class's bases should be modified by SubclassBackendMixin.
2193
+ #: should only be set to True in *one* subclass in hierarchy.
2194
+ _backend_mixin_target = False
2195
+
2196
+ #: map of backend name -> mixin class
2197
+ _backend_mixin_map: dict[str | None, type[GenericHandler]] | None = None
2198
+
2199
+ @classmethod
2200
+ def _get_backend_owner(cls):
2201
+ """
2202
+ return base class that we're actually switching backends on
2203
+ (needed in since backends frequently modify class attrs,
2204
+ and .set_backend may be called from a subclass).
2205
+ """
2206
+ if not cls._backend_mixin_target:
2207
+ raise AssertionError("_backend_mixin_target not set")
2208
+ for base in cls.__mro__:
2209
+ if base.__dict__.get("_backend_mixin_target"):
2210
+ return base
2211
+ raise AssertionError("expected to find class w/ '_backend_mixin_target' set")
2212
+
2213
+ @classmethod
2214
+ def _set_backend(cls, name, dryrun):
2215
+ # invoke backend loader (will throw error if fails)
2216
+ super()._set_backend(name, dryrun)
2217
+
2218
+ # sanity check call args (should trust .set_backend, but will really
2219
+ # foul things up if this isn't the owner)
2220
+ assert cls is cls._get_backend_owner(), (
2221
+ "_finalize_backend() not invoked on owner"
2222
+ )
2223
+
2224
+ # pick mixin class
2225
+ mixin_map = cls._backend_mixin_map
2226
+ assert mixin_map, "_backend_mixin_map not specified"
2227
+ mixin_cls = mixin_map[name]
2228
+ assert issubclass(mixin_cls, SubclassBackendMixin), "invalid mixin class"
2229
+
2230
+ # modify <cls> to remove existing backend mixins, and insert the new one
2231
+ update_mixin_classes(
2232
+ cls,
2233
+ add=mixin_cls,
2234
+ remove=mixin_map.values(),
2235
+ append=True,
2236
+ before=SubclassBackendMixin,
2237
+ dryrun=dryrun,
2238
+ )
2239
+
2240
+ @classmethod
2241
+ def _get_backend_loader(cls, name):
2242
+ assert cls._backend_mixin_map, "_backend_mixin_map not specified"
2243
+ return cls._backend_mixin_map[name]._load_backend_mixin
2244
+
2245
+
2246
+ # XXX: rename to ChecksumBackendMixin?
2247
+ class HasManyBackends(BackendMixin, GenericHandler):
2248
+ """
2249
+ GenericHandler mixin which provides selecting from multiple backends.
2250
+
2251
+ .. todo::
2252
+
2253
+ finish documenting this class's usage
2254
+
2255
+ For hashes which need to select from multiple backends,
2256
+ depending on the host environment, this class
2257
+ offers a way to specify alternate :meth:`_calc_checksum` methods,
2258
+ and will dynamically chose the best one at runtime.
2259
+
2260
+ .. versionchanged:: 1.7
2261
+
2262
+ This class now derives from :class:`BackendMixin`, which abstracts
2263
+ out a more generic framework for supporting multiple backends.
2264
+ The public api (:meth:`!get_backend`, :meth:`!has_backend`, :meth:`!set_backend`)
2265
+ is roughly the same.
2266
+
2267
+ Private API (Subclass Hooks)
2268
+ ----------------------------
2269
+ As of version 1.7, classes should implement :meth:`!_load_backend_{name}`, per
2270
+ :class:`BackendMixin`. This hook should invoke :meth:`!_set_calc_checksum_backcend`
2271
+ to install it's backend method.
2272
+
2273
+ .. deprecated:: 1.7
2274
+
2275
+ The following api is deprecated, and will be removed in Passlib 2.0:
2276
+
2277
+ .. attribute:: _has_backend_{name}
2278
+
2279
+ private class attribute checked by :meth:`has_backend` to see if a
2280
+ specific backend is available, it should be either ``True``
2281
+ or ``False``. One of these should be provided by
2282
+ the subclass for each backend listed in :attr:`backends`.
2283
+
2284
+ .. classmethod:: _calc_checksum_{name}
2285
+
2286
+ private class method that should implement :meth:`_calc_checksum`
2287
+ for a given backend. it will only be called if the backend has
2288
+ been selected by :meth:`set_backend`. One of these should be provided
2289
+ by the subclass for each backend listed in :attr:`backends`.
2290
+ """
2291
+
2292
+ def _calc_checksum(self, secret):
2293
+ "wrapper for backend, for common code"
2294
+ # NOTE: not overwriting _calc_checksum() directly, so that classes can provide
2295
+ # common behavior in that method,
2296
+ # and then invoke _calc_checksum_backend() to do the work.
2297
+ return self._calc_checksum_backend(secret)
2298
+
2299
+ def _calc_checksum_backend(self, secret):
2300
+ """
2301
+ stub for _calc_checksum_backend() --
2302
+ should load backend if one hasn't been loaded;
2303
+ if one has been loaded, this method should have been monkeypatched by _finalize_backend().
2304
+ """
2305
+ self._stub_requires_backend()
2306
+ return self._calc_checksum_backend(secret)
2307
+
2308
+ @classmethod
2309
+ def _get_backend_loader(cls, name):
2310
+ """
2311
+ subclassed to support legacy 1.6 HasManyBackends api.
2312
+ (will be removed in passlib 2.0)
2313
+ """
2314
+ # check for 1.7 loader
2315
+ loader = getattr(cls, "_load_backend_" + name, None)
2316
+ if loader is None:
2317
+ # fallback to pre-1.7 _has_backend_xxx + _calc_checksum_xxx() api
2318
+ def loader():
2319
+ return cls.__load_legacy_backend(name)
2320
+ else:
2321
+ # make sure 1.6 api isn't defined at same time
2322
+ assert not hasattr(cls, "_has_backend_" + name), (
2323
+ f"{cls.name}: can't specify both ._load_backend_{name}() "
2324
+ f"and ._has_backend_{name}"
2325
+ )
2326
+ return loader
2327
+
2328
+ @classmethod
2329
+ def __load_legacy_backend(cls, name):
2330
+ value = getattr(cls, "_has_backend_" + name)
2331
+ warn(
2332
+ f"{cls.name}: support for ._has_backend_{name} is deprecated as of Passlib 1.7, "
2333
+ "and will be removed in Passlib 1.9/2.0, please implement "
2334
+ f"._load_backend_{name}() instead",
2335
+ DeprecationWarning,
2336
+ )
2337
+ if value:
2338
+ func = getattr(cls, "_calc_checksum_" + name)
2339
+ cls._set_calc_checksum_backend(func)
2340
+ return True
2341
+ return False
2342
+
2343
+ @classmethod
2344
+ def _set_calc_checksum_backend(cls, func):
2345
+ """
2346
+ helper used by subclasses to validate & set backend-specific
2347
+ calc checksum helper.
2348
+ """
2349
+ backend = cls._pending_backend
2350
+ assert backend, "should only be called during set_backend()"
2351
+ if not callable(func):
2352
+ raise RuntimeError(
2353
+ f"{cls.name}: backend {backend!r} returned invalid callable: {func!r}"
2354
+ )
2355
+ if not cls._pending_dry_run:
2356
+ cls._calc_checksum_backend = func
2357
+
2358
+
2359
+ # XXX: should this inherit from PasswordHash?
2360
+ class PrefixWrapper:
2361
+ """wraps another handler, adding a constant prefix.
2362
+
2363
+ instances of this class wrap another password hash handler,
2364
+ altering the constant prefix that's prepended to the wrapped
2365
+ handlers' hashes.
2366
+
2367
+ this is used mainly by the :doc:`ldap crypt <passlib.hash.ldap_crypt>` handlers;
2368
+ such as :class:`~passlib.hash.ldap_md5_crypt` which wraps :class:`~passlib.hash.md5_crypt` and adds a ``{CRYPT}`` prefix.
2369
+
2370
+ usage::
2371
+
2372
+ myhandler = PrefixWrapper("myhandler", "md5_crypt", prefix="$mh$", orig_prefix="$1$")
2373
+
2374
+ :param name: name to assign to handler
2375
+ :param wrapped: handler object or name of registered handler
2376
+ :param prefix: identifying prefix to prepend to all hashes
2377
+ :param orig_prefix: prefix to strip (defaults to '').
2378
+ :param lazy: if True and wrapped handler is specified by name, don't look it up until needed.
2379
+ """
2380
+
2381
+ #: list of attributes which should be cloned by .using()
2382
+ _using_clone_attrs: tuple[str, ...] = ()
2383
+
2384
+ def __init__(
2385
+ self, name, wrapped, prefix="", orig_prefix="", lazy=False, doc=None, ident=None
2386
+ ):
2387
+ self.name = name
2388
+ if isinstance(prefix, bytes):
2389
+ prefix = prefix.decode("ascii")
2390
+ self.prefix = prefix
2391
+ if isinstance(orig_prefix, bytes):
2392
+ orig_prefix = orig_prefix.decode("ascii")
2393
+ self.orig_prefix = orig_prefix
2394
+ if doc:
2395
+ self.__doc__ = doc
2396
+ if hasattr(wrapped, "name"):
2397
+ self._set_wrapped(wrapped)
2398
+ else:
2399
+ self._wrapped_name = wrapped
2400
+ if not lazy:
2401
+ self._get_wrapped()
2402
+
2403
+ if ident is not None:
2404
+ if ident is True:
2405
+ # signal that prefix is identifiable in itself.
2406
+ if prefix:
2407
+ ident = prefix
2408
+ else:
2409
+ raise ValueError("no prefix specified")
2410
+ if isinstance(ident, bytes):
2411
+ ident = ident.decode("ascii")
2412
+ # XXX: what if ident includes parts of wrapped hash's ident?
2413
+ if ident[: len(prefix)] != prefix[: len(ident)]:
2414
+ raise ValueError("ident must agree with prefix")
2415
+ self._ident = ident
2416
+
2417
+ _wrapped_name = None
2418
+ _wrapped_handler = None
2419
+
2420
+ def _set_wrapped(self, handler):
2421
+ # check this is a valid handler
2422
+ if "ident" in handler.setting_kwds and self.orig_prefix:
2423
+ # TODO: look into way to fix the issues.
2424
+ warn(
2425
+ "PrefixWrapper: 'orig_prefix' option may not work correctly "
2426
+ f"for handlers which have multiple identifiers: {handler.name!r}",
2427
+ exc.PasslibRuntimeWarning,
2428
+ )
2429
+
2430
+ # store reference
2431
+ self._wrapped_handler = handler
2432
+
2433
+ def _get_wrapped(self):
2434
+ handler = self._wrapped_handler
2435
+ if handler is None:
2436
+ handler = get_crypt_handler(self._wrapped_name)
2437
+ self._set_wrapped(handler)
2438
+ return handler
2439
+
2440
+ wrapped = property(_get_wrapped)
2441
+
2442
+ _ident = False
2443
+
2444
+ @property
2445
+ def ident(self):
2446
+ value = self._ident
2447
+ if value is False:
2448
+ value = None
2449
+ # XXX: how will this interact with orig_prefix ?
2450
+ # not exposing attrs for now if orig_prefix is set.
2451
+ if not self.orig_prefix:
2452
+ wrapped = self.wrapped
2453
+ ident = getattr(wrapped, "ident", None)
2454
+ if ident is not None:
2455
+ value = self._wrap_hash(ident)
2456
+ self._ident = value
2457
+ return value
2458
+
2459
+ _ident_values = False
2460
+
2461
+ @property
2462
+ def ident_values(self):
2463
+ value = self._ident_values
2464
+ if value is False:
2465
+ value = None
2466
+ # XXX: how will this interact with orig_prefix ?
2467
+ # not exposing attrs for now if orig_prefix is set.
2468
+ if not self.orig_prefix:
2469
+ wrapped = self.wrapped
2470
+ idents = getattr(wrapped, "ident_values", None)
2471
+ if idents:
2472
+ value = tuple(self._wrap_hash(ident) for ident in idents)
2473
+ ##else:
2474
+ ## ident = self.ident
2475
+ ## if ident is not None:
2476
+ ## value = [ident]
2477
+ self._ident_values = value
2478
+ return value
2479
+
2480
+ # attrs that should be proxied
2481
+ # XXX: change this to proxy everything that doesn't start with "_"?
2482
+ _proxy_attrs = (
2483
+ "setting_kwds",
2484
+ "context_kwds",
2485
+ "default_rounds",
2486
+ "min_rounds",
2487
+ "max_rounds",
2488
+ "rounds_cost",
2489
+ "min_desired_rounds",
2490
+ "max_desired_rounds",
2491
+ "vary_rounds",
2492
+ "default_salt_size",
2493
+ "min_salt_size",
2494
+ "max_salt_size",
2495
+ "salt_chars",
2496
+ "default_salt_chars",
2497
+ "backends",
2498
+ "has_backend",
2499
+ "get_backend",
2500
+ "set_backend",
2501
+ "is_disabled",
2502
+ "truncate_size",
2503
+ "truncate_error",
2504
+ "truncate_verify_reject",
2505
+ # internal info attrs needed for test inspection
2506
+ "_salt_is_bytes",
2507
+ )
2508
+
2509
+ def __repr__(self):
2510
+ args = [repr(self._wrapped_name or self._wrapped_handler)]
2511
+ if self.prefix:
2512
+ args.append(f"prefix={self.prefix!r}")
2513
+ if self.orig_prefix:
2514
+ args.append(f"orig_prefix={self.orig_prefix!r}")
2515
+ args = ", ".join(args)
2516
+ return f"PrefixWrapper({self.name!r}, {args})"
2517
+
2518
+ def __dir__(self):
2519
+ attrs = set(dir(self.__class__))
2520
+ attrs.update(self.__dict__)
2521
+ wrapped = self.wrapped
2522
+ attrs.update(attr for attr in self._proxy_attrs if hasattr(wrapped, attr))
2523
+ return list(attrs)
2524
+
2525
+ def __getattr__(self, attr):
2526
+ """proxy most attributes from wrapped class (e.g. rounds, salt size, etc)"""
2527
+ if attr in self._proxy_attrs:
2528
+ return getattr(self.wrapped, attr)
2529
+ raise AttributeError(f"missing attribute: {attr!r}")
2530
+
2531
+ def __setattr__(self, attr, value):
2532
+ # if proxy attr present on wrapped object,
2533
+ # and we own it, modify *it* instead.
2534
+ # TODO: needs UTs
2535
+ # TODO: any other cases where wrapped is "owned"?
2536
+ # currently just if created via .using()
2537
+ if attr in self._proxy_attrs and self._derived_from:
2538
+ wrapped = self.wrapped
2539
+ if hasattr(wrapped, attr):
2540
+ setattr(wrapped, attr, value)
2541
+ return None
2542
+ return object.__setattr__(self, attr, value)
2543
+
2544
+ def _unwrap_hash(self, hash):
2545
+ """given hash belonging to wrapper, return orig version"""
2546
+ # NOTE: assumes hash has been validated as unicode already
2547
+ prefix = self.prefix
2548
+ if not hash.startswith(prefix):
2549
+ raise exc.InvalidHashError(self)
2550
+ # NOTE: always passing to handler as unicode, to save reconversion
2551
+ return self.orig_prefix + hash[len(prefix) :]
2552
+
2553
+ def _wrap_hash(self, hash):
2554
+ """given orig hash; return one belonging to wrapper"""
2555
+ # NOTE: should usually be native string.
2556
+ # (which does mean extra work under py2, but not py3)
2557
+ if isinstance(hash, bytes):
2558
+ hash = hash.decode("ascii")
2559
+ orig_prefix = self.orig_prefix
2560
+ if not hash.startswith(orig_prefix):
2561
+ raise exc.InvalidHashError(self.wrapped)
2562
+ return self.prefix + hash[len(orig_prefix) :]
2563
+
2564
+ #: set by _using(), helper for test harness' handler_derived_from()
2565
+ _derived_from = None
2566
+
2567
+ def using(self, **kwds):
2568
+ # generate subclass of wrapped handler
2569
+ subcls = self.wrapped.using(**kwds)
2570
+ assert subcls is not self.wrapped
2571
+ # then create identical wrapper which wraps the new subclass.
2572
+ wrapper = PrefixWrapper(
2573
+ self.name, subcls, prefix=self.prefix, orig_prefix=self.orig_prefix
2574
+ )
2575
+ wrapper._derived_from = self
2576
+ for attr in self._using_clone_attrs:
2577
+ setattr(wrapper, attr, getattr(self, attr))
2578
+ return wrapper
2579
+
2580
+ def needs_update(self, hash, **kwds):
2581
+ hash = self._unwrap_hash(hash)
2582
+ return self.wrapped.needs_update(hash, **kwds)
2583
+
2584
+ def identify(self, hash):
2585
+ hash = to_unicode_for_identify(hash)
2586
+ if not hash.startswith(self.prefix):
2587
+ return False
2588
+ hash = self._unwrap_hash(hash)
2589
+ return self.wrapped.identify(hash)
2590
+
2591
+ @deprecated_method(deprecated="1.7", removed="2.0")
2592
+ def genconfig(self, **kwds):
2593
+ config = self.wrapped.genconfig(**kwds)
2594
+ if config is None:
2595
+ raise RuntimeError(".genconfig() must return a string, not None")
2596
+ return self._wrap_hash(config)
2597
+
2598
+ @deprecated_method(deprecated="1.7", removed="2.0")
2599
+ def genhash(self, secret, config, **kwds):
2600
+ # TODO: under 2.0, throw TypeError if config is None, rather than passing it through
2601
+ if config is not None:
2602
+ config = to_unicode(config, "ascii", "config/hash")
2603
+ config = self._unwrap_hash(config)
2604
+ return self._wrap_hash(self.wrapped.genhash(secret, config, **kwds))
2605
+
2606
+ @deprecated_method(deprecated="1.7", removed="2.0", replacement=".hash()")
2607
+ def encrypt(self, secret, **kwds):
2608
+ return self.hash(secret, **kwds)
2609
+
2610
+ def hash(self, secret, **kwds):
2611
+ return self._wrap_hash(self.wrapped.hash(secret, **kwds))
2612
+
2613
+ def verify(self, secret, hash, **kwds):
2614
+ hash = to_unicode(hash, "ascii", "hash")
2615
+ hash = self._unwrap_hash(hash)
2616
+ return self.wrapped.verify(secret, hash, **kwds)