Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 

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