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

2679 lines
102 KiB

  1. """passlib.handler - code for implementing handlers, and global registry for handlers"""
  2. #=============================================================================
  3. # imports
  4. #=============================================================================
  5. from __future__ import with_statement
  6. # core
  7. import inspect
  8. import logging; log = logging.getLogger(__name__)
  9. import math
  10. import threading
  11. from warnings import warn
  12. # site
  13. # pkg
  14. import passlib.exc as exc, passlib.ifc as ifc
  15. from passlib.exc import MissingBackendError, PasslibConfigWarning, \
  16. PasslibHashWarning
  17. from passlib.ifc import PasswordHash
  18. from passlib.registry import get_crypt_handler
  19. from passlib.utils import (
  20. consteq, getrandstr, getrandbytes,
  21. rng, to_native_str,
  22. is_crypt_handler, to_unicode,
  23. MAX_PASSWORD_SIZE, accepts_keyword, as_bool,
  24. update_mixin_classes)
  25. from passlib.utils.binary import (
  26. BASE64_CHARS, HASH64_CHARS, PADDED_BASE64_CHARS,
  27. HEX_CHARS, UPPER_HEX_CHARS, LOWER_HEX_CHARS,
  28. ALL_BYTE_VALUES,
  29. )
  30. from passlib.utils.compat import join_byte_values, irange, u, native_string_types, \
  31. uascii_to_str, join_unicode, unicode, str_to_uascii, \
  32. join_unicode, unicode_or_bytes_types, PY2, int_types
  33. from passlib.utils.decor import classproperty, deprecated_method
  34. # local
  35. __all__ = [
  36. # helpers for implementing MCF handlers
  37. 'parse_mc2',
  38. 'parse_mc3',
  39. 'render_mc2',
  40. 'render_mc3',
  41. # framework for implementing handlers
  42. 'GenericHandler',
  43. 'StaticHandler',
  44. 'HasUserContext',
  45. 'HasRawChecksum',
  46. 'HasManyIdents',
  47. 'HasSalt',
  48. 'HasRawSalt',
  49. 'HasRounds',
  50. 'HasManyBackends',
  51. # other helpers
  52. 'PrefixWrapper',
  53. # TODO: a bunch of other things are commonly assumed in this namespace
  54. # (e.g. HEX_CHARS etc); need to audit uses and update this list.
  55. ]
  56. #=============================================================================
  57. # constants
  58. #=============================================================================
  59. # deprecated aliases - will be removed after passlib 1.8
  60. H64_CHARS = HASH64_CHARS
  61. B64_CHARS = BASE64_CHARS
  62. PADDED_B64_CHARS = PADDED_BASE64_CHARS
  63. UC_HEX_CHARS = UPPER_HEX_CHARS
  64. LC_HEX_CHARS = LOWER_HEX_CHARS
  65. #=============================================================================
  66. # support functions
  67. #=============================================================================
  68. def _bitsize(count, chars):
  69. """helper for bitsize() methods"""
  70. if chars and count:
  71. import math
  72. return int(count * math.log(len(chars), 2))
  73. else:
  74. return 0
  75. def guess_app_stacklevel(start=1):
  76. """
  77. try to guess stacklevel for application warning.
  78. looks for first frame not part of passlib.
  79. """
  80. frame = inspect.currentframe()
  81. count = -start
  82. try:
  83. while frame:
  84. name = frame.f_globals.get('__name__', "")
  85. if name.startswith("passlib.tests.") or not name.startswith("passlib."):
  86. return max(1, count)
  87. count += 1
  88. frame = frame.f_back
  89. return start
  90. finally:
  91. del frame
  92. def warn_hash_settings_deprecation(handler, kwds):
  93. warn("passing settings to %(handler)s.hash() is deprecated, and won't be supported in Passlib 2.0; "
  94. "use '%(handler)s.using(**settings).hash(secret)' instead" % dict(handler=handler.name),
  95. DeprecationWarning, stacklevel=guess_app_stacklevel(2))
  96. def extract_settings_kwds(handler, kwds):
  97. """
  98. helper to extract settings kwds from mix of context & settings kwds.
  99. pops settings keys from kwds, returns them as a dict.
  100. """
  101. context_keys = set(handler.context_kwds)
  102. return dict((key, kwds.pop(key)) for key in list(kwds) if key not in context_keys)
  103. #=============================================================================
  104. # parsing helpers
  105. #=============================================================================
  106. _UDOLLAR = u("$")
  107. _UZERO = u("0")
  108. def validate_secret(secret):
  109. """ensure secret has correct type & size"""
  110. if not isinstance(secret, unicode_or_bytes_types):
  111. raise exc.ExpectedStringError(secret, "secret")
  112. if len(secret) > MAX_PASSWORD_SIZE:
  113. raise exc.PasswordSizeError(MAX_PASSWORD_SIZE)
  114. def to_unicode_for_identify(hash):
  115. """convert hash to unicode for identify method"""
  116. if isinstance(hash, unicode):
  117. return hash
  118. elif isinstance(hash, bytes):
  119. # try as utf-8, but if it fails, use foolproof latin-1,
  120. # since we don't really care about non-ascii chars
  121. # when running identify.
  122. try:
  123. return hash.decode("utf-8")
  124. except UnicodeDecodeError:
  125. return hash.decode("latin-1")
  126. else:
  127. raise exc.ExpectedStringError(hash, "hash")
  128. def parse_mc2(hash, prefix, sep=_UDOLLAR, handler=None):
  129. """parse hash using 2-part modular crypt format.
  130. this expects a hash of the format :samp:`{prefix}{salt}[${checksum}]`,
  131. such as md5_crypt, and parses it into salt / checksum portions.
  132. :arg hash: the hash to parse (bytes or unicode)
  133. :arg prefix: the identifying prefix (unicode)
  134. :param sep: field separator (unicode, defaults to ``$``).
  135. :param handler: handler class to pass to error constructors.
  136. :returns:
  137. a ``(salt, chk | None)`` tuple.
  138. """
  139. # detect prefix
  140. hash = to_unicode(hash, "ascii", "hash")
  141. assert isinstance(prefix, unicode)
  142. if not hash.startswith(prefix):
  143. raise exc.InvalidHashError(handler)
  144. # parse 2-part hash or 1-part config string
  145. assert isinstance(sep, unicode)
  146. parts = hash[len(prefix):].split(sep)
  147. if len(parts) == 2:
  148. salt, chk = parts
  149. return salt, chk or None
  150. elif len(parts) == 1:
  151. return parts[0], None
  152. else:
  153. raise exc.MalformedHashError(handler)
  154. def parse_mc3(hash, prefix, sep=_UDOLLAR, rounds_base=10,
  155. default_rounds=None, handler=None):
  156. """parse hash using 3-part modular crypt format.
  157. this expects a hash of the format :samp:`{prefix}[{rounds}]${salt}[${checksum}]`,
  158. such as sha1_crypt, and parses it into rounds / salt / checksum portions.
  159. tries to convert the rounds to an integer,
  160. and throws error if it has zero-padding.
  161. :arg hash: the hash to parse (bytes or unicode)
  162. :arg prefix: the identifying prefix (unicode)
  163. :param sep: field separator (unicode, defaults to ``$``).
  164. :param rounds_base:
  165. the numeric base the rounds are encoded in (defaults to base 10).
  166. :param default_rounds:
  167. the default rounds value to return if the rounds field was omitted.
  168. if this is ``None`` (the default), the rounds field is *required*.
  169. :param handler: handler class to pass to error constructors.
  170. :returns:
  171. a ``(rounds : int, salt, chk | None)`` tuple.
  172. """
  173. # detect prefix
  174. hash = to_unicode(hash, "ascii", "hash")
  175. assert isinstance(prefix, unicode)
  176. if not hash.startswith(prefix):
  177. raise exc.InvalidHashError(handler)
  178. # parse 3-part hash or 2-part config string
  179. assert isinstance(sep, unicode)
  180. parts = hash[len(prefix):].split(sep)
  181. if len(parts) == 3:
  182. rounds, salt, chk = parts
  183. elif len(parts) == 2:
  184. rounds, salt = parts
  185. chk = None
  186. else:
  187. raise exc.MalformedHashError(handler)
  188. # validate & parse rounds portion
  189. if rounds.startswith(_UZERO) and rounds != _UZERO:
  190. raise exc.ZeroPaddedRoundsError(handler)
  191. elif rounds:
  192. rounds = int(rounds, rounds_base)
  193. elif default_rounds is None:
  194. raise exc.MalformedHashError(handler, "empty rounds field")
  195. else:
  196. rounds = default_rounds
  197. # return result
  198. return rounds, salt, chk or None
  199. # def parse_mc3_long(hash, prefix, sep=_UDOLLAR, handler=None):
  200. # """
  201. # parse hash using 3-part modular crypt format,
  202. # with complex settings string instead of simple rounds.
  203. # otherwise works same as :func:`parse_mc3`
  204. # """
  205. # # detect prefix
  206. # hash = to_unicode(hash, "ascii", "hash")
  207. # assert isinstance(prefix, unicode)
  208. # if not hash.startswith(prefix):
  209. # raise exc.InvalidHashError(handler)
  210. #
  211. # # parse 3-part hash or 2-part config string
  212. # assert isinstance(sep, unicode)
  213. # parts = hash[len(prefix):].split(sep)
  214. # if len(parts) == 3:
  215. # return parts
  216. # elif len(parts) == 2:
  217. # settings, salt = parts
  218. # return settings, salt, None
  219. # else:
  220. # raise exc.MalformedHashError(handler)
  221. def parse_int(source, base=10, default=None, param="value", handler=None):
  222. """
  223. helper to parse an integer config field
  224. :arg source: unicode source string
  225. :param base: numeric base
  226. :param default: optional default if source is empty
  227. :param param: name of variable, for error msgs
  228. :param handler: handler class, for error msgs
  229. """
  230. if source.startswith(_UZERO) and source != _UZERO:
  231. raise exc.MalformedHashError(handler, "zero-padded %s field" % param)
  232. elif source:
  233. return int(source, base)
  234. elif default is None:
  235. raise exc.MalformedHashError(handler, "empty %s field" % param)
  236. else:
  237. return default
  238. #=============================================================================
  239. # formatting helpers
  240. #=============================================================================
  241. def render_mc2(ident, salt, checksum, sep=u("$")):
  242. """format hash using 2-part modular crypt format; inverse of parse_mc2()
  243. returns native string with format :samp:`{ident}{salt}[${checksum}]`,
  244. such as used by md5_crypt.
  245. :arg ident: identifier prefix (unicode)
  246. :arg salt: encoded salt (unicode)
  247. :arg checksum: encoded checksum (unicode or None)
  248. :param sep: separator char (unicode, defaults to ``$``)
  249. :returns:
  250. config or hash (native str)
  251. """
  252. if checksum:
  253. parts = [ident, salt, sep, checksum]
  254. else:
  255. parts = [ident, salt]
  256. return uascii_to_str(join_unicode(parts))
  257. def render_mc3(ident, rounds, salt, checksum, sep=u("$"), rounds_base=10):
  258. """format hash using 3-part modular crypt format; inverse of parse_mc3()
  259. returns native string with format :samp:`{ident}[{rounds}$]{salt}[${checksum}]`,
  260. such as used by sha1_crypt.
  261. :arg ident: identifier prefix (unicode)
  262. :arg rounds: rounds field (int or None)
  263. :arg salt: encoded salt (unicode)
  264. :arg checksum: encoded checksum (unicode or None)
  265. :param sep: separator char (unicode, defaults to ``$``)
  266. :param rounds_base: base to encode rounds value (defaults to base 10)
  267. :returns:
  268. config or hash (native str)
  269. """
  270. if rounds is None:
  271. rounds = u('')
  272. elif rounds_base == 16:
  273. rounds = u("%x") % rounds
  274. else:
  275. assert rounds_base == 10
  276. rounds = unicode(rounds)
  277. if checksum:
  278. parts = [ident, rounds, sep, salt, sep, checksum]
  279. else:
  280. parts = [ident, rounds, sep, salt]
  281. return uascii_to_str(join_unicode(parts))
  282. #=============================================================================
  283. # parameter helpers
  284. #=============================================================================
  285. def validate_default_value(handler, default, norm, param="value"):
  286. """
  287. assert helper that quickly validates default value.
  288. designed to get out of the way and reduce overhead when asserts are stripped.
  289. """
  290. assert default is not None, "%s lacks default %s" % (handler.name, param)
  291. assert norm(default) == default, "%s: invalid default %s: %r" % (handler.name, param, default)
  292. return True
  293. def norm_integer(handler, value, min=1, max=None, # *
  294. param="value", relaxed=False):
  295. """
  296. helper to normalize and validate an integer value (e.g. rounds, salt_size)
  297. :arg value: value provided to constructor
  298. :arg default: default value if none provided. if set to ``None``, value is required.
  299. :arg param: name of parameter (xxx: move to first arg?)
  300. :param min: minimum value (defaults to 1)
  301. :param max: maximum value (default ``None`` means no maximum)
  302. :returns: validated value
  303. """
  304. # check type
  305. if not isinstance(value, int_types):
  306. raise exc.ExpectedTypeError(value, "integer", param)
  307. # check minimum
  308. if value < min:
  309. msg = "%s: %s (%d) is too low, must be at least %d" % (handler.name, param, value, min)
  310. if relaxed:
  311. warn(msg, exc.PasslibHashWarning)
  312. value = min
  313. else:
  314. raise ValueError(msg)
  315. # check maximum
  316. if max and value > max:
  317. msg = "%s: %s (%d) is too large, cannot be more than %d" % (handler.name, param, value, max)
  318. if relaxed:
  319. warn(msg, exc.PasslibHashWarning)
  320. value = max
  321. else:
  322. raise ValueError(msg)
  323. return value
  324. #=============================================================================
  325. # MinimalHandler
  326. #=============================================================================
  327. class MinimalHandler(PasswordHash):
  328. """
  329. helper class for implementing hash handlers.
  330. provides nothing besides a base implementation of the .using() subclass constructor.
  331. """
  332. #===================================================================
  333. # class attr
  334. #===================================================================
  335. #: private flag used by using() constructor to detect if this is already a subclass.
  336. _configured = False
  337. #===================================================================
  338. # configuration interface
  339. #===================================================================
  340. @classmethod
  341. def using(cls, relaxed=False):
  342. # NOTE: this provides the base implementation, which takes care of
  343. # creating the newly configured class. Mixins and subclasses
  344. # should wrap this, and modify the returned class to suit their options.
  345. # NOTE: 'relaxed' keyword is ignored here, but parsed so that subclasses
  346. # can check for it as argument, and modify their parsing behavior accordingly.
  347. name = cls.__name__
  348. if not cls._configured:
  349. # TODO: straighten out class naming, repr, and .name attr
  350. name = "<customized %s hasher>" % name
  351. return type(name, (cls,), dict(__module__=cls.__module__, _configured=True))
  352. #===================================================================
  353. # eoc
  354. #===================================================================
  355. class TruncateMixin(MinimalHandler):
  356. """
  357. PasswordHash mixin which provides a method
  358. that will check if secret would be truncated,
  359. and can be configured to throw an error.
  360. .. warning::
  361. Hashers using this mixin will generally need to override
  362. the default PasswordHash.truncate_error policy of "True",
  363. and will similarly want to override .truncate_verify_reject as well.
  364. TODO: This should be done explicitly, but for now this mixin sets
  365. these flags implicitly.
  366. """
  367. truncate_error = False
  368. truncate_verify_reject = False
  369. @classmethod
  370. def using(cls, truncate_error=None, **kwds):
  371. subcls = super(TruncateMixin, cls).using(**kwds)
  372. if truncate_error is not None:
  373. truncate_error = as_bool(truncate_error, param="truncate_error")
  374. if truncate_error is not None:
  375. subcls.truncate_error = truncate_error
  376. return subcls
  377. @classmethod
  378. def _check_truncate_policy(cls, secret):
  379. """
  380. make sure secret won't be truncated.
  381. NOTE: this should only be called for .hash(), not for .verify(),
  382. which should honor the .truncate_verify_reject policy.
  383. """
  384. assert cls.truncate_size is not None, "truncate_size must be set by subclass"
  385. if cls.truncate_error and len(secret) > cls.truncate_size:
  386. raise exc.PasswordTruncateError(cls)
  387. #=============================================================================
  388. # GenericHandler
  389. #=============================================================================
  390. class GenericHandler(MinimalHandler):
  391. """helper class for implementing hash handlers.
  392. GenericHandler-derived classes will have (at least) the following
  393. constructor options, though others may be added by mixins
  394. and by the class itself:
  395. :param checksum:
  396. this should contain the digest portion of a
  397. parsed hash (mainly provided when the constructor is called
  398. by :meth:`from_string()`).
  399. defaults to ``None``.
  400. :param use_defaults:
  401. If ``False`` (the default), a :exc:`TypeError` should be thrown
  402. if any settings required by the handler were not explicitly provided.
  403. If ``True``, the handler should attempt to provide a default for any
  404. missing values. This means generate missing salts, fill in default
  405. cost parameters, etc.
  406. This is typically only set to ``True`` when the constructor
  407. is called by :meth:`hash`, allowing user-provided values
  408. to be handled in a more permissive manner.
  409. :param relaxed:
  410. If ``False`` (the default), a :exc:`ValueError` should be thrown
  411. if any settings are out of bounds or otherwise invalid.
  412. If ``True``, they should be corrected if possible, and a warning
  413. issue. If not possible, only then should an error be raised.
  414. (e.g. under ``relaxed=True``, rounds values will be clamped
  415. to min/max rounds).
  416. This is mainly used when parsing the config strings of certain
  417. hashes, whose specifications implementations to be tolerant
  418. of incorrect values in salt strings.
  419. Class Attributes
  420. ================
  421. .. attribute:: ident
  422. [optional]
  423. If this attribute is filled in, the default :meth:`identify` method will use
  424. it as a identifying prefix that can be used to recognize instances of this handler's
  425. hash. Filling this out is recommended for speed.
  426. This should be a unicode str.
  427. .. attribute:: _hash_regex
  428. [optional]
  429. If this attribute is filled in, the default :meth:`identify` method
  430. will use it to recognize instances of the hash. If :attr:`ident`
  431. is specified, this will be ignored.
  432. This should be a unique regex object.
  433. .. attribute:: checksum_size
  434. [optional]
  435. Specifies the number of characters that should be expected in the checksum string.
  436. If omitted, no check will be performed.
  437. .. attribute:: checksum_chars
  438. [optional]
  439. A string listing all the characters allowed in the checksum string.
  440. If omitted, no check will be performed.
  441. This should be a unicode str.
  442. .. attribute:: _stub_checksum
  443. Placeholder checksum that will be used by genconfig()
  444. in lieu of actually generating a hash for the empty string.
  445. This should be a string of the same datatype as :attr:`checksum`.
  446. Instance Attributes
  447. ===================
  448. .. attribute:: checksum
  449. The checksum string provided to the constructor (after passing it
  450. through :meth:`_norm_checksum`).
  451. Required Subclass Methods
  452. =========================
  453. The following methods must be provided by handler subclass:
  454. .. automethod:: from_string
  455. .. automethod:: to_string
  456. .. automethod:: _calc_checksum
  457. Default Methods
  458. ===============
  459. The following methods have default implementations that should work for
  460. most cases, though they may be overridden if the hash subclass needs to:
  461. .. automethod:: _norm_checksum
  462. .. automethod:: genconfig
  463. .. automethod:: genhash
  464. .. automethod:: identify
  465. .. automethod:: hash
  466. .. automethod:: verify
  467. """
  468. #===================================================================
  469. # class attr
  470. #===================================================================
  471. # this must be provided by the actual class.
  472. setting_kwds = None
  473. # providing default since most classes don't use this at all.
  474. context_kwds = ()
  475. # optional prefix that uniquely identifies hash
  476. ident = None
  477. # optional regexp for recognizing hashes,
  478. # used by default identify() if .ident isn't specified.
  479. _hash_regex = None
  480. # if specified, _norm_checksum will require this length
  481. checksum_size = None
  482. # if specified, _norm_checksum() will validate this
  483. checksum_chars = None
  484. # private flag used by HasRawChecksum
  485. _checksum_is_bytes = False
  486. #===================================================================
  487. # instance attrs
  488. #===================================================================
  489. checksum = None # stores checksum
  490. # use_defaults = False # whether _norm_xxx() funcs should fill in defaults.
  491. # relaxed = False # when _norm_xxx() funcs should be strict about inputs
  492. #===================================================================
  493. # init
  494. #===================================================================
  495. def __init__(self, checksum=None, use_defaults=False, **kwds):
  496. self.use_defaults = use_defaults
  497. super(GenericHandler, self).__init__(**kwds)
  498. if checksum is not None:
  499. # XXX: do we need to set .relaxed for checksum coercion?
  500. self.checksum = self._norm_checksum(checksum)
  501. # NOTE: would like to make this classmethod, but fshp checksum size
  502. # is dependant on .variant, so leaving this as instance method.
  503. def _norm_checksum(self, checksum, relaxed=False):
  504. """validates checksum keyword against class requirements,
  505. returns normalized version of checksum.
  506. """
  507. # NOTE: by default this code assumes checksum should be unicode.
  508. # For classes where the checksum is raw bytes, the HasRawChecksum sets
  509. # the _checksum_is_bytes flag which alters various code paths below.
  510. # normalize to bytes / unicode
  511. raw = self._checksum_is_bytes
  512. if raw:
  513. # NOTE: no clear route to reasonably convert unicode -> raw bytes,
  514. # so 'relaxed' does nothing here
  515. if not isinstance(checksum, bytes):
  516. raise exc.ExpectedTypeError(checksum, "bytes", "checksum")
  517. elif not isinstance(checksum, unicode):
  518. if isinstance(checksum, bytes) and relaxed:
  519. warn("checksum should be unicode, not bytes", PasslibHashWarning)
  520. checksum = checksum.decode("ascii")
  521. else:
  522. raise exc.ExpectedTypeError(checksum, "unicode", "checksum")
  523. # check size
  524. cc = self.checksum_size
  525. if cc and len(checksum) != cc:
  526. raise exc.ChecksumSizeError(self, raw=raw)
  527. # check charset
  528. if not raw:
  529. cs = self.checksum_chars
  530. if cs and any(c not in cs for c in checksum):
  531. raise ValueError("invalid characters in %s checksum" % (self.name,))
  532. return checksum
  533. #===================================================================
  534. # password hash api - formatting interface
  535. #===================================================================
  536. @classmethod
  537. def identify(cls, hash):
  538. # NOTE: subclasses may wish to use faster / simpler identify,
  539. # and raise value errors only when an invalid (but identifiable)
  540. # string is parsed
  541. hash = to_unicode_for_identify(hash)
  542. if not hash:
  543. return False
  544. # does class specify a known unique prefix to look for?
  545. ident = cls.ident
  546. if ident is not None:
  547. return hash.startswith(ident)
  548. # does class provide a regexp to use?
  549. pat = cls._hash_regex
  550. if pat is not None:
  551. return pat.match(hash) is not None
  552. # as fallback, try to parse hash, and see if we succeed.
  553. # inefficient, but works for most cases.
  554. try:
  555. cls.from_string(hash)
  556. return True
  557. except ValueError:
  558. return False
  559. @classmethod
  560. def from_string(cls, hash, **context): # pragma: no cover
  561. r"""
  562. return parsed instance from hash/configuration string
  563. :param \*\*context:
  564. context keywords to pass to constructor (if applicable).
  565. :raises ValueError: if hash is incorrectly formatted
  566. :returns:
  567. hash parsed into components,
  568. for formatting / calculating checksum.
  569. """
  570. raise NotImplementedError("%s must implement from_string()" % (cls,))
  571. def to_string(self): # pragma: no cover
  572. """render instance to hash or configuration string
  573. :returns:
  574. hash string with salt & digest included.
  575. should return native string type (ascii-bytes under python 2,
  576. unicode under python 3)
  577. """
  578. raise NotImplementedError("%s must implement from_string()" % (self.__class__,))
  579. #===================================================================
  580. # checksum generation
  581. #===================================================================
  582. # NOTE: this is only used by genconfig(), and will be removed in passlib 2.0
  583. @property
  584. def _stub_checksum(self):
  585. """
  586. placeholder used by default .genconfig() so it can avoid expense of calculating digest.
  587. """
  588. # used fixed string if available
  589. if self.checksum_size:
  590. if self._checksum_is_bytes:
  591. return b'\x00' * self.checksum_size
  592. if self.checksum_chars:
  593. return self.checksum_chars[0] * self.checksum_size
  594. # hack to minimize cost of calculating real checksum
  595. if isinstance(self, HasRounds):
  596. orig = self.rounds
  597. self.rounds = self.min_rounds or 1
  598. try:
  599. return self._calc_checksum("")
  600. finally:
  601. self.rounds = orig
  602. # final fallback, generate a real checksum
  603. return self._calc_checksum("")
  604. def _calc_checksum(self, secret): # pragma: no cover
  605. """given secret; calcuate and return encoded checksum portion of hash
  606. string, taking config from object state
  607. calc checksum implementations may assume secret is always
  608. either unicode or bytes, checks are performed by verify/etc.
  609. """
  610. raise NotImplementedError("%s must implement _calc_checksum()" %
  611. (self.__class__,))
  612. #===================================================================
  613. #'application' interface (default implementation)
  614. #===================================================================
  615. @classmethod
  616. def hash(cls, secret, **kwds):
  617. if kwds:
  618. # Deprecating passing any settings keywords via .hash() as of passlib 1.7; everything
  619. # should use .using().hash() instead. If any keywords are specified, presume they're
  620. # context keywords by default (the common case), and extract out any settings kwds.
  621. # Support for passing settings via .hash() will be removed in Passlib 2.0, along with
  622. # this block of code.
  623. settings = extract_settings_kwds(cls, kwds)
  624. if settings:
  625. warn_hash_settings_deprecation(cls, settings)
  626. return cls.using(**settings).hash(secret, **kwds)
  627. # NOTE: at this point, 'kwds' should just contain context_kwds subset
  628. validate_secret(secret)
  629. self = cls(use_defaults=True, **kwds)
  630. self.checksum = self._calc_checksum(secret)
  631. return self.to_string()
  632. @classmethod
  633. def verify(cls, secret, hash, **context):
  634. # NOTE: classes with multiple checksum encodings should either
  635. # override this method, or ensure that from_string() / _norm_checksum()
  636. # ensures .checksum always uses a single canonical representation.
  637. validate_secret(secret)
  638. self = cls.from_string(hash, **context)
  639. chk = self.checksum
  640. if chk is None:
  641. raise exc.MissingDigestError(cls)
  642. return consteq(self._calc_checksum(secret), chk)
  643. #===================================================================
  644. # legacy crypt interface
  645. #===================================================================
  646. @deprecated_method(deprecated="1.7", removed="2.0")
  647. @classmethod
  648. def genconfig(cls, **kwds):
  649. # NOTE: 'kwds' should generally always be settings, so after this completes, *should* be empty.
  650. settings = extract_settings_kwds(cls, kwds)
  651. if settings:
  652. return cls.using(**settings).genconfig(**kwds)
  653. # NOTE: this uses optional stub checksum to bypass potentially expensive digest generation,
  654. # when caller just wants the config string.
  655. self = cls(use_defaults=True, **kwds)
  656. self.checksum = self._stub_checksum
  657. return self.to_string()
  658. @deprecated_method(deprecated="1.7", removed="2.0")
  659. @classmethod
  660. def genhash(cls, secret, config, **context):
  661. if config is None:
  662. raise TypeError("config must be string")
  663. validate_secret(secret)
  664. self = cls.from_string(config, **context)
  665. self.checksum = self._calc_checksum(secret)
  666. return self.to_string()
  667. #===================================================================
  668. # migration interface (basde implementation)
  669. #===================================================================
  670. @classmethod
  671. def needs_update(cls, hash, secret=None, **kwds):
  672. # NOTE: subclasses should generally just wrap _calc_needs_update()
  673. # to check their particular keywords.
  674. self = cls.from_string(hash)
  675. assert isinstance(self, cls)
  676. return self._calc_needs_update(secret=secret, **kwds)
  677. def _calc_needs_update(self, secret=None):
  678. """
  679. internal helper for :meth:`needs_update`.
  680. """
  681. # NOTE: this just provides a stub, subclasses & mixins
  682. # should override this with their own tests.
  683. return False
  684. #===================================================================
  685. # experimental - the following methods are not finished or tested,
  686. # but way work correctly for some hashes
  687. #===================================================================
  688. _unparsed_settings = ("salt_size", "relaxed")
  689. _unsafe_settings = ("salt", "checksum")
  690. @classproperty
  691. def _parsed_settings(cls):
  692. return (key for key in cls.setting_kwds
  693. if key not in cls._unparsed_settings)
  694. # XXX: make this a global function?
  695. @staticmethod
  696. def _sanitize(value, char=u("*")):
  697. """default method to obscure sensitive fields"""
  698. if value is None:
  699. return None
  700. if isinstance(value, bytes):
  701. from passlib.utils.binary import ab64_encode
  702. value = ab64_encode(value).decode("ascii")
  703. elif not isinstance(value, unicode):
  704. value = unicode(value)
  705. size = len(value)
  706. clip = min(4, size//8)
  707. return value[:clip] + char * (size-clip)
  708. @classmethod
  709. def parsehash(cls, hash, checksum=True, sanitize=False):
  710. """[experimental method] parse hash into dictionary of settings.
  711. this essentially acts as the inverse of :meth:`hash`: for most
  712. cases, if ``hash = cls.hash(secret, **opts)``, then
  713. ``cls.parsehash(hash)`` will return a dict matching the original options
  714. (with the extra keyword *checksum*).
  715. this method may not work correctly for all hashes,
  716. and may not be available on some few. its interface may
  717. change in future releases, if it's kept around at all.
  718. :arg hash: hash to parse
  719. :param checksum: include checksum keyword? (defaults to True)
  720. :param sanitize: mask data for sensitive fields? (defaults to False)
  721. """
  722. # FIXME: this may not work for hashes with non-standard settings.
  723. # XXX: how should this handle checksum/salt encoding?
  724. # need to work that out for hash() anyways.
  725. self = cls.from_string(hash)
  726. # XXX: could split next few lines out as self._parsehash() for subclassing
  727. # XXX: could try to resolve ident/variant to publically suitable alias.
  728. UNSET = object()
  729. kwds = dict((key, getattr(self, key)) for key in self._parsed_settings
  730. if getattr(self, key) != getattr(cls, key, UNSET))
  731. if checksum and self.checksum is not None:
  732. kwds['checksum'] = self.checksum
  733. if sanitize:
  734. if sanitize is True:
  735. sanitize = cls._sanitize
  736. for key in cls._unsafe_settings:
  737. if key in kwds:
  738. kwds[key] = sanitize(kwds[key])
  739. return kwds
  740. @classmethod
  741. def bitsize(cls, **kwds):
  742. """[experimental method] return info about bitsizes of hash"""
  743. try:
  744. info = super(GenericHandler, cls).bitsize(**kwds)
  745. except AttributeError:
  746. info = {}
  747. cc = ALL_BYTE_VALUES if cls._checksum_is_bytes else cls.checksum_chars
  748. if cls.checksum_size and cc:
  749. # FIXME: this may overestimate size due to padding bits (e.g. bcrypt)
  750. # FIXME: this will be off by 1 for case-insensitive hashes.
  751. info['checksum'] = _bitsize(cls.checksum_size, cc)
  752. return info
  753. #===================================================================
  754. # eoc
  755. #===================================================================
  756. class StaticHandler(GenericHandler):
  757. """GenericHandler mixin for classes which have no settings.
  758. This mixin assumes the entirety of the hash ise stored in the
  759. :attr:`checksum` attribute; that the hash has no rounds, salt,
  760. etc. This class provides the following:
  761. * a default :meth:`genconfig` that always returns None.
  762. * a default :meth:`from_string` and :meth:`to_string`
  763. that store the entire hash within :attr:`checksum`,
  764. after optionally stripping a constant prefix.
  765. All that is required by subclasses is an implementation of
  766. the :meth:`_calc_checksum` method.
  767. """
  768. # TODO: document _norm_hash()
  769. setting_kwds = ()
  770. # optional constant prefix subclasses can specify
  771. _hash_prefix = u("")
  772. @classmethod
  773. def from_string(cls, hash, **context):
  774. # default from_string() which strips optional prefix,
  775. # and passes rest unchanged as checksum value.
  776. hash = to_unicode(hash, "ascii", "hash")
  777. hash = cls._norm_hash(hash)
  778. # could enable this for extra strictness
  779. ##pat = cls._hash_regex
  780. ##if pat and pat.match(hash) is None:
  781. ## raise ValueError("not a valid %s hash" % (cls.name,))
  782. prefix = cls._hash_prefix
  783. if prefix:
  784. if hash.startswith(prefix):
  785. hash = hash[len(prefix):]
  786. else:
  787. raise exc.InvalidHashError(cls)
  788. return cls(checksum=hash, **context)
  789. @classmethod
  790. def _norm_hash(cls, hash):
  791. """helper for subclasses to normalize case if needed"""
  792. return hash
  793. def to_string(self):
  794. return uascii_to_str(self._hash_prefix + self.checksum)
  795. # per-subclass: stores dynamically created subclass used by _calc_checksum() stub
  796. __cc_compat_hack = None
  797. def _calc_checksum(self, secret):
  798. """given secret; calcuate and return encoded checksum portion of hash
  799. string, taking config from object state
  800. """
  801. # NOTE: prior to 1.6, StaticHandler required classes implement genhash
  802. # instead of this method. so if we reach here, we try calling genhash.
  803. # if that succeeds, we issue deprecation warning. if it fails,
  804. # we'll just recurse back to here, but in a different instance.
  805. # so before we call genhash, we create a subclass which handles
  806. # throwing the NotImplementedError.
  807. cls = self.__class__
  808. assert cls.__module__ != __name__
  809. wrapper_cls = cls.__cc_compat_hack
  810. if wrapper_cls is None:
  811. def inner(self, secret):
  812. raise NotImplementedError("%s must implement _calc_checksum()" %
  813. (cls,))
  814. wrapper_cls = cls.__cc_compat_hack = type(cls.__name__ + "_wrapper",
  815. (cls,), dict(_calc_checksum=inner, __module__=cls.__module__))
  816. context = dict((k,getattr(self,k)) for k in self.context_kwds)
  817. # NOTE: passing 'config=None' here even though not currently allowed by ifc,
  818. # since it *is* allowed under the old 1.5 ifc we're checking for here.
  819. try:
  820. hash = wrapper_cls.genhash(secret, None, **context)
  821. except TypeError as err:
  822. if str(err) == "config must be string":
  823. raise NotImplementedError("%s must implement _calc_checksum()" %
  824. (cls,))
  825. else:
  826. raise
  827. warn("%r should be updated to implement StaticHandler._calc_checksum() "
  828. "instead of StaticHandler.genhash(), support for the latter "
  829. "style will be removed in Passlib 1.8" % cls,
  830. DeprecationWarning)
  831. return str_to_uascii(hash)
  832. #=============================================================================
  833. # GenericHandler mixin classes
  834. #=============================================================================
  835. class HasEncodingContext(GenericHandler):
  836. """helper for classes which require knowledge of the encoding used"""
  837. context_kwds = ("encoding",)
  838. default_encoding = "utf-8"
  839. def __init__(self, encoding=None, **kwds):
  840. super(HasEncodingContext, self).__init__(**kwds)
  841. self.encoding = encoding or self.default_encoding
  842. class HasUserContext(GenericHandler):
  843. """helper for classes which require a user context keyword"""
  844. context_kwds = ("user",)
  845. def __init__(self, user=None, **kwds):
  846. super(HasUserContext, self).__init__(**kwds)
  847. self.user = user
  848. # XXX: would like to validate user input here, but calls to from_string()
  849. # which lack context keywords would then fail; so leaving code per-handler.
  850. # wrap funcs to accept 'user' as positional arg for ease of use.
  851. @classmethod
  852. def hash(cls, secret, user=None, **context):
  853. return super(HasUserContext, cls).hash(secret, user=user, **context)
  854. @classmethod
  855. def verify(cls, secret, hash, user=None, **context):
  856. return super(HasUserContext, cls).verify(secret, hash, user=user, **context)
  857. @deprecated_method(deprecated="1.7", removed="2.0")
  858. @classmethod
  859. def genhash(cls, secret, config, user=None, **context):
  860. return super(HasUserContext, cls).genhash(secret, config, user=user, **context)
  861. # XXX: how to guess the entropy of a username?
  862. # most of these hashes are for a system (e.g. Oracle)
  863. # which has a few *very common* names and thus really low entropy;
  864. # while the rest are slightly less predictable.
  865. # need to find good reference about this.
  866. ##@classmethod
  867. ##def bitsize(cls, **kwds):
  868. ## info = super(HasUserContext, cls).bitsize(**kwds)
  869. ## info['user'] = xxx
  870. ## return info
  871. #------------------------------------------------------------------------
  872. # checksum mixins
  873. #------------------------------------------------------------------------
  874. class HasRawChecksum(GenericHandler):
  875. """mixin for classes which work with decoded checksum bytes
  876. .. todo::
  877. document this class's usage
  878. """
  879. # NOTE: GenericHandler.checksum_chars is ignored by this implementation.
  880. # NOTE: all HasRawChecksum code is currently part of GenericHandler,
  881. # using private '_checksum_is_bytes' flag.
  882. # this arrangement may be changed in the future.
  883. _checksum_is_bytes = True
  884. #------------------------------------------------------------------------
  885. # ident mixins
  886. #------------------------------------------------------------------------
  887. class HasManyIdents(GenericHandler):
  888. """mixin for hashes which use multiple prefix identifiers
  889. For the hashes which may use multiple identifier prefixes,
  890. this mixin adds an ``ident`` keyword to constructor.
  891. Any value provided is passed through the :meth:`norm_idents` method,
  892. which takes care of validating the identifier,
  893. as well as allowing aliases for easier specification
  894. of the identifiers by the user.
  895. .. todo::
  896. document this class's usage
  897. Class Methods
  898. =============
  899. .. todo:: document using() and needs_update() options
  900. """
  901. #===================================================================
  902. # class attrs
  903. #===================================================================
  904. default_ident = None # should be unicode
  905. ident_values = None # should be list of unicode strings
  906. ident_aliases = None # should be dict of unicode -> unicode
  907. # NOTE: any aliases provided to norm_ident() as bytes
  908. # will have been converted to unicode before
  909. # comparing against this dictionary.
  910. # NOTE: relying on test_06_HasManyIdents() to verify
  911. # these are configured correctly.
  912. #===================================================================
  913. # instance attrs
  914. #===================================================================
  915. ident = None
  916. #===================================================================
  917. # variant constructor
  918. #===================================================================
  919. @classmethod
  920. def using(cls, # keyword only...
  921. default_ident=None, ident=None, **kwds):
  922. """
  923. This mixin adds support for the following :meth:`~passlib.ifc.PasswordHash.using` keywords:
  924. :param default_ident:
  925. default identifier that will be used by resulting customized hasher.
  926. :param ident:
  927. supported as alternate alias for **default_ident**.
  928. """
  929. # resolve aliases
  930. if ident is not None:
  931. if default_ident is not None:
  932. raise TypeError("'default_ident' and 'ident' are mutually exclusive")
  933. default_ident = ident
  934. # create subclass
  935. subcls = super(HasManyIdents, cls).using(**kwds)
  936. # add custom default ident
  937. # (NOTE: creates instance to run value through _norm_ident())
  938. if default_ident is not None:
  939. subcls.default_ident = cls(ident=default_ident, use_defaults=True).ident
  940. return subcls
  941. #===================================================================
  942. # init
  943. #===================================================================
  944. def __init__(self, ident=None, **kwds):
  945. super(HasManyIdents, self).__init__(**kwds)
  946. # init ident
  947. if ident is not None:
  948. ident = self._norm_ident(ident)
  949. elif self.use_defaults:
  950. ident = self.default_ident
  951. assert validate_default_value(self, ident, self._norm_ident, param="default_ident")
  952. else:
  953. raise TypeError("no ident specified")
  954. self.ident = ident
  955. @classmethod
  956. def _norm_ident(cls, ident):
  957. """
  958. helper which normalizes & validates 'ident' value.
  959. """
  960. # handle bytes
  961. assert ident is not None
  962. if isinstance(ident, bytes):
  963. ident = ident.decode('ascii')
  964. # check if identifier is valid
  965. iv = cls.ident_values
  966. if ident in iv:
  967. return ident
  968. # resolve aliases, and recheck against ident_values
  969. ia = cls.ident_aliases
  970. if ia:
  971. try:
  972. value = ia[ident]
  973. except KeyError:
  974. pass
  975. else:
  976. if value in iv:
  977. return value
  978. # failure!
  979. raise ValueError("invalid ident: %r" % (ident,))
  980. #===================================================================
  981. # password hash api
  982. #===================================================================
  983. @classmethod
  984. def identify(cls, hash):
  985. hash = to_unicode_for_identify(hash)
  986. return hash.startswith(cls.ident_values)
  987. @classmethod
  988. def _parse_ident(cls, hash):
  989. """extract ident prefix from hash, helper for subclasses' from_string()"""
  990. hash = to_unicode(hash, "ascii", "hash")
  991. for ident in cls.ident_values:
  992. if hash.startswith(ident):
  993. return ident, hash[len(ident):]
  994. raise exc.InvalidHashError(cls)
  995. # XXX: implement a needs_update() helper that marks everything but default_ident as deprecated?
  996. #===================================================================
  997. # eoc
  998. #===================================================================
  999. #------------------------------------------------------------------------
  1000. # salt mixins
  1001. #------------------------------------------------------------------------
  1002. class HasSalt(GenericHandler):
  1003. """mixin for validating salts.
  1004. This :class:`GenericHandler` mixin adds a ``salt`` keyword to the class constuctor;
  1005. any value provided is passed through the :meth:`_norm_salt` method,
  1006. which takes care of validating salt length and content,
  1007. as well as generating new salts if one it not provided.
  1008. :param salt:
  1009. optional salt string
  1010. :param salt_size:
  1011. optional size of salt (only used if no salt provided);
  1012. defaults to :attr:`default_salt_size`.
  1013. Class Attributes
  1014. ================
  1015. In order for :meth:`!_norm_salt` to do its job, the following
  1016. attributes should be provided by the handler subclass:
  1017. .. attribute:: min_salt_size
  1018. The minimum number of characters allowed in a salt string.
  1019. An :exc:`ValueError` will be throw if the provided salt is too small.
  1020. Defaults to ``0``.
  1021. .. attribute:: max_salt_size
  1022. The maximum number of characters allowed in a salt string.
  1023. By default an :exc:`ValueError` will be throw if the provided salt is
  1024. too large; but if ``relaxed=True``, it will be clipped and a warning
  1025. issued instead. Defaults to ``None``, for no maximum.
  1026. .. attribute:: default_salt_size
  1027. [required]
  1028. If no salt is provided, this should specify the size of the salt
  1029. that will be generated by :meth:`_generate_salt`. By default
  1030. this will fall back to :attr:`max_salt_size`.
  1031. .. attribute:: salt_chars
  1032. A string containing all the characters which are allowed in the salt
  1033. string. An :exc:`ValueError` will be throw if any other characters
  1034. are encountered. May be set to ``None`` to skip this check (but see
  1035. in :attr:`default_salt_chars`).
  1036. .. attribute:: default_salt_chars
  1037. [required]
  1038. This attribute controls the set of characters use to generate
  1039. *new* salt strings. By default, it mirrors :attr:`salt_chars`.
  1040. If :attr:`!salt_chars` is ``None``, this attribute must be specified
  1041. in order to generate new salts. Aside from that purpose,
  1042. the main use of this attribute is for hashes which wish to generate
  1043. salts from a restricted subset of :attr:`!salt_chars`; such as
  1044. accepting all characters, but only using a-z.
  1045. Instance Attributes
  1046. ===================
  1047. .. attribute:: salt
  1048. This instance attribute will be filled in with the salt provided
  1049. to the constructor (as adapted by :meth:`_norm_salt`)
  1050. Subclassable Methods
  1051. ====================
  1052. .. automethod:: _norm_salt
  1053. .. automethod:: _generate_salt
  1054. """
  1055. # TODO: document _truncate_salt()
  1056. # XXX: allow providing raw salt to this class, and encoding it?
  1057. #===================================================================
  1058. # class attrs
  1059. #===================================================================
  1060. min_salt_size = 0
  1061. max_salt_size = None
  1062. salt_chars = None
  1063. @classproperty
  1064. def default_salt_size(cls):
  1065. """default salt size (defaults to *max_salt_size*)"""
  1066. return cls.max_salt_size
  1067. @classproperty
  1068. def default_salt_chars(cls):
  1069. """charset used to generate new salt strings (defaults to *salt_chars*)"""
  1070. return cls.salt_chars
  1071. # private helpers for HasRawSalt, shouldn't be used by subclasses
  1072. _salt_is_bytes = False
  1073. _salt_unit = "chars"
  1074. # TODO: could support using(min/max_desired_salt_size) via using() and needs_update()
  1075. #===================================================================
  1076. # instance attrs
  1077. #===================================================================
  1078. salt = None
  1079. #===================================================================
  1080. # variant constructor
  1081. #===================================================================
  1082. @classmethod
  1083. def using(cls, # keyword only...
  1084. default_salt_size=None,
  1085. salt_size=None, # aliases used by CryptContext
  1086. salt=None,
  1087. **kwds):
  1088. # check for aliases used by CryptContext
  1089. if salt_size is not None:
  1090. if default_salt_size is not None:
  1091. raise TypeError("'salt_size' and 'default_salt_size' aliases are mutually exclusive")
  1092. default_salt_size = salt_size
  1093. # generate new subclass
  1094. subcls = super(HasSalt, cls).using(**kwds)
  1095. # replace default_rounds
  1096. relaxed = kwds.get("relaxed")
  1097. if default_salt_size is not None:
  1098. if isinstance(default_salt_size, native_string_types):
  1099. default_salt_size = int(default_salt_size)
  1100. subcls.default_salt_size = subcls._clip_to_valid_salt_size(default_salt_size,
  1101. param="salt_size",
  1102. relaxed=relaxed)
  1103. # if salt specified, replace _generate_salt() with fixed output.
  1104. # NOTE: this is mainly useful for testing / debugging.
  1105. if salt is not None:
  1106. salt = subcls._norm_salt(salt, relaxed=relaxed)
  1107. subcls._generate_salt = staticmethod(lambda: salt)
  1108. return subcls
  1109. # XXX: would like to combine w/ _norm_salt() code below, but doesn't quite fit.
  1110. @classmethod
  1111. def _clip_to_valid_salt_size(cls, salt_size, param="salt_size", relaxed=True):
  1112. """
  1113. internal helper --
  1114. clip salt size value to handler's absolute limits (min_salt_size / max_salt_size)
  1115. :param relaxed:
  1116. if ``True`` (the default), issues PasslibHashWarning is rounds are outside allowed range.
  1117. if ``False``, raises a ValueError instead.
  1118. :param param:
  1119. optional name of parameter to insert into error/warning messages.
  1120. :returns:
  1121. clipped rounds value
  1122. """
  1123. mn = cls.min_salt_size
  1124. mx = cls.max_salt_size
  1125. # check if salt size is fixed
  1126. if mn == mx:
  1127. if salt_size != mn:
  1128. msg = "%s: %s (%d) must be exactly %d" % (cls.name, param, salt_size, mn)
  1129. if relaxed:
  1130. warn(msg, PasslibHashWarning)
  1131. else:
  1132. raise ValueError(msg)
  1133. return mn
  1134. # check min size
  1135. if salt_size < mn:
  1136. msg = "%s: %s (%r) below min_salt_size (%d)" % (cls.name, param, salt_size, mn)
  1137. if relaxed:
  1138. warn(msg, PasslibHashWarning)
  1139. salt_size = mn
  1140. else:
  1141. raise ValueError(msg)
  1142. # check max size
  1143. if mx and salt_size > mx:
  1144. msg = "%s: %s (%r) above max_salt_size (%d)" % (cls.name, param, salt_size, mx)
  1145. if relaxed:
  1146. warn(msg, PasslibHashWarning)
  1147. salt_size = mx
  1148. else:
  1149. raise ValueError(msg)
  1150. return salt_size
  1151. #===================================================================
  1152. # init
  1153. #===================================================================
  1154. def __init__(self, salt=None, **kwds):
  1155. super(HasSalt, self).__init__(**kwds)
  1156. if salt is not None:
  1157. salt = self._parse_salt(salt)
  1158. elif self.use_defaults:
  1159. salt = self._generate_salt()
  1160. assert self._norm_salt(salt) == salt, "generated invalid salt: %r" % (salt,)
  1161. else:
  1162. raise TypeError("no salt specified")
  1163. self.salt = salt
  1164. # NOTE: split out mainly so sha256_crypt can subclass this
  1165. def _parse_salt(self, salt):
  1166. return self._norm_salt(salt)
  1167. @classmethod
  1168. def _norm_salt(cls, salt, relaxed=False):
  1169. """helper to normalize & validate user-provided salt string
  1170. :arg salt:
  1171. salt string
  1172. :raises TypeError:
  1173. If salt not correct type.
  1174. :raises ValueError:
  1175. * if salt contains chars that aren't in :attr:`salt_chars`.
  1176. * if salt contains less than :attr:`min_salt_size` characters.
  1177. * if ``relaxed=False`` and salt has more than :attr:`max_salt_size`
  1178. characters (if ``relaxed=True``, the salt is truncated
  1179. and a warning is issued instead).
  1180. :returns:
  1181. normalized salt
  1182. """
  1183. # check type
  1184. if cls._salt_is_bytes:
  1185. if not isinstance(salt, bytes):
  1186. raise exc.ExpectedTypeError(salt, "bytes", "salt")
  1187. else:
  1188. if not isinstance(salt, unicode):
  1189. # NOTE: allowing bytes under py2 so salt can be native str.
  1190. if isinstance(salt, bytes) and (PY2 or relaxed):
  1191. salt = salt.decode("ascii")
  1192. else:
  1193. raise exc.ExpectedTypeError(salt, "unicode", "salt")
  1194. # check charset
  1195. sc = cls.salt_chars
  1196. if sc is not None and any(c not in sc for c in salt):
  1197. raise ValueError("invalid characters in %s salt" % cls.name)
  1198. # check min size
  1199. mn = cls.min_salt_size
  1200. if mn and len(salt) < mn:
  1201. msg = "salt too small (%s requires %s %d %s)" % (cls.name,
  1202. "exactly" if mn == cls.max_salt_size else ">=", mn, cls._salt_unit)
  1203. raise ValueError(msg)
  1204. # check max size
  1205. mx = cls.max_salt_size
  1206. if mx and len(salt) > mx:
  1207. msg = "salt too large (%s requires %s %d %s)" % (cls.name,
  1208. "exactly" if mx == mn else "<=", mx, cls._salt_unit)
  1209. if relaxed:
  1210. warn(msg, PasslibHashWarning)
  1211. salt = cls._truncate_salt(salt, mx)
  1212. else:
  1213. raise ValueError(msg)
  1214. return salt
  1215. @staticmethod
  1216. def _truncate_salt(salt, mx):
  1217. # NOTE: some hashes (e.g. bcrypt) has structure within their
  1218. # salt string. this provides a method to override to perform
  1219. # the truncation properly
  1220. return salt[:mx]
  1221. @classmethod
  1222. def _generate_salt(cls):
  1223. """
  1224. helper method for _init_salt(); generates a new random salt string.
  1225. """
  1226. return getrandstr(rng, cls.default_salt_chars, cls.default_salt_size)
  1227. @classmethod
  1228. def bitsize(cls, salt_size=None, **kwds):
  1229. """[experimental method] return info about bitsizes of hash"""
  1230. info = super(HasSalt, cls).bitsize(**kwds)
  1231. if salt_size is None:
  1232. salt_size = cls.default_salt_size
  1233. # FIXME: this may overestimate size due to padding bits
  1234. # FIXME: this will be off by 1 for case-insensitive hashes.
  1235. info['salt'] = _bitsize(salt_size, cls.default_salt_chars)
  1236. return info
  1237. #===================================================================
  1238. # eoc
  1239. #===================================================================
  1240. class HasRawSalt(HasSalt):
  1241. """mixin for classes which use decoded salt parameter
  1242. A variant of :class:`!HasSalt` which takes in decoded bytes instead of an encoded string.
  1243. .. todo::
  1244. document this class's usage
  1245. """
  1246. salt_chars = ALL_BYTE_VALUES
  1247. # NOTE: all HasRawSalt code is currently part of HasSalt, using private
  1248. # '_salt_is_bytes' flag. this arrangement may be changed in the future.
  1249. _salt_is_bytes = True
  1250. _salt_unit = "bytes"
  1251. @classmethod
  1252. def _generate_salt(cls):
  1253. assert cls.salt_chars in [None, ALL_BYTE_VALUES]
  1254. return getrandbytes(rng, cls.default_salt_size)
  1255. #------------------------------------------------------------------------
  1256. # rounds mixin
  1257. #------------------------------------------------------------------------
  1258. class HasRounds(GenericHandler):
  1259. """mixin for validating rounds parameter
  1260. This :class:`GenericHandler` mixin adds a ``rounds`` keyword to the class
  1261. constuctor; any value provided is passed through the :meth:`_norm_rounds`
  1262. method, which takes care of validating the number of rounds.
  1263. :param rounds: optional number of rounds hash should use
  1264. Class Attributes
  1265. ================
  1266. In order for :meth:`!_norm_rounds` to do its job, the following
  1267. attributes must be provided by the handler subclass:
  1268. .. attribute:: min_rounds
  1269. The minimum number of rounds allowed. A :exc:`ValueError` will be
  1270. thrown if the rounds value is too small. Defaults to ``0``.
  1271. .. attribute:: max_rounds
  1272. The maximum number of rounds allowed. A :exc:`ValueError` will be
  1273. thrown if the rounds value is larger than this. Defaults to ``None``
  1274. which indicates no limit to the rounds value.
  1275. .. attribute:: default_rounds
  1276. If no rounds value is provided to constructor, this value will be used.
  1277. If this is not specified, a rounds value *must* be specified by the
  1278. application.
  1279. .. attribute:: rounds_cost
  1280. [required]
  1281. The ``rounds`` parameter typically encodes a cpu-time cost
  1282. for calculating a hash. This should be set to ``"linear"``
  1283. (the default) or ``"log2"``, depending on how the rounds value relates
  1284. to the actual amount of time that will be required.
  1285. Class Methods
  1286. =============
  1287. .. todo:: document using() and needs_update() options
  1288. Instance Attributes
  1289. ===================
  1290. .. attribute:: rounds
  1291. This instance attribute will be filled in with the rounds value provided
  1292. to the constructor (as adapted by :meth:`_norm_rounds`)
  1293. Subclassable Methods
  1294. ====================
  1295. .. automethod:: _norm_rounds
  1296. """
  1297. #===================================================================
  1298. # class attrs
  1299. #===================================================================
  1300. #-----------------
  1301. # algorithm options -- not application configurable
  1302. #-----------------
  1303. # XXX: rename to min_valid_rounds / max_valid_rounds,
  1304. # to clarify role compared to min_desired_rounds / max_desired_rounds?
  1305. min_rounds = 0
  1306. max_rounds = None
  1307. rounds_cost = "linear" # default to the common case
  1308. # hack to pass info to _CryptRecord (will be removed in passlib 2.0)
  1309. using_rounds_kwds = ("min_desired_rounds", "max_desired_rounds",
  1310. "min_rounds", "max_rounds",
  1311. "default_rounds", "vary_rounds")
  1312. #-----------------
  1313. # desired & default rounds -- configurable via .using() classmethod
  1314. #-----------------
  1315. min_desired_rounds = None
  1316. max_desired_rounds = None
  1317. default_rounds = None
  1318. vary_rounds = None
  1319. #===================================================================
  1320. # instance attrs
  1321. #===================================================================
  1322. rounds = None
  1323. #===================================================================
  1324. # variant constructor
  1325. #===================================================================
  1326. @classmethod
  1327. def using(cls, # keyword only...
  1328. min_desired_rounds=None, max_desired_rounds=None,
  1329. default_rounds=None, vary_rounds=None,
  1330. min_rounds=None, max_rounds=None, rounds=None, # aliases used by CryptContext
  1331. **kwds):
  1332. # check for aliases used by CryptContext
  1333. if min_rounds is not None:
  1334. if min_desired_rounds is not None:
  1335. raise TypeError("'min_rounds' and 'min_desired_rounds' aliases are mutually exclusive")
  1336. min_desired_rounds = min_rounds
  1337. if max_rounds is not None:
  1338. if max_desired_rounds is not None:
  1339. raise TypeError("'max_rounds' and 'max_desired_rounds' aliases are mutually exclusive")
  1340. max_desired_rounds = max_rounds
  1341. # use 'rounds' as fallback for min, max, AND default
  1342. # XXX: would it be better to make 'default_rounds' and 'rounds'
  1343. # aliases, and have a separate 'require_rounds' parameter for this behavior?
  1344. if rounds is not None:
  1345. if min_desired_rounds is None:
  1346. min_desired_rounds = rounds
  1347. if max_desired_rounds is None:
  1348. max_desired_rounds = rounds
  1349. if default_rounds is None:
  1350. default_rounds = rounds
  1351. # generate new subclass
  1352. subcls = super(HasRounds, cls).using(**kwds)
  1353. # replace min_desired_rounds
  1354. relaxed = kwds.get("relaxed")
  1355. if min_desired_rounds is None:
  1356. explicit_min_rounds = False
  1357. min_desired_rounds = cls.min_desired_rounds
  1358. else:
  1359. explicit_min_rounds = True
  1360. if isinstance(min_desired_rounds, native_string_types):
  1361. min_desired_rounds = int(min_desired_rounds)
  1362. subcls.min_desired_rounds = subcls._norm_rounds(min_desired_rounds,
  1363. param="min_desired_rounds",
  1364. relaxed=relaxed)
  1365. # replace max_desired_rounds
  1366. if max_desired_rounds is None:
  1367. max_desired_rounds = cls.max_desired_rounds
  1368. else:
  1369. if isinstance(max_desired_rounds, native_string_types):
  1370. max_desired_rounds = int(max_desired_rounds)
  1371. if min_desired_rounds and max_desired_rounds < min_desired_rounds:
  1372. msg = "%s: max_desired_rounds (%r) below min_desired_rounds (%r)" % \
  1373. (subcls.name, max_desired_rounds, min_desired_rounds)
  1374. if explicit_min_rounds:
  1375. raise ValueError(msg)
  1376. else:
  1377. warn(msg, PasslibConfigWarning)
  1378. max_desired_rounds = min_desired_rounds
  1379. subcls.max_desired_rounds = subcls._norm_rounds(max_desired_rounds,
  1380. param="max_desired_rounds",
  1381. relaxed=relaxed)
  1382. # replace default_rounds
  1383. if default_rounds is not None:
  1384. if isinstance(default_rounds, native_string_types):
  1385. default_rounds = int(default_rounds)
  1386. if min_desired_rounds and default_rounds < min_desired_rounds:
  1387. raise ValueError("%s: default_rounds (%r) below min_desired_rounds (%r)" %
  1388. (subcls.name, default_rounds, min_desired_rounds))
  1389. elif max_desired_rounds and default_rounds > max_desired_rounds:
  1390. raise ValueError("%s: default_rounds (%r) above max_desired_rounds (%r)" %
  1391. (subcls.name, default_rounds, max_desired_rounds))
  1392. subcls.default_rounds = subcls._norm_rounds(default_rounds,
  1393. param="default_rounds",
  1394. relaxed=relaxed)
  1395. # clip default rounds to new limits.
  1396. if subcls.default_rounds is not None:
  1397. subcls.default_rounds = subcls._clip_to_desired_rounds(subcls.default_rounds)
  1398. # replace / set vary_rounds
  1399. if vary_rounds is not None:
  1400. if isinstance(vary_rounds, native_string_types):
  1401. if vary_rounds.endswith("%"):
  1402. vary_rounds = float(vary_rounds[:-1]) * 0.01
  1403. elif "." in vary_rounds:
  1404. vary_rounds = float(vary_rounds)
  1405. else:
  1406. vary_rounds = int(vary_rounds)
  1407. if vary_rounds < 0:
  1408. raise ValueError("%s: vary_rounds (%r) below 0" %
  1409. (subcls.name, vary_rounds))
  1410. elif isinstance(vary_rounds, float):
  1411. # TODO: deprecate / disallow vary_rounds=1.0
  1412. if vary_rounds > 1:
  1413. raise ValueError("%s: vary_rounds (%r) above 1.0" %
  1414. (subcls.name, vary_rounds))
  1415. elif not isinstance(vary_rounds, int):
  1416. raise TypeError("vary_rounds must be int or float")
  1417. if vary_rounds:
  1418. warn("The 'vary_rounds' option is deprecated as of Passlib 1.7, "
  1419. "and will be removed in Passlib 2.0", PasslibConfigWarning)
  1420. subcls.vary_rounds = vary_rounds
  1421. # XXX: could cache _calc_vary_rounds_range() here if needed,
  1422. # but would need to handle user manually changing .default_rounds
  1423. return subcls
  1424. @classmethod
  1425. def _clip_to_desired_rounds(cls, rounds):
  1426. """
  1427. helper for :meth:`_generate_rounds` --
  1428. clips rounds value to desired min/max set by class (if any)
  1429. """
  1430. # NOTE: min/max_desired_rounds are None if unset.
  1431. # check minimum
  1432. mnd = cls.min_desired_rounds or 0
  1433. if rounds < mnd:
  1434. return mnd
  1435. # check maximum
  1436. mxd = cls.max_desired_rounds
  1437. if mxd and rounds > mxd:
  1438. return mxd
  1439. return rounds
  1440. @classmethod
  1441. def _calc_vary_rounds_range(cls, default_rounds):
  1442. """
  1443. helper for :meth:`_generate_rounds` --
  1444. returns range for vary rounds generation.
  1445. :returns:
  1446. (lower, upper) limits suitable for random.randint()
  1447. """
  1448. # XXX: could precalculate output of this in using() method, and save per-hash cost.
  1449. # but then users patching cls.vary_rounds / cls.default_rounds would get wrong value.
  1450. assert default_rounds
  1451. vary_rounds = cls.vary_rounds
  1452. # if vary_rounds specified as % of default, convert it to actual rounds
  1453. def linear_to_native(value, upper):
  1454. return value
  1455. if isinstance(vary_rounds, float):
  1456. assert 0 <= vary_rounds <= 1 # TODO: deprecate vary_rounds==1
  1457. if cls.rounds_cost == "log2":
  1458. # special case -- have to convert default_rounds to linear scale,
  1459. # apply +/- vary_rounds to that, and convert back to log scale again.
  1460. # linear_to_native() takes care of the "convert back" step.
  1461. default_rounds = 1 << default_rounds
  1462. def linear_to_native(value, upper):
  1463. if value <= 0: # log() undefined for <= 0
  1464. return 0
  1465. elif upper: # use smallest upper bound for start of range
  1466. return int(math.log(value, 2))
  1467. else: # use greatest lower bound for end of range
  1468. return int(math.ceil(math.log(value, 2)))
  1469. # calculate integer vary rounds based on current default_rounds
  1470. vary_rounds = int(default_rounds * vary_rounds)
  1471. # calculate bounds based on default_rounds +/- vary_rounds
  1472. assert vary_rounds >= 0 and isinstance(vary_rounds, int_types)
  1473. lower = linear_to_native(default_rounds - vary_rounds, False)
  1474. upper = linear_to_native(default_rounds + vary_rounds, True)
  1475. return cls._clip_to_desired_rounds(lower), cls._clip_to_desired_rounds(upper)
  1476. #===================================================================
  1477. # init
  1478. #===================================================================
  1479. def __init__(self, rounds=None, **kwds):
  1480. super(HasRounds, self).__init__(**kwds)
  1481. if rounds is not None:
  1482. rounds = self._parse_rounds(rounds)
  1483. elif self.use_defaults:
  1484. rounds = self._generate_rounds()
  1485. assert self._norm_rounds(rounds) == rounds, "generated invalid rounds: %r" % (rounds,)
  1486. else:
  1487. raise TypeError("no rounds specified")
  1488. self.rounds = rounds
  1489. # NOTE: split out mainly so sha256_crypt & bsdi_crypt can subclass this
  1490. def _parse_rounds(self, rounds):
  1491. return self._norm_rounds(rounds)
  1492. @classmethod
  1493. def _norm_rounds(cls, rounds, relaxed=False, param="rounds"):
  1494. """
  1495. helper for normalizing rounds value.
  1496. :arg rounds:
  1497. an integer cost parameter.
  1498. :param relaxed:
  1499. if ``True`` (the default), issues PasslibHashWarning is rounds are outside allowed range.
  1500. if ``False``, raises a ValueError instead.
  1501. :param param:
  1502. optional name of parameter to insert into error/warning messages.
  1503. :raises TypeError:
  1504. * if ``use_defaults=False`` and no rounds is specified
  1505. * if rounds is not an integer.
  1506. :raises ValueError:
  1507. * if rounds is ``None`` and class does not specify a value for
  1508. :attr:`default_rounds`.
  1509. * if ``relaxed=False`` and rounds is outside bounds of
  1510. :attr:`min_rounds` and :attr:`max_rounds` (if ``relaxed=True``,
  1511. the rounds value will be clamped, and a warning issued).
  1512. :returns:
  1513. normalized rounds value
  1514. """
  1515. return norm_integer(cls, rounds, cls.min_rounds, cls.max_rounds,
  1516. param=param, relaxed=relaxed)
  1517. @classmethod
  1518. def _generate_rounds(cls):
  1519. """
  1520. internal helper for :meth:`_norm_rounds` --
  1521. returns default rounds value, incorporating vary_rounds,
  1522. and any other limitations hash may place on rounds parameter.
  1523. """
  1524. # load default rounds
  1525. rounds = cls.default_rounds
  1526. if rounds is None:
  1527. raise TypeError("%s rounds value must be specified explicitly" % (cls.name,))
  1528. # randomly vary the rounds slightly basic on vary_rounds parameter.
  1529. # reads default_rounds internally.
  1530. if cls.vary_rounds:
  1531. lower, upper = cls._calc_vary_rounds_range(rounds)
  1532. assert lower <= rounds <= upper
  1533. if lower < upper:
  1534. rounds = rng.randint(lower, upper)
  1535. return rounds
  1536. #===================================================================
  1537. # migration interface
  1538. #===================================================================
  1539. def _calc_needs_update(self, **kwds):
  1540. """
  1541. mark hash as needing update if rounds is outside desired bounds.
  1542. """
  1543. min_desired_rounds = self.min_desired_rounds
  1544. if min_desired_rounds and self.rounds < min_desired_rounds:
  1545. return True
  1546. max_desired_rounds = self.max_desired_rounds
  1547. if max_desired_rounds and self.rounds > max_desired_rounds:
  1548. return True
  1549. return super(HasRounds, self)._calc_needs_update(**kwds)
  1550. #===================================================================
  1551. # experimental methods
  1552. #===================================================================
  1553. @classmethod
  1554. def bitsize(cls, rounds=None, vary_rounds=.1, **kwds):
  1555. """[experimental method] return info about bitsizes of hash"""
  1556. info = super(HasRounds, cls).bitsize(**kwds)
  1557. # NOTE: this essentially estimates how many bits of "salt"
  1558. # can be added by varying the rounds value just a little bit.
  1559. if cls.rounds_cost != "log2":
  1560. # assume rounds can be randomized within the range
  1561. # rounds*(1-vary_rounds) ... rounds*(1+vary_rounds)
  1562. # then this can be used to encode
  1563. # log2(rounds*(1+vary_rounds)-rounds*(1-vary_rounds))
  1564. # worth of salt-like bits. this works out to
  1565. # 1+log2(rounds*vary_rounds)
  1566. import math
  1567. if rounds is None:
  1568. rounds = cls.default_rounds
  1569. info['rounds'] = max(0, int(1+math.log(rounds*vary_rounds,2)))
  1570. ## else: # log2 rounds
  1571. # all bits of the rounds value are critical to choosing
  1572. # the time-cost, and can't be randomized.
  1573. return info
  1574. #===================================================================
  1575. # eoc
  1576. #===================================================================
  1577. #------------------------------------------------------------------------
  1578. # other common parameters
  1579. #------------------------------------------------------------------------
  1580. class ParallelismMixin(GenericHandler):
  1581. """
  1582. mixin which provides common behavior for 'parallelism' setting
  1583. """
  1584. #===================================================================
  1585. # class attrs
  1586. #===================================================================
  1587. # NOTE: subclasses should add "parallelism" to their settings_kwds
  1588. #===================================================================
  1589. # instance attrs
  1590. #===================================================================
  1591. #: parallelism setting (class-level value used as default)
  1592. parallelism = 1
  1593. #===================================================================
  1594. # variant constructor
  1595. #===================================================================
  1596. @classmethod
  1597. def using(cls, parallelism=None, **kwds):
  1598. subcls = super(ParallelismMixin, cls).using(**kwds)
  1599. if parallelism is not None:
  1600. if isinstance(parallelism, native_string_types):
  1601. parallelism = int(parallelism)
  1602. subcls.parallelism = subcls._norm_parallelism(parallelism, relaxed=kwds.get("relaxed"))
  1603. return subcls
  1604. #===================================================================
  1605. # init
  1606. #===================================================================
  1607. def __init__(self, parallelism=None, **kwds):
  1608. super(ParallelismMixin, self).__init__(**kwds)
  1609. # init parallelism
  1610. if parallelism is None:
  1611. assert validate_default_value(self, self.parallelism, self._norm_parallelism,
  1612. param="parallelism")
  1613. else:
  1614. self.parallelism = self._norm_parallelism(parallelism)
  1615. @classmethod
  1616. def _norm_parallelism(cls, parallelism, relaxed=False):
  1617. return norm_integer(cls, parallelism, min=1, param="parallelism", relaxed=relaxed)
  1618. #===================================================================
  1619. # hash migration
  1620. #===================================================================
  1621. def _calc_needs_update(self, **kwds):
  1622. """
  1623. mark hash as needing update if rounds is outside desired bounds.
  1624. """
  1625. # XXX: for now, marking all hashes which don't have matching parallelism setting
  1626. if self.parallelism != type(self).parallelism:
  1627. return True
  1628. return super(ParallelismMixin, self)._calc_needs_update(**kwds)
  1629. #===================================================================
  1630. # eoc
  1631. #===================================================================
  1632. #------------------------------------------------------------------------
  1633. # backend mixin & helpers
  1634. #------------------------------------------------------------------------
  1635. #: global lock that must be held when changing backends.
  1636. #: not bothering to make this more granular, as backend switching
  1637. #: isn't a speed-critical path. lock is needed since there is some
  1638. #: class-level state that may be modified during a "dry run"
  1639. _backend_lock = threading.RLock()
  1640. class BackendMixin(PasswordHash):
  1641. """
  1642. PasswordHash mixin which provides generic framework for supporting multiple backends
  1643. within the class.
  1644. Public API
  1645. ----------
  1646. .. attribute:: backends
  1647. This attribute should be a tuple containing the names of the backends
  1648. which are supported. Two common names are ``"os_crypt"`` (if backend
  1649. uses :mod:`crypt`), and ``"builtin"`` (if the backend is a pure-python
  1650. fallback).
  1651. .. automethod:: get_backend
  1652. .. automethod:: set_backend
  1653. .. automethod:: has_backend
  1654. .. warning::
  1655. :meth:`set_backend` is intended to be called during application startup --
  1656. it affects global state, and switching backends is not guaranteed threadsafe.
  1657. Private API (Subclass Hooks)
  1658. ----------------------------
  1659. Subclasses should set the :attr:`!backends` attribute to a tuple of the backends
  1660. they wish to support. They should also define one method:
  1661. .. classmethod:: _load_backend_{name}(dryrun=False)
  1662. One copy of this method should be defined for each :samp:`name` within :attr:`!backends`.
  1663. It will be called in order to load the backend, and should take care of whatever
  1664. is needed to enable the backend. This may include importing modules, running tests,
  1665. issuing warnings, etc.
  1666. :param name:
  1667. [Optional] name of backend.
  1668. :param dryrun:
  1669. [Optional] True/False if currently performing a "dry run".
  1670. if True, the method should perform all setup actions *except*
  1671. switching the class over to the new backend.
  1672. :raises passlib.exc.PasslibSecurityError:
  1673. if the backend is available, but cannot be loaded due to a security issue.
  1674. :returns:
  1675. False if backend not available, True if backend loaded.
  1676. .. warning::
  1677. Due to the way passlib's internals are arranged,
  1678. backends should generally store stateful data at the class level
  1679. (not the module level), and be prepared to be called on subclasses
  1680. which may be set to a different backend from their parent.
  1681. (Idempotent module-level data such as lazy imports are fine).
  1682. .. automethod:: _finalize_backend
  1683. .. versionadded:: 1.7
  1684. """
  1685. #===================================================================
  1686. # class attrs
  1687. #===================================================================
  1688. #: list of backend names, provided by subclass.
  1689. backends = None
  1690. #: private attr mixin uses to hold currently loaded backend (or ``None``)
  1691. __backend = None
  1692. #: optional class-specific text containing suggestion about what to do
  1693. #: when no backends are available.
  1694. _no_backend_suggestion = None
  1695. #: shared attr used by set_backend() to indicate what backend it's loaded;
  1696. #: meaningless while not in set_backend().
  1697. _pending_backend = None
  1698. #: shared attr used by set_backend() to indicate if it's in "dry run" mode;
  1699. #: meaningless while not in set_backend().
  1700. _pending_dry_run = False
  1701. #===================================================================
  1702. # public api
  1703. #===================================================================
  1704. @classmethod
  1705. def get_backend(cls):
  1706. """
  1707. Return name of currently active backend.
  1708. if no backend has been loaded, loads and returns name of default backend.
  1709. :raises passlib.exc.MissingBackendError:
  1710. if no backends are available.
  1711. :returns:
  1712. name of active backend
  1713. """
  1714. if not cls.__backend:
  1715. cls.set_backend()
  1716. assert cls.__backend, "set_backend() failed to load a default backend"
  1717. return cls.__backend
  1718. @classmethod
  1719. def has_backend(cls, name="any"):
  1720. """
  1721. Check if support is currently available for specified backend.
  1722. :arg name:
  1723. name of backend to check for.
  1724. can be any string accepted by :meth:`set_backend`.
  1725. :raises ValueError:
  1726. if backend name is unknown
  1727. :returns:
  1728. * ``True`` if backend is available.
  1729. * ``False`` if it's available / can't be loaded.
  1730. * ``None`` if it's present, but won't load due to a security issue.
  1731. """
  1732. try:
  1733. cls.set_backend(name, dryrun=True)
  1734. return True
  1735. except (exc.MissingBackendError, exc.PasslibSecurityError):
  1736. return False
  1737. @classmethod
  1738. def set_backend(cls, name="any", dryrun=False):
  1739. """
  1740. Load specified backend.
  1741. :arg name:
  1742. name of backend to load, can be any of the following:
  1743. * ``"any"`` -- use current backend if one is loaded,
  1744. otherwise load the first available backend.
  1745. * ``"default"`` -- use the first available backend.
  1746. * any string in :attr:`backends`, loads specified backend.
  1747. :param dryrun:
  1748. If True, this perform all setup actions *except* switching over to the new backend.
  1749. (this flag is used to implement :meth:`has_backend`).
  1750. .. versionadded:: 1.7
  1751. :raises ValueError:
  1752. If backend name is unknown.
  1753. :raises passlib.exc.MissingBackendError:
  1754. If specific backend is missing;
  1755. or in the case of ``"any"`` / ``"default"``, if *no* backends are available.
  1756. :raises passlib.exc.PasslibSecurityError:
  1757. If ``"any"`` or ``"default"`` was specified,
  1758. but the only backend available has a PasslibSecurityError.
  1759. """
  1760. # check if active backend is acceptable
  1761. if (name == "any" and cls.__backend) or (name and name == cls.__backend):
  1762. return cls.__backend
  1763. # if this isn't the final subclass, whose bases we can modify,
  1764. # find that class, and recursively call this method for the proper class.
  1765. owner = cls._get_backend_owner()
  1766. if owner is not cls:
  1767. return owner.set_backend(name, dryrun=dryrun)
  1768. # pick first available backend
  1769. if name == "any" or name == "default":
  1770. default_error = None
  1771. for name in cls.backends:
  1772. try:
  1773. return cls.set_backend(name, dryrun=dryrun)
  1774. except exc.MissingBackendError:
  1775. continue
  1776. except exc.PasslibSecurityError as err:
  1777. # backend is available, but refuses to load due to security issue.
  1778. if default_error is None:
  1779. default_error = err
  1780. continue
  1781. if default_error is None:
  1782. msg = "%s: no backends available" % cls.name
  1783. if cls._no_backend_suggestion:
  1784. msg += cls._no_backend_suggestion
  1785. default_error = exc.MissingBackendError(msg)
  1786. raise default_error
  1787. # validate name
  1788. if name not in cls.backends:
  1789. raise exc.UnknownBackendError(cls, name)
  1790. # hand off to _set_backend()
  1791. with _backend_lock:
  1792. orig = cls._pending_backend, cls._pending_dry_run
  1793. try:
  1794. cls._pending_backend = name
  1795. cls._pending_dry_run = dryrun
  1796. cls._set_backend(name, dryrun)
  1797. finally:
  1798. cls._pending_backend, cls._pending_dry_run = orig
  1799. if not dryrun:
  1800. cls.__backend = name
  1801. return name
  1802. #===================================================================
  1803. # subclass hooks
  1804. #===================================================================
  1805. @classmethod
  1806. def _get_backend_owner(cls):
  1807. """
  1808. return class that set_backend() should actually be modifying.
  1809. for SubclassBackendMixin, this may not always be the class that was invoked.
  1810. """
  1811. return cls
  1812. @classmethod
  1813. def _set_backend(cls, name, dryrun):
  1814. """
  1815. Internal method invoked by :meth:`set_backend`.
  1816. handles actual loading of specified backend.
  1817. global _backend_lock will be held for duration of this method,
  1818. and _pending_dry_run & _pending_backend will also be set.
  1819. should return True / False.
  1820. """
  1821. loader = cls._get_backend_loader(name)
  1822. kwds = {}
  1823. if accepts_keyword(loader, "name"):
  1824. kwds['name'] = name
  1825. if accepts_keyword(loader, "dryrun"):
  1826. kwds['dryrun'] = dryrun
  1827. ok = loader(**kwds)
  1828. if ok is False:
  1829. raise exc.MissingBackendError("%s: backend not available: %s" %
  1830. (cls.name, name))
  1831. elif ok is not True:
  1832. raise AssertionError("backend loaders must return True or False"
  1833. ": %r" % (ok,))
  1834. @classmethod
  1835. def _get_backend_loader(cls, name):
  1836. """
  1837. Hook called to get the specified backend's loader.
  1838. Should return callable which optionally takes ``"name"`` and/or
  1839. ``"dryrun"`` keywords.
  1840. Callable should return True if backend initialized successfully.
  1841. If backend can't be loaded, callable should return False
  1842. OR raise MissingBackendError directly.
  1843. """
  1844. raise NotImplementedError("implement in subclass")
  1845. @classmethod
  1846. def _stub_requires_backend(cls):
  1847. """
  1848. helper for subclasses to create stub methods which auto-load backend.
  1849. """
  1850. if cls.__backend:
  1851. raise AssertionError("%s: _finalize_backend(%r) failed to replace lazy loader" %
  1852. (cls.name, cls.__backend))
  1853. cls.set_backend()
  1854. if not cls.__backend:
  1855. raise AssertionError("%s: set_backend() failed to load a default backend" %
  1856. (cls.name))
  1857. #===================================================================
  1858. # eoc
  1859. #===================================================================
  1860. class SubclassBackendMixin(BackendMixin):
  1861. """
  1862. variant of BackendMixin which allows backends to be implemented
  1863. as separate mixin classes, and dynamically switches them out.
  1864. backend classes should implement a _load_backend() classmethod,
  1865. which will be invoked with an optional 'dryrun' keyword,
  1866. and should return True or False.
  1867. _load_backend() will be invoked with ``cls`` equal to the mixin,
  1868. *not* the overall class.
  1869. .. versionadded:: 1.7
  1870. """
  1871. #===================================================================
  1872. # class attrs
  1873. #===================================================================
  1874. # 'backends' required by BackendMixin
  1875. #: NON-INHERITED flag that this class's bases should be modified by SubclassBackendMixin.
  1876. #: should only be set to True in *one* subclass in hierarchy.
  1877. _backend_mixin_target = False
  1878. #: map of backend name -> mixin class
  1879. _backend_mixin_map = None
  1880. #===================================================================
  1881. # backend loading
  1882. #===================================================================
  1883. @classmethod
  1884. def _get_backend_owner(cls):
  1885. """
  1886. return base class that we're actually switching backends on
  1887. (needed in since backends frequently modify class attrs,
  1888. and .set_backend may be called from a subclass).
  1889. """
  1890. if not cls._backend_mixin_target:
  1891. raise AssertionError("_backend_mixin_target not set")
  1892. for base in cls.__mro__:
  1893. if base.__dict__.get("_backend_mixin_target"):
  1894. return base
  1895. raise AssertionError("expected to find class w/ '_backend_mixin_target' set")
  1896. @classmethod
  1897. def _set_backend(cls, name, dryrun):
  1898. # invoke backend loader (will throw error if fails)
  1899. super(SubclassBackendMixin, cls)._set_backend(name, dryrun)
  1900. # sanity check call args (should trust .set_backend, but will really
  1901. # foul things up if this isn't the owner)
  1902. assert cls is cls._get_backend_owner(), "_finalize_backend() not invoked on owner"
  1903. # pick mixin class
  1904. mixin_map = cls._backend_mixin_map
  1905. assert mixin_map, "_backend_mixin_map not specified"
  1906. mixin_cls = mixin_map[name]
  1907. assert issubclass(mixin_cls, SubclassBackendMixin), "invalid mixin class"
  1908. # modify <cls> to remove existing backend mixins, and insert the new one
  1909. update_mixin_classes(cls,
  1910. add=mixin_cls,
  1911. remove=mixin_map.values(),
  1912. append=True, before=SubclassBackendMixin,
  1913. dryrun=dryrun,
  1914. )
  1915. @classmethod
  1916. def _get_backend_loader(cls, name):
  1917. assert cls._backend_mixin_map, "_backend_mixin_map not specified"
  1918. return cls._backend_mixin_map[name]._load_backend_mixin
  1919. #===================================================================
  1920. # eoc
  1921. #===================================================================
  1922. # XXX: rename to ChecksumBackendMixin?
  1923. class HasManyBackends(BackendMixin, GenericHandler):
  1924. """
  1925. GenericHandler mixin which provides selecting from multiple backends.
  1926. .. todo::
  1927. finish documenting this class's usage
  1928. For hashes which need to select from multiple backends,
  1929. depending on the host environment, this class
  1930. offers a way to specify alternate :meth:`_calc_checksum` methods,
  1931. and will dynamically chose the best one at runtime.
  1932. .. versionchanged:: 1.7
  1933. This class now derives from :class:`BackendMixin`, which abstracts
  1934. out a more generic framework for supporting multiple backends.
  1935. The public api (:meth:`!get_backend`, :meth:`!has_backend`, :meth:`!set_backend`)
  1936. is roughly the same.
  1937. Private API (Subclass Hooks)
  1938. ----------------------------
  1939. As of version 1.7, classes should implement :meth:`!_load_backend_{name}`, per
  1940. :class:`BackendMixin`. This hook should invoke :meth:`!_set_calc_checksum_backcend`
  1941. to install it's backend method.
  1942. .. deprecated:: 1.7
  1943. The following api is deprecated, and will be removed in Passlib 2.0:
  1944. .. attribute:: _has_backend_{name}
  1945. private class attribute checked by :meth:`has_backend` to see if a
  1946. specific backend is available, it should be either ``True``
  1947. or ``False``. One of these should be provided by
  1948. the subclass for each backend listed in :attr:`backends`.
  1949. .. classmethod:: _calc_checksum_{name}
  1950. private class method that should implement :meth:`_calc_checksum`
  1951. for a given backend. it will only be called if the backend has
  1952. been selected by :meth:`set_backend`. One of these should be provided
  1953. by the subclass for each backend listed in :attr:`backends`.
  1954. """
  1955. #===================================================================
  1956. # digest calculation
  1957. #===================================================================
  1958. def _calc_checksum(self, secret):
  1959. "wrapper for backend, for common code"""
  1960. # NOTE: not overwriting _calc_checksum() directly, so that classes can provide
  1961. # common behavior in that method,
  1962. # and then invoke _calc_checksum_backend() to do the work.
  1963. return self._calc_checksum_backend(secret)
  1964. def _calc_checksum_backend(self, secret):
  1965. """
  1966. stub for _calc_checksum_backend() --
  1967. should load backend if one hasn't been loaded;
  1968. if one has been loaded, this method should have been monkeypatched by _finalize_backend().
  1969. """
  1970. self._stub_requires_backend()
  1971. return self._calc_checksum_backend(secret)
  1972. #===================================================================
  1973. # BackendMixin hooks
  1974. #===================================================================
  1975. @classmethod
  1976. def _get_backend_loader(cls, name):
  1977. """
  1978. subclassed to support legacy 1.6 HasManyBackends api.
  1979. (will be removed in passlib 2.0)
  1980. """
  1981. # check for 1.7 loader
  1982. loader = getattr(cls, "_load_backend_" + name, None)
  1983. if loader is None:
  1984. # fallback to pre-1.7 _has_backend_xxx + _calc_checksum_xxx() api
  1985. def loader():
  1986. return cls.__load_legacy_backend(name)
  1987. else:
  1988. # make sure 1.6 api isn't defined at same time
  1989. assert not hasattr(cls, "_has_backend_" + name), (
  1990. "%s: can't specify both ._load_backend_%s() "
  1991. "and ._has_backend_%s" % (cls.name, name, name)
  1992. )
  1993. return loader
  1994. @classmethod
  1995. def __load_legacy_backend(cls, name):
  1996. value = getattr(cls, "_has_backend_" + name)
  1997. warn("%s: support for ._has_backend_%s is deprecated as of Passlib 1.7, "
  1998. "and will be removed in Passlib 1.9/2.0, please implement "
  1999. "._load_backend_%s() instead" % (cls.name, name, name),
  2000. DeprecationWarning,
  2001. )
  2002. if value:
  2003. func = getattr(cls, "_calc_checksum_" + name)
  2004. cls._set_calc_checksum_backend(func)
  2005. return True
  2006. else:
  2007. return False
  2008. @classmethod
  2009. def _set_calc_checksum_backend(cls, func):
  2010. """
  2011. helper used by subclasses to validate & set backend-specific
  2012. calc checksum helper.
  2013. """
  2014. backend = cls._pending_backend
  2015. assert backend, "should only be called during set_backend()"
  2016. if not callable(func):
  2017. raise RuntimeError("%s: backend %r returned invalid callable: %r" %
  2018. (cls.name, backend, func))
  2019. if not cls._pending_dry_run:
  2020. cls._calc_checksum_backend = func
  2021. #===================================================================
  2022. # eoc
  2023. #===================================================================
  2024. #=============================================================================
  2025. # wrappers
  2026. #=============================================================================
  2027. # XXX: should this inherit from PasswordHash?
  2028. class PrefixWrapper(object):
  2029. """wraps another handler, adding a constant prefix.
  2030. instances of this class wrap another password hash handler,
  2031. altering the constant prefix that's prepended to the wrapped
  2032. handlers' hashes.
  2033. this is used mainly by the :doc:`ldap crypt <passlib.hash.ldap_crypt>` handlers;
  2034. such as :class:`~passlib.hash.ldap_md5_crypt` which wraps :class:`~passlib.hash.md5_crypt` and adds a ``{CRYPT}`` prefix.
  2035. usage::
  2036. myhandler = PrefixWrapper("myhandler", "md5_crypt", prefix="$mh$", orig_prefix="$1$")
  2037. :param name: name to assign to handler
  2038. :param wrapped: handler object or name of registered handler
  2039. :param prefix: identifying prefix to prepend to all hashes
  2040. :param orig_prefix: prefix to strip (defaults to '').
  2041. :param lazy: if True and wrapped handler is specified by name, don't look it up until needed.
  2042. """
  2043. #: list of attributes which should be cloned by .using()
  2044. _using_clone_attrs = ()
  2045. def __init__(self, name, wrapped, prefix=u(''), orig_prefix=u(''), lazy=False,
  2046. doc=None, ident=None):
  2047. self.name = name
  2048. if isinstance(prefix, bytes):
  2049. prefix = prefix.decode("ascii")
  2050. self.prefix = prefix
  2051. if isinstance(orig_prefix, bytes):
  2052. orig_prefix = orig_prefix.decode("ascii")
  2053. self.orig_prefix = orig_prefix
  2054. if doc:
  2055. self.__doc__ = doc
  2056. if hasattr(wrapped, "name"):
  2057. self._set_wrapped(wrapped)
  2058. else:
  2059. self._wrapped_name = wrapped
  2060. if not lazy:
  2061. self._get_wrapped()
  2062. if ident is not None:
  2063. if ident is True:
  2064. # signal that prefix is identifiable in itself.
  2065. if prefix:
  2066. ident = prefix
  2067. else:
  2068. raise ValueError("no prefix specified")
  2069. if isinstance(ident, bytes):
  2070. ident = ident.decode("ascii")
  2071. # XXX: what if ident includes parts of wrapped hash's ident?
  2072. if ident[:len(prefix)] != prefix[:len(ident)]:
  2073. raise ValueError("ident must agree with prefix")
  2074. self._ident = ident
  2075. _wrapped_name = None
  2076. _wrapped_handler = None
  2077. def _set_wrapped(self, handler):
  2078. # check this is a valid handler
  2079. if 'ident' in handler.setting_kwds and self.orig_prefix:
  2080. # TODO: look into way to fix the issues.
  2081. warn("PrefixWrapper: 'orig_prefix' option may not work correctly "
  2082. "for handlers which have multiple identifiers: %r" %
  2083. (handler.name,), exc.PasslibRuntimeWarning)
  2084. # store reference
  2085. self._wrapped_handler = handler
  2086. def _get_wrapped(self):
  2087. handler = self._wrapped_handler
  2088. if handler is None:
  2089. handler = get_crypt_handler(self._wrapped_name)
  2090. self._set_wrapped(handler)
  2091. return handler
  2092. wrapped = property(_get_wrapped)
  2093. _ident = False
  2094. @property
  2095. def ident(self):
  2096. value = self._ident
  2097. if value is False:
  2098. value = None
  2099. # XXX: how will this interact with orig_prefix ?
  2100. # not exposing attrs for now if orig_prefix is set.
  2101. if not self.orig_prefix:
  2102. wrapped = self.wrapped
  2103. ident = getattr(wrapped, "ident", None)
  2104. if ident is not None:
  2105. value = self._wrap_hash(ident)
  2106. self._ident = value
  2107. return value
  2108. _ident_values = False
  2109. @property
  2110. def ident_values(self):
  2111. value = self._ident_values
  2112. if value is False:
  2113. value = None
  2114. # XXX: how will this interact with orig_prefix ?
  2115. # not exposing attrs for now if orig_prefix is set.
  2116. if not self.orig_prefix:
  2117. wrapped = self.wrapped
  2118. idents = getattr(wrapped, "ident_values", None)
  2119. if idents:
  2120. value = tuple(self._wrap_hash(ident) for ident in idents)
  2121. ##else:
  2122. ## ident = self.ident
  2123. ## if ident is not None:
  2124. ## value = [ident]
  2125. self._ident_values = value
  2126. return value
  2127. # attrs that should be proxied
  2128. # XXX: change this to proxy everything that doesn't start with "_"?
  2129. _proxy_attrs = (
  2130. "setting_kwds", "context_kwds",
  2131. "default_rounds", "min_rounds", "max_rounds", "rounds_cost",
  2132. "min_desired_rounds", "max_desired_rounds", "vary_rounds",
  2133. "default_salt_size", "min_salt_size", "max_salt_size",
  2134. "salt_chars", "default_salt_chars",
  2135. "backends", "has_backend", "get_backend", "set_backend",
  2136. "is_disabled", "truncate_size", "truncate_error",
  2137. "truncate_verify_reject",
  2138. # internal info attrs needed for test inspection
  2139. "_salt_is_bytes",
  2140. )
  2141. def __repr__(self):
  2142. args = [ repr(self._wrapped_name or self._wrapped_handler) ]
  2143. if self.prefix:
  2144. args.append("prefix=%r" % self.prefix)
  2145. if self.orig_prefix:
  2146. args.append("orig_prefix=%r" % self.orig_prefix)
  2147. args = ", ".join(args)
  2148. return 'PrefixWrapper(%r, %s)' % (self.name, args)
  2149. def __dir__(self):
  2150. attrs = set(dir(self.__class__))
  2151. attrs.update(self.__dict__)
  2152. wrapped = self.wrapped
  2153. attrs.update(
  2154. attr for attr in self._proxy_attrs
  2155. if hasattr(wrapped, attr)
  2156. )
  2157. return list(attrs)
  2158. def __getattr__(self, attr):
  2159. """proxy most attributes from wrapped class (e.g. rounds, salt size, etc)"""
  2160. if attr in self._proxy_attrs:
  2161. return getattr(self.wrapped, attr)
  2162. raise AttributeError("missing attribute: %r" % (attr,))
  2163. def __setattr__(self, attr, value):
  2164. # if proxy attr present on wrapped object,
  2165. # and we own it, modify *it* instead.
  2166. # TODO: needs UTs
  2167. # TODO: any other cases where wrapped is "owned"?
  2168. # currently just if created via .using()
  2169. if attr in self._proxy_attrs and self._derived_from:
  2170. wrapped = self.wrapped
  2171. if hasattr(wrapped, attr):
  2172. setattr(wrapped, attr, value)
  2173. return
  2174. return object.__setattr__(self, attr, value)
  2175. def _unwrap_hash(self, hash):
  2176. """given hash belonging to wrapper, return orig version"""
  2177. # NOTE: assumes hash has been validated as unicode already
  2178. prefix = self.prefix
  2179. if not hash.startswith(prefix):
  2180. raise exc.InvalidHashError(self)
  2181. # NOTE: always passing to handler as unicode, to save reconversion
  2182. return self.orig_prefix + hash[len(prefix):]
  2183. def _wrap_hash(self, hash):
  2184. """given orig hash; return one belonging to wrapper"""
  2185. # NOTE: should usually be native string.
  2186. # (which does mean extra work under py2, but not py3)
  2187. if isinstance(hash, bytes):
  2188. hash = hash.decode("ascii")
  2189. orig_prefix = self.orig_prefix
  2190. if not hash.startswith(orig_prefix):
  2191. raise exc.InvalidHashError(self.wrapped)
  2192. wrapped = self.prefix + hash[len(orig_prefix):]
  2193. return uascii_to_str(wrapped)
  2194. #: set by _using(), helper for test harness' handler_derived_from()
  2195. _derived_from = None
  2196. def using(self, **kwds):
  2197. # generate subclass of wrapped handler
  2198. subcls = self.wrapped.using(**kwds)
  2199. assert subcls is not self.wrapped
  2200. # then create identical wrapper which wraps the new subclass.
  2201. wrapper = PrefixWrapper(self.name, subcls, prefix=self.prefix, orig_prefix=self.orig_prefix)
  2202. wrapper._derived_from = self
  2203. for attr in self._using_clone_attrs:
  2204. setattr(wrapper, attr, getattr(self, attr))
  2205. return wrapper
  2206. def needs_update(self, hash, **kwds):
  2207. hash = self._unwrap_hash(hash)
  2208. return self.wrapped.needs_update(hash, **kwds)
  2209. def identify(self, hash):
  2210. hash = to_unicode_for_identify(hash)
  2211. if not hash.startswith(self.prefix):
  2212. return False
  2213. hash = self._unwrap_hash(hash)
  2214. return self.wrapped.identify(hash)
  2215. @deprecated_method(deprecated="1.7", removed="2.0")
  2216. def genconfig(self, **kwds):
  2217. config = self.wrapped.genconfig(**kwds)
  2218. if config is None:
  2219. raise RuntimeError(".genconfig() must return a string, not None")
  2220. return self._wrap_hash(config)
  2221. @deprecated_method(deprecated="1.7", removed="2.0")
  2222. def genhash(self, secret, config, **kwds):
  2223. # TODO: under 2.0, throw TypeError if config is None, rather than passing it through
  2224. if config is not None:
  2225. config = to_unicode(config, "ascii", "config/hash")
  2226. config = self._unwrap_hash(config)
  2227. return self._wrap_hash(self.wrapped.genhash(secret, config, **kwds))
  2228. @deprecated_method(deprecated="1.7", removed="2.0", replacement=".hash()")
  2229. def encrypt(self, secret, **kwds):
  2230. return self.hash(secret, **kwds)
  2231. def hash(self, secret, **kwds):
  2232. return self._wrap_hash(self.wrapped.hash(secret, **kwds))
  2233. def verify(self, secret, hash, **kwds):
  2234. hash = to_unicode(hash, "ascii", "hash")
  2235. hash = self._unwrap_hash(hash)
  2236. return self.wrapped.verify(secret, hash, **kwds)
  2237. #=============================================================================
  2238. # eof
  2239. #=============================================================================