您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 

1247 行
45 KiB

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