passlib 1.9.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. passlib/__init__.py +3 -0
  2. passlib/_data/wordsets/bip39.txt +2049 -0
  3. passlib/_data/wordsets/eff_long.txt +7776 -0
  4. passlib/_data/wordsets/eff_prefixed.txt +1296 -0
  5. passlib/_data/wordsets/eff_short.txt +1296 -0
  6. passlib/_logging.py +3 -0
  7. passlib/_protocols.py +33 -0
  8. passlib/apache.py +1106 -0
  9. passlib/apps.py +215 -0
  10. passlib/context.py +1944 -0
  11. passlib/crypto/__init__.py +1 -0
  12. passlib/crypto/_blowfish/__init__.py +153 -0
  13. passlib/crypto/_blowfish/_gen_files.py +238 -0
  14. passlib/crypto/_blowfish/base.py +1212 -0
  15. passlib/crypto/_blowfish/unrolled.py +1664 -0
  16. passlib/crypto/_md4.py +229 -0
  17. passlib/crypto/des.py +2250 -0
  18. passlib/crypto/digest.py +760 -0
  19. passlib/crypto/scrypt/__init__.py +273 -0
  20. passlib/crypto/scrypt/_builtin.py +220 -0
  21. passlib/crypto/scrypt/_gen_files.py +142 -0
  22. passlib/crypto/scrypt/_salsa.py +180 -0
  23. passlib/exc.py +409 -0
  24. passlib/ext/__init__.py +1 -0
  25. passlib/ext/django/__init__.py +6 -0
  26. passlib/ext/django/models.py +21 -0
  27. passlib/ext/django/utils.py +1181 -0
  28. passlib/handlers/__init__.py +1 -0
  29. passlib/handlers/argon2.py +999 -0
  30. passlib/handlers/bcrypt.py +996 -0
  31. passlib/handlers/cisco.py +396 -0
  32. passlib/handlers/des_crypt.py +504 -0
  33. passlib/handlers/digests.py +149 -0
  34. passlib/handlers/django.py +510 -0
  35. passlib/handlers/fshp.py +185 -0
  36. passlib/handlers/ldap_digests.py +356 -0
  37. passlib/handlers/md5_crypt.py +286 -0
  38. passlib/handlers/misc.py +201 -0
  39. passlib/handlers/mssql.py +217 -0
  40. passlib/handlers/mysql.py +92 -0
  41. passlib/handlers/oracle.py +137 -0
  42. passlib/handlers/pbkdf2.py +454 -0
  43. passlib/handlers/phpass.py +110 -0
  44. passlib/handlers/postgres.py +34 -0
  45. passlib/handlers/roundup.py +18 -0
  46. passlib/handlers/scram.py +532 -0
  47. passlib/handlers/scrypt.py +357 -0
  48. passlib/handlers/sha1_crypt.py +121 -0
  49. passlib/handlers/sha2_crypt.py +562 -0
  50. passlib/handlers/sun_md5_crypt.py +334 -0
  51. passlib/handlers/windows.py +299 -0
  52. passlib/hash.py +106 -0
  53. passlib/hosts.py +85 -0
  54. passlib/ifc.py +307 -0
  55. passlib/pwd.py +709 -0
  56. passlib/registry.py +547 -0
  57. passlib/totp.py +1852 -0
  58. passlib/utils/__init__.py +901 -0
  59. passlib/utils/binary.py +852 -0
  60. passlib/utils/compat/__init__.py +141 -0
  61. passlib/utils/decor.py +220 -0
  62. passlib/utils/des.py +31 -0
  63. passlib/utils/handlers.py +2616 -0
  64. passlib/utils/md4.py +25 -0
  65. passlib/utils/pbkdf2.py +172 -0
  66. passlib-1.9.5.dist-info/METADATA +90 -0
  67. passlib-1.9.5.dist-info/RECORD +69 -0
  68. passlib-1.9.5.dist-info/WHEEL +4 -0
  69. passlib-1.9.5.dist-info/licenses/LICENSE +116 -0
