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,396 @@
1
+ """Cisco password hashes"""
2
+
3
+ from binascii import hexlify, unhexlify
4
+ from hashlib import md5
5
+ from warnings import warn
6
+
7
+ import passlib.utils.handlers as uh
8
+ from passlib.utils import repeat_string, right_pad_string, to_unicode
9
+ from passlib.utils.binary import h64
10
+
11
+ __all__ = [
12
+ "cisco_pix",
13
+ "cisco_asa",
14
+ "cisco_type7",
15
+ ]
16
+
17
+
18
+ #: dummy bytes used by spoil_digest var in cisco_pix._calc_checksum()
19
+ _DUMMY_BYTES = b"\xff" * 32
20
+
21
+
22
+ class cisco_pix(uh.HasUserContext, uh.StaticHandler):
23
+ """
24
+ This class implements the password hash used by older Cisco PIX firewalls,
25
+ and follows the :ref:`password-hash-api`.
26
+ It does a single round of hashing, and relies on the username
27
+ as the salt.
28
+
29
+ This class only allows passwords <= 16 bytes, anything larger
30
+ will result in a :exc:`~passlib.exc.PasswordSizeError` if passed to :meth:`~cisco_pix.hash`,
31
+ and be silently rejected if passed to :meth:`~cisco_pix.verify`.
32
+
33
+ The :meth:`~passlib.ifc.PasswordHash.hash`,
34
+ :meth:`~passlib.ifc.PasswordHash.genhash`, and
35
+ :meth:`~passlib.ifc.PasswordHash.verify` methods
36
+ all support the following extra keyword:
37
+
38
+ :param str user:
39
+ String containing name of user account this password is associated with.
40
+
41
+ This is *required* in order to correctly hash passwords associated
42
+ with a user account on the Cisco device, as it is used to salt
43
+ the hash.
44
+
45
+ Conversely, this *must* be omitted or set to ``""`` in order to correctly
46
+ hash passwords which don't have an associated user account
47
+ (such as the "enable" password).
48
+
49
+ .. versionadded:: 1.6
50
+
51
+ .. versionchanged:: 1.7.1
52
+
53
+ Passwords > 16 bytes are now rejected / throw error instead of being silently truncated,
54
+ to match Cisco behavior. A number of :ref:`bugs <passlib-asa96-bug>` were fixed
55
+ which caused prior releases to generate unverifiable hashes in certain cases.
56
+ """
57
+
58
+ # --------------------
59
+ # PasswordHash
60
+ # --------------------
61
+ name = "cisco_pix"
62
+
63
+ truncate_size = 16
64
+
65
+ # NOTE: these are the default policy for PasswordHash,
66
+ # but want to set them explicitly for now.
67
+ truncate_error = True
68
+ truncate_verify_reject = True
69
+
70
+ # --------------------
71
+ # GenericHandler
72
+ # --------------------
73
+ checksum_size = 16
74
+ checksum_chars = uh.HASH64_CHARS
75
+
76
+ # --------------------
77
+ # custom
78
+ # --------------------
79
+
80
+ #: control flag signalling "cisco_asa" mode, set by cisco_asa class
81
+ _is_asa = False
82
+
83
+ def _calc_checksum(self, secret):
84
+ """
85
+ This function implements the "encrypted" hash format used by Cisco
86
+ PIX & ASA. It's behavior has been confirmed for ASA 9.6,
87
+ but is presumed correct for PIX & other ASA releases,
88
+ as it fits with known test vectors, and existing literature.
89
+
90
+ While nearly the same, the PIX & ASA hashes have slight differences,
91
+ so this function performs differently based on the _is_asa class flag.
92
+ Noteable changes from PIX to ASA include password size limit
93
+ increased from 16 -> 32, and other internal changes.
94
+ """
95
+ # select PIX vs or ASA mode
96
+ asa = self._is_asa
97
+
98
+ #
99
+ # encode secret
100
+ #
101
+ # per ASA 8.4 documentation,
102
+ # http://www.cisco.com/c/en/us/td/docs/security/asa/asa84/configuration/guide/asa_84_cli_config/ref_cli.html#Supported_Character_Sets,
103
+ # it supposedly uses UTF-8 -- though some double-encoding issues have
104
+ # been observed when trying to actually *set* a non-ascii password
105
+ # via ASDM, and access via SSH seems to strip 8-bit chars.
106
+ #
107
+ if isinstance(secret, str):
108
+ secret = secret.encode("utf-8")
109
+
110
+ #
111
+ # check if password too large
112
+ #
113
+ # Per ASA 9.6 changes listed in
114
+ # http://www.cisco.com/c/en/us/td/docs/security/asa/roadmap/asa_new_features.html,
115
+ # prior releases had a maximum limit of 32 characters.
116
+ # Testing with an ASA 9.6 system bears this out --
117
+ # setting 32-char password for a user account,
118
+ # and logins will fail if any chars are appended.
119
+ # (ASA 9.6 added new PBKDF2-based hash algorithm,
120
+ # which supports larger passwords).
121
+ #
122
+ # Per PIX documentation
123
+ # http://www.cisco.com/en/US/docs/security/pix/pix50/configuration/guide/commands.html,
124
+ # it would not allow passwords > 16 chars.
125
+ #
126
+ # Thus, we unconditionally throw a password size error here,
127
+ # as nothing valid can come from a larger password.
128
+ # NOTE: assuming PIX has same behavior, but at 16 char limit.
129
+ #
130
+ spoil_digest = None
131
+ if len(secret) > self.truncate_size:
132
+ if self.use_defaults:
133
+ # called from hash()
134
+ msg = "Password too long (%s allows at most %d bytes)" % (
135
+ self.name,
136
+ self.truncate_size,
137
+ )
138
+ raise uh.exc.PasswordSizeError(self.truncate_size, msg=msg)
139
+ # called from verify() --
140
+ # We don't want to throw error, or return early,
141
+ # as that would let attacker know too much. Instead, we set a
142
+ # flag to add some dummy data into the md5 digest, so that
143
+ # output won't match truncated version of secret, or anything
144
+ # else that's fixed and predictable.
145
+ spoil_digest = secret + _DUMMY_BYTES
146
+
147
+ #
148
+ # append user to secret
149
+ #
150
+ # Policy appears to be:
151
+ #
152
+ # * Nothing appended for enable password (user = "")
153
+ #
154
+ # * ASA: If user present, but secret is >= 28 chars, nothing appended.
155
+ #
156
+ # * 1-2 byte users not allowed.
157
+ # DEVIATION: we're letting them through, and repeating their
158
+ # chars ala 3-char user, to simplify testing.
159
+ # Could issue warning in the future though.
160
+ #
161
+ # * 3 byte user has first char repeated, to pad to 4.
162
+ # (observed under ASA 9.6, assuming true elsewhere)
163
+ #
164
+ # * 4 byte users are used directly.
165
+ #
166
+ # * 5+ byte users are truncated to 4 bytes.
167
+ #
168
+ user = self.user
169
+ if user:
170
+ if isinstance(user, str):
171
+ user = user.encode("utf-8")
172
+ if not asa or len(secret) < 28:
173
+ secret += repeat_string(user, 4)
174
+
175
+ #
176
+ # pad / truncate result to limit
177
+ #
178
+ # While PIX always pads to 16 bytes, ASA increases to 32 bytes IFF
179
+ # secret+user > 16 bytes. This makes PIX & ASA have different results
180
+ # where secret size in range(13,16), and user is present --
181
+ # PIX will truncate to 16, ASA will truncate to 32.
182
+ #
183
+ if asa and len(secret) > 16: # noqa: SIM108
184
+ pad_size = 32
185
+ else:
186
+ pad_size = 16
187
+ secret = right_pad_string(secret, pad_size)
188
+
189
+ #
190
+ # md5 digest
191
+ #
192
+ if spoil_digest:
193
+ # make sure digest won't match truncated version of secret
194
+ secret += spoil_digest
195
+ digest = md5(secret).digest()
196
+
197
+ #
198
+ # drop every 4th byte
199
+ # NOTE: guessing this was done because it makes output exactly
200
+ # 16 bytes, which may have been a general 'char password[]'
201
+ # size limit under PIX
202
+ #
203
+ digest = bytes(c for i, c in enumerate(digest) if (i + 1) & 3)
204
+
205
+ #
206
+ # encode using Hash64
207
+ #
208
+ return h64.encode_bytes(digest).decode("ascii")
209
+
210
+ # NOTE: works, but needs UTs.
211
+ # @classmethod
212
+ # def same_as_pix(cls, secret, user=""):
213
+ # """
214
+ # test whether (secret + user) combination should
215
+ # have the same hash under PIX and ASA.
216
+ #
217
+ # mainly present to help unittests.
218
+ # """
219
+ # # see _calc_checksum() above for details of this logic.
220
+ # size = len(to_bytes(secret, "utf-8"))
221
+ # if user and size < 28:
222
+ # size += 4
223
+ # return size < 17
224
+
225
+
226
+ class cisco_asa(cisco_pix):
227
+ """
228
+ This class implements the password hash used by Cisco ASA/PIX 7.0 and newer (2005).
229
+ Aside from a different internal algorithm, it's use and format is identical
230
+ to the older :class:`cisco_pix` class.
231
+
232
+ For passwords less than 13 characters, this should be identical to :class:`!cisco_pix`,
233
+ but will generate a different hash for most larger inputs
234
+ (See the `Format & Algorithm`_ section for the details).
235
+
236
+ This class only allows passwords <= 32 bytes, anything larger
237
+ will result in a :exc:`~passlib.exc.PasswordSizeError` if passed to :meth:`~cisco_asa.hash`,
238
+ and be silently rejected if passed to :meth:`~cisco_asa.verify`.
239
+
240
+ .. versionadded:: 1.7
241
+
242
+ .. versionchanged:: 1.7.1
243
+
244
+ Passwords > 32 bytes are now rejected / throw error instead of being silently truncated,
245
+ to match Cisco behavior. A number of :ref:`bugs <passlib-asa96-bug>` were fixed
246
+ which caused prior releases to generate unverifiable hashes in certain cases.
247
+ """
248
+
249
+ # --------------------
250
+ # PasswordHash
251
+ # --------------------
252
+ name = "cisco_asa"
253
+
254
+ # --------------------
255
+ # TruncateMixin
256
+ # --------------------
257
+ truncate_size = 32
258
+
259
+ # --------------------
260
+ # cisco_pix
261
+ # --------------------
262
+ _is_asa = True
263
+
264
+
265
+ class cisco_type7(uh.GenericHandler):
266
+ """
267
+ This class implements the "Type 7" password encoding used by Cisco IOS,
268
+ and follows the :ref:`password-hash-api`.
269
+ It has a simple 4-5 bit salt, but is nonetheless a reversible encoding
270
+ instead of a real hash.
271
+
272
+ The :meth:`~passlib.ifc.PasswordHash.using` method accepts the following optional keywords:
273
+
274
+ :type salt: int
275
+ :param salt:
276
+ This may be an optional salt integer drawn from ``range(0,16)``.
277
+ If omitted, one will be chosen at random.
278
+
279
+ :type relaxed: bool
280
+ :param relaxed:
281
+ By default, providing an invalid value for one of the other
282
+ keywords will result in a :exc:`ValueError`. If ``relaxed=True``,
283
+ and the error can be corrected, a :exc:`~passlib.exc.PasslibHashWarning`
284
+ will be issued instead. Correctable errors include
285
+ ``salt`` values that are out of range.
286
+
287
+ Note that while this class outputs digests in upper-case hexadecimal,
288
+ it will accept lower-case as well.
289
+
290
+ This class also provides the following additional method:
291
+
292
+ .. automethod:: decode
293
+ """
294
+
295
+ # --------------------
296
+ # PasswordHash
297
+ # --------------------
298
+ name = "cisco_type7"
299
+ setting_kwds = ("salt",)
300
+
301
+ # --------------------
302
+ # GenericHandler
303
+ # --------------------
304
+ checksum_chars = uh.UPPER_HEX_CHARS
305
+
306
+ # --------------------
307
+ # HasSalt
308
+ # --------------------
309
+
310
+ # NOTE: encoding could handle max_salt_value=99, but since key is only 52
311
+ # chars in size, not sure what appropriate behavior is for that edge case.
312
+ min_salt_value = 0
313
+ max_salt_value = 52
314
+
315
+ @classmethod
316
+ def using(cls, salt=None, **kwds):
317
+ subcls = super().using(**kwds)
318
+ if salt is not None:
319
+ salt = subcls._norm_salt(salt, relaxed=kwds.get("relaxed"))
320
+ subcls._generate_salt = staticmethod(lambda: salt)
321
+ return subcls
322
+
323
+ @classmethod
324
+ def from_string(cls, hash):
325
+ hash = to_unicode(hash, "ascii", "hash")
326
+ if len(hash) < 2:
327
+ raise uh.exc.InvalidHashError(cls)
328
+ salt = int(hash[:2]) # may throw ValueError
329
+ return cls(salt=salt, checksum=hash[2:].upper())
330
+
331
+ def __init__(self, salt=None, **kwds):
332
+ super().__init__(**kwds)
333
+ if salt is not None:
334
+ salt = self._norm_salt(salt)
335
+ elif self.use_defaults:
336
+ salt = self._generate_salt()
337
+ assert self._norm_salt(salt) == salt, f"generated invalid salt: {salt!r}"
338
+ else:
339
+ raise TypeError("no salt specified")
340
+ self.salt = salt
341
+
342
+ @classmethod
343
+ def _norm_salt(cls, salt, relaxed=False):
344
+ """
345
+ validate & normalize salt value.
346
+ .. note::
347
+ the salt for this algorithm is an integer 0-52, not a string
348
+ """
349
+ if not isinstance(salt, int):
350
+ raise uh.exc.ExpectedTypeError(salt, "integer", "salt")
351
+ if 0 <= salt <= cls.max_salt_value:
352
+ return salt
353
+ msg = "salt/offset must be in 0..52 range"
354
+ if relaxed:
355
+ warn(msg, uh.PasslibHashWarning)
356
+ return 0 if salt < 0 else cls.max_salt_value
357
+ raise ValueError(msg)
358
+
359
+ @staticmethod
360
+ def _generate_salt():
361
+ return uh.rng.randint(0, 15)
362
+
363
+ def to_string(self):
364
+ return "%02d%s" % (self.salt, self.checksum)
365
+
366
+ def _calc_checksum(self, secret):
367
+ # XXX: no idea what unicode policy is, but all examples are
368
+ # 7-bit ascii compatible, so using UTF-8
369
+ if isinstance(secret, str):
370
+ secret = secret.encode("utf-8")
371
+ return hexlify(self._cipher(secret, self.salt)).decode("ascii").upper()
372
+
373
+ @classmethod
374
+ def decode(cls, hash, encoding="utf-8"):
375
+ """decode hash, returning original password.
376
+
377
+ :arg hash: encoded password
378
+ :param encoding: optional encoding to use (defaults to ``UTF-8``).
379
+ :returns: password as unicode
380
+ """
381
+ self = cls.from_string(hash)
382
+ tmp = unhexlify(self.checksum.encode("ascii"))
383
+ raw = self._cipher(tmp, self.salt)
384
+ return raw.decode(encoding) if encoding else raw
385
+
386
+ # type7 uses a xor-based vingere variant, using the following secret key:
387
+ _key = "dsfd;kfoA,.iyewrkldJKDHSUBsgvca69834ncxv9873254k;fg87"
388
+
389
+ @classmethod
390
+ def _cipher(cls, data: bytes, salt: int):
391
+ """xor static key against data - encrypts & decrypts"""
392
+ key = cls._key
393
+ key_size = len(key)
394
+ return bytes(
395
+ value ^ ord(key[(salt + idx) % key_size]) for idx, value in enumerate(data)
396
+ )