libpass 1.7.5.post0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. libpass-1.7.5.post0.dist-info/METADATA +81 -0
  2. libpass-1.7.5.post0.dist-info/RECORD +69 -0
  3. libpass-1.7.5.post0.dist-info/WHEEL +4 -0
  4. libpass-1.7.5.post0.dist-info/licenses/LICENSE +116 -0
  5. passlib/__init__.py +3 -0
  6. passlib/_data/wordsets/bip39.txt +2049 -0
  7. passlib/_data/wordsets/eff_long.txt +7776 -0
  8. passlib/_data/wordsets/eff_prefixed.txt +1296 -0
  9. passlib/_data/wordsets/eff_short.txt +1296 -0
  10. passlib/_setup/__init__.py +1 -0
  11. passlib/_setup/stamp.py +159 -0
  12. passlib/apache.py +1185 -0
  13. passlib/apps.py +260 -0
  14. passlib/context.py +2066 -0
  15. passlib/crypto/__init__.py +1 -0
  16. passlib/crypto/_blowfish/__init__.py +171 -0
  17. passlib/crypto/_blowfish/_gen_files.py +256 -0
  18. passlib/crypto/_blowfish/base.py +1239 -0
  19. passlib/crypto/_blowfish/unrolled.py +1691 -0
  20. passlib/crypto/_md4.py +249 -0
  21. passlib/crypto/des.py +2283 -0
  22. passlib/crypto/digest.py +1111 -0
  23. passlib/crypto/scrypt/__init__.py +299 -0
  24. passlib/crypto/scrypt/_builtin.py +254 -0
  25. passlib/crypto/scrypt/_gen_files.py +161 -0
  26. passlib/crypto/scrypt/_salsa.py +188 -0
  27. passlib/exc.py +432 -0
  28. passlib/ext/__init__.py +1 -0
  29. passlib/ext/django/__init__.py +6 -0
  30. passlib/ext/django/models.py +38 -0
  31. passlib/ext/django/utils.py +1326 -0
  32. passlib/handlers/__init__.py +1 -0
  33. passlib/handlers/argon2.py +1119 -0
  34. passlib/handlers/bcrypt.py +1217 -0
  35. passlib/handlers/cisco.py +450 -0
  36. passlib/handlers/des_crypt.py +642 -0
  37. passlib/handlers/digests.py +184 -0
  38. passlib/handlers/django.py +545 -0
  39. passlib/handlers/fshp.py +223 -0
  40. passlib/handlers/ldap_digests.py +379 -0
  41. passlib/handlers/md5_crypt.py +375 -0
  42. passlib/handlers/misc.py +224 -0
  43. passlib/handlers/mssql.py +258 -0
  44. passlib/handlers/mysql.py +136 -0
  45. passlib/handlers/oracle.py +177 -0
  46. passlib/handlers/pbkdf2.py +521 -0
  47. passlib/handlers/phpass.py +142 -0
  48. passlib/handlers/postgres.py +61 -0
  49. passlib/handlers/roundup.py +33 -0
  50. passlib/handlers/scram.py +589 -0
  51. passlib/handlers/scrypt.py +413 -0
  52. passlib/handlers/sha1_crypt.py +173 -0
  53. passlib/handlers/sha2_crypt.py +657 -0
  54. passlib/handlers/sun_md5_crypt.py +387 -0
  55. passlib/handlers/windows.py +349 -0
  56. passlib/hash.py +111 -0
  57. passlib/hosts.py +112 -0
  58. passlib/ifc.py +354 -0
  59. passlib/pwd.py +813 -0
  60. passlib/registry.py +583 -0
  61. passlib/totp.py +1968 -0
  62. passlib/utils/__init__.py +1221 -0
  63. passlib/utils/binary.py +897 -0
  64. passlib/utils/compat/__init__.py +200 -0
  65. passlib/utils/decor.py +234 -0
  66. passlib/utils/des.py +35 -0
  67. passlib/utils/handlers.py +2857 -0
  68. passlib/utils/md4.py +34 -0
  69. passlib/utils/pbkdf2.py +188 -0