passlib/apache.py ADDED
@@ -0,0 +1,1106 @@
1
+ """Apache password support"""
2
+
3
+ # XXX: relocate this to passlib.ext.apache?
4
+ from __future__ import annotations
5
+
6
+ import os
7
+ from io import BytesIO
8
+ from os import PathLike
9
+ from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar, cast
10
+ from warnings import warn
11
+
12
+ from passlib._logging import logger
13
+
14
+ if TYPE_CHECKING:
15
+ from collections.abc import Iterable, Iterator
16
+ from typing import Self
17
+
18
+ from passlib import exc, registry
19
+ from passlib.context import CryptContext
20
+ from passlib.exc import ExpectedStringError
21
+ from passlib.hash import htdigest
22
+ from passlib.utils import is_ascii_codec, render_bytes, to_bytes
23
+ from passlib.utils.compat import join_bytes
24
+
25
+ # local
26
+ __all__ = [
27
+ "HtpasswdFile",
28
+ "HtdigestFile",
29
+ ]
30
+
31
+ _UNSET = object()
32
+
33
+ _BCOLON = b":"
34
+ _BHASH = b"#"
35
+
36
+ # byte values that aren't allowed in fields.
37
+ _INVALID_FIELD_CHARS = b":\n\r\t\x00"
38
+
39
+ #: _CommonFile._source token types
40
+ _SKIPPED: Literal["skipped"] = "skipped"
41
+ _RECORD: Literal["record"] = "record"
42
+ _TRecordKey = TypeVar("_TRecordKey")
43
+
44
+ if TYPE_CHECKING:
45
+ _SourceTypes = (
46
+ tuple[Literal["skipped"], bytes] | tuple[Literal["record"], _TRecordKey]
47
+ )
48
+ else:
49
+ _SourceTypes = None
50
+
51
+
52
+ class _CommonFile(Generic[_TRecordKey]):
53
+ """Common framework for HtpasswdFile & HtdigestFile"""
54
+
55
+ def __init__(
56
+ self,
57
+ path: PathLike | None = None,
58
+ new: bool = False,
59
+ autosave: bool = False,
60
+ encoding: str = "utf-8",
61
+ return_unicode: bool = True,
62
+ ) -> None:
63
+ # set encoding
64
+ if not encoding:
65
+ raise TypeError("'encoding' is required")
66
+ if not is_ascii_codec(encoding):
67
+ # htpasswd/htdigest files assumes 1-byte chars, and use ":" separator,
68
+ # so only ascii-compatible encodings are allowed.
69
+ raise ValueError("encoding must be 7-bit ascii compatible")
70
+
71
+ # charset encoding used by file (defaults to utf-8)
72
+ self.encoding = encoding
73
+ # whether users() and other public methods should return str or bytes?
74
+ self.return_unicode = return_unicode
75
+ # if true, automatically save to local file after changes are made.
76
+ self.autosave = autosave
77
+ self._path = path # local file path
78
+ self._mtime: float = 0 # mtime when last loaded, or 0
79
+
80
+ # dict mapping key -> value for all records in database.
81
+ # (e.g. user => hash for Htpasswd)
82
+ self._records: dict[_TRecordKey, str] = {}
83
+ #: list of tokens for recreating original file contents when saving. if present,
84
+ #: will be sequence of (_SKIPPED, b"whitespace/comments") and (_RECORD, <record key>) tuples.
85
+ self._source: list[_SourceTypes] = []
86
+
87
+ # init db
88
+ if path and not new:
89
+ self.load()
90
+
91
+ @classmethod
92
+ def from_string(cls, data: str | bytes, **kwargs: Any) -> Self:
93
+ """create new object from raw string.
94
+
95
+ :type data: str or bytes
96
+ :arg data:
97
+ database to load, as single string.
98
+
99
+ :param \\*\\*kwds:
100
+ all other keywords are the same as in the class constructor
101
+ """
102
+ if "path" in kwargs:
103
+ raise TypeError("'path' not accepted by from_string()")
104
+ instance = cls(**kwargs)
105
+ instance.load_string(data)
106
+ return instance
107
+
108
+ @classmethod
109
+ def from_path(cls, path: PathLike, **kwds: Any) -> Self:
110
+ """create new object from file, without binding object to file.
111
+
112
+ :type path: str
113
+ :arg path:
114
+ local filepath to load from
115
+
116
+ :param \\*\\*kwds:
117
+ all other keywords are the same as in the class constructor
118
+ """
119
+ self = cls(**kwds)
120
+ self.load(path)
121
+ return self
122
+
123
+ # XXX: add a new() classmethod, ala TOTP.new()?
124
+
125
+ def __repr__(self) -> str:
126
+ tail = ""
127
+ if self.autosave:
128
+ tail += " autosave=True"
129
+ if self._path:
130
+ tail += f" path={self._path!r}"
131
+ if self.encoding != "utf-8":
132
+ tail += f" encoding={self.encoding!r}"
133
+ return f"<{self.__class__.__name__} 0x{id(self):0x}{tail}>"
134
+
135
+ # NOTE: ``path`` is a property so that ``_mtime`` is wiped when it's set.
136
+
137
+ @property
138
+ def path(self) -> PathLike | None:
139
+ return self._path
140
+
141
+ @path.setter
142
+ def path(self, value: PathLike | None) -> None:
143
+ if value != self._path:
144
+ self._mtime = 0
145
+ self._path = value
146
+
147
+ @property
148
+ def mtime(self) -> float:
149
+ """modify time when last loaded (if bound to a local file)"""
150
+ return self._mtime
151
+
152
+ def load_if_changed(self) -> bool:
153
+ """Reload from ``self.path`` only if file has changed since last load"""
154
+ if not self._path:
155
+ raise RuntimeError(f"{self!r} is not bound to a local file")
156
+ if self._mtime and self._mtime == os.path.getmtime(self._path):
157
+ return False
158
+ self.load()
159
+ return True
160
+
161
+ def load(self, path: PathLike | None = None) -> bool:
162
+ """Load state from local file.
163
+ If no path is specified, attempts to load from ``self.path``.
164
+
165
+ :type path: str
166
+ :arg path: local file to load from
167
+ """
168
+ if path is not None:
169
+ with open(path, "rb") as fh:
170
+ self._mtime = 0
171
+ self._load_lines(fh)
172
+ elif self._path:
173
+ with open(self._path, "rb") as fh:
174
+ self._mtime = os.path.getmtime(self._path)
175
+ self._load_lines(fh)
176
+ else:
177
+ raise RuntimeError(
178
+ f"{self.__class__.__name__}().path is not set, an explicit path is required"
179
+ )
180
+ return True
181
+
182
+ def load_string(self, data: str | bytes) -> None:
183
+ """Load state from unicode or bytes string, replacing current state"""
184
+ self._mtime = 0
185
+ self._load_lines(BytesIO(to_bytes(data, self.encoding, "data")))
186
+
187
+ def _load_lines(self, lines: Iterable[bytes]) -> None:
188
+ """load from sequence of lists"""
189
+ records = {}
190
+ source: list[_SourceTypes] = []
191
+ skipped = b""
192
+ for idx, line in enumerate(lines):
193
+ # NOTE: per htpasswd source (https://github.com/apache/httpd/blob/trunk/support/htpasswd.c),
194
+ # lines with only whitespace, or with "#" as first non-whitespace char,
195
+ # are left alone / ignored.
196
+ tmp = line.lstrip()
197
+ if not tmp or tmp.startswith(_BHASH):
198
+ skipped += line
199
+ continue
200
+
201
+ # parse valid line
202
+ key, value = self._parse_record(line, idx + 1)
203
+
204
+ # NOTE: if multiple entries for a key, we use the first one,
205
+ # which seems to match htpasswd source
206
+ if key in records:
207
+ logger.warning(
208
+ "username occurs multiple times in source file: %r",
209
+ key,
210
+ )
211
+ skipped += line
212
+ continue
213
+
214
+ # flush buffer of skipped whitespace lines
215
+ if skipped:
216
+ source.append((_SKIPPED, skipped))
217
+ skipped = b""
218
+
219
+ # store new user line
220
+ records[key] = value
221
+ source.append((_RECORD, key))
222
+
223
+ # don't bother preserving trailing whitespace, but do preserve trailing comments
224
+ if skipped.rstrip():
225
+ source.append((_SKIPPED, skipped))
226
+
227
+ # NOTE: not replacing ._records until parsing succeeds, so loading is atomic.
228
+ self._records = records
229
+ self._source = source
230
+
231
+ def _parse_record(
232
+ self, record: bytes, lineno: int
233
+ ) -> tuple[_TRecordKey, Any]: # pragma: no cover - abstract method
234
+ """parse line of file into (key, value) pair"""
235
+ raise NotImplementedError("should be implemented in subclass")
236
+
237
+ def _set_record(self, key: _TRecordKey, value: Any) -> bool:
238
+ """
239
+ helper for setting record which takes care of inserting source line if needed;
240
+
241
+ :returns:
242
+ bool if key already present
243
+ """
244
+ existing = key in self._records
245
+ self._records[key] = value
246
+ if not existing:
247
+ self._source.append((_RECORD, key))
248
+ return existing
249
+
250
+ def _autosave(self) -> None:
251
+ """subclass helper to call save() after any changes"""
252
+ if self.autosave and self._path:
253
+ self.save()
254
+
255
+ def save(self, path: PathLike | None = None) -> None:
256
+ """Save current state to file.
257
+ If no path is specified, attempts to save to ``self.path``.
258
+ """
259
+ if path is not None:
260
+ with open(path, "wb") as fh:
261
+ fh.writelines(self._iter_lines())
262
+ elif self._path:
263
+ self.save(self._path)
264
+ self._mtime = os.path.getmtime(self._path)
265
+ else:
266
+ raise RuntimeError(
267
+ f"{self.__class__.__name__}().path is not set, cannot autosave"
268
+ )
269
+
270
+ def to_string(self) -> bytes:
271
+ """Export current state as a string of bytes"""
272
+ return join_bytes(self._iter_lines())
273
+
274
+ # def clean(self):
275
+ # """
276
+ # discard any comments or whitespace that were being preserved from the source file,
277
+ # and re-sort keys in alphabetical order
278
+ # """
279
+ # self._source = [(_RECORD, key) for key in sorted(self._records)]
280
+ # self._autosave()
281
+
282
+ def _iter_lines(self) -> Iterator[Any]:
283
+ """iterator yielding lines of database"""
284
+ # NOTE: this relies on <records> being an OrderedDict so that it outputs
285
+ # records in a deterministic order.
286
+ records = self._records
287
+ if __debug__:
288
+ pending = set(records)
289
+ for action, content in self._source:
290
+ if action == _SKIPPED:
291
+ # 'content' is whitespace/comments to write
292
+ yield content
293
+ else:
294
+ assert action == _RECORD
295
+ content = cast(
296
+ "_TRecordKey", content
297
+ ) # Should be _TRecordKey at this point
298
+
299
+ # 'content' is record key
300
+ if content not in records:
301
+ # record was deleted
302
+ # NOTE: doing it lazily like this so deleting & re-adding user
303
+ # preserves their original location in the file.
304
+ continue
305
+ yield self._render_record(content, records[content])
306
+ if __debug__:
307
+ pending.remove(content)
308
+ if __debug__:
309
+ # sanity check that we actually wrote all the records
310
+ # (otherwise _source & _records are somehow out of sync)
311
+ assert not pending, f"failed to write all records: missing={pending!r}"
312
+
313
+ def _render_record(self, key, value): # pragma: no cover - abstract method
314
+ """given key/value pair, encode as line of file"""
315
+ raise NotImplementedError("should be implemented in subclass")
316
+
317
+ def _encode_user(self, user: str | bytes) -> bytes:
318
+ """user-specific wrapper for _encode_field()"""
319
+ return self._encode_field(user, "user")
320
+
321
+ def _encode_realm(
322
+ self, realm: str | bytes
323
+ ) -> bytes: # pragma: no cover - abstract method
324
+ """realm-specific wrapper for _encode_field()"""
325
+ return self._encode_field(realm, "realm")
326
+
327
+ def _encode_field(self, value: str | bytes, param="field") -> bytes:
328
+ """convert field to internal representation.
329
+
330
+ internal representation is always bytes. byte strings are left as-is,
331
+ unicode strings encoding using file's default encoding (or ``utf-8``
332
+ if no encoding has been specified).
333
+
334
+ :raises UnicodeEncodeError:
335
+ if unicode value cannot be encoded using default encoding.
336
+
337
+ :raises ValueError:
338
+ if resulting byte string contains a forbidden character,
339
+ or is too long (>255 bytes).
340
+
341
+ :returns:
342
+ encoded identifer as bytes
343
+ """
344
+ if isinstance(value, str):
345
+ value = value.encode(self.encoding)
346
+ elif not isinstance(value, bytes):
347
+ raise ExpectedStringError(value, param)
348
+
349
+ if len(value) > 255:
350
+ raise ValueError(f"{param} must be at most 255 characters: {value!r}")
351
+ if any(c in _INVALID_FIELD_CHARS for c in value):
352
+ raise ValueError(f"{param} contains invalid characters: {value!r}")
353
+ return value
354
+
355
+ def _decode_field(self, value: bytes) -> bytes | str:
356
+ """decode field from internal representation to format
357
+ returns by users() method, etc.
358
+
359
+ :raises UnicodeDecodeError:
360
+ if unicode value cannot be decoded using default encoding.
361
+ (usually indicates wrong encoding set for file).
362
+
363
+ :returns:
364
+ field as str or bytes, as appropriate.
365
+ """
366
+ assert isinstance(value, bytes), "expected value to be bytes"
367
+ if self.return_unicode:
368
+ return value.decode(self.encoding)
369
+ return value
370
+
371
+ # FIXME: htpasswd doc says passwords limited to 255 chars under Windows & MPE,
372
+ # and that longer ones are truncated. this may be side-effect of those
373
+ # platforms supporting the 'plaintext' scheme. these classes don't currently
374
+ # check for this.
375
+
376
+
377
+ # =============================================================================
378
+ # htpasswd context
379
+ #
380
+ # This section sets up a CryptContexts to mimic what schemes Apache
381
+ # (and the htpasswd tool) should support on the current system.
382
+ #
383
+ # Apache has long-time supported some basic builtin schemes (listed below),
384
+ # as well as the host's crypt() method -- though it's limited to being able
385
+ # to *verify* any scheme using that method, but can only generate "des_crypt" hashes.
386
+ #
387
+ # Apache 2.4 added builtin bcrypt support (even for platforms w/o native support).
388
+ # c.f. http://httpd.apache.org/docs/2.4/programs/htpasswd.html vs the 2.2 docs.
389
+ # =============================================================================
390
+
391
+ #: set of default schemes that (if chosen) should be using bcrypt,
392
+ #: but can't due to lack of bcrypt.
393
+ _warn_no_bcrypt: set[str] = set()
394
+
395
+
396
+ def _init_default_schemes():
397
+ #: pick strongest one for host
398
+ host_best = None
399
+ for name in ["bcrypt", "sha256_crypt"]:
400
+ if registry.has_os_crypt_support(name):
401
+ host_best = name
402
+ break
403
+
404
+ # check if we have a bcrypt backend -- otherwise issue warning
405
+ # XXX: would like to not spam this unless the user *requests* apache 24
406
+ bcrypt = "bcrypt" if registry.has_backend("bcrypt") else None
407
+ _warn_no_bcrypt.clear()
408
+ if not bcrypt:
409
+ _warn_no_bcrypt.update(
410
+ [
411
+ "portable_apache_24",
412
+ "host_apache_24",
413
+ "linux_apache_24",
414
+ "portable",
415
+ "host",
416
+ ]
417
+ )
418
+
419
+ defaults = dict(
420
+ # strongest hash builtin to specific apache version
421
+ portable_apache_24=bcrypt or "apr_md5_crypt",
422
+ portable_apache_22="apr_md5_crypt",
423
+ # strongest hash across current host & specific apache version
424
+ host_apache_24=bcrypt or host_best or "apr_md5_crypt",
425
+ host_apache_22=host_best or "apr_md5_crypt",
426
+ # strongest hash on a linux host
427
+ linux_apache_24=bcrypt or "sha256_crypt",
428
+ linux_apache_22="sha256_crypt",
429
+ )
430
+
431
+ # set latest-apache version aliases
432
+ # XXX: could check for apache install, and pick correct host 22/24 default?
433
+ # could reuse _detect_htpasswd() helper in UTs
434
+ defaults.update(
435
+ portable=defaults["portable_apache_24"],
436
+ host=defaults["host_apache_24"],
437
+ )
438
+ return defaults
439
+
440
+
441
+ #: dict mapping default alias -> appropriate scheme
442
+ htpasswd_defaults = _init_default_schemes()
443
+
444
+
445
+ def _init_htpasswd_context():
446
+ # start with schemes built into apache
447
+ schemes = [
448
+ # builtin support added in apache 2.4
449
+ # (https://bz.apache.org/bugzilla/show_bug.cgi?id=49288)
450
+ "bcrypt",
451
+ # support not "builtin" to apache, instead it requires support through host's crypt().
452
+ # adding them here to allow editing htpasswd under windows and then deploying under unix.
453
+ "sha256_crypt",
454
+ "sha512_crypt",
455
+ "des_crypt",
456
+ # apache default as of 2.2.18, and still default in 2.4
457
+ "apr_md5_crypt",
458
+ # NOTE: apache says ONLY intended for transitioning htpasswd <-> ldap
459
+ "ldap_sha1",
460
+ # NOTE: apache says ONLY supported on Windows, Netware, TPF
461
+ "plaintext",
462
+ ]
463
+
464
+ # apache can verify anything supported by the native crypt(),
465
+ # though htpasswd tool can only generate a limited set of hashes.
466
+ # (this list may overlap w/ builtin apache schemes)
467
+ schemes.extend(registry.get_supported_os_crypt_schemes())
468
+
469
+ # hack to remove dups and sort into preferred order
470
+ preferred = schemes[:3] + ["apr_md5_crypt"] + schemes
471
+ schemes = sorted(set(schemes), key=preferred.index)
472
+
473
+ # create context object
474
+ return CryptContext(
475
+ schemes=schemes,
476
+ # NOTE: default will change to "portable" in passlib 2.0
477
+ default=htpasswd_defaults["portable_apache_22"],
478
+ # NOTE: bcrypt "2y" is required, "2b" isn't recognized by libapr (issue 95)
479
+ bcrypt__ident="2y",
480
+ )
481
+
482
+
483
+ #: CryptContext configured to match htpasswd
484
+ htpasswd_context = _init_htpasswd_context()
485
+
486
+
487
+ class HtpasswdFile(_CommonFile[bytes]):
488
+ """class for reading & writing Htpasswd files.
489
+
490
+ The class constructor accepts the following arguments:
491
+
492
+ :type path: filepath
493
+ :param path:
494
+
495
+ Specifies path to htpasswd file, use to implicitly load from and save to.
496
+
497
+ This class has two modes of operation:
498
+
499
+ 1. It can be "bound" to a local file by passing a ``path`` to the class
500
+ constructor. In this case it will load the contents of the file when
501
+ created, and the :meth:`load` and :meth:`save` methods will automatically
502
+ load from and save to that file if they are called without arguments.
503
+
504
+ 2. Alternately, it can exist as an independant object, in which case
505
+ :meth:`load` and :meth:`save` will require an explicit path to be
506
+ provided whenever they are called. As well, ``autosave`` behavior
507
+ will not be available.
508
+
509
+ This feature is new in Passlib 1.6, and is the default if no
510
+ ``path`` value is provided to the constructor.
511
+
512
+ This is also exposed as a readonly instance attribute.
513
+
514
+ :type new: bool
515
+ :param new:
516
+
517
+ Normally, if *path* is specified, :class:`HtpasswdFile` will
518
+ immediately load the contents of the file. However, when creating
519
+ a new htpasswd file, applications can set ``new=True`` so that
520
+ the existing file (if any) will not be loaded.
521
+
522
+ .. versionadded:: 1.6
523
+ This feature was previously enabled by setting ``autoload=False``.
524
+ That alias was removed in Passlib 1.8
525
+
526
+ :type autosave: bool
527
+ :param autosave:
528
+
529
+ Normally, any changes made to an :class:`HtpasswdFile` instance
530
+ will not be saved until :meth:`save` is explicitly called. However,
531
+ if ``autosave=True`` is specified, any changes made will be
532
+ saved to disk immediately (assuming *path* has been set).
533
+
534
+ This is also exposed as a writeable instance attribute.
535
+
536
+ :type encoding: str
537
+ :param encoding:
538
+
539
+ Optionally specify character encoding used to read/write file
540
+ and hash passwords. Defaults to ``utf-8``, though ``latin-1``
541
+ is the only other commonly encountered encoding.
542
+
543
+ This is also exposed as a readonly instance attribute.
544
+
545
+ :type default_scheme: str
546
+ :param default_scheme:
547
+ Optionally specify default scheme to use when encoding new passwords.
548
+
549
+ This can be any of the schemes with builtin Apache support,
550
+ OR natively supported by the host OS's :func:`crypt.crypt` function.
551
+
552
+ * Builtin schemes include ``"bcrypt"`` (apache 2.4+), ``"apr_md5_crypt"`,
553
+ and ``"des_crypt"``.
554
+
555
+ * Schemes commonly supported by Unix hosts
556
+ include ``"bcrypt"``, ``"sha256_crypt"``, and ``"des_crypt"``.
557
+
558
+ In order to not have to sort out what you should use,
559
+ passlib offers a number of aliases, that will resolve
560
+ to the most appropriate scheme based on your needs:
561
+
562
+ * ``"portable"``, ``"portable_apache_24"`` -- pick scheme that's portable across hosts
563
+ running apache >= 2.4. **This will be the default as of Passlib 2.0**.
564
+
565
+ * ``"portable_apache_22"`` -- pick scheme that's portable across hosts
566
+ running apache >= 2.4. **This is the default up to Passlib 1.9**.
567
+
568
+ * ``"host"``, ``"host_apache_24"`` -- pick strongest scheme supported by
569
+ apache >= 2.4 and/or host OS.
570
+
571
+ * ``"host_apache_22"`` -- pick strongest scheme supported by
572
+ apache >= 2.2 and/or host OS.
573
+
574
+ .. versionadded:: 1.6
575
+ This keyword was previously named ``default``. That alias
576
+ was removed in Passlib 1.8.
577
+
578
+ .. versionchanged:: 1.6.3
579
+
580
+ Added support for ``"bcrypt"``, ``"sha256_crypt"``, and ``"portable"`` alias.
581
+
582
+ .. versionchanged:: 1.7
583
+
584
+ Added apache 2.4 semantics, and additional aliases.
585
+
586
+ :type context: :class:`~passlib.context.CryptContext`
587
+ :param context:
588
+ :class:`!CryptContext` instance used to create
589
+ and verify the hashes found in the htpasswd file.
590
+ The default value is a pre-built context which supports all
591
+ of the hashes officially allowed in an htpasswd file.
592
+
593
+ This is also exposed as a readonly instance attribute.
594
+
595
+ .. warning::
596
+
597
+ This option may be used to add support for non-standard hash
598
+ formats to an htpasswd file. However, the resulting file
599
+ will probably not be usable by another application,
600
+ and particularly not by Apache.
601
+
602
+ Loading & Saving
603
+ ================
604
+ .. automethod:: load
605
+ .. automethod:: load_if_changed
606
+ .. automethod:: load_string
607
+ .. automethod:: save
608
+ .. automethod:: to_string
609
+
610
+ Inspection
611
+ ================
612
+ .. automethod:: users
613
+ .. automethod:: check_password
614
+ .. automethod:: get_hash
615
+
616
+ Modification
617
+ ================
618
+ .. automethod:: set_password
619
+ .. automethod:: delete
620
+
621
+ Alternate Constructors
622
+ ======================
623
+ .. automethod:: from_string
624
+
625
+ Attributes
626
+ ==========
627
+ .. attribute:: path
628
+
629
+ Path to local file that will be used as the default
630
+ for all :meth:`load` and :meth:`save` operations.
631
+ May be written to, initialized by the *path* constructor keyword.
632
+
633
+ .. attribute:: autosave
634
+
635
+ Writeable flag indicating whether changes will be automatically
636
+ written to *path*.
637
+
638
+ Errors
639
+ ======
640
+ :raises ValueError:
641
+ All of the methods in this class will raise a :exc:`ValueError` if
642
+ any user name contains a forbidden character (one of ``:\\r\\n\\t\\x00``),
643
+ or is longer than 255 characters.
644
+ """
645
+
646
+ # NOTE: _records map stores <user> for the key, and <hash> for the value,
647
+ # both in bytes which use self.encoding
648
+ def __init__(
649
+ self, path=None, default_scheme=None, context=htpasswd_context, **kwds
650
+ ):
651
+ if default_scheme:
652
+ if default_scheme in _warn_no_bcrypt:
653
+ warn(
654
+ "HtpasswdFile: no bcrypt backends available, "
655
+ f"using fallback for default scheme {default_scheme!r}",
656
+ exc.PasslibSecurityWarning,
657
+ )
658
+ default_scheme = htpasswd_defaults.get(default_scheme, default_scheme)
659
+ context = context.copy(default=default_scheme)
660
+ self.context = context
661
+ super().__init__(path, **kwds)
662
+
663
+ def _parse_record(self, record, lineno):
664
+ # NOTE: should return (user, hash) tuple
665
+ result = record.rstrip().split(_BCOLON)
666
+ if len(result) != 2:
667
+ raise ValueError("malformed htpasswd file (error reading line %d)" % lineno)
668
+ return result
669
+
670
+ def _render_record(self, user, hash):
671
+ return render_bytes("%s:%s\n", user, hash)
672
+
673
+ def users(self) -> list[bytes | str]:
674
+ """
675
+ Return list of all users in database
676
+ """
677
+ return [self._decode_field(user) for user in self._records]
678
+
679
+ ##def has_user(self, user):
680
+ ## "check whether entry is present for user"
681
+ ## return self._encode_user(user) in self._records
682
+
683
+ ##def rename(self, old, new):
684
+ ## """rename user account"""
685
+ ## old = self._encode_user(old)
686
+ ## new = self._encode_user(new)
687
+ ## hash = self._records.pop(old)
688
+ ## self._records[new] = hash
689
+ ## self._autosave()
690
+
691
+ def set_password(self, user, password):
692
+ """Set password for user; adds user if needed.
693
+
694
+ :returns:
695
+ * ``True`` if existing user was updated.
696
+ * ``False`` if user account was added.
697
+
698
+ .. versionchanged:: 1.6
699
+ This method was previously called ``update``, it was renamed
700
+ to prevent ambiguity with the dictionary method.
701
+ The old alias was removed in Passlib 1.8.
702
+ """
703
+ hash = self.context.hash(password)
704
+ return self.set_hash(user, hash)
705
+
706
+ def get_hash(self, user):
707
+ """Return hash stored for user, or ``None`` if user not found.
708
+
709
+ .. versionchanged:: 1.6
710
+ This method was previously named ``find``, it was renamed
711
+ for clarity. The old name was removed in Passlib 1.8.
712
+ """
713
+ try:
714
+ return self._records[self._encode_user(user)]
715
+ except KeyError:
716
+ return None
717
+
718
+ def set_hash(self, user, hash):
719
+ """
720
+ semi-private helper which allows writing a hash directly;
721
+ adds user if needed.
722
+
723
+ .. warning::
724
+ does not (currently) do any validation of the hash string
725
+
726
+ .. versionadded:: 1.7
727
+ """
728
+ # assert self.context.identify(hash), "unrecognized hash format"
729
+ if isinstance(hash, str):
730
+ hash = hash.encode(self.encoding)
731
+ user = self._encode_user(user)
732
+ existing = self._set_record(user, hash)
733
+ self._autosave()
734
+ return existing
735
+
736
+ # XXX: rename to something more explicit, like delete_user()?
737
+ def delete(self, user):
738
+ """Delete user's entry.
739
+
740
+ :returns:
741
+ * ``True`` if user deleted.
742
+ * ``False`` if user not found.
743
+ """
744
+ try:
745
+ del self._records[self._encode_user(user)]
746
+ except KeyError:
747
+ return False
748
+ self._autosave()
749
+ return True
750
+
751
+ def check_password(self, user, password):
752
+ """
753
+ Verify password for specified user.
754
+ If algorithm marked as deprecated by CryptContext, will automatically be re-hashed.
755
+
756
+ :returns:
757
+ * ``None`` if user not found.
758
+ * ``False`` if user found, but password does not match.
759
+ * ``True`` if user found and password matches.
760
+
761
+ .. versionchanged:: 1.6
762
+ This method was previously called ``verify``, it was renamed
763
+ to prevent ambiguity with the :class:`!CryptContext` method.
764
+ The old alias was removed in Passlib 1.8.
765
+ """
766
+ user = self._encode_user(user)
767
+ hash = self._records.get(user)
768
+ if hash is None:
769
+ return None
770
+ if isinstance(password, str):
771
+ # NOTE: encoding password to match file, making the assumption
772
+ # that server will use same encoding to hash the password.
773
+ password = password.encode(self.encoding)
774
+ ok, new_hash = self.context.verify_and_update(password, hash)
775
+ if ok and new_hash is not None:
776
+ # rehash user's password if old hash was deprecated
777
+ assert user in self._records # otherwise would have to use ._set_record()
778
+ self._records[user] = new_hash
779
+ self._autosave()
780
+ return ok
781
+
782
+
783
+ class HtdigestFile(_CommonFile[tuple[bytes, bytes]]):
784
+ """class for reading & writing Htdigest files.
785
+
786
+ The class constructor accepts the following arguments:
787
+
788
+ :type path: filepath
789
+ :param path:
790
+
791
+ Specifies path to htdigest file, use to implicitly load from and save to.
792
+
793
+ This class has two modes of operation:
794
+
795
+ 1. It can be "bound" to a local file by passing a ``path`` to the class
796
+ constructor. In this case it will load the contents of the file when
797
+ created, and the :meth:`load` and :meth:`save` methods will automatically
798
+ load from and save to that file if they are called without arguments.
799
+
800
+ 2. Alternately, it can exist as an independant object, in which case
801
+ :meth:`load` and :meth:`save` will require an explicit path to be
802
+ provided whenever they are called. As well, ``autosave`` behavior
803
+ will not be available.
804
+
805
+ This feature is new in Passlib 1.6, and is the default if no
806
+ ``path`` value is provided to the constructor.
807
+
808
+ This is also exposed as a readonly instance attribute.
809
+
810
+ :type default_realm: str
811
+ :param default_realm:
812
+
813
+ If ``default_realm`` is set, all the :class:`HtdigestFile`
814
+ methods that require a realm will use this value if one is not
815
+ provided explicitly. If unset, they will raise an error stating
816
+ that an explicit realm is required.
817
+
818
+ This is also exposed as a writeable instance attribute.
819
+
820
+ .. versionadded:: 1.6
821
+
822
+ :type new: bool
823
+ :param new:
824
+
825
+ Normally, if *path* is specified, :class:`HtdigestFile` will
826
+ immediately load the contents of the file. However, when creating
827
+ a new htpasswd file, applications can set ``new=True`` so that
828
+ the existing file (if any) will not be loaded.
829
+
830
+ .. versionadded:: 1.6
831
+ This feature was previously enabled by setting ``autoload=False``.
832
+ That alias was removed in Passlib 1.8
833
+
834
+ :type autosave: bool
835
+ :param autosave:
836
+
837
+ Normally, any changes made to an :class:`HtdigestFile` instance
838
+ will not be saved until :meth:`save` is explicitly called. However,
839
+ if ``autosave=True`` is specified, any changes made will be
840
+ saved to disk immediately (assuming *path* has been set).
841
+
842
+ This is also exposed as a writeable instance attribute.
843
+
844
+ :type encoding: str
845
+ :param encoding:
846
+
847
+ Optionally specify character encoding used to read/write file
848
+ and hash passwords. Defaults to ``utf-8``, though ``latin-1``
849
+ is the only other commonly encountered encoding.
850
+
851
+ This is also exposed as a readonly instance attribute.
852
+
853
+ Loading & Saving
854
+ ================
855
+ .. automethod:: load
856
+ .. automethod:: load_if_changed
857
+ .. automethod:: load_string
858
+ .. automethod:: save
859
+ .. automethod:: to_string
860
+
861
+ Inspection
862
+ ==========
863
+ .. automethod:: realms
864
+ .. automethod:: users
865
+ .. automethod:: check_password(user[, realm], password)
866
+ .. automethod:: get_hash
867
+
868
+ Modification
869
+ ============
870
+ .. automethod:: set_password(user[, realm], password)
871
+ .. automethod:: delete
872
+ .. automethod:: delete_realm
873
+
874
+ Alternate Constructors
875
+ ======================
876
+ .. automethod:: from_string
877
+
878
+ Attributes
879
+ ==========
880
+ .. attribute:: default_realm
881
+
882
+ The default realm that will be used if one is not provided
883
+ to methods that require it. By default this is ``None``,
884
+ in which case an explicit realm must be provided for every
885
+ method call. Can be written to.
886
+
887
+ .. attribute:: path
888
+
889
+ Path to local file that will be used as the default
890
+ for all :meth:`load` and :meth:`save` operations.
891
+ May be written to, initialized by the *path* constructor keyword.
892
+
893
+ .. attribute:: autosave
894
+
895
+ Writeable flag indicating whether changes will be automatically
896
+ written to *path*.
897
+
898
+ Errors
899
+ ======
900
+ :raises ValueError:
901
+ All of the methods in this class will raise a :exc:`ValueError` if
902
+ any user name or realm contains a forbidden character (one of ``:\\r\\n\\t\\x00``),
903
+ or is longer than 255 characters.
904
+ """
905
+
906
+ # NOTE: _records map stores (<user>,<realm>) for the key,
907
+ # and <hash> as the value, all as <self.encoding> bytes.
908
+
909
+ # NOTE: unlike htpasswd, this class doesn't use a CryptContext,
910
+ # as only one hash format is supported: htdigest.
911
+
912
+ # optionally specify default realm that will be used if none
913
+ # is provided to a method call. otherwise realm is always required.
914
+ default_realm = None
915
+
916
+ def __init__(self, path=None, default_realm=None, **kwds):
917
+ self.default_realm = default_realm
918
+ super().__init__(path, **kwds)
919
+
920
+ def _parse_record(self, record, lineno):
921
+ result = record.rstrip().split(_BCOLON)
922
+ if len(result) != 3:
923
+ raise ValueError("malformed htdigest file (error reading line %d)" % lineno)
924
+ user, realm, hash = result
925
+ return (user, realm), hash
926
+
927
+ def _render_record(self, key, hash):
928
+ user, realm = key
929
+ return render_bytes("%s:%s:%s\n", user, realm, hash)
930
+
931
+ def _require_realm(self, realm):
932
+ if realm is None:
933
+ realm = self.default_realm
934
+ if realm is None:
935
+ raise TypeError(
936
+ "you must specify a realm explicitly, "
937
+ "or set the default_realm attribute"
938
+ )
939
+ return realm
940
+
941
+ def _encode_realm(self, realm):
942
+ realm = self._require_realm(realm)
943
+ return self._encode_field(realm, "realm")
944
+
945
+ def _encode_key(self, user, realm):
946
+ return self._encode_user(user), self._encode_realm(realm)
947
+
948
+ def realms(self):
949
+ """Return list of all realms in database"""
950
+ realms = set(key[1] for key in self._records)
951
+ return [self._decode_field(realm) for realm in realms]
952
+
953
+ def users(self, realm=None):
954
+ """Return list of all users in specified realm.
955
+
956
+ * uses ``self.default_realm`` if no realm explicitly provided.
957
+ * returns empty list if realm not found.
958
+ """
959
+ realm = self._encode_realm(realm)
960
+ return [self._decode_field(key[0]) for key in self._records if key[1] == realm]
961
+
962
+ ##def has_user(self, user, realm=None):
963
+ ## "check if user+realm combination exists"
964
+ ## return self._encode_key(user,realm) in self._records
965
+
966
+ ##def rename_realm(self, old, new):
967
+ ## """rename all accounts in realm"""
968
+ ## old = self._encode_realm(old)
969
+ ## new = self._encode_realm(new)
970
+ ## keys = [key for key in self._records if key[1] == old]
971
+ ## for key in keys:
972
+ ## hash = self._records.pop(key)
973
+ ## self._set_record((key[0], new), hash)
974
+ ## self._autosave()
975
+ ## return len(keys)
976
+
977
+ ##def rename(self, old, new, realm=None):
978
+ ## """rename user account"""
979
+ ## old = self._encode_user(old)
980
+ ## new = self._encode_user(new)
981
+ ## realm = self._encode_realm(realm)
982
+ ## hash = self._records.pop((old,realm))
983
+ ## self._set_record((new, realm), hash)
984
+ ## self._autosave()
985
+
986
+ def set_password(self, user, realm=None, password=_UNSET):
987
+ """Set password for user; adds user & realm if needed.
988
+
989
+ If ``self.default_realm`` has been set, this may be called
990
+ with the syntax ``set_password(user, password)``,
991
+ otherwise it must be called with all three arguments:
992
+ ``set_password(user, realm, password)``.
993
+
994
+ :returns:
995
+ * ``True`` if existing user was updated
996
+ * ``False`` if user account added.
997
+ """
998
+ if password is _UNSET:
999
+ # called w/ two args - (user, password), use default realm
1000
+ realm, password = None, realm
1001
+ realm = self._require_realm(realm)
1002
+ hash = htdigest.hash(password, user, realm, encoding=self.encoding)
1003
+ return self.set_hash(user, realm, hash)
1004
+
1005
+ def get_hash(self, user, realm=None):
1006
+ """Return :class:`~passlib.hash.htdigest` hash stored for user.
1007
+
1008
+ * uses ``self.default_realm`` if no realm explicitly provided.
1009
+ * returns ``None`` if user or realm not found.
1010
+
1011
+ .. versionchanged:: 1.6
1012
+ This method was previously named ``find``, it was renamed
1013
+ for clarity. The old name is was removed Passlib 1.8.
1014
+ """
1015
+ key = self._encode_key(user, realm)
1016
+ hash = self._records.get(key)
1017
+ if hash is None:
1018
+ return None
1019
+ return hash.decode(self.encoding)
1020
+
1021
+ def set_hash(self, user, realm=None, hash=_UNSET):
1022
+ """
1023
+ semi-private helper which allows writing a hash directly;
1024
+ adds user & realm if needed.
1025
+
1026
+ If ``self.default_realm`` has been set, this may be called
1027
+ with the syntax ``set_hash(user, hash)``,
1028
+ otherwise it must be called with all three arguments:
1029
+ ``set_hash(user, realm, hash)``.
1030
+
1031
+ .. warning::
1032
+ does not (currently) do any validation of the hash string
1033
+
1034
+ .. versionadded:: 1.7
1035
+ """
1036
+ if hash is _UNSET:
1037
+ # called w/ two args - (user, hash), use default realm
1038
+ realm, hash = None, realm
1039
+ # assert htdigest.identify(hash), "unrecognized hash format"
1040
+ if isinstance(hash, str):
1041
+ hash = hash.encode(self.encoding)
1042
+ key = self._encode_key(user, realm)
1043
+ existing = self._set_record(key, hash)
1044
+ self._autosave()
1045
+ return existing
1046
+
1047
+ # XXX: rename to something more explicit, like delete_user()?
1048
+ def delete(self, user, realm=None):
1049
+ """Delete user's entry for specified realm.
1050
+
1051
+ if realm is not specified, uses ``self.default_realm``.
1052
+
1053
+ :returns:
1054
+ * ``True`` if user deleted,
1055
+ * ``False`` if user not found in realm.
1056
+ """
1057
+ key = self._encode_key(user, realm)
1058
+ try:
1059
+ del self._records[key]
1060
+ except KeyError:
1061
+ return False
1062
+ self._autosave()
1063
+ return True
1064
+
1065
+ def delete_realm(self, realm):
1066
+ """Delete all users for specified realm.
1067
+
1068
+ if realm is not specified, uses ``self.default_realm``.
1069
+
1070
+ :returns: number of users deleted (0 if realm not found)
1071
+ """
1072
+ realm = self._encode_realm(realm)
1073
+ records = self._records
1074
+ keys = [key for key in records if key[1] == realm]
1075
+ for key in keys:
1076
+ del records[key]
1077
+ self._autosave()
1078
+ return len(keys)
1079
+
1080
+ def check_password(self, user, realm=None, password=_UNSET):
1081
+ """Verify password for specified user + realm.
1082
+
1083
+ If ``self.default_realm`` has been set, this may be called
1084
+ with the syntax ``check_password(user, password)``,
1085
+ otherwise it must be called with all three arguments:
1086
+ ``check_password(user, realm, password)``.
1087
+
1088
+ :returns:
1089
+ * ``None`` if user or realm not found.
1090
+ * ``False`` if user found, but password does not match.
1091
+ * ``True`` if user found and password matches.
1092
+
1093
+ .. versionchanged:: 1.6
1094
+ This method was previously called ``verify``, it was renamed
1095
+ to prevent ambiguity with the :class:`!CryptContext` method.
1096
+ The old alias was removed in Passlib 1.8.
1097
+ """
1098
+ if password is _UNSET:
1099
+ # called w/ two args - (user, password), use default realm
1100
+ realm, password = None, realm
1101
+ user = self._encode_user(user)
1102
+ realm = self._encode_realm(realm)
1103
+ hash = self._records.get((user, realm))
1104
+ if hash is None:
1105
+ return None
1106
+ return htdigest.verify(password, hash, user, realm, encoding=self.encoding)