You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

2638 lines
107 KiB

  1. """passlib.context - CryptContext implementation"""
  2. #=============================================================================
  3. # imports
  4. #=============================================================================
  5. from __future__ import with_statement
  6. # core
  7. import re
  8. import logging; log = logging.getLogger(__name__)
  9. import threading
  10. import time
  11. from warnings import warn
  12. # site
  13. # pkg
  14. from passlib import exc
  15. from passlib.exc import ExpectedStringError, ExpectedTypeError, PasslibConfigWarning
  16. from passlib.registry import get_crypt_handler, _validate_handler_name
  17. from passlib.utils import (handlers as uh, to_bytes,
  18. to_unicode, splitcomma,
  19. as_bool, timer, rng, getrandstr,
  20. )
  21. from passlib.utils.binary import BASE64_CHARS
  22. from passlib.utils.compat import (iteritems, num_types, irange,
  23. PY2, PY3, unicode, SafeConfigParser,
  24. NativeStringIO, BytesIO,
  25. unicode_or_bytes_types, native_string_types,
  26. )
  27. from passlib.utils.decor import deprecated_method, memoized_property
  28. # local
  29. __all__ = [
  30. 'CryptContext',
  31. 'LazyCryptContext',
  32. 'CryptPolicy',
  33. ]
  34. #=============================================================================
  35. # support
  36. #=============================================================================
  37. # private object to detect unset params
  38. _UNSET = object()
  39. def _coerce_vary_rounds(value):
  40. """parse vary_rounds string to percent as [0,1) float, or integer"""
  41. if value.endswith("%"):
  42. # XXX: deprecate this in favor of raw float?
  43. return float(value.rstrip("%"))*.01
  44. try:
  45. return int(value)
  46. except ValueError:
  47. return float(value)
  48. # set of options which aren't allowed to be set via policy
  49. _forbidden_scheme_options = set(["salt"])
  50. # 'salt' - not allowed since a fixed salt would defeat the purpose.
  51. # dict containing funcs used to coerce strings to correct type for scheme option keys.
  52. # NOTE: this isn't really needed any longer, since Handler.using() handles the actual parsing.
  53. # keeping this around for now, though, since it makes context.to_dict() output cleaner.
  54. _coerce_scheme_options = dict(
  55. min_rounds=int,
  56. max_rounds=int,
  57. default_rounds=int,
  58. vary_rounds=_coerce_vary_rounds,
  59. salt_size=int,
  60. )
  61. def _is_handler_registered(handler):
  62. """detect if handler is registered or a custom handler"""
  63. return get_crypt_handler(handler.name, None) is handler
  64. @staticmethod
  65. def _always_needs_update(hash, secret=None):
  66. """
  67. dummy function patched into handler.needs_update() by _CryptConfig
  68. when hash alg has been deprecated for context.
  69. """
  70. return True
  71. #: list of keys allowed under wildcard "all" scheme w/o a security warning.
  72. _global_settings = set(["truncate_error", "vary_rounds"])
  73. #=============================================================================
  74. # crypt policy
  75. #=============================================================================
  76. _preamble = ("The CryptPolicy class has been deprecated as of "
  77. "Passlib 1.6, and will be removed in Passlib 1.8. ")
  78. class CryptPolicy(object):
  79. """
  80. .. deprecated:: 1.6
  81. This class has been deprecated, and will be removed in Passlib 1.8.
  82. All of its functionality has been rolled into :class:`CryptContext`.
  83. This class previously stored the configuration options for the
  84. CryptContext class. In the interest of interface simplification,
  85. all of this class' functionality has been rolled into the CryptContext
  86. class itself.
  87. The documentation for this class is now focused on documenting how to
  88. migrate to the new api. Additionally, where possible, the deprecation
  89. warnings issued by the CryptPolicy methods will list the replacement call
  90. that should be used.
  91. Constructors
  92. ============
  93. CryptPolicy objects can be constructed directly using any of
  94. the keywords accepted by :class:`CryptContext`. Direct uses of the
  95. :class:`!CryptPolicy` constructor should either pass the keywords
  96. directly into the CryptContext constructor, or to :meth:`CryptContext.update`
  97. if the policy object was being used to update an existing context object.
  98. In addition to passing in keywords directly,
  99. CryptPolicy objects can be constructed by the following methods:
  100. .. automethod:: from_path
  101. .. automethod:: from_string
  102. .. automethod:: from_source
  103. .. automethod:: from_sources
  104. .. automethod:: replace
  105. Introspection
  106. =============
  107. All of the informational methods provided by this class have been deprecated
  108. by identical or similar methods in the :class:`CryptContext` class:
  109. .. automethod:: has_schemes
  110. .. automethod:: schemes
  111. .. automethod:: iter_handlers
  112. .. automethod:: get_handler
  113. .. automethod:: get_options
  114. .. automethod:: handler_is_deprecated
  115. .. automethod:: get_min_verify_time
  116. Exporting
  117. =========
  118. .. automethod:: iter_config
  119. .. automethod:: to_dict
  120. .. automethod:: to_file
  121. .. automethod:: to_string
  122. .. note::
  123. CryptPolicy are immutable.
  124. Use the :meth:`replace` method to mutate existing instances.
  125. .. deprecated:: 1.6
  126. """
  127. #===================================================================
  128. # class methods
  129. #===================================================================
  130. @classmethod
  131. def from_path(cls, path, section="passlib", encoding="utf-8"):
  132. """create a CryptPolicy instance from a local file.
  133. .. deprecated:: 1.6
  134. Creating a new CryptContext from a file, which was previously done via
  135. ``CryptContext(policy=CryptPolicy.from_path(path))``, can now be
  136. done via ``CryptContext.from_path(path)``.
  137. See :meth:`CryptContext.from_path` for details.
  138. Updating an existing CryptContext from a file, which was previously done
  139. ``context.policy = CryptPolicy.from_path(path)``, can now be
  140. done via ``context.load_path(path)``.
  141. See :meth:`CryptContext.load_path` for details.
  142. """
  143. warn(_preamble +
  144. "Instead of ``CryptPolicy.from_path(path)``, "
  145. "use ``CryptContext.from_path(path)`` "
  146. " or ``context.load_path(path)`` for an existing CryptContext.",
  147. DeprecationWarning, stacklevel=2)
  148. return cls(_internal_context=CryptContext.from_path(path, section,
  149. encoding))
  150. @classmethod
  151. def from_string(cls, source, section="passlib", encoding="utf-8"):
  152. """create a CryptPolicy instance from a string.
  153. .. deprecated:: 1.6
  154. Creating a new CryptContext from a string, which was previously done via
  155. ``CryptContext(policy=CryptPolicy.from_string(data))``, can now be
  156. done via ``CryptContext.from_string(data)``.
  157. See :meth:`CryptContext.from_string` for details.
  158. Updating an existing CryptContext from a string, which was previously done
  159. ``context.policy = CryptPolicy.from_string(data)``, can now be
  160. done via ``context.load(data)``.
  161. See :meth:`CryptContext.load` for details.
  162. """
  163. warn(_preamble +
  164. "Instead of ``CryptPolicy.from_string(source)``, "
  165. "use ``CryptContext.from_string(source)`` or "
  166. "``context.load(source)`` for an existing CryptContext.",
  167. DeprecationWarning, stacklevel=2)
  168. return cls(_internal_context=CryptContext.from_string(source, section,
  169. encoding))
  170. @classmethod
  171. def from_source(cls, source, _warn=True):
  172. """create a CryptPolicy instance from some source.
  173. this method autodetects the source type, and invokes
  174. the appropriate constructor automatically. it attempts
  175. to detect whether the source is a configuration string, a filepath,
  176. a dictionary, or an existing CryptPolicy instance.
  177. .. deprecated:: 1.6
  178. Create a new CryptContext, which could previously be done via
  179. ``CryptContext(policy=CryptPolicy.from_source(source))``, should
  180. now be done using an explicit method: the :class:`CryptContext`
  181. constructor itself, :meth:`CryptContext.from_path`,
  182. or :meth:`CryptContext.from_string`.
  183. Updating an existing CryptContext, which could previously be done via
  184. ``context.policy = CryptPolicy.from_source(source)``, should
  185. now be done using an explicit method: :meth:`CryptContext.update`,
  186. or :meth:`CryptContext.load`.
  187. """
  188. if _warn:
  189. warn(_preamble +
  190. "Instead of ``CryptPolicy.from_source()``, "
  191. "use ``CryptContext.from_string(path)`` "
  192. " or ``CryptContext.from_path(source)``, as appropriate.",
  193. DeprecationWarning, stacklevel=2)
  194. if isinstance(source, CryptPolicy):
  195. return source
  196. elif isinstance(source, dict):
  197. return cls(_internal_context=CryptContext(**source))
  198. elif not isinstance(source, (bytes,unicode)):
  199. raise TypeError("source must be CryptPolicy, dict, config string, "
  200. "or file path: %r" % (type(source),))
  201. elif any(c in source for c in "\n\r\t") or not source.strip(" \t./;:"):
  202. return cls(_internal_context=CryptContext.from_string(source))
  203. else:
  204. return cls(_internal_context=CryptContext.from_path(source))
  205. @classmethod
  206. def from_sources(cls, sources, _warn=True):
  207. """create a CryptPolicy instance by merging multiple sources.
  208. each source is interpreted as by :meth:`from_source`,
  209. and the results are merged together.
  210. .. deprecated:: 1.6
  211. Instead of using this method to merge multiple policies together,
  212. a :class:`CryptContext` instance should be created, and then
  213. the multiple sources merged together via :meth:`CryptContext.load`.
  214. """
  215. if _warn:
  216. warn(_preamble +
  217. "Instead of ``CryptPolicy.from_sources()``, "
  218. "use the various CryptContext constructors "
  219. " followed by ``context.update()``.",
  220. DeprecationWarning, stacklevel=2)
  221. if len(sources) == 0:
  222. raise ValueError("no sources specified")
  223. if len(sources) == 1:
  224. return cls.from_source(sources[0], _warn=False)
  225. kwds = {}
  226. for source in sources:
  227. kwds.update(cls.from_source(source, _warn=False)._context.to_dict(resolve=True))
  228. return cls(_internal_context=CryptContext(**kwds))
  229. def replace(self, *args, **kwds):
  230. """create a new CryptPolicy, optionally updating parts of the
  231. existing configuration.
  232. .. deprecated:: 1.6
  233. Callers of this method should :meth:`CryptContext.update` or
  234. :meth:`CryptContext.copy` instead.
  235. """
  236. if self._stub_policy:
  237. warn(_preamble + # pragma: no cover -- deprecated & unused
  238. "Instead of ``context.policy.replace()``, "
  239. "use ``context.update()`` or ``context.copy()``.",
  240. DeprecationWarning, stacklevel=2)
  241. else:
  242. warn(_preamble +
  243. "Instead of ``CryptPolicy().replace()``, "
  244. "create a CryptContext instance and "
  245. "use ``context.update()`` or ``context.copy()``.",
  246. DeprecationWarning, stacklevel=2)
  247. sources = [ self ]
  248. if args:
  249. sources.extend(args)
  250. if kwds:
  251. sources.append(kwds)
  252. return CryptPolicy.from_sources(sources, _warn=False)
  253. #===================================================================
  254. # instance attrs
  255. #===================================================================
  256. # internal CryptContext we're wrapping to handle everything
  257. # until this class is removed.
  258. _context = None
  259. # flag indicating this is wrapper generated by the CryptContext.policy
  260. # attribute, rather than one created independantly by the application.
  261. _stub_policy = False
  262. #===================================================================
  263. # init
  264. #===================================================================
  265. def __init__(self, *args, **kwds):
  266. context = kwds.pop("_internal_context", None)
  267. if context:
  268. assert isinstance(context, CryptContext)
  269. self._context = context
  270. self._stub_policy = kwds.pop("_stub_policy", False)
  271. assert not (args or kwds), "unexpected args: %r %r" % (args,kwds)
  272. else:
  273. if args:
  274. if len(args) != 1:
  275. raise TypeError("only one positional argument accepted")
  276. if kwds:
  277. raise TypeError("cannot specify positional arg and kwds")
  278. kwds = args[0]
  279. warn(_preamble +
  280. "Instead of constructing a CryptPolicy instance, "
  281. "create a CryptContext directly, or use ``context.update()`` "
  282. "and ``context.load()`` to reconfigure existing CryptContext "
  283. "instances.",
  284. DeprecationWarning, stacklevel=2)
  285. self._context = CryptContext(**kwds)
  286. #===================================================================
  287. # public interface for examining options
  288. #===================================================================
  289. def has_schemes(self):
  290. """return True if policy defines *any* schemes for use.
  291. .. deprecated:: 1.6
  292. applications should use ``bool(context.schemes())`` instead.
  293. see :meth:`CryptContext.schemes`.
  294. """
  295. if self._stub_policy:
  296. warn(_preamble + # pragma: no cover -- deprecated & unused
  297. "Instead of ``context.policy.has_schemes()``, "
  298. "use ``bool(context.schemes())``.",
  299. DeprecationWarning, stacklevel=2)
  300. else:
  301. warn(_preamble +
  302. "Instead of ``CryptPolicy().has_schemes()``, "
  303. "create a CryptContext instance and "
  304. "use ``bool(context.schemes())``.",
  305. DeprecationWarning, stacklevel=2)
  306. return bool(self._context.schemes())
  307. def iter_handlers(self):
  308. """return iterator over handlers defined in policy.
  309. .. deprecated:: 1.6
  310. applications should use ``context.schemes(resolve=True))`` instead.
  311. see :meth:`CryptContext.schemes`.
  312. """
  313. if self._stub_policy:
  314. warn(_preamble +
  315. "Instead of ``context.policy.iter_handlers()``, "
  316. "use ``context.schemes(resolve=True)``.",
  317. DeprecationWarning, stacklevel=2)
  318. else:
  319. warn(_preamble +
  320. "Instead of ``CryptPolicy().iter_handlers()``, "
  321. "create a CryptContext instance and "
  322. "use ``context.schemes(resolve=True)``.",
  323. DeprecationWarning, stacklevel=2)
  324. return self._context.schemes(resolve=True, unconfigured=True)
  325. def schemes(self, resolve=False):
  326. """return list of schemes defined in policy.
  327. .. deprecated:: 1.6
  328. applications should use :meth:`CryptContext.schemes` instead.
  329. """
  330. if self._stub_policy:
  331. warn(_preamble + # pragma: no cover -- deprecated & unused
  332. "Instead of ``context.policy.schemes()``, "
  333. "use ``context.schemes()``.",
  334. DeprecationWarning, stacklevel=2)
  335. else:
  336. warn(_preamble +
  337. "Instead of ``CryptPolicy().schemes()``, "
  338. "create a CryptContext instance and "
  339. "use ``context.schemes()``.",
  340. DeprecationWarning, stacklevel=2)
  341. return list(self._context.schemes(resolve=resolve, unconfigured=True))
  342. def get_handler(self, name=None, category=None, required=False):
  343. """return handler as specified by name, or default handler.
  344. .. deprecated:: 1.6
  345. applications should use :meth:`CryptContext.handler` instead,
  346. though note that the ``required`` keyword has been removed,
  347. and the new method will always act as if ``required=True``.
  348. """
  349. if self._stub_policy:
  350. warn(_preamble +
  351. "Instead of ``context.policy.get_handler()``, "
  352. "use ``context.handler()``.",
  353. DeprecationWarning, stacklevel=2)
  354. else:
  355. warn(_preamble +
  356. "Instead of ``CryptPolicy().get_handler()``, "
  357. "create a CryptContext instance and "
  358. "use ``context.handler()``.",
  359. DeprecationWarning, stacklevel=2)
  360. # CryptContext.handler() doesn't support required=False,
  361. # so wrapping it in try/except
  362. try:
  363. return self._context.handler(name, category, unconfigured=True)
  364. except KeyError:
  365. if required:
  366. raise
  367. else:
  368. return None
  369. def get_min_verify_time(self, category=None):
  370. """get min_verify_time setting for policy.
  371. .. deprecated:: 1.6
  372. min_verify_time option will be removed entirely in passlib 1.8
  373. .. versionchanged:: 1.7
  374. this method now always returns the value automatically
  375. calculated by :meth:`CryptContext.min_verify_time`,
  376. any value specified by policy is ignored.
  377. """
  378. warn("get_min_verify_time() and min_verify_time option is deprecated and ignored, "
  379. "and will be removed in Passlib 1.8", DeprecationWarning,
  380. stacklevel=2)
  381. return 0
  382. def get_options(self, name, category=None):
  383. """return dictionary of options specific to a given handler.
  384. .. deprecated:: 1.6
  385. this method has no direct replacement in the 1.6 api, as there
  386. is not a clearly defined use-case. however, examining the output of
  387. :meth:`CryptContext.to_dict` should serve as the closest alternative.
  388. """
  389. # XXX: might make a public replacement, but need more study of the use cases.
  390. if self._stub_policy:
  391. warn(_preamble + # pragma: no cover -- deprecated & unused
  392. "``context.policy.get_options()`` will no longer be available.",
  393. DeprecationWarning, stacklevel=2)
  394. else:
  395. warn(_preamble +
  396. "``CryptPolicy().get_options()`` will no longer be available.",
  397. DeprecationWarning, stacklevel=2)
  398. if hasattr(name, "name"):
  399. name = name.name
  400. return self._context._config._get_record_options_with_flag(name, category)[0]
  401. def handler_is_deprecated(self, name, category=None):
  402. """check if handler has been deprecated by policy.
  403. .. deprecated:: 1.6
  404. this method has no direct replacement in the 1.6 api, as there
  405. is not a clearly defined use-case. however, examining the output of
  406. :meth:`CryptContext.to_dict` should serve as the closest alternative.
  407. """
  408. # XXX: might make a public replacement, but need more study of the use cases.
  409. if self._stub_policy:
  410. warn(_preamble +
  411. "``context.policy.handler_is_deprecated()`` will no longer be available.",
  412. DeprecationWarning, stacklevel=2)
  413. else:
  414. warn(_preamble +
  415. "``CryptPolicy().handler_is_deprecated()`` will no longer be available.",
  416. DeprecationWarning, stacklevel=2)
  417. if hasattr(name, "name"):
  418. name = name.name
  419. return self._context.handler(name, category).deprecated
  420. #===================================================================
  421. # serialization
  422. #===================================================================
  423. def iter_config(self, ini=False, resolve=False):
  424. """iterate over key/value pairs representing the policy object.
  425. .. deprecated:: 1.6
  426. applications should use :meth:`CryptContext.to_dict` instead.
  427. """
  428. if self._stub_policy:
  429. warn(_preamble + # pragma: no cover -- deprecated & unused
  430. "Instead of ``context.policy.iter_config()``, "
  431. "use ``context.to_dict().items()``.",
  432. DeprecationWarning, stacklevel=2)
  433. else:
  434. warn(_preamble +
  435. "Instead of ``CryptPolicy().iter_config()``, "
  436. "create a CryptContext instance and "
  437. "use ``context.to_dict().items()``.",
  438. DeprecationWarning, stacklevel=2)
  439. # hacked code that renders keys & values in manner that approximates
  440. # old behavior. context.to_dict() is much cleaner.
  441. context = self._context
  442. if ini:
  443. def render_key(key):
  444. return context._render_config_key(key).replace("__", ".")
  445. def render_value(value):
  446. if isinstance(value, (list,tuple)):
  447. value = ", ".join(value)
  448. return value
  449. resolve = False
  450. else:
  451. render_key = context._render_config_key
  452. render_value = lambda value: value
  453. return (
  454. (render_key(key), render_value(value))
  455. for key, value in context._config.iter_config(resolve)
  456. )
  457. def to_dict(self, resolve=False):
  458. """export policy object as dictionary of options.
  459. .. deprecated:: 1.6
  460. applications should use :meth:`CryptContext.to_dict` instead.
  461. """
  462. if self._stub_policy:
  463. warn(_preamble +
  464. "Instead of ``context.policy.to_dict()``, "
  465. "use ``context.to_dict()``.",
  466. DeprecationWarning, stacklevel=2)
  467. else:
  468. warn(_preamble +
  469. "Instead of ``CryptPolicy().to_dict()``, "
  470. "create a CryptContext instance and "
  471. "use ``context.to_dict()``.",
  472. DeprecationWarning, stacklevel=2)
  473. return self._context.to_dict(resolve)
  474. def to_file(self, stream, section="passlib"): # pragma: no cover -- deprecated & unused
  475. """export policy to file.
  476. .. deprecated:: 1.6
  477. applications should use :meth:`CryptContext.to_string` instead,
  478. and then write the output to a file as desired.
  479. """
  480. if self._stub_policy:
  481. warn(_preamble +
  482. "Instead of ``context.policy.to_file(stream)``, "
  483. "use ``stream.write(context.to_string())``.",
  484. DeprecationWarning, stacklevel=2)
  485. else:
  486. warn(_preamble +
  487. "Instead of ``CryptPolicy().to_file(stream)``, "
  488. "create a CryptContext instance and "
  489. "use ``stream.write(context.to_string())``.",
  490. DeprecationWarning, stacklevel=2)
  491. out = self._context.to_string(section=section)
  492. if PY2:
  493. out = out.encode("utf-8")
  494. stream.write(out)
  495. def to_string(self, section="passlib", encoding=None):
  496. """export policy to file.
  497. .. deprecated:: 1.6
  498. applications should use :meth:`CryptContext.to_string` instead.
  499. """
  500. if self._stub_policy:
  501. warn(_preamble + # pragma: no cover -- deprecated & unused
  502. "Instead of ``context.policy.to_string()``, "
  503. "use ``context.to_string()``.",
  504. DeprecationWarning, stacklevel=2)
  505. else:
  506. warn(_preamble +
  507. "Instead of ``CryptPolicy().to_string()``, "
  508. "create a CryptContext instance and "
  509. "use ``context.to_string()``.",
  510. DeprecationWarning, stacklevel=2)
  511. out = self._context.to_string(section=section)
  512. if encoding:
  513. out = out.encode(encoding)
  514. return out
  515. #===================================================================
  516. # eoc
  517. #===================================================================
  518. #=============================================================================
  519. # _CryptConfig helper class
  520. #=============================================================================
  521. class _CryptConfig(object):
  522. """parses, validates, and stores CryptContext config
  523. this is a helper used internally by CryptContext to handle
  524. parsing, validation, and serialization of its config options.
  525. split out from the main class, but not made public since
  526. that just complicates interface too much (c.f. CryptPolicy)
  527. :arg source: config as dict mapping ``(cat,scheme,option) -> value``
  528. """
  529. #===================================================================
  530. # instance attrs
  531. #===================================================================
  532. # triple-nested dict which maps scheme -> category -> key -> value,
  533. # storing all hash-specific options
  534. _scheme_options = None
  535. # double-nested dict which maps key -> category -> value
  536. # storing all CryptContext options
  537. _context_options = None
  538. # tuple of handler objects
  539. handlers = None
  540. # tuple of scheme objects in same order as handlers
  541. schemes = None
  542. # tuple of categories in alphabetical order (not including None)
  543. categories = None
  544. # set of all context keywords used by active schemes
  545. context_kwds = None
  546. # dict mapping category -> default scheme
  547. _default_schemes = None
  548. # dict mapping (scheme, category) -> custom handler
  549. _records = None
  550. # dict mapping category -> list of custom handler instances for that category,
  551. # in order of schemes(). populated on demand by _get_record_list()
  552. _record_lists = None
  553. #===================================================================
  554. # constructor
  555. #===================================================================
  556. def __init__(self, source):
  557. self._init_scheme_list(source.get((None,None,"schemes")))
  558. self._init_options(source)
  559. self._init_default_schemes()
  560. self._init_records()
  561. def _init_scheme_list(self, data):
  562. """initialize .handlers and .schemes attributes"""
  563. handlers = []
  564. schemes = []
  565. if isinstance(data, native_string_types):
  566. data = splitcomma(data)
  567. for elem in data or ():
  568. # resolve elem -> handler & scheme
  569. if hasattr(elem, "name"):
  570. handler = elem
  571. scheme = handler.name
  572. _validate_handler_name(scheme)
  573. elif isinstance(elem, native_string_types):
  574. handler = get_crypt_handler(elem)
  575. scheme = handler.name
  576. else:
  577. raise TypeError("scheme must be name or CryptHandler, "
  578. "not %r" % type(elem))
  579. # check scheme name isn't already in use
  580. if scheme in schemes:
  581. raise KeyError("multiple handlers with same name: %r" %
  582. (scheme,))
  583. # add to handler list
  584. handlers.append(handler)
  585. schemes.append(scheme)
  586. self.handlers = tuple(handlers)
  587. self.schemes = tuple(schemes)
  588. #===================================================================
  589. # lowlevel options
  590. #===================================================================
  591. #---------------------------------------------------------------
  592. # init lowlevel option storage
  593. #---------------------------------------------------------------
  594. def _init_options(self, source):
  595. """load config dict into internal representation,
  596. and init .categories attr
  597. """
  598. # prepare dicts & locals
  599. norm_scheme_option = self._norm_scheme_option
  600. norm_context_option = self._norm_context_option
  601. self._scheme_options = scheme_options = {}
  602. self._context_options = context_options = {}
  603. categories = set()
  604. # load source config into internal storage
  605. for (cat, scheme, key), value in iteritems(source):
  606. categories.add(cat)
  607. explicit_scheme = scheme
  608. if not cat and not scheme and key in _global_settings:
  609. # going forward, not using "<cat>__all__<key>" format. instead...
  610. # whitelisting set of keys which should be passed to (all) schemes,
  611. # rather than passed to the CryptContext itself
  612. scheme = "all"
  613. if scheme:
  614. # normalize scheme option
  615. key, value = norm_scheme_option(key, value)
  616. # e.g. things like "min_rounds" should never be set cross-scheme
  617. # this will be fatal under 2.0.
  618. if scheme == "all" and key not in _global_settings:
  619. warn("The '%s' option should be configured per-algorithm, and not set "
  620. "globally in the context; This will be an error in Passlib 2.0" %
  621. (key,), PasslibConfigWarning)
  622. # this scheme is going away in 2.0;
  623. # but most keys deserve an extra warning since it impacts security.
  624. if explicit_scheme == "all":
  625. warn("The 'all' scheme is deprecated as of Passlib 1.7, "
  626. "and will be removed in Passlib 2.0; Please configure "
  627. "options on a per-algorithm basis.", DeprecationWarning)
  628. # store in scheme_options
  629. # map structure: scheme_options[scheme][category][key] = value
  630. try:
  631. category_map = scheme_options[scheme]
  632. except KeyError:
  633. scheme_options[scheme] = {cat: {key: value}}
  634. else:
  635. try:
  636. option_map = category_map[cat]
  637. except KeyError:
  638. category_map[cat] = {key: value}
  639. else:
  640. option_map[key] = value
  641. else:
  642. # normalize context option
  643. if cat and key == "schemes":
  644. raise KeyError("'schemes' context option is not allowed "
  645. "per category")
  646. key, value = norm_context_option(cat, key, value)
  647. if key == "min_verify_time": # ignored in 1.7, to be removed in 1.8
  648. continue
  649. # store in context_options
  650. # map structure: context_options[key][category] = value
  651. try:
  652. category_map = context_options[key]
  653. except KeyError:
  654. context_options[key] = {cat: value}
  655. else:
  656. category_map[cat] = value
  657. # store list of configured categories
  658. categories.discard(None)
  659. self.categories = tuple(sorted(categories))
  660. def _norm_scheme_option(self, key, value):
  661. # check for invalid options
  662. if key in _forbidden_scheme_options:
  663. raise KeyError("%r option not allowed in CryptContext "
  664. "configuration" % (key,))
  665. # coerce strings for certain fields (e.g. min_rounds uses ints)
  666. if isinstance(value, native_string_types):
  667. func = _coerce_scheme_options.get(key)
  668. if func:
  669. value = func(value)
  670. return key, value
  671. def _norm_context_option(self, cat, key, value):
  672. schemes = self.schemes
  673. if key == "default":
  674. if hasattr(value, "name"):
  675. value = value.name
  676. elif not isinstance(value, native_string_types):
  677. raise ExpectedTypeError(value, "str", "default")
  678. if schemes and value not in schemes:
  679. raise KeyError("default scheme not found in policy")
  680. elif key == "deprecated":
  681. if isinstance(value, native_string_types):
  682. value = splitcomma(value)
  683. elif not isinstance(value, (list,tuple)):
  684. raise ExpectedTypeError(value, "str or seq", "deprecated")
  685. if 'auto' in value:
  686. # XXX: have any statements been made about when this is default?
  687. # should do it in 1.8 at latest.
  688. if len(value) > 1:
  689. raise ValueError("cannot list other schemes if "
  690. "``deprecated=['auto']`` is used")
  691. elif schemes:
  692. # make sure list of deprecated schemes is subset of configured schemes
  693. for scheme in value:
  694. if not isinstance(scheme, native_string_types):
  695. raise ExpectedTypeError(value, "str", "deprecated element")
  696. if scheme not in schemes:
  697. raise KeyError("deprecated scheme not found "
  698. "in policy: %r" % (scheme,))
  699. elif key == "min_verify_time":
  700. warn("'min_verify_time' was deprecated in Passlib 1.6, is "
  701. "ignored in 1.7, and will be removed in 1.8",
  702. DeprecationWarning)
  703. elif key == "harden_verify":
  704. warn("'harden_verify' is deprecated & ignored as of Passlib 1.7.1, "
  705. " and will be removed in 1.8",
  706. DeprecationWarning)
  707. elif key != "schemes":
  708. raise KeyError("unknown CryptContext keyword: %r" % (key,))
  709. return key, value
  710. #---------------------------------------------------------------
  711. # reading context options
  712. #---------------------------------------------------------------
  713. def get_context_optionmap(self, key, _default={}):
  714. """return dict mapping category->value for specific context option.
  715. .. warning:: treat return value as readonly!
  716. """
  717. return self._context_options.get(key, _default)
  718. def get_context_option_with_flag(self, category, key):
  719. """return value of specific option, handling category inheritance.
  720. also returns flag indicating whether value is category-specific.
  721. """
  722. try:
  723. category_map = self._context_options[key]
  724. except KeyError:
  725. return None, False
  726. value = category_map.get(None)
  727. if category:
  728. try:
  729. alt = category_map[category]
  730. except KeyError:
  731. pass
  732. else:
  733. if value is None or alt != value:
  734. return alt, True
  735. return value, False
  736. #---------------------------------------------------------------
  737. # reading scheme options
  738. #---------------------------------------------------------------
  739. def _get_scheme_optionmap(self, scheme, category, default={}):
  740. """return all options for (scheme,category) combination
  741. .. warning:: treat return value as readonly!
  742. """
  743. try:
  744. return self._scheme_options[scheme][category]
  745. except KeyError:
  746. return default
  747. def get_base_handler(self, scheme):
  748. return self.handlers[self.schemes.index(scheme)]
  749. @staticmethod
  750. def expand_settings(handler):
  751. setting_kwds = handler.setting_kwds
  752. if 'rounds' in handler.setting_kwds:
  753. # XXX: historically this extras won't be listed in setting_kwds
  754. setting_kwds += uh.HasRounds.using_rounds_kwds
  755. return setting_kwds
  756. # NOTE: this is only used by _get_record_options_with_flag()...
  757. def get_scheme_options_with_flag(self, scheme, category):
  758. """return composite dict of all options set for scheme.
  759. includes options inherited from 'all' and from default category.
  760. result can be modified.
  761. returns (kwds, has_cat_specific_options)
  762. """
  763. # start out with copy of global options
  764. get_optionmap = self._get_scheme_optionmap
  765. kwds = get_optionmap("all", None).copy()
  766. has_cat_options = False
  767. # add in category-specific global options
  768. if category:
  769. defkwds = kwds.copy() # <-- used to detect category-specific options
  770. kwds.update(get_optionmap("all", category))
  771. # filter out global settings not supported by handler
  772. allowed_settings = self.expand_settings(self.get_base_handler(scheme))
  773. for key in set(kwds).difference(allowed_settings):
  774. kwds.pop(key)
  775. if category:
  776. for key in set(defkwds).difference(allowed_settings):
  777. defkwds.pop(key)
  778. # add in default options for scheme
  779. other = get_optionmap(scheme, None)
  780. kwds.update(other)
  781. # load category-specific options for scheme
  782. if category:
  783. defkwds.update(other)
  784. kwds.update(get_optionmap(scheme, category))
  785. # compare default category options to see if there's anything
  786. # category-specific
  787. if kwds != defkwds:
  788. has_cat_options = True
  789. return kwds, has_cat_options
  790. #===================================================================
  791. # deprecated & default schemes
  792. #===================================================================
  793. def _init_default_schemes(self):
  794. """initialize maps containing default scheme for each category.
  795. have to do this after _init_options(), since the default scheme
  796. is affected by the list of deprecated schemes.
  797. """
  798. # init maps & locals
  799. get_optionmap = self.get_context_optionmap
  800. default_map = self._default_schemes = get_optionmap("default").copy()
  801. dep_map = get_optionmap("deprecated")
  802. schemes = self.schemes
  803. if not schemes:
  804. return
  805. # figure out default scheme
  806. deps = dep_map.get(None) or ()
  807. default = default_map.get(None)
  808. if not default:
  809. for scheme in schemes:
  810. if scheme not in deps:
  811. default_map[None] = scheme
  812. break
  813. else:
  814. raise ValueError("must have at least one non-deprecated scheme")
  815. elif default in deps:
  816. raise ValueError("default scheme cannot be deprecated")
  817. # figure out per-category default schemes,
  818. for cat in self.categories:
  819. cdeps = dep_map.get(cat, deps)
  820. cdefault = default_map.get(cat, default)
  821. if not cdefault:
  822. for scheme in schemes:
  823. if scheme not in cdeps:
  824. default_map[cat] = scheme
  825. break
  826. else:
  827. raise ValueError("must have at least one non-deprecated "
  828. "scheme for %r category" % cat)
  829. elif cdefault in cdeps:
  830. raise ValueError("default scheme for %r category "
  831. "cannot be deprecated" % cat)
  832. def default_scheme(self, category):
  833. """return default scheme for specific category"""
  834. defaults = self._default_schemes
  835. try:
  836. return defaults[category]
  837. except KeyError:
  838. pass
  839. if not self.schemes:
  840. raise KeyError("no hash schemes configured for this "
  841. "CryptContext instance")
  842. return defaults[None]
  843. def is_deprecated_with_flag(self, scheme, category):
  844. """is scheme deprecated under particular category?"""
  845. depmap = self.get_context_optionmap("deprecated")
  846. def test(cat):
  847. source = depmap.get(cat, depmap.get(None))
  848. if source is None:
  849. return None
  850. elif 'auto' in source:
  851. return scheme != self.default_scheme(cat)
  852. else:
  853. return scheme in source
  854. value = test(None) or False
  855. if category:
  856. alt = test(category)
  857. if alt is not None and value != alt:
  858. return alt, True
  859. return value, False
  860. #===================================================================
  861. # CryptRecord objects
  862. #===================================================================
  863. def _init_records(self):
  864. # NOTE: this step handles final validation of settings,
  865. # checking for violations against handler's internal invariants.
  866. # this is why we create all the records now,
  867. # so CryptContext throws error immediately rather than later.
  868. self._record_lists = {}
  869. records = self._records = {}
  870. all_context_kwds = self.context_kwds = set()
  871. get_options = self._get_record_options_with_flag
  872. categories = (None,) + self.categories
  873. for handler in self.handlers:
  874. scheme = handler.name
  875. all_context_kwds.update(handler.context_kwds)
  876. for cat in categories:
  877. kwds, has_cat_options = get_options(scheme, cat)
  878. if cat is None or has_cat_options:
  879. records[scheme, cat] = self._create_record(handler, cat, **kwds)
  880. # NOTE: if handler has no category-specific opts, get_record()
  881. # will automatically use the default category's record.
  882. # NOTE: default records for specific category stored under the
  883. # key (None,category); these are populated on-demand by get_record().
  884. @staticmethod
  885. def _create_record(handler, category=None, deprecated=False, **settings):
  886. # create custom handler if needed.
  887. try:
  888. # XXX: relaxed=True is mostly here to retain backwards-compat behavior.
  889. # could make this optional flag in future.
  890. subcls = handler.using(relaxed=True, **settings)
  891. except TypeError as err:
  892. m = re.match(r".* unexpected keyword argument '(.*)'$", str(err))
  893. if m and m.group(1) in settings:
  894. # translate into KeyError, for backwards compat.
  895. # XXX: push this down to GenericHandler.using() implementation?
  896. key = m.group(1)
  897. raise KeyError("keyword not supported by %s handler: %r" %
  898. (handler.name, key))
  899. raise
  900. # using private attrs to store some extra metadata in custom handler
  901. assert subcls is not handler, "expected unique variant of handler"
  902. ##subcls._Context__category = category
  903. subcls._Context__orig_handler = handler
  904. subcls.deprecated = deprecated # attr reserved for this purpose
  905. return subcls
  906. def _get_record_options_with_flag(self, scheme, category):
  907. """return composite dict of options for given scheme + category.
  908. this is currently a private method, though some variant
  909. of its output may eventually be made public.
  910. given a scheme & category, it returns two things:
  911. a set of all the keyword options to pass to :meth:`_create_record`,
  912. and a bool flag indicating whether any of these options
  913. were specific to the named category. if this flag is false,
  914. the options are identical to the options for the default category.
  915. the options dict includes all the scheme-specific settings,
  916. as well as optional *deprecated* keyword.
  917. """
  918. # get scheme options
  919. kwds, has_cat_options = self.get_scheme_options_with_flag(scheme, category)
  920. # throw in deprecated flag
  921. value, not_inherited = self.is_deprecated_with_flag(scheme, category)
  922. if value:
  923. kwds['deprecated'] = True
  924. if not_inherited:
  925. has_cat_options = True
  926. return kwds, has_cat_options
  927. def get_record(self, scheme, category):
  928. """return record for specific scheme & category (cached)"""
  929. # NOTE: this is part of the critical path shared by
  930. # all of CryptContext's PasswordHash methods,
  931. # hence all the caching and error checking.
  932. # quick lookup in cache
  933. try:
  934. return self._records[scheme, category]
  935. except KeyError:
  936. pass
  937. # type check
  938. if category is not None and not isinstance(category, native_string_types):
  939. if PY2 and isinstance(category, unicode):
  940. # for compatibility with unicode-centric py2 apps
  941. return self.get_record(scheme, category.encode("utf-8"))
  942. raise ExpectedTypeError(category, "str or None", "category")
  943. if scheme is not None and not isinstance(scheme, native_string_types):
  944. raise ExpectedTypeError(scheme, "str or None", "scheme")
  945. # if scheme=None,
  946. # use record for category's default scheme, and cache result.
  947. if not scheme:
  948. default = self.default_scheme(category)
  949. assert default
  950. record = self._records[None, category] = self.get_record(default,
  951. category)
  952. return record
  953. # if no record for (scheme, category),
  954. # use record for (scheme, None), and cache result.
  955. if category:
  956. try:
  957. cache = self._records
  958. record = cache[scheme, category] = cache[scheme, None]
  959. return record
  960. except KeyError:
  961. pass
  962. # scheme not found in configuration for default category
  963. raise KeyError("crypt algorithm not found in policy: %r" % (scheme,))
  964. def _get_record_list(self, category=None):
  965. """return list of records for category (cached)
  966. this is an internal helper used only by identify_record()
  967. """
  968. # type check of category - handled by _get_record()
  969. # quick lookup in cache
  970. try:
  971. return self._record_lists[category]
  972. except KeyError:
  973. pass
  974. # cache miss - build list from scratch
  975. value = self._record_lists[category] = [
  976. self.get_record(scheme, category)
  977. for scheme in self.schemes
  978. ]
  979. return value
  980. def identify_record(self, hash, category, required=True):
  981. """internal helper to identify appropriate custom handler for hash"""
  982. # NOTE: this is part of the critical path shared by
  983. # all of CryptContext's PasswordHash methods,
  984. # hence all the caching and error checking.
  985. # FIXME: if multiple hashes could match (e.g. lmhash vs nthash)
  986. # this will only return first match. might want to do something
  987. # about this in future, but for now only hashes with
  988. # unique identifiers will work properly in a CryptContext.
  989. # XXX: if all handlers have a unique prefix (e.g. all are MCF / LDAP),
  990. # could use dict-lookup to speed up this search.
  991. if not isinstance(hash, unicode_or_bytes_types):
  992. raise ExpectedStringError(hash, "hash")
  993. # type check of category - handled by _get_record_list()
  994. for record in self._get_record_list(category):
  995. if record.identify(hash):
  996. return record
  997. if not required:
  998. return None
  999. elif not self.schemes:
  1000. raise KeyError("no crypt algorithms supported")
  1001. else:
  1002. raise exc.UnknownHashError("hash could not be identified")
  1003. @memoized_property
  1004. def disabled_record(self):
  1005. for record in self._get_record_list(None):
  1006. if record.is_disabled:
  1007. return record
  1008. raise RuntimeError("no disabled hasher present "
  1009. "(perhaps add 'unix_disabled' to list of schemes?)")
  1010. #===================================================================
  1011. # serialization
  1012. #===================================================================
  1013. def iter_config(self, resolve=False):
  1014. """regenerate original config.
  1015. this is an iterator which yields ``(cat,scheme,option),value`` items,
  1016. in the order they generally appear inside an INI file.
  1017. if interpreted as a dictionary, it should match the original
  1018. keywords passed to the CryptContext (aside from any canonization).
  1019. it's mainly used as the internal backend for most of the public
  1020. serialization methods.
  1021. """
  1022. # grab various bits of data
  1023. scheme_options = self._scheme_options
  1024. context_options = self._context_options
  1025. scheme_keys = sorted(scheme_options)
  1026. context_keys = sorted(context_options)
  1027. # write loaded schemes (may differ from 'schemes' local var)
  1028. if 'schemes' in context_keys:
  1029. context_keys.remove("schemes")
  1030. value = self.handlers if resolve else self.schemes
  1031. if value:
  1032. yield (None, None, "schemes"), list(value)
  1033. # then run through config for each user category
  1034. for cat in (None,) + self.categories:
  1035. # write context options
  1036. for key in context_keys:
  1037. try:
  1038. value = context_options[key][cat]
  1039. except KeyError:
  1040. pass
  1041. else:
  1042. if isinstance(value, list):
  1043. value = list(value)
  1044. yield (cat, None, key), value
  1045. # write per-scheme options for all schemes.
  1046. for scheme in scheme_keys:
  1047. try:
  1048. kwds = scheme_options[scheme][cat]
  1049. except KeyError:
  1050. pass
  1051. else:
  1052. for key in sorted(kwds):
  1053. yield (cat, scheme, key), kwds[key]
  1054. #===================================================================
  1055. # eoc
  1056. #===================================================================
  1057. #=============================================================================
  1058. # main CryptContext class
  1059. #=============================================================================
  1060. class CryptContext(object):
  1061. """Helper for hashing & verifying passwords using multiple algorithms.
  1062. Instances of this class allow applications to choose a specific
  1063. set of hash algorithms which they wish to support, set limits and defaults
  1064. for the rounds and salt sizes those algorithms should use, flag
  1065. which algorithms should be deprecated, and automatically handle
  1066. migrating users to stronger hashes when they log in.
  1067. Basic usage::
  1068. >>> ctx = CryptContext(schemes=[...])
  1069. See the Passlib online documentation for details and full documentation.
  1070. """
  1071. # FIXME: altering the configuration of this object isn't threadsafe,
  1072. # but is generally only done during application init, so not a major
  1073. # issue (just yet).
  1074. # XXX: would like some way to restrict the categories that are allowed,
  1075. # to restrict what the app OR the config can use.
  1076. # XXX: add wrap/unwrap callback hooks so app can mutate hash format?
  1077. # XXX: add method for detecting and warning user about schemes
  1078. # which don't have any good distinguishing marks?
  1079. # or greedy ones (unix_disabled, plaintext) which are not listed at the end?
  1080. #===================================================================
  1081. # instance attrs
  1082. #===================================================================
  1083. # _CryptConfig instance holding current parsed config
  1084. _config = None
  1085. # copy of _config methods, stored in CryptContext instance for speed.
  1086. _get_record = None
  1087. _identify_record = None
  1088. #===================================================================
  1089. # secondary constructors
  1090. #===================================================================
  1091. @classmethod
  1092. def _norm_source(cls, source):
  1093. """internal helper - accepts string, dict, or context"""
  1094. if isinstance(source, dict):
  1095. return cls(**source)
  1096. elif isinstance(source, cls):
  1097. return source
  1098. else:
  1099. self = cls()
  1100. self.load(source)
  1101. return self
  1102. @classmethod
  1103. def from_string(cls, source, section="passlib", encoding="utf-8"):
  1104. """create new CryptContext instance from an INI-formatted string.
  1105. :type source: unicode or bytes
  1106. :arg source:
  1107. string containing INI-formatted content.
  1108. :type section: str
  1109. :param section:
  1110. option name of section to read from, defaults to ``"passlib"``.
  1111. :type encoding: str
  1112. :arg encoding:
  1113. optional encoding used when source is bytes, defaults to ``"utf-8"``.
  1114. :returns:
  1115. new :class:`CryptContext` instance, configured based on the
  1116. parameters in the *source* string.
  1117. Usage example::
  1118. >>> from passlib.context import CryptContext
  1119. >>> context = CryptContext.from_string('''
  1120. ... [passlib]
  1121. ... schemes = sha256_crypt, des_crypt
  1122. ... sha256_crypt__default_rounds = 30000
  1123. ... ''')
  1124. .. versionadded:: 1.6
  1125. .. seealso:: :meth:`to_string`, the inverse of this constructor.
  1126. """
  1127. if not isinstance(source, unicode_or_bytes_types):
  1128. raise ExpectedTypeError(source, "unicode or bytes", "source")
  1129. self = cls(_autoload=False)
  1130. self.load(source, section=section, encoding=encoding)
  1131. return self
  1132. @classmethod
  1133. def from_path(cls, path, section="passlib", encoding="utf-8"):
  1134. """create new CryptContext instance from an INI-formatted file.
  1135. this functions exactly the same as :meth:`from_string`,
  1136. except that it loads from a local file.
  1137. :type path: str
  1138. :arg path:
  1139. path to local file containing INI-formatted config.
  1140. :type section: str
  1141. :param section:
  1142. option name of section to read from, defaults to ``"passlib"``.
  1143. :type encoding: str
  1144. :arg encoding:
  1145. encoding used to load file, defaults to ``"utf-8"``.
  1146. :returns:
  1147. new CryptContext instance, configured based on the parameters
  1148. stored in the file *path*.
  1149. .. versionadded:: 1.6
  1150. .. seealso:: :meth:`from_string` for an equivalent usage example.
  1151. """
  1152. self = cls(_autoload=False)
  1153. self.load_path(path, section=section, encoding=encoding)
  1154. return self
  1155. def copy(self, **kwds):
  1156. """Return copy of existing CryptContext instance.
  1157. This function returns a new CryptContext instance whose configuration
  1158. is exactly the same as the original, with the exception that any keywords
  1159. passed in will take precedence over the original settings.
  1160. As an example::
  1161. >>> from passlib.context import CryptContext
  1162. >>> # given an existing context...
  1163. >>> ctx1 = CryptContext(["sha256_crypt", "md5_crypt"])
  1164. >>> # copy can be used to make a clone, and update
  1165. >>> # some of the settings at the same time...
  1166. >>> ctx2 = custom_app_context.copy(default="md5_crypt")
  1167. >>> # and the original will be unaffected by the change
  1168. >>> ctx1.default_scheme()
  1169. "sha256_crypt"
  1170. >>> ctx2.default_scheme()
  1171. "md5_crypt"
  1172. .. versionadded:: 1.6
  1173. This method was previously named :meth:`!replace`. That alias
  1174. has been deprecated, and will be removed in Passlib 1.8.
  1175. .. seealso:: :meth:`update`
  1176. """
  1177. # XXX: it would be faster to store ref to self._config,
  1178. # but don't want to share config objects til sure
  1179. # can rely on them being immutable.
  1180. other = CryptContext(_autoload=False)
  1181. other.load(self)
  1182. if kwds:
  1183. other.load(kwds, update=True)
  1184. return other
  1185. def using(self, **kwds):
  1186. """
  1187. alias for :meth:`copy`, to match PasswordHash.using()
  1188. """
  1189. return self.copy(**kwds)
  1190. def replace(self, **kwds):
  1191. """deprecated alias of :meth:`copy`"""
  1192. warn("CryptContext().replace() has been deprecated in Passlib 1.6, "
  1193. "and will be removed in Passlib 1.8, "
  1194. "it has been renamed to CryptContext().copy()",
  1195. DeprecationWarning, stacklevel=2)
  1196. return self.copy(**kwds)
  1197. #===================================================================
  1198. # init
  1199. #===================================================================
  1200. def __init__(self, schemes=None,
  1201. # keyword only...
  1202. policy=_UNSET, # <-- deprecated
  1203. _autoload=True, **kwds):
  1204. # XXX: add ability to make flag certain contexts as immutable,
  1205. # e.g. the builtin passlib ones?
  1206. # XXX: add a name or import path for the contexts, to help out repr?
  1207. if schemes is not None:
  1208. kwds['schemes'] = schemes
  1209. if policy is not _UNSET:
  1210. warn("The CryptContext ``policy`` keyword has been deprecated as of Passlib 1.6, "
  1211. "and will be removed in Passlib 1.8; please use "
  1212. "``CryptContext.from_string()` or "
  1213. "``CryptContext.from_path()`` instead.",
  1214. DeprecationWarning)
  1215. if policy is None:
  1216. self.load(kwds)
  1217. elif isinstance(policy, CryptPolicy):
  1218. self.load(policy._context)
  1219. self.update(kwds)
  1220. else:
  1221. raise TypeError("policy must be a CryptPolicy instance")
  1222. elif _autoload:
  1223. self.load(kwds)
  1224. else:
  1225. assert not kwds, "_autoload=False and kwds are mutually exclusive"
  1226. # XXX: would this be useful?
  1227. ##def __str__(self):
  1228. ## if PY3:
  1229. ## return self.to_string()
  1230. ## else:
  1231. ## return self.to_string().encode("utf-8")
  1232. def __repr__(self):
  1233. return "<CryptContext at 0x%0x>" % id(self)
  1234. #===================================================================
  1235. # deprecated policy object
  1236. #===================================================================
  1237. def _get_policy(self):
  1238. # The CryptPolicy class has been deprecated, so to support any
  1239. # legacy accesses, we create a stub policy object so .policy attr
  1240. # will continue to work.
  1241. #
  1242. # the code waits until app accesses a specific policy object attribute
  1243. # before issuing deprecation warning, so developer gets method-specific
  1244. # suggestion for how to upgrade.
  1245. # NOTE: making a copy of the context so the policy acts like a snapshot,
  1246. # to retain the pre-1.6 behavior.
  1247. return CryptPolicy(_internal_context=self.copy(), _stub_policy=True)
  1248. def _set_policy(self, policy):
  1249. warn("The CryptPolicy class and the ``context.policy`` attribute have "
  1250. "been deprecated as of Passlib 1.6, and will be removed in "
  1251. "Passlib 1.8; please use the ``context.load()`` and "
  1252. "``context.update()`` methods instead.",
  1253. DeprecationWarning, stacklevel=2)
  1254. if isinstance(policy, CryptPolicy):
  1255. self.load(policy._context)
  1256. else:
  1257. raise TypeError("expected CryptPolicy instance")
  1258. policy = property(_get_policy, _set_policy,
  1259. doc="[deprecated] returns CryptPolicy instance "
  1260. "tied to this CryptContext")
  1261. #===================================================================
  1262. # loading / updating configuration
  1263. #===================================================================
  1264. @staticmethod
  1265. def _parse_ini_stream(stream, section, filename):
  1266. """helper read INI from stream, extract passlib section as dict"""
  1267. # NOTE: this expects a unicode stream under py3,
  1268. # and a utf-8 bytes stream under py2,
  1269. # allowing the resulting dict to always use native strings.
  1270. p = SafeConfigParser()
  1271. if PY3:
  1272. # python 3.2 deprecated readfp in favor of read_file
  1273. p.read_file(stream, filename)
  1274. else:
  1275. p.readfp(stream, filename)
  1276. # XXX: could change load() to accept list of items,
  1277. # and skip intermediate dict creation
  1278. return dict(p.items(section))
  1279. def load_path(self, path, update=False, section="passlib", encoding="utf-8"):
  1280. """Load new configuration into CryptContext from a local file.
  1281. This function is a wrapper for :meth:`load` which
  1282. loads a configuration string from the local file *path*,
  1283. instead of an in-memory source. Its behavior and options
  1284. are otherwise identical to :meth:`!load` when provided with
  1285. an INI-formatted string.
  1286. .. versionadded:: 1.6
  1287. """
  1288. def helper(stream):
  1289. kwds = self._parse_ini_stream(stream, section, path)
  1290. return self.load(kwds, update=update)
  1291. if PY3:
  1292. # decode to unicode, which load() expected under py3
  1293. with open(path, "rt", encoding=encoding) as stream:
  1294. return helper(stream)
  1295. elif encoding in ["utf-8", "ascii"]:
  1296. # keep as utf-8 bytes, which load() expects under py2
  1297. with open(path, "rb") as stream:
  1298. return helper(stream)
  1299. else:
  1300. # transcode to utf-8 bytes
  1301. with open(path, "rb") as fh:
  1302. tmp = fh.read().decode(encoding).encode("utf-8")
  1303. return helper(BytesIO(tmp))
  1304. def load(self, source, update=False, section="passlib", encoding="utf-8"):
  1305. """Load new configuration into CryptContext, replacing existing config.
  1306. :arg source:
  1307. source of new configuration to load.
  1308. this value can be a number of different types:
  1309. * a :class:`!dict` object, or compatible Mapping
  1310. the key/value pairs will be interpreted the same
  1311. keywords for the :class:`CryptContext` class constructor.
  1312. * a :class:`!unicode` or :class:`!bytes` string
  1313. this will be interpreted as an INI-formatted file,
  1314. and appropriate key/value pairs will be loaded from
  1315. the specified *section*.
  1316. * another :class:`!CryptContext` object.
  1317. this will export a snapshot of its configuration
  1318. using :meth:`to_dict`.
  1319. :type update: bool
  1320. :param update:
  1321. By default, :meth:`load` will replace the existing configuration
  1322. entirely. If ``update=True``, it will preserve any existing
  1323. configuration options that are not overridden by the new source,
  1324. much like the :meth:`update` method.
  1325. :type section: str
  1326. :param section:
  1327. When parsing an INI-formatted string, :meth:`load` will look for
  1328. a section named ``"passlib"``. This option allows an alternate
  1329. section name to be used. Ignored when loading from a dictionary.
  1330. :type encoding: str
  1331. :param encoding:
  1332. Encoding to use when **source** is bytes.
  1333. Defaults to ``"utf-8"``. Ignored when loading from a dictionary.
  1334. .. deprecated:: 1.8
  1335. This keyword, and support for bytes input, will be dropped in Passlib 2.0
  1336. :raises TypeError:
  1337. * If the source cannot be identified.
  1338. * If an unknown / malformed keyword is encountered.
  1339. :raises ValueError:
  1340. If an invalid keyword value is encountered.
  1341. .. note::
  1342. If an error occurs during a :meth:`!load` call, the :class:`!CryptContext`
  1343. instance will be restored to the configuration it was in before
  1344. the :meth:`!load` call was made; this is to ensure it is
  1345. *never* left in an inconsistent state due to a load error.
  1346. .. versionadded:: 1.6
  1347. """
  1348. #-----------------------------------------------------------
  1349. # autodetect source type, convert to dict
  1350. #-----------------------------------------------------------
  1351. parse_keys = True
  1352. if isinstance(source, unicode_or_bytes_types):
  1353. if PY3:
  1354. source = to_unicode(source, encoding, param="source")
  1355. else:
  1356. source = to_bytes(source, "utf-8", source_encoding=encoding,
  1357. param="source")
  1358. source = self._parse_ini_stream(NativeStringIO(source), section,
  1359. "<string passed to CryptContext.load()>")
  1360. elif isinstance(source, CryptContext):
  1361. # extract dict directly from config, so it can be merged later
  1362. source = dict(source._config.iter_config(resolve=True))
  1363. parse_keys = False
  1364. elif not hasattr(source, "items"):
  1365. # mappings are left alone, otherwise throw an error.
  1366. raise ExpectedTypeError(source, "string or dict", "source")
  1367. # XXX: add support for other iterable types, e.g. sequence of pairs?
  1368. #-----------------------------------------------------------
  1369. # parse dict keys into (category, scheme, option) format,
  1370. # and merge with existing configuration if needed.
  1371. #-----------------------------------------------------------
  1372. if parse_keys:
  1373. parse = self._parse_config_key
  1374. source = dict((parse(key), value)
  1375. for key, value in iteritems(source))
  1376. if update and self._config is not None:
  1377. # if updating, do nothing if source is empty,
  1378. if not source:
  1379. return
  1380. # otherwise overlay source on top of existing config
  1381. tmp = source
  1382. source = dict(self._config.iter_config(resolve=True))
  1383. source.update(tmp)
  1384. #-----------------------------------------------------------
  1385. # compile into _CryptConfig instance, and update state
  1386. #-----------------------------------------------------------
  1387. config = _CryptConfig(source)
  1388. self._config = config
  1389. self._reset_dummy_verify()
  1390. self._get_record = config.get_record
  1391. self._identify_record = config.identify_record
  1392. if config.context_kwds:
  1393. # (re-)enable method for this instance (in case ELSE clause below ran last load).
  1394. self.__dict__.pop("_strip_unused_context_kwds", None)
  1395. else:
  1396. # disable method for this instance, it's not needed.
  1397. self._strip_unused_context_kwds = None
  1398. @staticmethod
  1399. def _parse_config_key(ckey):
  1400. """helper used to parse ``cat__scheme__option`` keys into a tuple"""
  1401. # split string into 1-3 parts
  1402. assert isinstance(ckey, native_string_types)
  1403. parts = ckey.replace(".", "__").split("__")
  1404. count = len(parts)
  1405. if count == 1:
  1406. cat, scheme, key = None, None, parts[0]
  1407. elif count == 2:
  1408. cat = None
  1409. scheme, key = parts
  1410. elif count == 3:
  1411. cat, scheme, key = parts
  1412. else:
  1413. raise TypeError("keys must have less than 3 separators: %r" %
  1414. (ckey,))
  1415. # validate & normalize the parts
  1416. if cat == "default":
  1417. cat = None
  1418. elif not cat and cat is not None:
  1419. raise TypeError("empty category: %r" % ckey)
  1420. if scheme == "context":
  1421. scheme = None
  1422. elif not scheme and scheme is not None:
  1423. raise TypeError("empty scheme: %r" % ckey)
  1424. if not key:
  1425. raise TypeError("empty option: %r" % ckey)
  1426. return cat, scheme, key
  1427. def update(self, *args, **kwds):
  1428. """Helper for quickly changing configuration.
  1429. This acts much like the :meth:`!dict.update` method:
  1430. it updates the context's configuration,
  1431. replacing the original value(s) for the specified keys,
  1432. and preserving the rest.
  1433. It accepts any :ref:`keyword <context-options>`
  1434. accepted by the :class:`!CryptContext` constructor.
  1435. .. versionadded:: 1.6
  1436. .. seealso:: :meth:`copy`
  1437. """
  1438. if args:
  1439. if len(args) > 1:
  1440. raise TypeError("expected at most one positional argument")
  1441. if kwds:
  1442. raise TypeError("positional arg and keywords mutually exclusive")
  1443. self.load(args[0], update=True)
  1444. elif kwds:
  1445. self.load(kwds, update=True)
  1446. # XXX: make this public? even just as flag to load?
  1447. # FIXME: this function suffered some bitrot in 1.6.1,
  1448. # will need to be updated before works again.
  1449. ##def _simplify(self):
  1450. ## "helper to remove redundant/unused options"
  1451. ## # don't do anything if no schemes are defined
  1452. ## if not self._schemes:
  1453. ## return
  1454. ##
  1455. ## def strip_items(target, filter):
  1456. ## keys = [key for key,value in iteritems(target)
  1457. ## if filter(key,value)]
  1458. ## for key in keys:
  1459. ## del target[key]
  1460. ##
  1461. ## # remove redundant default.
  1462. ## defaults = self._default_schemes
  1463. ## if defaults.get(None) == self._schemes[0]:
  1464. ## del defaults[None]
  1465. ##
  1466. ## # remove options for unused schemes.
  1467. ## scheme_options = self._scheme_options
  1468. ## schemes = self._schemes + ("all",)
  1469. ## strip_items(scheme_options, lambda k,v: k not in schemes)
  1470. ##
  1471. ## # remove rendundant cat defaults.
  1472. ## cur = self.default_scheme()
  1473. ## strip_items(defaults, lambda k,v: k and v==cur)
  1474. ##
  1475. ## # remove redundant category deprecations.
  1476. ## # TODO: this should work w/ 'auto', but needs closer inspection
  1477. ## deprecated = self._deprecated_schemes
  1478. ## cur = self._deprecated_schemes.get(None)
  1479. ## strip_items(deprecated, lambda k,v: k and v==cur)
  1480. ##
  1481. ## # remove redundant category options.
  1482. ## for scheme, config in iteritems(scheme_options):
  1483. ## if None in config:
  1484. ## cur = config[None]
  1485. ## strip_items(config, lambda k,v: k and v==cur)
  1486. ##
  1487. ## # XXX: anything else?
  1488. #===================================================================
  1489. # reading configuration
  1490. #===================================================================
  1491. def schemes(self, resolve=False, category=None, unconfigured=False):
  1492. """return schemes loaded into this CryptContext instance.
  1493. :type resolve: bool
  1494. :arg resolve:
  1495. if ``True``, will return a tuple of :class:`~passlib.ifc.PasswordHash`
  1496. objects instead of their names.
  1497. :returns:
  1498. returns tuple of the schemes configured for this context
  1499. via the *schemes* option.
  1500. .. versionadded:: 1.6
  1501. This was previously available as ``CryptContext().policy.schemes()``
  1502. .. seealso:: the :ref:`schemes <context-schemes-option>` option for usage example.
  1503. """
  1504. # XXX: should resolv return records rather than handlers?
  1505. # or deprecate resolve keyword completely?
  1506. # offering up a .hashers Mapping in v1.8 would be great.
  1507. # NOTE: supporting 'category' and 'unconfigured' kwds as of 1.7
  1508. # just to pass through to .handler(), but not documenting them...
  1509. # may not need to put them to use.
  1510. schemes = self._config.schemes
  1511. if resolve:
  1512. return tuple(self.handler(scheme, category, unconfigured=unconfigured)
  1513. for scheme in schemes)
  1514. else:
  1515. return schemes
  1516. def default_scheme(self, category=None, resolve=False, unconfigured=False):
  1517. """return name of scheme that :meth:`hash` will use by default.
  1518. :type resolve: bool
  1519. :arg resolve:
  1520. if ``True``, will return a :class:`~passlib.ifc.PasswordHash`
  1521. object instead of the name.
  1522. :type category: str or None
  1523. :param category:
  1524. Optional :ref:`user category <user-categories>`.
  1525. If specified, this will return the catgory-specific default scheme instead.
  1526. :returns:
  1527. name of the default scheme.
  1528. .. seealso:: the :ref:`default <context-default-option>` option for usage example.
  1529. .. versionadded:: 1.6
  1530. .. versionchanged:: 1.7
  1531. This now returns a hasher configured with any CryptContext-specific
  1532. options (custom rounds settings, etc). Previously this returned
  1533. the base hasher from :mod:`passlib.hash`.
  1534. """
  1535. # XXX: deprecate this in favor of .handler() or whatever it's replaced with?
  1536. # NOTE: supporting 'unconfigured' kwds as of 1.7
  1537. # just to pass through to .handler(), but not documenting them...
  1538. # may not need to put them to use.
  1539. hasher = self.handler(None, category, unconfigured=unconfigured)
  1540. return hasher if resolve else hasher.name
  1541. # XXX: need to decide if exposing this would be useful in any way
  1542. ##def categories(self):
  1543. ## """return user-categories with algorithm-specific options in this CryptContext.
  1544. ##
  1545. ## this will always return a tuple.
  1546. ## if no categories besides the default category have been configured,
  1547. ## the tuple will be empty.
  1548. ## """
  1549. ## return self._config.categories
  1550. # XXX: need to decide if exposing this would be useful to applications
  1551. # in any meaningful way that isn't already served by to_dict()
  1552. ##def options(self, scheme, category=None):
  1553. ## kwds, percat = self._config.get_options(scheme, category)
  1554. ## return kwds
  1555. def handler(self, scheme=None, category=None, unconfigured=False):
  1556. """helper to resolve name of scheme -> :class:`~passlib.ifc.PasswordHash` object used by scheme.
  1557. :arg scheme:
  1558. This should identify the scheme to lookup.
  1559. If omitted or set to ``None``, this will return the handler
  1560. for the default scheme.
  1561. :arg category:
  1562. If a user category is specified, and no scheme is provided,
  1563. it will use the default for that category.
  1564. Otherwise this parameter is ignored.
  1565. :param unconfigured:
  1566. By default, this returns a handler object whose .hash()
  1567. and .needs_update() methods will honor the configured
  1568. provided by CryptContext. See ``unconfigured=True``
  1569. to get the underlying handler from before any context-specific
  1570. configuration was applied.
  1571. :raises KeyError:
  1572. If the scheme does not exist OR is not being used within this context.
  1573. :returns:
  1574. :class:`~passlib.ifc.PasswordHash` object used to implement
  1575. the named scheme within this context (this will usually
  1576. be one of the objects from :mod:`passlib.hash`)
  1577. .. versionadded:: 1.6
  1578. This was previously available as ``CryptContext().policy.get_handler()``
  1579. .. versionchanged:: 1.7
  1580. This now returns a hasher configured with any CryptContext-specific
  1581. options (custom rounds settings, etc). Previously this returned
  1582. the base hasher from :mod:`passlib.hash`.
  1583. """
  1584. try:
  1585. hasher = self._get_record(scheme, category)
  1586. if unconfigured:
  1587. return hasher._Context__orig_handler
  1588. else:
  1589. return hasher
  1590. except KeyError:
  1591. pass
  1592. if self._config.handlers:
  1593. raise KeyError("crypt algorithm not found in this "
  1594. "CryptContext instance: %r" % (scheme,))
  1595. else:
  1596. raise KeyError("no crypt algorithms loaded in this "
  1597. "CryptContext instance")
  1598. def _get_unregistered_handlers(self):
  1599. """check if any handlers in this context aren't in the global registry"""
  1600. return tuple(handler for handler in self._config.handlers
  1601. if not _is_handler_registered(handler))
  1602. @property
  1603. def context_kwds(self):
  1604. """
  1605. return :class:`!set` containing union of all :ref:`contextual keywords <context-keywords>`
  1606. supported by the handlers in this context.
  1607. .. versionadded:: 1.6.6
  1608. """
  1609. return self._config.context_kwds
  1610. #===================================================================
  1611. # exporting config
  1612. #===================================================================
  1613. @staticmethod
  1614. def _render_config_key(key):
  1615. """convert 3-part config key to single string"""
  1616. cat, scheme, option = key
  1617. if cat:
  1618. return "%s__%s__%s" % (cat, scheme or "context", option)
  1619. elif scheme:
  1620. return "%s__%s" % (scheme, option)
  1621. else:
  1622. return option
  1623. @staticmethod
  1624. def _render_ini_value(key, value):
  1625. """render value to string suitable for INI file"""
  1626. # convert lists to comma separated lists
  1627. # (mainly 'schemes' & 'deprecated')
  1628. if isinstance(value, (list,tuple)):
  1629. value = ", ".join(value)
  1630. # convert numbers to strings
  1631. elif isinstance(value, num_types):
  1632. if isinstance(value, float) and key[2] == "vary_rounds":
  1633. value = ("%.2f" % value).rstrip("0") if value else "0"
  1634. else:
  1635. value = str(value)
  1636. assert isinstance(value, native_string_types), \
  1637. "expected string for key: %r %r" % (key, value)
  1638. # escape any percent signs.
  1639. return value.replace("%", "%%")
  1640. def to_dict(self, resolve=False):
  1641. """Return current configuration as a dictionary.
  1642. :type resolve: bool
  1643. :arg resolve:
  1644. if ``True``, the ``schemes`` key will contain a list of
  1645. a :class:`~passlib.ifc.PasswordHash` objects instead of just
  1646. their names.
  1647. This method dumps the current configuration of the CryptContext
  1648. instance. The key/value pairs should be in the format accepted
  1649. by the :class:`!CryptContext` class constructor, in fact
  1650. ``CryptContext(**myctx.to_dict())`` will create an exact copy of ``myctx``.
  1651. As an example::
  1652. >>> # you can dump the configuration of any crypt context...
  1653. >>> from passlib.apps import ldap_nocrypt_context
  1654. >>> ldap_nocrypt_context.to_dict()
  1655. {'schemes': ['ldap_salted_sha1',
  1656. 'ldap_salted_md5',
  1657. 'ldap_sha1',
  1658. 'ldap_md5',
  1659. 'ldap_plaintext']}
  1660. .. versionadded:: 1.6
  1661. This was previously available as ``CryptContext().policy.to_dict()``
  1662. .. seealso:: the :ref:`context-serialization-example` example in the tutorial.
  1663. """
  1664. # XXX: should resolve default to conditional behavior
  1665. # based on presence of unregistered handlers?
  1666. render_key = self._render_config_key
  1667. return dict((render_key(key), value)
  1668. for key, value in self._config.iter_config(resolve))
  1669. def _write_to_parser(self, parser, section):
  1670. """helper to write to ConfigParser instance"""
  1671. render_key = self._render_config_key
  1672. render_value = self._render_ini_value
  1673. parser.add_section(section)
  1674. for k,v in self._config.iter_config():
  1675. v = render_value(k, v)
  1676. k = render_key(k)
  1677. parser.set(section, k, v)
  1678. def to_string(self, section="passlib"):
  1679. """serialize to INI format and return as unicode string.
  1680. :param section:
  1681. name of INI section to output, defaults to ``"passlib"``.
  1682. :returns:
  1683. CryptContext configuration, serialized to a INI unicode string.
  1684. This function acts exactly like :meth:`to_dict`, except that it
  1685. serializes all the contents into a single human-readable string,
  1686. which can be hand edited, and/or stored in a file. The
  1687. output of this method is accepted by :meth:`from_string`,
  1688. :meth:`from_path`, and :meth:`load`. As an example::
  1689. >>> # you can dump the configuration of any crypt context...
  1690. >>> from passlib.apps import ldap_nocrypt_context
  1691. >>> print ldap_nocrypt_context.to_string()
  1692. [passlib]
  1693. schemes = ldap_salted_sha1, ldap_salted_md5, ldap_sha1, ldap_md5, ldap_plaintext
  1694. .. versionadded:: 1.6
  1695. This was previously available as ``CryptContext().policy.to_string()``
  1696. .. seealso:: the :ref:`context-serialization-example` example in the tutorial.
  1697. """
  1698. parser = SafeConfigParser()
  1699. self._write_to_parser(parser, section)
  1700. buf = NativeStringIO()
  1701. parser.write(buf)
  1702. unregistered = self._get_unregistered_handlers()
  1703. if unregistered:
  1704. buf.write((
  1705. "# NOTE: the %s handler(s) are not registered with Passlib,\n"
  1706. "# this string may not correctly reproduce the current configuration.\n\n"
  1707. ) % ", ".join(repr(handler.name) for handler in unregistered))
  1708. out = buf.getvalue()
  1709. if not PY3:
  1710. out = out.decode("utf-8")
  1711. return out
  1712. # XXX: is this useful enough to enable?
  1713. ##def write_to_path(self, path, section="passlib", update=False):
  1714. ## "write to INI file"
  1715. ## parser = ConfigParser()
  1716. ## if update and os.path.exists(path):
  1717. ## if not parser.read([path]):
  1718. ## raise EnvironmentError("failed to read existing file")
  1719. ## parser.remove_section(section)
  1720. ## self._write_to_parser(parser, section)
  1721. ## fh = file(path, "w")
  1722. ## parser.write(fh)
  1723. ## fh.close()
  1724. #===================================================================
  1725. # verify() hardening
  1726. # NOTE: this entire feature has been disabled.
  1727. # all contents of this section are NOOPs as of 1.7.1,
  1728. # and will be removed in 1.8.
  1729. #===================================================================
  1730. mvt_estimate_max_samples = 20
  1731. mvt_estimate_min_samples = 10
  1732. mvt_estimate_max_time = 2
  1733. mvt_estimate_resolution = 0.01
  1734. harden_verify = None
  1735. min_verify_time = 0
  1736. def reset_min_verify_time(self):
  1737. self._reset_dummy_verify()
  1738. #===================================================================
  1739. # password hash api
  1740. #===================================================================
  1741. # NOTE: all the following methods do is look up the appropriate
  1742. # custom handler for a given (scheme,category) combination,
  1743. # and hand off the real work to the handler itself,
  1744. # which is optimized for the specific (scheme,category) configuration.
  1745. #
  1746. # The custom handlers are cached inside the _CryptConfig
  1747. # instance stored in self._config, and are retrieved
  1748. # via get_record() and identify_record().
  1749. #
  1750. # _get_record() and _identify_record() are references
  1751. # to _config methods of the same name,
  1752. # stored in CryptContext for speed.
  1753. def _get_or_identify_record(self, hash, scheme=None, category=None):
  1754. """return record based on scheme, or failing that, by identifying hash"""
  1755. if scheme:
  1756. if not isinstance(hash, unicode_or_bytes_types):
  1757. raise ExpectedStringError(hash, "hash")
  1758. return self._get_record(scheme, category)
  1759. else:
  1760. # hash typecheck handled by identify_record()
  1761. return self._identify_record(hash, category)
  1762. def _strip_unused_context_kwds(self, kwds, record):
  1763. """
  1764. helper which removes any context keywords from **kwds**
  1765. that are known to be used by another scheme in this context,
  1766. but are NOT supported by handler specified by **record**.
  1767. .. note::
  1768. as optimization, load() will set this method to None on a per-instance basis
  1769. if there are no context kwds.
  1770. """
  1771. if not kwds:
  1772. return
  1773. unused_kwds = self._config.context_kwds.difference(record.context_kwds)
  1774. for key in unused_kwds:
  1775. kwds.pop(key, None)
  1776. def needs_update(self, hash, scheme=None, category=None, secret=None):
  1777. """Check if hash needs to be replaced for some reason,
  1778. in which case the secret should be re-hashed.
  1779. This function is the core of CryptContext's support for hash migration:
  1780. This function takes in a hash string, and checks the scheme,
  1781. number of rounds, and other properties against the current policy.
  1782. It returns ``True`` if the hash is using a deprecated scheme,
  1783. or is otherwise outside of the bounds specified by the policy
  1784. (e.g. the number of rounds is lower than :ref:`min_rounds <context-min-rounds-option>`
  1785. configuration for that algorithm).
  1786. If so, the password should be re-hashed using :meth:`hash`
  1787. Otherwise, it will return ``False``.
  1788. :type hash: unicode or bytes
  1789. :arg hash:
  1790. The hash string to examine.
  1791. :type scheme: str or None
  1792. :param scheme:
  1793. Optional scheme to use. Scheme must be one of the ones
  1794. configured for this context (see the
  1795. :ref:`schemes <context-schemes-option>` option).
  1796. If no scheme is specified, it will be identified
  1797. based on the value of *hash*.
  1798. .. deprecated:: 1.7
  1799. Support for this keyword is deprecated, and will be removed in Passlib 2.0.
  1800. :type category: str or None
  1801. :param category:
  1802. Optional :ref:`user category <user-categories>`.
  1803. If specified, this will cause any category-specific defaults to
  1804. be used when determining if the hash needs to be updated
  1805. (e.g. is below the minimum rounds).
  1806. :type secret: unicode, bytes, or None
  1807. :param secret:
  1808. Optional secret associated with the provided ``hash``.
  1809. This is not required, or even currently used for anything...
  1810. it's for forward-compatibility with any future
  1811. update checks that might need this information.
  1812. If provided, Passlib assumes the secret has already been
  1813. verified successfully against the hash.
  1814. .. versionadded:: 1.6
  1815. :returns: ``True`` if hash should be replaced, otherwise ``False``.
  1816. :raises ValueError:
  1817. If the hash did not match any of the configured :meth:`schemes`.
  1818. .. versionadded:: 1.6
  1819. This method was previously named :meth:`hash_needs_update`.
  1820. .. seealso:: the :ref:`context-migration-example` example in the tutorial.
  1821. """
  1822. if scheme is not None:
  1823. # TODO: offer replacement alternative.
  1824. # ``context.handler(scheme).needs_update()`` would work,
  1825. # but may deprecate .handler() in passlib 1.8.
  1826. warn("CryptContext.needs_update(): 'scheme' keyword is deprecated as of "
  1827. "Passlib 1.7, and will be removed in Passlib 2.0",
  1828. DeprecationWarning)
  1829. record = self._get_or_identify_record(hash, scheme, category)
  1830. return record.deprecated or record.needs_update(hash, secret=secret)
  1831. @deprecated_method(deprecated="1.6", removed="2.0", replacement="CryptContext.needs_update()")
  1832. def hash_needs_update(self, hash, scheme=None, category=None):
  1833. """Legacy alias for :meth:`needs_update`.
  1834. .. deprecated:: 1.6
  1835. This method was renamed to :meth:`!needs_update` in version 1.6.
  1836. This alias will be removed in version 2.0, and should only
  1837. be used for compatibility with Passlib 1.3 - 1.5.
  1838. """
  1839. return self.needs_update(hash, scheme, category)
  1840. @deprecated_method(deprecated="1.7", removed="2.0")
  1841. def genconfig(self, scheme=None, category=None, **settings):
  1842. """Generate a config string for specified scheme.
  1843. .. deprecated:: 1.7
  1844. This method will be removed in version 2.0, and should only
  1845. be used for compatibility with Passlib 1.3 - 1.6.
  1846. """
  1847. record = self._get_record(scheme, category)
  1848. strip_unused = self._strip_unused_context_kwds
  1849. if strip_unused:
  1850. strip_unused(settings, record)
  1851. return record.genconfig(**settings)
  1852. @deprecated_method(deprecated="1.7", removed="2.0")
  1853. def genhash(self, secret, config, scheme=None, category=None, **kwds):
  1854. """Generate hash for the specified secret using another hash.
  1855. .. deprecated:: 1.7
  1856. This method will be removed in version 2.0, and should only
  1857. be used for compatibility with Passlib 1.3 - 1.6.
  1858. """
  1859. record = self._get_or_identify_record(config, scheme, category)
  1860. strip_unused = self._strip_unused_context_kwds
  1861. if strip_unused:
  1862. strip_unused(kwds, record)
  1863. return record.genhash(secret, config, **kwds)
  1864. def identify(self, hash, category=None, resolve=False, required=False,
  1865. unconfigured=False):
  1866. """Attempt to identify which algorithm the hash belongs to.
  1867. Note that this will only consider the algorithms
  1868. currently configured for this context
  1869. (see the :ref:`schemes <context-schemes-option>` option).
  1870. All registered algorithms will be checked, from first to last,
  1871. and whichever one positively identifies the hash first will be returned.
  1872. :type hash: unicode or bytes
  1873. :arg hash:
  1874. The hash string to test.
  1875. :type category: str or None
  1876. :param category:
  1877. Optional :ref:`user category <user-categories>`.
  1878. Ignored by this function, this parameter
  1879. is provided for symmetry with the other methods.
  1880. :type resolve: bool
  1881. :param resolve:
  1882. If ``True``, returns the hash handler itself,
  1883. instead of the name of the hash.
  1884. :type required: bool
  1885. :param required:
  1886. If ``True``, this will raise a ValueError if the hash
  1887. cannot be identified, instead of returning ``None``.
  1888. :returns:
  1889. The handler which first identifies the hash,
  1890. or ``None`` if none of the algorithms identify the hash.
  1891. """
  1892. record = self._identify_record(hash, category, required)
  1893. if record is None:
  1894. return None
  1895. elif resolve:
  1896. if unconfigured:
  1897. return record._Context__orig_handler
  1898. else:
  1899. return record
  1900. else:
  1901. return record.name
  1902. def hash(self, secret, scheme=None, category=None, **kwds):
  1903. """run secret through selected algorithm, returning resulting hash.
  1904. :type secret: unicode or bytes
  1905. :arg secret:
  1906. the password to hash.
  1907. :type scheme: str or None
  1908. :param scheme:
  1909. Optional scheme to use. Scheme must be one of the ones
  1910. configured for this context (see the
  1911. :ref:`schemes <context-schemes-option>` option).
  1912. If no scheme is specified, the configured default
  1913. will be used.
  1914. .. deprecated:: 1.7
  1915. Support for this keyword is deprecated, and will be removed in Passlib 2.0.
  1916. :type category: str or None
  1917. :param category:
  1918. Optional :ref:`user category <user-categories>`.
  1919. If specified, this will cause any category-specific defaults to
  1920. be used when hashing the password (e.g. different default scheme,
  1921. different default rounds values, etc).
  1922. :param \\*\\*kwds:
  1923. All other keyword options are passed to the selected algorithm's
  1924. :meth:`PasswordHash.hash() <passlib.ifc.PasswordHash.hash>` method.
  1925. :returns:
  1926. The secret as encoded by the specified algorithm and options.
  1927. The return value will always be a :class:`!str`.
  1928. :raises TypeError, ValueError:
  1929. * If any of the arguments have an invalid type or value.
  1930. This includes any keywords passed to the underlying hash's
  1931. :meth:`PasswordHash.hash() <passlib.ifc.PasswordHash.hash>` method.
  1932. .. seealso:: the :ref:`context-basic-example` example in the tutorial
  1933. """
  1934. # XXX: could insert normalization to preferred unicode encoding here
  1935. if scheme is not None:
  1936. # TODO: offer replacement alternative.
  1937. # ``context.handler(scheme).hash()`` would work,
  1938. # but may deprecate .handler() in passlib 1.8.
  1939. warn("CryptContext.hash(): 'scheme' keyword is deprecated as of "
  1940. "Passlib 1.7, and will be removed in Passlib 2.0",
  1941. DeprecationWarning)
  1942. record = self._get_record(scheme, category)
  1943. strip_unused = self._strip_unused_context_kwds
  1944. if strip_unused:
  1945. strip_unused(kwds, record)
  1946. return record.hash(secret, **kwds)
  1947. @deprecated_method(deprecated="1.7", removed="2.0", replacement="CryptContext.hash()")
  1948. def encrypt(self, *args, **kwds):
  1949. """
  1950. Legacy alias for :meth:`hash`.
  1951. .. deprecated:: 1.7
  1952. This method was renamed to :meth:`!hash` in version 1.7.
  1953. This alias will be removed in version 2.0, and should only
  1954. be used for compatibility with Passlib 1.3 - 1.6.
  1955. """
  1956. return self.hash(*args, **kwds)
  1957. def verify(self, secret, hash, scheme=None, category=None, **kwds):
  1958. """verify secret against an existing hash.
  1959. If no scheme is specified, this will attempt to identify
  1960. the scheme based on the contents of the provided hash
  1961. (limited to the schemes configured for this context).
  1962. It will then check whether the password verifies against the hash.
  1963. :type secret: unicode or bytes
  1964. :arg secret:
  1965. the secret to verify
  1966. :type hash: unicode or bytes
  1967. :arg hash:
  1968. hash string to compare to
  1969. if ``None`` is passed in, this will be treated as "never verifying"
  1970. :type scheme: str
  1971. :param scheme:
  1972. Optionally force context to use specific scheme.
  1973. This is usually not needed, as most hashes can be unambiguously
  1974. identified. Scheme must be one of the ones configured
  1975. for this context
  1976. (see the :ref:`schemes <context-schemes-option>` option).
  1977. .. deprecated:: 1.7
  1978. Support for this keyword is deprecated, and will be removed in Passlib 2.0.
  1979. :type category: str or None
  1980. :param category:
  1981. Optional :ref:`user category <user-categories>` string.
  1982. This is mainly used when generating new hashes, it has little
  1983. effect when verifying; this keyword is mainly provided for symmetry.
  1984. :param \\*\\*kwds:
  1985. All additional keywords are passed to the appropriate handler,
  1986. and should match its :attr:`~passlib.ifc.PasswordHash.context_kwds`.
  1987. :returns:
  1988. ``True`` if the password matched the hash, else ``False``.
  1989. :raises ValueError:
  1990. * if the hash did not match any of the configured :meth:`schemes`.
  1991. * if any of the arguments have an invalid value (this includes
  1992. any keywords passed to the underlying hash's
  1993. :meth:`PasswordHash.verify() <passlib.ifc.PasswordHash.verify>` method).
  1994. :raises TypeError:
  1995. * if any of the arguments have an invalid type (this includes
  1996. any keywords passed to the underlying hash's
  1997. :meth:`PasswordHash.verify() <passlib.ifc.PasswordHash.verify>` method).
  1998. .. seealso:: the :ref:`context-basic-example` example in the tutorial
  1999. """
  2000. # XXX: could insert normalization to preferred unicode encoding here
  2001. # XXX: what about supporting a setter() callback ala django 1.4 ?
  2002. if scheme is not None:
  2003. # TODO: offer replacement alternative.
  2004. # ``context.handler(scheme).verify()`` would work,
  2005. # but may deprecate .handler() in passlib 1.8.
  2006. warn("CryptContext.verify(): 'scheme' keyword is deprecated as of "
  2007. "Passlib 1.7, and will be removed in Passlib 2.0",
  2008. DeprecationWarning)
  2009. if hash is None:
  2010. # convenience feature -- let apps pass in hash=None when user
  2011. # isn't found / has no hash; useful because it invokes dummy_verify()
  2012. self.dummy_verify()
  2013. return False
  2014. record = self._get_or_identify_record(hash, scheme, category)
  2015. strip_unused = self._strip_unused_context_kwds
  2016. if strip_unused:
  2017. strip_unused(kwds, record)
  2018. return record.verify(secret, hash, **kwds)
  2019. def verify_and_update(self, secret, hash, scheme=None, category=None, **kwds):
  2020. """verify password and re-hash the password if needed, all in a single call.
  2021. This is a convenience method which takes care of all the following:
  2022. first it verifies the password (:meth:`~CryptContext.verify`), if this is successfull
  2023. it checks if the hash needs updating (:meth:`~CryptContext.needs_update`), and if so,
  2024. re-hashes the password (:meth:`~CryptContext.hash`), returning the replacement hash.
  2025. This series of steps is a very common task for applications
  2026. which wish to update deprecated hashes, and this call takes
  2027. care of all 3 steps efficiently.
  2028. :type secret: unicode or bytes
  2029. :arg secret:
  2030. the secret to verify
  2031. :type secret: unicode or bytes
  2032. :arg hash:
  2033. hash string to compare to.
  2034. if ``None`` is passed in, this will be treated as "never verifying"
  2035. :type scheme: str
  2036. :param scheme:
  2037. Optionally force context to use specific scheme.
  2038. This is usually not needed, as most hashes can be unambiguously
  2039. identified. Scheme must be one of the ones configured
  2040. for this context
  2041. (see the :ref:`schemes <context-schemes-option>` option).
  2042. .. deprecated:: 1.7
  2043. Support for this keyword is deprecated, and will be removed in Passlib 2.0.
  2044. :type category: str or None
  2045. :param category:
  2046. Optional :ref:`user category <user-categories>`.
  2047. If specified, this will cause any category-specific defaults to
  2048. be used if the password has to be re-hashed.
  2049. :param \\*\\*kwds:
  2050. all additional keywords are passed to the appropriate handler,
  2051. and should match that hash's
  2052. :attr:`PasswordHash.context_kwds <passlib.ifc.PasswordHash.context_kwds>`.
  2053. :returns:
  2054. This function returns a tuple containing two elements:
  2055. ``(verified, replacement_hash)``. The first is a boolean
  2056. flag indicating whether the password verified,
  2057. and the second an optional replacement hash.
  2058. The tuple will always match one of the following 3 cases:
  2059. * ``(False, None)`` indicates the secret failed to verify.
  2060. * ``(True, None)`` indicates the secret verified correctly,
  2061. and the hash does not need updating.
  2062. * ``(True, str)`` indicates the secret verified correctly,
  2063. but the current hash needs to be updated. The :class:`!str`
  2064. will be the freshly generated hash, to replace the old one.
  2065. :raises TypeError, ValueError:
  2066. For the same reasons as :meth:`verify`.
  2067. .. seealso:: the :ref:`context-migration-example` example in the tutorial.
  2068. """
  2069. # XXX: could insert normalization to preferred unicode encoding here.
  2070. if scheme is not None:
  2071. warn("CryptContext.verify(): 'scheme' keyword is deprecated as of "
  2072. "Passlib 1.7, and will be removed in Passlib 2.0",
  2073. DeprecationWarning)
  2074. if hash is None:
  2075. # convenience feature -- let apps pass in hash=None when user
  2076. # isn't found / has no hash; useful because it invokes dummy_verify()
  2077. self.dummy_verify()
  2078. return False, None
  2079. record = self._get_or_identify_record(hash, scheme, category)
  2080. strip_unused = self._strip_unused_context_kwds
  2081. if strip_unused and kwds:
  2082. clean_kwds = kwds.copy()
  2083. strip_unused(clean_kwds, record)
  2084. else:
  2085. clean_kwds = kwds
  2086. # XXX: if record is default scheme, could extend PasswordHash
  2087. # api to combine verify & needs_update to single call,
  2088. # potentially saving some round-trip parsing.
  2089. # but might make these codepaths more complex...
  2090. if not record.verify(secret, hash, **clean_kwds):
  2091. return False, None
  2092. elif record.deprecated or record.needs_update(hash, secret=secret):
  2093. # NOTE: we re-hash with default scheme, not current one.
  2094. return True, self.hash(secret, category=category, **kwds)
  2095. else:
  2096. return True, None
  2097. #===================================================================
  2098. # missing-user helper
  2099. #===================================================================
  2100. #: secret used for dummy_verify()
  2101. _dummy_secret = "too many secrets"
  2102. @memoized_property
  2103. def _dummy_hash(self):
  2104. """
  2105. precalculated hash for dummy_verify() to use
  2106. """
  2107. return self.hash(self._dummy_secret)
  2108. def _reset_dummy_verify(self):
  2109. """
  2110. flush memoized values used by dummy_verify()
  2111. """
  2112. type(self)._dummy_hash.clear_cache(self)
  2113. def dummy_verify(self, elapsed=0):
  2114. """
  2115. Helper that applications can call when user wasn't found,
  2116. in order to simulate time it would take to hash a password.
  2117. Runs verify() against a dummy hash, to simulate verification
  2118. of a real account password.
  2119. :param elapsed:
  2120. .. deprecated:: 1.7.1
  2121. this option is ignored, and will be removed in passlib 1.8.
  2122. .. versionadded:: 1.7
  2123. """
  2124. self.verify(self._dummy_secret, self._dummy_hash)
  2125. return False
  2126. #===================================================================
  2127. # disabled hash support
  2128. #===================================================================
  2129. def is_enabled(self, hash):
  2130. """
  2131. test if hash represents a usuable password --
  2132. i.e. does not represent an unusuable password such as ``"!"``,
  2133. which is recognized by the :class:`~passlib.hash.unix_disabled` hash.
  2134. :raises ValueError:
  2135. if the hash is not recognized
  2136. (typically solved by adding ``unix_disabled`` to the list of schemes).
  2137. """
  2138. return not self._identify_record(hash, None).is_disabled
  2139. def disable(self, hash=None):
  2140. """
  2141. return a string to disable logins for user,
  2142. usually by returning a non-verifying string such as ``"!"``.
  2143. :param hash:
  2144. Callers can optionally provide the account's existing hash.
  2145. Some disabled handlers (such as :class:`!unix_disabled`)
  2146. will encode this into the returned value,
  2147. so that it can be recovered via :meth:`enable`.
  2148. :raises RuntimeError:
  2149. if this function is called w/o a disabled hasher
  2150. (such as :class:`~passlib.hash.unix_disabled`) included
  2151. in the list of schemes.
  2152. :returns:
  2153. hash string which will be recognized as valid by the context,
  2154. but is guaranteed to not validate against *any* password.
  2155. """
  2156. record = self._config.disabled_record
  2157. assert record.is_disabled
  2158. return record.disable(hash)
  2159. def enable(self, hash):
  2160. """
  2161. inverse of :meth:`disable` --
  2162. attempts to recover original hash which was converted
  2163. by a :meth:`!disable` call into a disabled hash --
  2164. thus restoring the user's original password.
  2165. :raises ValueError:
  2166. if original hash not present, or if the disabled handler doesn't
  2167. support encoding the original hash (e.g. ``django_disabled``)
  2168. :returns:
  2169. the original hash.
  2170. """
  2171. record = self._identify_record(hash, None)
  2172. if record.is_disabled:
  2173. # XXX: should we throw error if result can't be identified by context?
  2174. return record.enable(hash)
  2175. else:
  2176. # hash wasn't a disabled hash, so return unchanged
  2177. return hash
  2178. #===================================================================
  2179. # eoc
  2180. #===================================================================
  2181. class LazyCryptContext(CryptContext):
  2182. """CryptContext subclass which doesn't load handlers until needed.
  2183. This is a subclass of CryptContext which takes in a set of arguments
  2184. exactly like CryptContext, but won't import any handlers
  2185. (or even parse its arguments) until
  2186. the first time one of its methods is accessed.
  2187. :arg schemes:
  2188. The first positional argument can be a list of schemes, or omitted,
  2189. just like CryptContext.
  2190. :param onload:
  2191. If a callable is passed in via this keyword,
  2192. it will be invoked at lazy-load time
  2193. with the following signature:
  2194. ``onload(**kwds) -> kwds``;
  2195. where ``kwds`` is all the additional kwds passed to LazyCryptContext.
  2196. It should perform any additional deferred initialization,
  2197. and return the final dict of options to be passed to CryptContext.
  2198. .. versionadded:: 1.6
  2199. :param create_policy:
  2200. .. deprecated:: 1.6
  2201. This option will be removed in Passlib 1.8,
  2202. applications should use ``onload`` instead.
  2203. :param kwds:
  2204. All additional keywords are passed to CryptContext;
  2205. or to the *onload* function (if provided).
  2206. This is mainly used internally by modules such as :mod:`passlib.apps`,
  2207. which define a large number of contexts, but only a few of them will be needed
  2208. at any one time. Use of this class saves the memory needed to import
  2209. the specified handlers until the context instance is actually accessed.
  2210. As well, it allows constructing a context at *module-init* time,
  2211. but using :func:`!onload()` to provide dynamic configuration
  2212. at *application-run* time.
  2213. .. note::
  2214. This class is only useful if you're referencing handler objects by name,
  2215. and don't want them imported until runtime. If you want to have the config
  2216. validated before your application runs, or are passing in already-imported
  2217. handler instances, you should use :class:`CryptContext` instead.
  2218. .. versionadded:: 1.4
  2219. """
  2220. _lazy_kwds = None
  2221. # NOTE: the way this class works changed in 1.6.
  2222. # previously it just called _lazy_init() when ``.policy`` was
  2223. # first accessed. now that is done whenever any of the public
  2224. # attributes are accessed, and the class itself is changed
  2225. # to a regular CryptContext, to remove the overhead once it's unneeded.
  2226. def __init__(self, schemes=None, **kwds):
  2227. if schemes is not None:
  2228. kwds['schemes'] = schemes
  2229. self._lazy_kwds = kwds
  2230. def _lazy_init(self):
  2231. kwds = self._lazy_kwds
  2232. if 'create_policy' in kwds:
  2233. warn("The CryptPolicy class, and LazyCryptContext's "
  2234. "``create_policy`` keyword have been deprecated as of "
  2235. "Passlib 1.6, and will be removed in Passlib 1.8; "
  2236. "please use the ``onload`` keyword instead.",
  2237. DeprecationWarning)
  2238. create_policy = kwds.pop("create_policy")
  2239. result = create_policy(**kwds)
  2240. policy = CryptPolicy.from_source(result, _warn=False)
  2241. kwds = policy._context.to_dict()
  2242. elif 'onload' in kwds:
  2243. onload = kwds.pop("onload")
  2244. kwds = onload(**kwds)
  2245. del self._lazy_kwds
  2246. super(LazyCryptContext, self).__init__(**kwds)
  2247. self.__class__ = CryptContext
  2248. def __getattribute__(self, attr):
  2249. if (not attr.startswith("_") or attr.startswith("__")) and \
  2250. self._lazy_kwds is not None:
  2251. self._lazy_init()
  2252. return object.__getattribute__(self, attr)
  2253. #=============================================================================
  2254. # eof
  2255. #=============================================================================