libpass 1.7.5.post0__py3-none-any.whl

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