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

1256 行
46 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. # could reuse _detect_htpasswd() helper in UTs
  401. defaults.update(
  402. portable=defaults['portable_apache_24'],
  403. host=defaults['host_apache_24'],
  404. )
  405. return defaults
  406. #: dict mapping default alias -> appropriate scheme
  407. htpasswd_defaults = _init_default_schemes()
  408. def _init_htpasswd_context():
  409. # start with schemes built into apache
  410. schemes = [
  411. # builtin support added in apache 2.4
  412. # (https://bz.apache.org/bugzilla/show_bug.cgi?id=49288)
  413. "bcrypt",
  414. # support not "builtin" to apache, instead it requires support through host's crypt().
  415. # adding them here to allow editing htpasswd under windows and then deploying under unix.
  416. "sha256_crypt",
  417. "sha512_crypt",
  418. "des_crypt",
  419. # apache default as of 2.2.18, and still default in 2.4
  420. "apr_md5_crypt",
  421. # NOTE: apache says ONLY intended for transitioning htpasswd <-> ldap
  422. "ldap_sha1",
  423. # NOTE: apache says ONLY supported on Windows, Netware, TPF
  424. "plaintext"
  425. ]
  426. # apache can verify anything supported by the native crypt(),
  427. # though htpasswd tool can only generate a limited set of hashes.
  428. # (this list may overlap w/ builtin apache schemes)
  429. schemes.extend(registry.get_supported_os_crypt_schemes())
  430. # hack to remove dups and sort into preferred order
  431. preferred = schemes[:3] + ["apr_md5_crypt"] + schemes
  432. schemes = sorted(set(schemes), key=preferred.index)
  433. # create context object
  434. return CryptContext(
  435. schemes=schemes,
  436. # NOTE: default will change to "portable" in passlib 2.0
  437. default=htpasswd_defaults['portable_apache_22'],
  438. # NOTE: bcrypt "2y" is required, "2b" isn't recognized by libapr (issue 95)
  439. bcrypt__ident="2y",
  440. )
  441. #: CryptContext configured to match htpasswd
  442. htpasswd_context = _init_htpasswd_context()
  443. #=============================================================================
  444. # htpasswd editing
  445. #=============================================================================
  446. class HtpasswdFile(_CommonFile):
  447. """class for reading & writing Htpasswd files.
  448. The class constructor accepts the following arguments:
  449. :type path: filepath
  450. :param path:
  451. Specifies path to htpasswd file, use to implicitly load from and save to.
  452. This class has two modes of operation:
  453. 1. It can be "bound" to a local file by passing a ``path`` to the class
  454. constructor. In this case it will load the contents of the file when
  455. created, and the :meth:`load` and :meth:`save` methods will automatically
  456. load from and save to that file if they are called without arguments.
  457. 2. Alternately, it can exist as an independant object, in which case
  458. :meth:`load` and :meth:`save` will require an explicit path to be
  459. provided whenever they are called. As well, ``autosave`` behavior
  460. will not be available.
  461. This feature is new in Passlib 1.6, and is the default if no
  462. ``path`` value is provided to the constructor.
  463. This is also exposed as a readonly instance attribute.
  464. :type new: bool
  465. :param new:
  466. Normally, if *path* is specified, :class:`HtpasswdFile` will
  467. immediately load the contents of the file. However, when creating
  468. a new htpasswd file, applications can set ``new=True`` so that
  469. the existing file (if any) will not be loaded.
  470. .. versionadded:: 1.6
  471. This feature was previously enabled by setting ``autoload=False``.
  472. That alias has been deprecated, and will be removed in Passlib 1.8
  473. :type autosave: bool
  474. :param autosave:
  475. Normally, any changes made to an :class:`HtpasswdFile` instance
  476. will not be saved until :meth:`save` is explicitly called. However,
  477. if ``autosave=True`` is specified, any changes made will be
  478. saved to disk immediately (assuming *path* has been set).
  479. This is also exposed as a writeable instance attribute.
  480. :type encoding: str
  481. :param encoding:
  482. Optionally specify character encoding used to read/write file
  483. and hash passwords. Defaults to ``utf-8``, though ``latin-1``
  484. is the only other commonly encountered encoding.
  485. This is also exposed as a readonly instance attribute.
  486. :type default_scheme: str
  487. :param default_scheme:
  488. Optionally specify default scheme to use when encoding new passwords.
  489. This can be any of the schemes with builtin Apache support,
  490. OR natively supported by the host OS's :func:`crypt.crypt` function.
  491. * Builtin schemes include ``"bcrypt"`` (apache 2.4+), ``"apr_md5_crypt"`,
  492. and ``"des_crypt"``.
  493. * Schemes commonly supported by Unix hosts
  494. include ``"bcrypt"``, ``"sha256_crypt"``, and ``"des_crypt"``.
  495. In order to not have to sort out what you should use,
  496. passlib offers a number of aliases, that will resolve
  497. to the most appropriate scheme based on your needs:
  498. * ``"portable"``, ``"portable_apache_24"`` -- pick scheme that's portable across hosts
  499. running apache >= 2.4. **This will be the default as of Passlib 2.0**.
  500. * ``"portable_apache_22"`` -- pick scheme that's portable across hosts
  501. running apache >= 2.4. **This is the default up to Passlib 1.9**.
  502. * ``"host"``, ``"host_apache_24"`` -- pick strongest scheme supported by
  503. apache >= 2.4 and/or host OS.
  504. * ``"host_apache_22"`` -- pick strongest scheme supported by
  505. apache >= 2.2 and/or host OS.
  506. .. versionadded:: 1.6
  507. This keyword was previously named ``default``. That alias
  508. has been deprecated, and will be removed in Passlib 1.8.
  509. .. versionchanged:: 1.6.3
  510. Added support for ``"bcrypt"``, ``"sha256_crypt"``, and ``"portable"`` alias.
  511. .. versionchanged:: 1.7
  512. Added apache 2.4 semantics, and additional aliases.
  513. :type context: :class:`~passlib.context.CryptContext`
  514. :param context:
  515. :class:`!CryptContext` instance used to create
  516. and verify the hashes found in the htpasswd file.
  517. The default value is a pre-built context which supports all
  518. of the hashes officially allowed in an htpasswd file.
  519. This is also exposed as a readonly instance attribute.
  520. .. warning::
  521. This option may be used to add support for non-standard hash
  522. formats to an htpasswd file. However, the resulting file
  523. will probably not be usable by another application,
  524. and particularly not by Apache.
  525. :param autoload:
  526. Set to ``False`` to prevent the constructor from automatically
  527. loaded the file from disk.
  528. .. deprecated:: 1.6
  529. This has been replaced by the *new* keyword.
  530. Instead of setting ``autoload=False``, you should use
  531. ``new=True``. Support for this keyword will be removed
  532. in Passlib 1.8.
  533. :param default:
  534. Change the default algorithm used to hash new passwords.
  535. .. deprecated:: 1.6
  536. This has been renamed to *default_scheme* for clarity.
  537. Support for this alias will be removed in Passlib 1.8.
  538. Loading & Saving
  539. ================
  540. .. automethod:: load
  541. .. automethod:: load_if_changed
  542. .. automethod:: load_string
  543. .. automethod:: save
  544. .. automethod:: to_string
  545. Inspection
  546. ================
  547. .. automethod:: users
  548. .. automethod:: check_password
  549. .. automethod:: get_hash
  550. Modification
  551. ================
  552. .. automethod:: set_password
  553. .. automethod:: delete
  554. Alternate Constructors
  555. ======================
  556. .. automethod:: from_string
  557. Attributes
  558. ==========
  559. .. attribute:: path
  560. Path to local file that will be used as the default
  561. for all :meth:`load` and :meth:`save` operations.
  562. May be written to, initialized by the *path* constructor keyword.
  563. .. attribute:: autosave
  564. Writeable flag indicating whether changes will be automatically
  565. written to *path*.
  566. Errors
  567. ======
  568. :raises ValueError:
  569. All of the methods in this class will raise a :exc:`ValueError` if
  570. any user name contains a forbidden character (one of ``:\\r\\n\\t\\x00``),
  571. or is longer than 255 characters.
  572. """
  573. #===================================================================
  574. # instance attrs
  575. #===================================================================
  576. # NOTE: _records map stores <user> for the key, and <hash> for the value,
  577. # both in bytes which use self.encoding
  578. #===================================================================
  579. # init & serialization
  580. #===================================================================
  581. def __init__(self, path=None, default_scheme=None, context=htpasswd_context,
  582. **kwds):
  583. if 'default' in kwds:
  584. warn("``default`` is deprecated as of Passlib 1.6, "
  585. "and will be removed in Passlib 1.8, it has been renamed "
  586. "to ``default_scheem``.",
  587. DeprecationWarning, stacklevel=2)
  588. default_scheme = kwds.pop("default")
  589. if default_scheme:
  590. if default_scheme in _warn_no_bcrypt:
  591. warn("HtpasswdFile: no bcrypt backends available, "
  592. "using fallback for default scheme %r" % default_scheme,
  593. exc.PasslibSecurityWarning)
  594. default_scheme = htpasswd_defaults.get(default_scheme, default_scheme)
  595. context = context.copy(default=default_scheme)
  596. self.context = context
  597. super(HtpasswdFile, self).__init__(path, **kwds)
  598. def _parse_record(self, record, lineno):
  599. # NOTE: should return (user, hash) tuple
  600. result = record.rstrip().split(_BCOLON)
  601. if len(result) != 2:
  602. raise ValueError("malformed htpasswd file (error reading line %d)"
  603. % lineno)
  604. return result
  605. def _render_record(self, user, hash):
  606. return render_bytes("%s:%s\n", user, hash)
  607. #===================================================================
  608. # public methods
  609. #===================================================================
  610. def users(self):
  611. """
  612. Return list of all users in database
  613. """
  614. return [self._decode_field(user) for user in self._records]
  615. ##def has_user(self, user):
  616. ## "check whether entry is present for user"
  617. ## return self._encode_user(user) in self._records
  618. ##def rename(self, old, new):
  619. ## """rename user account"""
  620. ## old = self._encode_user(old)
  621. ## new = self._encode_user(new)
  622. ## hash = self._records.pop(old)
  623. ## self._records[new] = hash
  624. ## self._autosave()
  625. def set_password(self, user, password):
  626. """Set password for user; adds user if needed.
  627. :returns:
  628. * ``True`` if existing user was updated.
  629. * ``False`` if user account was added.
  630. .. versionchanged:: 1.6
  631. This method was previously called ``update``, it was renamed
  632. to prevent ambiguity with the dictionary method.
  633. The old alias is deprecated, and will be removed in Passlib 1.8.
  634. """
  635. hash = self.context.hash(password)
  636. return self.set_hash(user, hash)
  637. @deprecated_method(deprecated="1.6", removed="1.8",
  638. replacement="set_password")
  639. def update(self, user, password):
  640. """set password for user"""
  641. return self.set_password(user, password)
  642. def get_hash(self, user):
  643. """Return hash stored for user, or ``None`` if user not found.
  644. .. versionchanged:: 1.6
  645. This method was previously named ``find``, it was renamed
  646. for clarity. The old name is deprecated, and will be removed
  647. in Passlib 1.8.
  648. """
  649. try:
  650. return self._records[self._encode_user(user)]
  651. except KeyError:
  652. return None
  653. def set_hash(self, user, hash):
  654. """
  655. semi-private helper which allows writing a hash directly;
  656. adds user if needed.
  657. .. warning::
  658. does not (currently) do any validation of the hash string
  659. .. versionadded:: 1.7
  660. """
  661. # assert self.context.identify(hash), "unrecognized hash format"
  662. if PY3 and isinstance(hash, str):
  663. hash = hash.encode(self.encoding)
  664. user = self._encode_user(user)
  665. existing = self._set_record(user, hash)
  666. self._autosave()
  667. return existing
  668. @deprecated_method(deprecated="1.6", removed="1.8",
  669. replacement="get_hash")
  670. def find(self, user):
  671. """return hash for user"""
  672. return self.get_hash(user)
  673. # XXX: rename to something more explicit, like delete_user()?
  674. def delete(self, user):
  675. """Delete user's entry.
  676. :returns:
  677. * ``True`` if user deleted.
  678. * ``False`` if user not found.
  679. """
  680. try:
  681. del self._records[self._encode_user(user)]
  682. except KeyError:
  683. return False
  684. self._autosave()
  685. return True
  686. def check_password(self, user, password):
  687. """
  688. Verify password for specified user.
  689. If algorithm marked as deprecated by CryptContext, will automatically be re-hashed.
  690. :returns:
  691. * ``None`` if user not found.
  692. * ``False`` if user found, but password does not match.
  693. * ``True`` if user found and password matches.
  694. .. versionchanged:: 1.6
  695. This method was previously called ``verify``, it was renamed
  696. to prevent ambiguity with the :class:`!CryptContext` method.
  697. The old alias is deprecated, and will be removed in Passlib 1.8.
  698. """
  699. user = self._encode_user(user)
  700. hash = self._records.get(user)
  701. if hash is None:
  702. return None
  703. if isinstance(password, unicode):
  704. # NOTE: encoding password to match file, making the assumption
  705. # that server will use same encoding to hash the password.
  706. password = password.encode(self.encoding)
  707. ok, new_hash = self.context.verify_and_update(password, hash)
  708. if ok and new_hash is not None:
  709. # rehash user's password if old hash was deprecated
  710. assert user in self._records # otherwise would have to use ._set_record()
  711. self._records[user] = new_hash
  712. self._autosave()
  713. return ok
  714. @deprecated_method(deprecated="1.6", removed="1.8",
  715. replacement="check_password")
  716. def verify(self, user, password):
  717. """verify password for user"""
  718. return self.check_password(user, password)
  719. #===================================================================
  720. # eoc
  721. #===================================================================
  722. #=============================================================================
  723. # htdigest editing
  724. #=============================================================================
  725. class HtdigestFile(_CommonFile):
  726. """class for reading & writing Htdigest files.
  727. The class constructor accepts the following arguments:
  728. :type path: filepath
  729. :param path:
  730. Specifies path to htdigest file, use to implicitly load from and save to.
  731. This class has two modes of operation:
  732. 1. It can be "bound" to a local file by passing a ``path`` to the class
  733. constructor. In this case it will load the contents of the file when
  734. created, and the :meth:`load` and :meth:`save` methods will automatically
  735. load from and save to that file if they are called without arguments.
  736. 2. Alternately, it can exist as an independant object, in which case
  737. :meth:`load` and :meth:`save` will require an explicit path to be
  738. provided whenever they are called. As well, ``autosave`` behavior
  739. will not be available.
  740. This feature is new in Passlib 1.6, and is the default if no
  741. ``path`` value is provided to the constructor.
  742. This is also exposed as a readonly instance attribute.
  743. :type default_realm: str
  744. :param default_realm:
  745. If ``default_realm`` is set, all the :class:`HtdigestFile`
  746. methods that require a realm will use this value if one is not
  747. provided explicitly. If unset, they will raise an error stating
  748. that an explicit realm is required.
  749. This is also exposed as a writeable instance attribute.
  750. .. versionadded:: 1.6
  751. :type new: bool
  752. :param new:
  753. Normally, if *path* is specified, :class:`HtdigestFile` will
  754. immediately load the contents of the file. However, when creating
  755. a new htpasswd file, applications can set ``new=True`` so that
  756. the existing file (if any) will not be loaded.
  757. .. versionadded:: 1.6
  758. This feature was previously enabled by setting ``autoload=False``.
  759. That alias has been deprecated, and will be removed in Passlib 1.8
  760. :type autosave: bool
  761. :param autosave:
  762. Normally, any changes made to an :class:`HtdigestFile` instance
  763. will not be saved until :meth:`save` is explicitly called. However,
  764. if ``autosave=True`` is specified, any changes made will be
  765. saved to disk immediately (assuming *path* has been set).
  766. This is also exposed as a writeable instance attribute.
  767. :type encoding: str
  768. :param encoding:
  769. Optionally specify character encoding used to read/write file
  770. and hash passwords. Defaults to ``utf-8``, though ``latin-1``
  771. is the only other commonly encountered encoding.
  772. This is also exposed as a readonly instance attribute.
  773. :param autoload:
  774. Set to ``False`` to prevent the constructor from automatically
  775. loaded the file from disk.
  776. .. deprecated:: 1.6
  777. This has been replaced by the *new* keyword.
  778. Instead of setting ``autoload=False``, you should use
  779. ``new=True``. Support for this keyword will be removed
  780. in Passlib 1.8.
  781. Loading & Saving
  782. ================
  783. .. automethod:: load
  784. .. automethod:: load_if_changed
  785. .. automethod:: load_string
  786. .. automethod:: save
  787. .. automethod:: to_string
  788. Inspection
  789. ==========
  790. .. automethod:: realms
  791. .. automethod:: users
  792. .. automethod:: check_password(user[, realm], password)
  793. .. automethod:: get_hash
  794. Modification
  795. ============
  796. .. automethod:: set_password(user[, realm], password)
  797. .. automethod:: delete
  798. .. automethod:: delete_realm
  799. Alternate Constructors
  800. ======================
  801. .. automethod:: from_string
  802. Attributes
  803. ==========
  804. .. attribute:: default_realm
  805. The default realm that will be used if one is not provided
  806. to methods that require it. By default this is ``None``,
  807. in which case an explicit realm must be provided for every
  808. method call. Can be written to.
  809. .. attribute:: path
  810. Path to local file that will be used as the default
  811. for all :meth:`load` and :meth:`save` operations.
  812. May be written to, initialized by the *path* constructor keyword.
  813. .. attribute:: autosave
  814. Writeable flag indicating whether changes will be automatically
  815. written to *path*.
  816. Errors
  817. ======
  818. :raises ValueError:
  819. All of the methods in this class will raise a :exc:`ValueError` if
  820. any user name or realm contains a forbidden character (one of ``:\\r\\n\\t\\x00``),
  821. or is longer than 255 characters.
  822. """
  823. #===================================================================
  824. # instance attrs
  825. #===================================================================
  826. # NOTE: _records map stores (<user>,<realm>) for the key,
  827. # and <hash> as the value, all as <self.encoding> bytes.
  828. # NOTE: unlike htpasswd, this class doesn't use a CryptContext,
  829. # as only one hash format is supported: htdigest.
  830. # optionally specify default realm that will be used if none
  831. # is provided to a method call. otherwise realm is always required.
  832. default_realm = None
  833. #===================================================================
  834. # init & serialization
  835. #===================================================================
  836. def __init__(self, path=None, default_realm=None, **kwds):
  837. self.default_realm = default_realm
  838. super(HtdigestFile, self).__init__(path, **kwds)
  839. def _parse_record(self, record, lineno):
  840. result = record.rstrip().split(_BCOLON)
  841. if len(result) != 3:
  842. raise ValueError("malformed htdigest file (error reading line %d)"
  843. % lineno)
  844. user, realm, hash = result
  845. return (user, realm), hash
  846. def _render_record(self, key, hash):
  847. user, realm = key
  848. return render_bytes("%s:%s:%s\n", user, realm, hash)
  849. def _require_realm(self, realm):
  850. if realm is None:
  851. realm = self.default_realm
  852. if realm is None:
  853. raise TypeError("you must specify a realm explicitly, "
  854. "or set the default_realm attribute")
  855. return realm
  856. def _encode_realm(self, realm):
  857. realm = self._require_realm(realm)
  858. return self._encode_field(realm, "realm")
  859. def _encode_key(self, user, realm):
  860. return self._encode_user(user), self._encode_realm(realm)
  861. #===================================================================
  862. # public methods
  863. #===================================================================
  864. def realms(self):
  865. """Return list of all realms in database"""
  866. realms = set(key[1] for key in self._records)
  867. return [self._decode_field(realm) for realm in realms]
  868. def users(self, realm=None):
  869. """Return list of all users in specified realm.
  870. * uses ``self.default_realm`` if no realm explicitly provided.
  871. * returns empty list if realm not found.
  872. """
  873. realm = self._encode_realm(realm)
  874. return [self._decode_field(key[0]) for key in self._records
  875. if key[1] == realm]
  876. ##def has_user(self, user, realm=None):
  877. ## "check if user+realm combination exists"
  878. ## return self._encode_key(user,realm) in self._records
  879. ##def rename_realm(self, old, new):
  880. ## """rename all accounts in realm"""
  881. ## old = self._encode_realm(old)
  882. ## new = self._encode_realm(new)
  883. ## keys = [key for key in self._records if key[1] == old]
  884. ## for key in keys:
  885. ## hash = self._records.pop(key)
  886. ## self._set_record((key[0], new), hash)
  887. ## self._autosave()
  888. ## return len(keys)
  889. ##def rename(self, old, new, realm=None):
  890. ## """rename user account"""
  891. ## old = self._encode_user(old)
  892. ## new = self._encode_user(new)
  893. ## realm = self._encode_realm(realm)
  894. ## hash = self._records.pop((old,realm))
  895. ## self._set_record((new, realm), hash)
  896. ## self._autosave()
  897. def set_password(self, user, realm=None, password=_UNSET):
  898. """Set password for user; adds user & realm if needed.
  899. If ``self.default_realm`` has been set, this may be called
  900. with the syntax ``set_password(user, password)``,
  901. otherwise it must be called with all three arguments:
  902. ``set_password(user, realm, password)``.
  903. :returns:
  904. * ``True`` if existing user was updated
  905. * ``False`` if user account added.
  906. """
  907. if password is _UNSET:
  908. # called w/ two args - (user, password), use default realm
  909. realm, password = None, realm
  910. realm = self._require_realm(realm)
  911. hash = htdigest.hash(password, user, realm, encoding=self.encoding)
  912. return self.set_hash(user, realm, hash)
  913. @deprecated_method(deprecated="1.6", removed="1.8",
  914. replacement="set_password")
  915. def update(self, user, realm, password):
  916. """set password for user"""
  917. return self.set_password(user, realm, password)
  918. def get_hash(self, user, realm=None):
  919. """Return :class:`~passlib.hash.htdigest` hash stored for user.
  920. * uses ``self.default_realm`` if no realm explicitly provided.
  921. * returns ``None`` if user or realm not found.
  922. .. versionchanged:: 1.6
  923. This method was previously named ``find``, it was renamed
  924. for clarity. The old name is deprecated, and will be removed
  925. in Passlib 1.8.
  926. """
  927. key = self._encode_key(user, realm)
  928. hash = self._records.get(key)
  929. if hash is None:
  930. return None
  931. if PY3:
  932. hash = hash.decode(self.encoding)
  933. return hash
  934. def set_hash(self, user, realm=None, hash=_UNSET):
  935. """
  936. semi-private helper which allows writing a hash directly;
  937. adds user & realm if needed.
  938. If ``self.default_realm`` has been set, this may be called
  939. with the syntax ``set_hash(user, hash)``,
  940. otherwise it must be called with all three arguments:
  941. ``set_hash(user, realm, hash)``.
  942. .. warning::
  943. does not (currently) do any validation of the hash string
  944. .. versionadded:: 1.7
  945. """
  946. if hash is _UNSET:
  947. # called w/ two args - (user, hash), use default realm
  948. realm, hash = None, realm
  949. # assert htdigest.identify(hash), "unrecognized hash format"
  950. if PY3 and isinstance(hash, str):
  951. hash = hash.encode(self.encoding)
  952. key = self._encode_key(user, realm)
  953. existing = self._set_record(key, hash)
  954. self._autosave()
  955. return existing
  956. @deprecated_method(deprecated="1.6", removed="1.8",
  957. replacement="get_hash")
  958. def find(self, user, realm):
  959. """return hash for user"""
  960. return self.get_hash(user, realm)
  961. # XXX: rename to something more explicit, like delete_user()?
  962. def delete(self, user, realm=None):
  963. """Delete user's entry for specified realm.
  964. if realm is not specified, uses ``self.default_realm``.
  965. :returns:
  966. * ``True`` if user deleted,
  967. * ``False`` if user not found in realm.
  968. """
  969. key = self._encode_key(user, realm)
  970. try:
  971. del self._records[key]
  972. except KeyError:
  973. return False
  974. self._autosave()
  975. return True
  976. def delete_realm(self, realm):
  977. """Delete all users for specified realm.
  978. if realm is not specified, uses ``self.default_realm``.
  979. :returns: number of users deleted (0 if realm not found)
  980. """
  981. realm = self._encode_realm(realm)
  982. records = self._records
  983. keys = [key for key in records if key[1] == realm]
  984. for key in keys:
  985. del records[key]
  986. self._autosave()
  987. return len(keys)
  988. def check_password(self, user, realm=None, password=_UNSET):
  989. """Verify password for specified user + realm.
  990. If ``self.default_realm`` has been set, this may be called
  991. with the syntax ``check_password(user, password)``,
  992. otherwise it must be called with all three arguments:
  993. ``check_password(user, realm, password)``.
  994. :returns:
  995. * ``None`` if user or realm not found.
  996. * ``False`` if user found, but password does not match.
  997. * ``True`` if user found and password matches.
  998. .. versionchanged:: 1.6
  999. This method was previously called ``verify``, it was renamed
  1000. to prevent ambiguity with the :class:`!CryptContext` method.
  1001. The old alias is deprecated, and will be removed in Passlib 1.8.
  1002. """
  1003. if password is _UNSET:
  1004. # called w/ two args - (user, password), use default realm
  1005. realm, password = None, realm
  1006. user = self._encode_user(user)
  1007. realm = self._encode_realm(realm)
  1008. hash = self._records.get((user,realm))
  1009. if hash is None:
  1010. return None
  1011. return htdigest.verify(password, hash, user, realm,
  1012. encoding=self.encoding)
  1013. @deprecated_method(deprecated="1.6", removed="1.8",
  1014. replacement="check_password")
  1015. def verify(self, user, realm, password):
  1016. """verify password for user"""
  1017. return self.check_password(user, realm, password)
  1018. #===================================================================
  1019. # eoc
  1020. #===================================================================
  1021. #=============================================================================
  1022. # eof
  1023. #=============================================================================