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

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