@@ -0,0 +1,1221 @@
1
+ """passlib.utils -- helpers for writing password hashes"""
2
+
3
+ from passlib.utils.compat import JYTHON, join_bytes, join_unicode
4
+
5
+ from collections.abc import Sequence
6
+ from collections.abc import Iterable
7
+
8
+ from codecs import lookup as _lookup_codec
9
+ import itertools
10
+ import inspect
11
+
12
+
13
+ import math
14
+ import os
15
+ import sys
16
+ import random
17
+ import re
18
+
19
+ import stringprep
20
+ import time
21
+
22
+ import unicodedata
23
+ import threading
24
+ import timeit
25
+
26
+ from passlib.utils.binary import (
27
+ # [remove these aliases in 2.0]
28
+ BASE64_CHARS,
29
+ AB64_CHARS,
30
+ HASH64_CHARS,
31
+ BCRYPT_CHARS,
32
+ Base64Engine,
33
+ LazyBase64Engine,
34
+ h64,
35
+ h64big,
36
+ bcrypt64,
37
+ ab64_encode,
38
+ ab64_decode,
39
+ b64s_encode,
40
+ b64s_decode,
41
+ )
42
+ from passlib.utils.decor import (
43
+ # [remove these aliases in 2.0]
44
+ deprecated_function,
45
+ deprecated_method,
46
+ memoized_property,
47
+ classproperty,
48
+ hybrid_method,
49
+ )
50
+ from passlib.exc import ExpectedStringError, ExpectedTypeError
51
+ from passlib.utils.compat import (
52
+ add_doc,
53
+ unicode_or_bytes,
54
+ get_method_function,
55
+ PYPY,
56
+ )
57
+
58
+
59
+ __all__ = [
60
+ "AB64_CHARS",
61
+ "BASE64_CHARS",
62
+ "BCRYPT_CHARS",
63
+ "Base64Engine",
64
+ "HASH64_CHARS",
65
+ "JYTHON",
66
+ "LazyBase64Engine",
67
+ "ab64_decode",
68
+ "ab64_encode",
69
+ "b64s_decode",
70
+ "b64s_encode",
71
+ "bcrypt64",
72
+ "classproperty",
73
+ "consteq",
74
+ "deprecated_method",
75
+ "generate_password",
76
+ "getrandbytes",
77
+ "getrandstr",
78
+ "h64",
79
+ "h64big",
80
+ "has_crypt",
81
+ "has_rounds_info",
82
+ "has_salt_info",
83
+ "hybrid_method",
84
+ "is_ascii_safe",
85
+ "is_crypt_context",
86
+ "is_crypt_handler",
87
+ "is_same_codec",
88
+ "join_bytes",
89
+ "join_unicode",
90
+ "memoized_property",
91
+ "render_bytes",
92
+ "rng",
93
+ "rounds_cost_values",
94
+ "safe_crypt",
95
+ "saslprep",
96
+ "sys_bits",
97
+ "test_crypt",
98
+ "tick",
99
+ "to_bytes",
100
+ "to_native_str",
101
+ "to_unicode",
102
+ "unix_crypt_schemes",
103
+ "xor_bytes",
104
+ ]
105
+
106
+
107
+ # bitsize of system architecture (32 or 64)
108
+ sys_bits = int(math.log(sys.maxsize, 2) + 1.5)
109
+
110
+ # list of hashes algs supported by crypt() on at least one OS.
111
+ # XXX: move to .registry for passlib 2.0?
112
+ unix_crypt_schemes = [
113
+ "sha512_crypt",
114
+ "sha256_crypt",
115
+ "sha1_crypt",
116
+ "bcrypt",
117
+ "md5_crypt",
118
+ # "bsd_nthash",
119
+ "bsdi_crypt",
120
+ "des_crypt",
121
+ ]
122
+
123
+
124
+ rounds_cost_values = ["linear", "log2"]
125
+
126
+
127
+ _BEMPTY = b""
128
+ _UEMPTY = ""
129
+ _USPACE = " "
130
+
131
+ # maximum password size which passlib will allow; see exc.PasswordSizeError
132
+ MAX_PASSWORD_SIZE = int(os.environ.get("PASSLIB_MAX_PASSWORD_SIZE") or 4096)
133
+
134
+
135
+ class SequenceMixin(object):
136
+ """
137
+ helper which lets result object act like a fixed-length sequence.
138
+ subclass just needs to provide :meth:`_as_tuple()`.
139
+ """
140
+
141
+ def _as_tuple(self):
142
+ raise NotImplementedError("implement in subclass")
143
+
144
+ def __repr__(self):
145
+ return repr(self._as_tuple())
146
+
147
+ def __getitem__(self, idx):
148
+ return self._as_tuple()[idx]
149
+
150
+ def __iter__(self):
151
+ return iter(self._as_tuple())
152
+
153
+ def __len__(self):
154
+ return len(self._as_tuple())
155
+
156
+ def __eq__(self, other):
157
+ return self._as_tuple() == other
158
+
159
+ def __ne__(self, other):
160
+ return not self.__eq__(other)
161
+
162
+
163
+ # getargspec() is deprecated, use this under py3.
164
+ # even though it's a lot more awkward to get basic info :|
165
+
166
+ _VAR_KEYWORD = inspect.Parameter.VAR_KEYWORD
167
+ _VAR_ANY_SET = {_VAR_KEYWORD, inspect.Parameter.VAR_POSITIONAL}
168
+
169
+
170
+ def accepts_keyword(func, key):
171
+ """test if function accepts specified keyword"""
172
+ params = inspect.signature(get_method_function(func)).parameters
173
+ if not params:
174
+ return False
175
+ arg = params.get(key)
176
+ if arg and arg.kind not in _VAR_ANY_SET:
177
+ return True
178
+ # XXX: annoying what we have to do to determine if VAR_KWDS in use.
179
+ return params[list(params)[-1]].kind == _VAR_KEYWORD
180
+
181
+
182
+ def update_mixin_classes(
183
+ target, add=None, remove=None, append=False, before=None, after=None, dryrun=False
184
+ ):
185
+ """
186
+ helper to update mixin classes installed in target class.
187
+
188
+ :param target:
189
+ target class whose bases will be modified.
190
+
191
+ :param add:
192
+ class / classes to install into target's base class list.
193
+
194
+ :param remove:
195
+ class / classes to remove from target's base class list.
196
+
197
+ :param append:
198
+ by default, prepends mixins to front of list.
199
+ if True, appends to end of list instead.
200
+
201
+ :param after:
202
+ optionally make sure all mixins are inserted after
203
+ this class / classes.
204
+
205
+ :param before:
206
+ optionally make sure all mixins are inserted before
207
+ this class / classes.
208
+
209
+ :param dryrun:
210
+ optionally perform all calculations / raise errors,
211
+ but don't actually modify the class.
212
+ """
213
+ if isinstance(add, type):
214
+ add = [add]
215
+
216
+ bases = list(target.__bases__)
217
+
218
+ # strip out requested mixins
219
+ if remove:
220
+ if isinstance(remove, type):
221
+ remove = [remove]
222
+ for mixin in remove:
223
+ if add and mixin in add:
224
+ continue
225
+ if mixin in bases:
226
+ bases.remove(mixin)
227
+
228
+ # add requested mixins
229
+ if add:
230
+ for mixin in add:
231
+ # if mixin already present (explicitly or not), leave alone
232
+ if any(issubclass(base, mixin) for base in bases):
233
+ continue
234
+
235
+ # determine insertion point
236
+ if append:
237
+ for idx, base in enumerate(bases):
238
+ if issubclass(mixin, base):
239
+ # don't insert mixin after one of it's own bases
240
+ break
241
+ if before and issubclass(base, before):
242
+ # don't insert mixin after any <before> classes.
243
+ break
244
+ else:
245
+ # append to end
246
+ idx = len(bases)
247
+ elif after:
248
+ for end_idx, base in enumerate(reversed(bases)):
249
+ if issubclass(base, after):
250
+ # don't insert mixin before any <after> classes.
251
+ idx = len(bases) - end_idx
252
+ assert bases[idx - 1] == base
253
+ break
254
+ else:
255
+ idx = 0
256
+ else:
257
+ # insert at start
258
+ idx = 0
259
+
260
+ # insert mixin
261
+ bases.insert(idx, mixin)
262
+
263
+ # modify class
264
+ if not dryrun:
265
+ target.__bases__ = tuple(bases)
266
+
267
+
268
+ # =============================================================================
269
+ # collection helpers
270
+ # =============================================================================
271
+ def batch(source, size):
272
+ """
273
+ split iterable into chunks of <size> elements.
274
+ """
275
+ if size < 1:
276
+ raise ValueError("size must be positive integer")
277
+ if isinstance(source, Sequence):
278
+ end = len(source)
279
+ i = 0
280
+ while i < end:
281
+ n = i + size
282
+ yield source[i:n]
283
+ i = n
284
+ elif isinstance(source, Iterable):
285
+ itr = iter(source)
286
+ while True:
287
+ chunk_itr = itertools.islice(itr, size)
288
+ try:
289
+ first = next(chunk_itr)
290
+ except StopIteration:
291
+ break
292
+ yield itertools.chain((first,), chunk_itr)
293
+ else:
294
+ raise TypeError("source must be iterable")
295
+
296
+
297
+ # =============================================================================
298
+ # unicode helpers
299
+ # =============================================================================
300
+
301
+ # XXX: should this be moved to passlib.crypto, or compat backports?
302
+
303
+
304
+ def consteq(left, right):
305
+ """Check two strings/bytes for equality.
306
+
307
+ This function uses an approach designed to prevent
308
+ timing analysis, making it appropriate for cryptography.
309
+ a and b must both be of the same type: either str (ASCII only),
310
+ or any type that supports the buffer protocol (e.g. bytes).
311
+
312
+ Note: If a and b are of different lengths, or if an error occurs,
313
+ a timing attack could theoretically reveal information about the
314
+ types and lengths of a and b--but not their values.
315
+ """
316
+ # NOTE:
317
+ # resources & discussions considered in the design of this function:
318
+ # hmac timing attack --
319
+ # http://rdist.root.org/2009/05/28/timing-attack-in-google-keyczar-library/
320
+ # python developer discussion surrounding similar function --
321
+ # http://bugs.python.org/issue15061
322
+ # http://bugs.python.org/issue14955
323
+
324
+ # validate types
325
+ if isinstance(left, str):
326
+ if not isinstance(right, str):
327
+ raise TypeError("inputs must be both str or both bytes")
328
+ is_bytes = False
329
+ elif isinstance(left, bytes):
330
+ if not isinstance(right, bytes):
331
+ raise TypeError("inputs must be both str or both bytes")
332
+ is_bytes = True
333
+ else:
334
+ raise TypeError("inputs must be both str or both bytes")
335
+
336
+ # do size comparison.
337
+ # NOTE: the double-if construction below is done deliberately, to ensure
338
+ # the same number of operations (including branches) is performed regardless
339
+ # of whether left & right are the same size.
340
+ same_size = len(left) == len(right)
341
+ if same_size:
342
+ # if sizes are the same, setup loop to perform actual check of contents.
343
+ tmp = left
344
+ result = 0
345
+ if not same_size:
346
+ # if sizes aren't the same, set 'result' so equality will fail regardless
347
+ # of contents. then, to ensure we do exactly 'len(right)' iterations
348
+ # of the loop, just compare 'right' against itself.
349
+ tmp = right
350
+ result = 1
351
+
352
+ # run constant-time string comparision
353
+ if is_bytes:
354
+ for left_char, right_char in zip(tmp, right):
355
+ result |= left_char ^ right_char
356
+ else:
357
+ for left_char, right_char in zip(tmp, right):
358
+ result |= ord(left_char) ^ ord(right_char)
359
+ return result == 0
360
+
361
+
362
+ # keep copy of this around since stdlib's version throws error on non-ascii chars in unicode strings.
363
+ # our version does, but suffers from some underlying VM issues. but something is better than
364
+ # nothing for plaintext hashes, which need this. everything else should use consteq(),
365
+ # since the stdlib one is going to be as good / better in the general case.
366
+ str_consteq = consteq
367
+
368
+ try:
369
+ # for py3.3 and up, use the stdlib version
370
+ from hmac import compare_digest as consteq
371
+ except ImportError:
372
+ pass
373
+
374
+ # TODO: could check for cryptography package's version,
375
+ # but only operates on bytes, so would need a wrapper,
376
+ # or separate consteq() into a unicode & a bytes variant.
377
+ # from cryptography.hazmat.primitives.constant_time import bytes_eq as consteq
378
+
379
+
380
+ def splitcomma(source, sep=","):
381
+ """split comma-separated string into list of elements,
382
+ stripping whitespace.
383
+ """
384
+ source = source.strip()
385
+ if source.endswith(sep):
386
+ source = source[:-1]
387
+ if not source:
388
+ return []
389
+ return [elem.strip() for elem in source.split(sep)]
390
+
391
+
392
+ def saslprep(source, param="value"):
393
+ """Normalizes unicode strings using SASLPrep stringprep profile.
394
+
395
+ The SASLPrep profile is defined in :rfc:`4013`.
396
+ It provides a uniform scheme for normalizing unicode usernames
397
+ and passwords before performing byte-value sensitive operations
398
+ such as hashing. Among other things, it normalizes diacritic
399
+ representations, removes non-printing characters, and forbids
400
+ invalid characters such as ``\\n``. Properly internationalized
401
+ applications should run user passwords through this function
402
+ before hashing.
403
+
404
+ :arg source:
405
+ unicode string to normalize & validate
406
+
407
+ :param param:
408
+ Optional noun identifying source parameter in error messages
409
+ (Defaults to the string ``"value"``). This is mainly useful to make the caller's error
410
+ messages make more sense contextually.
411
+
412
+ :raises ValueError:
413
+ if any characters forbidden by the SASLPrep profile are encountered.
414
+
415
+ :raises TypeError:
416
+ if input is not :class:`!unicode`
417
+
418
+ :returns:
419
+ normalized unicode string
420
+
421
+ .. note::
422
+
423
+ This function is not available under Jython,
424
+ as the Jython stdlib is missing the :mod:`!stringprep` module
425
+ (`Jython issue 1758320 <http://bugs.jython.org/issue1758320>`_).
426
+
427
+ .. versionadded:: 1.6
428
+ """
429
+ # saslprep - http://tools.ietf.org/html/rfc4013
430
+ # stringprep - http://tools.ietf.org/html/rfc3454
431
+ # http://docs.python.org/library/stringprep.html
432
+
433
+ # validate type
434
+ # XXX: support bytes (e.g. run through want_unicode)?
435
+ # might be easier to just integrate this into cryptcontext.
436
+ if not isinstance(source, str):
437
+ raise TypeError("input must be string, not %s" % (type(source),))
438
+
439
+ # mapping stage
440
+ # - map non-ascii spaces to U+0020 (stringprep C.1.2)
441
+ # - strip 'commonly mapped to nothing' chars (stringprep B.1)
442
+ in_table_c12 = stringprep.in_table_c12
443
+ in_table_b1 = stringprep.in_table_b1
444
+ data = "".join(
445
+ _USPACE if in_table_c12(c) else c for c in source if not in_table_b1(c)
446
+ )
447
+
448
+ # normalize to KC form
449
+ data = unicodedata.normalize("NFKC", data)
450
+ if not data:
451
+ return _UEMPTY
452
+
453
+ # check for invalid bi-directional strings.
454
+ # stringprep requires the following:
455
+ # - chars in C.8 must be prohibited.
456
+ # - if any R/AL chars in string:
457
+ # - no L chars allowed in string
458
+ # - first and last must be R/AL chars
459
+ # this checks if start/end are R/AL chars. if so, prohibited loop
460
+ # will forbid all L chars. if not, prohibited loop will forbid all
461
+ # R/AL chars instead. in both cases, prohibited loop takes care of C.8.
462
+ is_ral_char = stringprep.in_table_d1
463
+ if is_ral_char(data[0]):
464
+ if not is_ral_char(data[-1]):
465
+ raise ValueError("malformed bidi sequence in " + param)
466
+ # forbid L chars within R/AL sequence.
467
+ is_forbidden_bidi_char = stringprep.in_table_d2
468
+ else:
469
+ # forbid R/AL chars if start not setup correctly; L chars allowed.
470
+ is_forbidden_bidi_char = is_ral_char
471
+
472
+ # check for prohibited output - stringprep tables A.1, B.1, C.1.2, C.2 - C.9
473
+ in_table_a1 = stringprep.in_table_a1
474
+ in_table_c21_c22 = stringprep.in_table_c21_c22
475
+ in_table_c3 = stringprep.in_table_c3
476
+ in_table_c4 = stringprep.in_table_c4
477
+ in_table_c5 = stringprep.in_table_c5
478
+ in_table_c6 = stringprep.in_table_c6
479
+ in_table_c7 = stringprep.in_table_c7
480
+ in_table_c8 = stringprep.in_table_c8
481
+ in_table_c9 = stringprep.in_table_c9
482
+ for c in data:
483
+ # check for chars mapping stage should have removed
484
+ assert not in_table_b1(c), "failed to strip B.1 in mapping stage"
485
+ assert not in_table_c12(c), "failed to replace C.1.2 in mapping stage"
486
+
487
+ # check for forbidden chars
488
+ if in_table_a1(c):
489
+ raise ValueError("unassigned code points forbidden in " + param)
490
+ if in_table_c21_c22(c):
491
+ raise ValueError("control characters forbidden in " + param)
492
+ if in_table_c3(c):
493
+ raise ValueError("private use characters forbidden in " + param)
494
+ if in_table_c4(c):
495
+ raise ValueError("non-char code points forbidden in " + param)
496
+ if in_table_c5(c):
497
+ raise ValueError("surrogate codes forbidden in " + param)
498
+ if in_table_c6(c):
499
+ raise ValueError("non-plaintext chars forbidden in " + param)
500
+ if in_table_c7(c):
501
+ # XXX: should these have been caught by normalize?
502
+ # if so, should change this to an assert
503
+ raise ValueError("non-canonical chars forbidden in " + param)
504
+ if in_table_c8(c):
505
+ raise ValueError(
506
+ "display-modifying / deprecated chars " "forbidden in" + param
507
+ )
508
+ if in_table_c9(c):
509
+ raise ValueError("tagged characters forbidden in " + param)
510
+
511
+ # do bidi constraint check chosen by bidi init, above
512
+ if is_forbidden_bidi_char(c):
513
+ raise ValueError("forbidden bidi character in " + param)
514
+
515
+ return data
516
+
517
+
518
+ def render_bytes(source, *args):
519
+ """Peform ``%`` formating using bytes in a uniform manner across Python 2/3.
520
+
521
+ This function is motivated by the fact that
522
+ :class:`bytes` instances do not support ``%`` or ``{}`` formatting under Python 3.
523
+ This function is an attempt to provide a replacement:
524
+ it converts everything to unicode (decoding bytes instances as ``latin-1``),
525
+ performs the required formatting, then encodes the result to ``latin-1``.
526
+
527
+ Calling ``render_bytes(source, *args)`` should function roughly the same as
528
+ ``source % args`` under Python 2.
529
+
530
+ .. todo::
531
+ python >= 3.5 added back limited support for bytes %,
532
+ can revisit when 3.3/3.4 is dropped.
533
+ """
534
+ if isinstance(source, bytes):
535
+ source = source.decode("latin-1")
536
+ result = source % tuple(
537
+ arg.decode("latin-1") if isinstance(arg, bytes) else arg for arg in args
538
+ )
539
+ return result.encode("latin-1")
540
+
541
+
542
+ def bytes_to_int(value):
543
+ return int.from_bytes(value, "big")
544
+
545
+
546
+ def int_to_bytes(value, count):
547
+ return value.to_bytes(count, "big")
548
+
549
+
550
+ add_doc(bytes_to_int, "decode byte string as single big-endian integer")
551
+ add_doc(int_to_bytes, "encode integer as single big-endian byte string")
552
+
553
+
554
+ def xor_bytes(left, right):
555
+ """Perform bitwise-xor of two byte strings (must be same size)"""
556
+ return int_to_bytes(bytes_to_int(left) ^ bytes_to_int(right), len(left))
557
+
558
+
559
+ def repeat_string(source, size):
560
+ """
561
+ repeat or truncate <source> string, so it has length <size>
562
+ """
563
+ mult = 1 + (size - 1) // len(source)
564
+ return (source * mult)[:size]
565
+
566
+
567
+ def utf8_repeat_string(source, size):
568
+ """
569
+ variant of repeat_string() which truncates to nearest UTF8 boundary.
570
+ """
571
+ mult = 1 + (size - 1) // len(source)
572
+ return utf8_truncate(source * mult, size)
573
+
574
+
575
+ _BNULL = b"\x00"
576
+ _UNULL = "\x00"
577
+
578
+
579
+ def right_pad_string(source, size, pad=None):
580
+ """right-pad or truncate <source> string, so it has length <size>"""
581
+ cur = len(source)
582
+ if size > cur:
583
+ if pad is None:
584
+ pad = _UNULL if isinstance(source, str) else _BNULL
585
+ return source + pad * (size - cur)
586
+ else:
587
+ return source[:size]
588
+
589
+
590
+ def utf8_truncate(source, index):
591
+ """
592
+ helper to truncate UTF8 byte string to nearest character boundary ON OR AFTER <index>.
593
+ returned prefix will always have length of at least <index>, and will stop on the
594
+ first byte that's not a UTF8 continuation byte (128 - 191 inclusive).
595
+ since utf8 should never take more than 4 bytes to encode known unicode values,
596
+ we can stop after ``index+3`` is reached.
597
+
598
+ :param bytes source:
599
+ :param int index:
600
+ :rtype: bytes
601
+ """
602
+ # general approach:
603
+ #
604
+ # * UTF8 bytes will have high two bits (0xC0) as one of:
605
+ # 00 -- ascii char
606
+ # 01 -- ascii char
607
+ # 10 -- continuation of multibyte char
608
+ # 11 -- start of multibyte char.
609
+ # thus we can cut on anything where high bits aren't "10" (0x80; continuation byte)
610
+ #
611
+ # * UTF8 characters SHOULD always be 1 to 4 bytes, though they may be unbounded.
612
+ # so we just keep going until first non-continuation byte is encountered, or end of str.
613
+ # this should work predictably even for malformed/non UTF8 inputs.
614
+
615
+ if not isinstance(source, bytes):
616
+ raise ExpectedTypeError(source, bytes, "source")
617
+
618
+ # validate index
619
+ end = len(source)
620
+ if index < 0:
621
+ index = max(0, index + end)
622
+ if index >= end:
623
+ return source
624
+
625
+ # can stop search after 4 bytes, won't ever have longer utf8 sequence.
626
+ end = min(index + 3, end)
627
+
628
+ # loop until we find non-continuation byte
629
+ while index < end:
630
+ if source[index] & 0xC0 != 0x80:
631
+ # found single-char byte, or start-char byte.
632
+ break
633
+ # else: found continuation byte.
634
+ index += 1
635
+ else:
636
+ assert index == end
637
+
638
+ # truncate at final index
639
+ result = source[:index]
640
+
641
+ def sanity_check():
642
+ # try to decode source
643
+ try:
644
+ text = source.decode("utf-8")
645
+ except UnicodeDecodeError:
646
+ # if source isn't valid utf8, byte level match is enough
647
+ return True
648
+
649
+ # validate that result was cut on character boundary
650
+ assert text.startswith(result.decode("utf-8"))
651
+ return True
652
+
653
+ assert sanity_check()
654
+
655
+ return result
656
+
657
+
658
+ # =============================================================================
659
+ # encoding helpers
660
+ # =============================================================================
661
+ _ASCII_TEST_BYTES = b"\x00\n aA:#!\x7f"
662
+ _ASCII_TEST_UNICODE = _ASCII_TEST_BYTES.decode("ascii")
663
+
664
+
665
+ def is_ascii_codec(codec):
666
+ """Test if codec is compatible with 7-bit ascii (e.g. latin-1, utf-8; but not utf-16)"""
667
+ return _ASCII_TEST_UNICODE.encode(codec) == _ASCII_TEST_BYTES
668
+
669
+
670
+ def is_same_codec(left, right):
671
+ """Check if two codec names are aliases for same codec"""
672
+ if left == right:
673
+ return True
674
+ if not (left and right):
675
+ return False
676
+ return _lookup_codec(left).name == _lookup_codec(right).name
677
+
678
+
679
+ _B80 = b"\x80"[0]
680
+ _U80 = "\x80"
681
+
682
+
683
+ def is_ascii_safe(source):
684
+ """Check if string (bytes or unicode) contains only 7-bit ascii"""
685
+ r = _B80 if isinstance(source, bytes) else _U80
686
+ return all(c < r for c in source)
687
+
688
+
689
+ def to_bytes(source, encoding="utf-8", param="value", source_encoding=None):
690
+ """Helper to normalize input to bytes.
691
+
692
+ :arg source:
693
+ Source bytes/unicode to process.
694
+
695
+ :arg encoding:
696
+ Target encoding (defaults to ``"utf-8"``).
697
+
698
+ :param param:
699
+ Optional name of variable/noun to reference when raising errors
700
+
701
+ :param source_encoding:
702
+ If this is specified, and the source is bytes,
703
+ the source will be transcoded from *source_encoding* to *encoding*
704
+ (via unicode).
705
+
706
+ :raises TypeError: if source is not str or bytes.
707
+
708
+ :returns:
709
+ * unicode strings will be encoded using *encoding*, and returned.
710
+ * if *source_encoding* is not specified, byte strings will be
711
+ returned unchanged.
712
+ * if *source_encoding* is specified, byte strings will be transcoded
713
+ to *encoding*.
714
+ """
715
+ assert encoding
716
+ if isinstance(source, bytes):
717
+ if source_encoding and not is_same_codec(source_encoding, encoding):
718
+ return source.decode(source_encoding).encode(encoding)
719
+ else:
720
+ return source
721
+ elif isinstance(source, str):
722
+ return source.encode(encoding)
723
+ else:
724
+ raise ExpectedStringError(source, param)
725
+
726
+
727
+ def to_unicode(source, encoding="utf-8", param="value"):
728
+ """Helper to normalize input to unicode.
729
+
730
+ :arg source:
731
+ source bytes/unicode to process.
732
+
733
+ :arg encoding:
734
+ encoding to use when decoding bytes instances.
735
+
736
+ :param param:
737
+ optional name of variable/noun to reference when raising errors.
738
+
739
+ :raises TypeError: if source is not str or bytes.
740
+
741
+ :returns:
742
+ * returns unicode strings unchanged.
743
+ * returns bytes strings decoded using *encoding*
744
+ """
745
+ assert encoding
746
+ if isinstance(source, str):
747
+ return source
748
+ elif isinstance(source, bytes):
749
+ return source.decode(encoding)
750
+ else:
751
+ raise ExpectedStringError(source, param)
752
+
753
+
754
+ def to_native_str(source, encoding="utf-8", param="value"):
755
+ if isinstance(source, bytes):
756
+ return source.decode(encoding)
757
+ elif isinstance(source, str):
758
+ return source
759
+ else:
760
+ raise ExpectedStringError(source, param)
761
+
762
+
763
+ add_doc(
764
+ to_native_str,
765
+ """Take in str or bytes, returns str.
766
+
767
+ leaves str alone, decodes bytes using specified encoding.
768
+
769
+ :raises TypeError: if source is not unicode or bytes.
770
+
771
+ :arg source:
772
+ source unicode or bytes string.
773
+
774
+ :arg encoding:
775
+ encoding to use when encoding unicode or decoding bytes.
776
+ this defaults to ``"utf-8"``.
777
+
778
+ :param param:
779
+ optional name of variable/noun to reference when raising errors.
780
+
781
+ :returns: :class:`str` instance
782
+ """,
783
+ )
784
+
785
+
786
+ @deprecated_function(deprecated="1.6", removed="1.7")
787
+ def to_hash_str(source, encoding="ascii"): # pragma: no cover -- deprecated & unused
788
+ """deprecated, use to_native_str() instead"""
789
+ return to_native_str(source, encoding, param="hash")
790
+
791
+
792
+ _true_set = set("true t yes y on 1 enable enabled".split())
793
+ _false_set = set("false f no n off 0 disable disabled".split())
794
+ _none_set = set(["", "none"])
795
+
796
+
797
+ def as_bool(value, none=None, param="boolean"):
798
+ """
799
+ helper to convert value to boolean.
800
+ recognizes strings such as "true", "false"
801
+ """
802
+ assert none in [True, False, None]
803
+ if isinstance(value, unicode_or_bytes):
804
+ clean = value.lower().strip()
805
+ if clean in _true_set:
806
+ return True
807
+ if clean in _false_set:
808
+ return False
809
+ if clean in _none_set:
810
+ return none
811
+ raise ValueError("unrecognized %s value: %r" % (param, value))
812
+ elif isinstance(value, bool):
813
+ return value
814
+ elif value is None:
815
+ return none
816
+ else:
817
+ return bool(value)
818
+
819
+
820
+ # =============================================================================
821
+ # host OS helpers
822
+ # =============================================================================
823
+
824
+
825
+ def is_safe_crypt_input(value):
826
+ """
827
+ UT helper --
828
+ test if value is safe to pass to crypt.crypt();
829
+ since PY3 won't let us pass non-UTF8 bytes to crypt.crypt.
830
+ """
831
+ if crypt_accepts_bytes or not isinstance(value, bytes):
832
+ return True
833
+ try:
834
+ value.decode("utf-8")
835
+ return True
836
+ except UnicodeDecodeError:
837
+ return False
838
+
839
+
840
+ try:
841
+ from crypt import crypt as _crypt
842
+ except ImportError: # pragma: no cover
843
+ _crypt = None
844
+ has_crypt = False
845
+ crypt_accepts_bytes = False
846
+ crypt_needs_lock = False
847
+ _safe_crypt_lock = None
848
+
849
+ def safe_crypt(secret, hash):
850
+ return None
851
+ else:
852
+ has_crypt = True
853
+ _NULL = "\x00"
854
+
855
+ # XXX: replace this with lazy-evaluated bug detection?
856
+ if threading and PYPY and (7, 2, 0) <= sys.pypy_version_info <= (7, 3, 3):
857
+ #: internal lock used to wrap crypt() calls.
858
+ #: WARNING: if non-passlib code invokes crypt(), this lock won't be enough!
859
+ _safe_crypt_lock = threading.Lock()
860
+
861
+ #: detect if crypt.crypt() needs a thread lock around calls.
862
+ crypt_needs_lock = True
863
+
864
+ else:
865
+ from passlib.utils.compat import nullcontext
866
+
867
+ _safe_crypt_lock = nullcontext()
868
+ crypt_needs_lock = False
869
+
870
+ # some crypt() variants will return various constant strings when
871
+ # an invalid/unrecognized config string is passed in; instead of
872
+ # returning NULL / None. examples include ":", ":0", "*0", etc.
873
+ # safe_crypt() returns None for any string starting with one of the
874
+ # chars in this string...
875
+ _invalid_prefixes = "*:!"
876
+
877
+ if True: # legacy block from PY3 compat
878
+ # * pypy3 (as of v7.3.1) has a crypt which accepts bytes, or ASCII-only unicode.
879
+ # * whereas CPython3 (as of v3.9) has a crypt which doesn't take bytes,
880
+ # but accepts ANY unicode (which it always encodes to UTF8).
881
+ crypt_accepts_bytes = True
882
+ try:
883
+ _crypt(b"\xee", "xx")
884
+ except TypeError:
885
+ # CPython will throw TypeError
886
+ crypt_accepts_bytes = False
887
+ except Exception: # no pragma
888
+ # don't care about other errors this might throw,
889
+ # just want to see if we get past initial type-coercion step.
890
+ pass
891
+
892
+ def safe_crypt(secret, hash):
893
+ if crypt_accepts_bytes:
894
+ # PyPy3 -- all bytes accepted, but unicode encoded to ASCII,
895
+ # so handling that ourselves.
896
+ if isinstance(secret, str):
897
+ secret = secret.encode("utf-8")
898
+ if _BNULL in secret:
899
+ raise ValueError("null character in secret")
900
+ if isinstance(hash, str):
901
+ hash = hash.encode("ascii")
902
+ else:
903
+ # CPython3's crypt() doesn't take bytes, only unicode; unicode which is then
904
+ # encoding using utf-8 before passing to the C-level crypt().
905
+ # so we have to decode the secret.
906
+ if isinstance(secret, bytes):
907
+ orig = secret
908
+ try:
909
+ secret = secret.decode("utf-8")
910
+ except UnicodeDecodeError:
911
+ return None
912
+ # sanity check it encodes back to original byte string,
913
+ # otherwise when crypt() does it's encoding, it'll hash the wrong bytes!
914
+ assert (
915
+ secret.encode("utf-8") == orig
916
+ ), "utf-8 spec says this can't happen!"
917
+ if _NULL in secret:
918
+ raise ValueError("null character in secret")
919
+ if isinstance(hash, bytes):
920
+ hash = hash.decode("ascii")
921
+ try:
922
+ with _safe_crypt_lock:
923
+ result = _crypt(secret, hash)
924
+ except OSError:
925
+ # new in py39 -- per https://bugs.python.org/issue39289,
926
+ # crypt() now throws OSError for various things, mainly unknown hash formats
927
+ # translating that to None for now (may revise safe_crypt behavior in future)
928
+ return None
929
+ # NOTE: per issue 113, crypt() may return bytes in some odd cases.
930
+ # assuming it should still return an ASCII hash though,
931
+ # or there's a bigger issue at hand.
932
+ if isinstance(result, bytes):
933
+ result = result.decode("ascii")
934
+ if not result or result[0] in _invalid_prefixes:
935
+ return None
936
+ return result
937
+
938
+
939
+ add_doc(
940
+ safe_crypt,
941
+ """Wrapper around stdlib's crypt.
942
+
943
+ This is a wrapper around stdlib's :func:`!crypt.crypt`, which attempts
944
+ to provide uniform behavior across Python 2 and 3.
945
+
946
+ :arg secret:
947
+ password, as bytes or unicode (unicode will be encoded as ``utf-8``).
948
+
949
+ :arg hash:
950
+ hash or config string, as ascii bytes or unicode.
951
+
952
+ :returns:
953
+ resulting hash as ascii unicode; or ``None`` if the password
954
+ couldn't be hashed due to one of the issues:
955
+
956
+ * :func:`crypt()` not available on platform.
957
+
958
+ * Under Python 3, if *secret* is specified as bytes,
959
+ it must be use ``utf-8`` or it can't be passed
960
+ to :func:`crypt()`.
961
+
962
+ * Some OSes will return ``None`` if they don't recognize
963
+ the algorithm being used (though most will simply fall
964
+ back to des-crypt).
965
+
966
+ * Some OSes will return an error string if the input config
967
+ is recognized but malformed; current code converts these to ``None``
968
+ as well.
969
+ """,
970
+ )
971
+
972
+
973
+ def test_crypt(secret, hash):
974
+ """check if :func:`crypt.crypt` supports specific hash
975
+ :arg secret: password to test
976
+ :arg hash: known hash of password to use as reference
977
+ :returns: True or False
978
+ """
979
+ # safe_crypt() always returns unicode, which means that for py3,
980
+ # 'hash' can't be bytes, or "== hash" will never be True.
981
+ # under py2 unicode & str(bytes) will compare fine;
982
+ # so just enforcing "str" limitation
983
+ assert isinstance(hash, str), "hash must be str, got %s" % type(hash)
984
+ assert hash, "hash must be non-empty"
985
+ return safe_crypt(secret, hash) == hash
986
+
987
+
988
+ timer = timeit.default_timer
989
+ # legacy alias, will be removed in passlib 2.0
990
+ tick = timer
991
+
992
+
993
+ def parse_version(source):
994
+ """helper to parse version string"""
995
+ m = re.search(r"(\d+(?:\.\d+)+)", source)
996
+ if m:
997
+ return tuple(int(elem) for elem in m.group(1).split("."))
998
+ return None
999
+
1000
+
1001
+ # =============================================================================
1002
+ # randomness
1003
+ # =============================================================================
1004
+
1005
+ # ------------------------------------------------------------------------
1006
+ # setup rng for generating salts
1007
+ # ------------------------------------------------------------------------
1008
+
1009
+ # NOTE:
1010
+ # generating salts (e.g. h64_gensalt, below) doesn't require cryptographically
1011
+ # strong randomness. it just requires enough range of possible outputs
1012
+ # that making a rainbow table is too costly. so it should be ok to
1013
+ # fall back on python's builtin mersenne twister prng, as long as it's seeded each time
1014
+ # this module is imported, using a couple of minor entropy sources.
1015
+
1016
+ try:
1017
+ os.urandom(1)
1018
+ has_urandom = True
1019
+ except NotImplementedError: # pragma: no cover
1020
+ has_urandom = False
1021
+
1022
+
1023
+ def genseed(value=None):
1024
+ """generate prng seed value from system resources"""
1025
+ from hashlib import sha512
1026
+
1027
+ if hasattr(value, "getstate") and hasattr(value, "getrandbits"):
1028
+ # caller passed in RNG as seed value
1029
+ try:
1030
+ value = value.getstate()
1031
+ except NotImplementedError:
1032
+ # this method throws error for e.g. SystemRandom instances,
1033
+ # so fall back to extracting 4k of state
1034
+ value = value.getrandbits(1 << 15)
1035
+ text = "%s %s %s %.15f %.15f %s" % (
1036
+ # if caller specified a seed value, mix it in
1037
+ value,
1038
+ # add current process id
1039
+ # NOTE: not available in some environments, e.g. GAE
1040
+ os.getpid() if hasattr(os, "getpid") else None,
1041
+ # id of a freshly created object.
1042
+ # (at least 1 byte of which should be hard to predict)
1043
+ id(object()),
1044
+ # the current time, to whatever precision os uses
1045
+ time.time(),
1046
+ tick(),
1047
+ # if urandom available, might as well mix some bytes in.
1048
+ os.urandom(32).decode("latin-1") if has_urandom else 0,
1049
+ )
1050
+ # hash it all up and return it as int/long
1051
+ return int(sha512(text.encode("utf-8")).hexdigest(), 16)
1052
+
1053
+
1054
+ if has_urandom:
1055
+ rng = random.SystemRandom()
1056
+ else: # pragma: no cover -- runtime detection
1057
+ # NOTE: to reseed use ``rng.seed(genseed(rng))``
1058
+ # XXX: could reseed on every call
1059
+ rng = random.Random(genseed())
1060
+
1061
+
1062
+ # ------------------------------------------------------------------------
1063
+ # some rng helpers
1064
+ # ------------------------------------------------------------------------
1065
+ def getrandbytes(rng, count):
1066
+ """return byte-string containing *count* number of randomly generated bytes, using specified rng"""
1067
+ # NOTE: would be nice if this was present in stdlib Random class
1068
+
1069
+ ###just in case rng provides this...
1070
+ ##meth = getattr(rng, "getrandbytes", None)
1071
+ ##if meth:
1072
+ ## return meth(count)
1073
+
1074
+ if not count:
1075
+ return _BEMPTY
1076
+
1077
+ def helper():
1078
+ # XXX: break into chunks for large number of bits?
1079
+ value = rng.getrandbits(count << 3)
1080
+ i = 0
1081
+ while i < count:
1082
+ yield value & 0xFF
1083
+ value >>= 3
1084
+ i += 1
1085
+
1086
+ return bytes(helper())
1087
+
1088
+
1089
+ def getrandstr(rng, charset, count):
1090
+ """return string containing *count* number of chars/bytes, whose elements are drawn from specified charset, using specified rng"""
1091
+ # NOTE: tests determined this is 4x faster than rng.sample(),
1092
+ # which is why that's not being used here.
1093
+
1094
+ # check alphabet & count
1095
+ if count < 0:
1096
+ raise ValueError("count must be >= 0")
1097
+ letters = len(charset)
1098
+ if letters == 0:
1099
+ raise ValueError("alphabet must not be empty")
1100
+ if letters == 1:
1101
+ return charset * count
1102
+
1103
+ # get random value, and write out to buffer
1104
+ def helper():
1105
+ # XXX: break into chunks for large number of letters?
1106
+ value = rng.randrange(0, letters**count)
1107
+ i = 0
1108
+ while i < count:
1109
+ yield charset[value % letters]
1110
+ value //= letters
1111
+ i += 1
1112
+
1113
+ if isinstance(charset, str):
1114
+ return "".join(helper())
1115
+ else:
1116
+ return bytes(helper())
1117
+
1118
+
1119
+ _52charset = "2346789ABCDEFGHJKMNPQRTUVWXYZabcdefghjkmnpqrstuvwxyz"
1120
+
1121
+
1122
+ @deprecated_function(
1123
+ deprecated="1.7",
1124
+ removed="2.0",
1125
+ replacement="passlib.pwd.genword() / passlib.pwd.genphrase()",
1126
+ )
1127
+ def generate_password(size=10, charset=_52charset):
1128
+ """generate random password using given length & charset
1129
+
1130
+ :param size:
1131
+ size of password.
1132
+
1133
+ :param charset:
1134
+ optional string specified set of characters to draw from.
1135
+
1136
+ the default charset contains all normal alphanumeric characters,
1137
+ except for the characters ``1IiLl0OoS5``, which were omitted
1138
+ due to their visual similarity.
1139
+
1140
+ :returns: :class:`!str` containing randomly generated password.
1141
+
1142
+ .. note::
1143
+
1144
+ Using the default character set, on a OS with :class:`!SystemRandom` support,
1145
+ this function should generate passwords with 5.7 bits of entropy per character.
1146
+ """
1147
+ return getrandstr(rng, charset, size)
1148
+
1149
+
1150
+ # =============================================================================
1151
+ # object type / interface tests
1152
+ # =============================================================================
1153
+ _handler_attrs = (
1154
+ "name",
1155
+ "setting_kwds",
1156
+ "context_kwds",
1157
+ "verify",
1158
+ "hash",
1159
+ "identify",
1160
+ )
1161
+
1162
+
1163
+ def is_crypt_handler(obj):
1164
+ """check if object follows the :ref:`password-hash-api`"""
1165
+ # XXX: change to use isinstance(obj, PasswordHash) under py26+?
1166
+ return all(hasattr(obj, name) for name in _handler_attrs)
1167
+
1168
+
1169
+ _context_attrs = (
1170
+ "needs_update",
1171
+ "genconfig",
1172
+ "genhash",
1173
+ "verify",
1174
+ "encrypt",
1175
+ "identify",
1176
+ )
1177
+
1178
+
1179
+ def is_crypt_context(obj):
1180
+ """check if object appears to be a :class:`~passlib.context.CryptContext` instance"""
1181
+ # XXX: change to use isinstance(obj, CryptContext)?
1182
+ return all(hasattr(obj, name) for name in _context_attrs)
1183
+
1184
+
1185
+ ##def has_many_backends(handler):
1186
+ ## "check if handler provides multiple baceknds"
1187
+ ## # NOTE: should also provide get_backend(), .has_backend(), and .backends attr
1188
+ ## return hasattr(handler, "set_backend")
1189
+
1190
+
1191
+ def has_rounds_info(handler):
1192
+ """check if handler provides the optional :ref:`rounds information <rounds-attributes>` attributes"""
1193
+ return (
1194
+ "rounds" in handler.setting_kwds
1195
+ and getattr(handler, "min_rounds", None) is not None
1196
+ )
1197
+
1198
+
1199
+ def has_salt_info(handler):
1200
+ """check if handler provides the optional :ref:`salt information <salt-attributes>` attributes"""
1201
+ return (
1202
+ "salt" in handler.setting_kwds
1203
+ and getattr(handler, "min_salt_size", None) is not None
1204
+ )
1205
+
1206
+
1207
+ ##def has_raw_salt(handler):
1208
+ ## "check if handler takes in encoded salt as unicode (False), or decoded salt as bytes (True)"
1209
+ ## sc = getattr(handler, "salt_chars", None)
1210
+ ## if sc is None:
1211
+ ## return None
1212
+ ## elif isinstance(sc, unicode):
1213
+ ## return False
1214
+ ## elif isinstance(sc, bytes):
1215
+ ## return True
1216
+ ## else:
1217
+ ## raise TypeError("handler.salt_chars must be None/unicode/bytes")
1218
+
1219
+ # =============================================================================
1220
+ # eof
1221
+ # =============================================================================