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

3402 lines
135 KiB

  1. """helpers for passlib unittests"""
  2. #=============================================================================
  3. # imports
  4. #=============================================================================
  5. from __future__ import with_statement
  6. # core
  7. from binascii import unhexlify
  8. import contextlib
  9. from functools import wraps, partial
  10. import hashlib
  11. import logging; log = logging.getLogger(__name__)
  12. import random
  13. import re
  14. import os
  15. import sys
  16. import tempfile
  17. import threading
  18. import time
  19. from passlib.exc import PasslibHashWarning, PasslibConfigWarning
  20. from passlib.utils.compat import PY3, JYTHON
  21. import warnings
  22. from warnings import warn
  23. # site
  24. # pkg
  25. from passlib import exc
  26. from passlib.exc import MissingBackendError
  27. import passlib.registry as registry
  28. from passlib.tests.backports import TestCase as _TestCase, skip, skipIf, skipUnless, SkipTest
  29. from passlib.utils import has_rounds_info, has_salt_info, rounds_cost_values, \
  30. rng as sys_rng, getrandstr, is_ascii_safe, to_native_str, \
  31. repeat_string, tick, batch
  32. from passlib.utils.compat import iteritems, irange, u, unicode, PY2
  33. from passlib.utils.decor import classproperty
  34. import passlib.utils.handlers as uh
  35. # local
  36. __all__ = [
  37. # util funcs
  38. 'TEST_MODE',
  39. 'set_file', 'get_file',
  40. # unit testing
  41. 'TestCase',
  42. 'HandlerCase',
  43. ]
  44. #=============================================================================
  45. # environment detection
  46. #=============================================================================
  47. # figure out if we're running under GAE;
  48. # some tests (e.g. FS writing) should be skipped.
  49. # XXX: is there better way to do this?
  50. try:
  51. import google.appengine
  52. except ImportError:
  53. GAE = False
  54. else:
  55. GAE = True
  56. def ensure_mtime_changed(path):
  57. """ensure file's mtime has changed"""
  58. # NOTE: this is hack to deal w/ filesystems whose mtime resolution is >= 1s,
  59. # when a test needs to be sure the mtime changed after writing to the file.
  60. last = os.path.getmtime(path)
  61. while os.path.getmtime(path) == last:
  62. time.sleep(0.1)
  63. os.utime(path, None)
  64. def _get_timer_resolution(timer):
  65. def sample():
  66. start = cur = timer()
  67. while start == cur:
  68. cur = timer()
  69. return cur-start
  70. return min(sample() for _ in range(3))
  71. TICK_RESOLUTION = _get_timer_resolution(tick)
  72. #=============================================================================
  73. # test mode
  74. #=============================================================================
  75. _TEST_MODES = ["quick", "default", "full"]
  76. _test_mode = _TEST_MODES.index(os.environ.get("PASSLIB_TEST_MODE",
  77. "default").strip().lower())
  78. def TEST_MODE(min=None, max=None):
  79. """check if test for specified mode should be enabled.
  80. ``"quick"``
  81. run the bare minimum tests to ensure functionality.
  82. variable-cost hashes are tested at their lowest setting.
  83. hash algorithms are only tested against the backend that will
  84. be used on the current host. no fuzz testing is done.
  85. ``"default"``
  86. same as ``"quick"``, except: hash algorithms are tested
  87. at default levels, and a brief round of fuzz testing is done
  88. for each hash.
  89. ``"full"``
  90. extra regression and internal tests are enabled, hash algorithms are tested
  91. against all available backends, unavailable ones are mocked whre possible,
  92. additional time is devoted to fuzz testing.
  93. """
  94. if min and _test_mode < _TEST_MODES.index(min):
  95. return False
  96. if max and _test_mode > _TEST_MODES.index(max):
  97. return False
  98. return True
  99. #=============================================================================
  100. # hash object inspection
  101. #=============================================================================
  102. def has_relaxed_setting(handler):
  103. """check if handler supports 'relaxed' kwd"""
  104. # FIXME: I've been lazy, should probably just add 'relaxed' kwd
  105. # to all handlers that derive from GenericHandler
  106. # ignore wrapper classes for now.. though could introspec.
  107. if hasattr(handler, "orig_prefix"):
  108. return False
  109. return 'relaxed' in handler.setting_kwds or issubclass(handler,
  110. uh.GenericHandler)
  111. def get_effective_rounds(handler, rounds=None):
  112. """get effective rounds value from handler"""
  113. handler = unwrap_handler(handler)
  114. return handler(rounds=rounds, use_defaults=True).rounds
  115. def is_default_backend(handler, backend):
  116. """check if backend is the default for source"""
  117. try:
  118. orig = handler.get_backend()
  119. except MissingBackendError:
  120. return False
  121. try:
  122. handler.set_backend("default")
  123. return handler.get_backend() == backend
  124. finally:
  125. handler.set_backend(orig)
  126. def iter_alt_backends(handler, current=None, fallback=False):
  127. """
  128. iterate over alternate backends available to handler.
  129. .. warning::
  130. not thread-safe due to has_backend() call
  131. """
  132. if current is None:
  133. current = handler.get_backend()
  134. backends = handler.backends
  135. idx = backends.index(current)+1 if fallback else 0
  136. for backend in backends[idx:]:
  137. if backend != current and handler.has_backend(backend):
  138. yield backend
  139. def get_alt_backend(*args, **kwds):
  140. for backend in iter_alt_backends(*args, **kwds):
  141. return backend
  142. return None
  143. def unwrap_handler(handler):
  144. """return original handler, removing any wrapper objects"""
  145. while hasattr(handler, "wrapped"):
  146. handler = handler.wrapped
  147. return handler
  148. def handler_derived_from(handler, base):
  149. """
  150. test if <handler> was derived from <base> via <base.using()>.
  151. """
  152. # XXX: need way to do this more formally via ifc,
  153. # for now just hacking in the cases we encounter in testing.
  154. if handler == base:
  155. return True
  156. elif isinstance(handler, uh.PrefixWrapper):
  157. while handler:
  158. if handler == base:
  159. return True
  160. # helper set by PrefixWrapper().using() just for this case...
  161. handler = handler._derived_from
  162. return False
  163. elif isinstance(handler, type) and issubclass(handler, uh.MinimalHandler):
  164. return issubclass(handler, base)
  165. else:
  166. raise NotImplementedError("don't know how to inspect handler: %r" % (handler,))
  167. @contextlib.contextmanager
  168. def patch_calc_min_rounds(handler):
  169. """
  170. internal helper for do_config_encrypt() --
  171. context manager which temporarily replaces handler's _calc_checksum()
  172. with one that uses min_rounds; useful when trying to generate config
  173. with high rounds value, but don't care if output is correct.
  174. """
  175. if isinstance(handler, type) and issubclass(handler, uh.HasRounds):
  176. # XXX: also require GenericHandler for this branch?
  177. wrapped = handler._calc_checksum
  178. def wrapper(self, *args, **kwds):
  179. rounds = self.rounds
  180. try:
  181. self.rounds = self.min_rounds
  182. return wrapped(self, *args, **kwds)
  183. finally:
  184. self.rounds = rounds
  185. handler._calc_checksum = wrapper
  186. try:
  187. yield
  188. finally:
  189. handler._calc_checksum = wrapped
  190. elif isinstance(handler, uh.PrefixWrapper):
  191. with patch_calc_min_rounds(handler.wrapped):
  192. yield
  193. else:
  194. yield
  195. return
  196. #=============================================================================
  197. # misc helpers
  198. #=============================================================================
  199. def set_file(path, content):
  200. """set file to specified bytes"""
  201. if isinstance(content, unicode):
  202. content = content.encode("utf-8")
  203. with open(path, "wb") as fh:
  204. fh.write(content)
  205. def get_file(path):
  206. """read file as bytes"""
  207. with open(path, "rb") as fh:
  208. return fh.read()
  209. def tonn(source):
  210. """convert native string to non-native string"""
  211. if not isinstance(source, str):
  212. return source
  213. elif PY3:
  214. return source.encode("utf-8")
  215. else:
  216. try:
  217. return source.decode("utf-8")
  218. except UnicodeDecodeError:
  219. return source.decode("latin-1")
  220. def hb(source):
  221. """
  222. helper for represent byte strings in hex.
  223. usage: ``hb("deadbeef23")``
  224. """
  225. return unhexlify(re.sub(r"\s", "", source))
  226. def limit(value, lower, upper):
  227. if value < lower:
  228. return lower
  229. elif value > upper:
  230. return upper
  231. return value
  232. def quicksleep(delay):
  233. """because time.sleep() doesn't even have 10ms accuracy on some OSes"""
  234. start = tick()
  235. while tick()-start < delay:
  236. pass
  237. def time_call(func, setup=None, maxtime=1, bestof=10):
  238. """
  239. timeit() wrapper which tries to get as accurate a measurement as possible w/in maxtime seconds.
  240. :returns:
  241. ``(avg_seconds_per_call, log10_number_of_repetitions)``
  242. """
  243. from timeit import Timer
  244. from math import log
  245. timer = Timer(func, setup=setup or '')
  246. number = 1
  247. end = tick() + maxtime
  248. while True:
  249. delta = min(timer.repeat(bestof, number))
  250. if tick() >= end:
  251. return delta/number, int(log(number, 10))
  252. number *= 10
  253. def run_with_fixed_seeds(count=128, master_seed=0x243F6A8885A308D3):
  254. """
  255. decorator run test method w/ multiple fixed seeds.
  256. """
  257. def builder(func):
  258. @wraps(func)
  259. def wrapper(*args, **kwds):
  260. rng = random.Random(master_seed)
  261. for _ in irange(count):
  262. kwds['seed'] = rng.getrandbits(32)
  263. func(*args, **kwds)
  264. return wrapper
  265. return builder
  266. #=============================================================================
  267. # custom test harness
  268. #=============================================================================
  269. class TestCase(_TestCase):
  270. """passlib-specific test case class
  271. this class adds a number of features to the standard TestCase...
  272. * common prefix for all test descriptions
  273. * resets warnings filter & registry for every test
  274. * tweaks to message formatting
  275. * __msg__ kwd added to assertRaises()
  276. * suite of methods for matching against warnings
  277. """
  278. #===================================================================
  279. # add various custom features
  280. #===================================================================
  281. #---------------------------------------------------------------
  282. # make it easy for test cases to add common prefix to shortDescription
  283. #---------------------------------------------------------------
  284. # string prepended to all tests in TestCase
  285. descriptionPrefix = None
  286. def shortDescription(self):
  287. """wrap shortDescription() method to prepend descriptionPrefix"""
  288. desc = super(TestCase, self).shortDescription()
  289. prefix = self.descriptionPrefix
  290. if prefix:
  291. desc = "%s: %s" % (prefix, desc or str(self))
  292. return desc
  293. #---------------------------------------------------------------
  294. # hack things so nose and ut2 both skip subclasses who have
  295. # "__unittest_skip=True" set, or whose names start with "_"
  296. #---------------------------------------------------------------
  297. @classproperty
  298. def __unittest_skip__(cls):
  299. # NOTE: this attr is technically a unittest2 internal detail.
  300. name = cls.__name__
  301. return name.startswith("_") or \
  302. getattr(cls, "_%s__unittest_skip" % name, False)
  303. @classproperty
  304. def __test__(cls):
  305. # make nose just proxy __unittest_skip__
  306. return not cls.__unittest_skip__
  307. # flag to skip *this* class
  308. __unittest_skip = True
  309. #---------------------------------------------------------------
  310. # reset warning filters & registry before each test
  311. #---------------------------------------------------------------
  312. # flag to reset all warning filters & ignore state
  313. resetWarningState = True
  314. def setUp(self):
  315. super(TestCase, self).setUp()
  316. self.setUpWarnings()
  317. def setUpWarnings(self):
  318. """helper to init warning filters before subclass setUp()"""
  319. if self.resetWarningState:
  320. ctx = reset_warnings()
  321. ctx.__enter__()
  322. self.addCleanup(ctx.__exit__)
  323. # ignore warnings about PasswordHash features deprecated in 1.7
  324. # TODO: should be cleaned in 2.0, when support will be dropped.
  325. # should be kept until then, so we test the legacy paths.
  326. warnings.filterwarnings("ignore", r"the method .*\.(encrypt|genconfig|genhash)\(\) is deprecated")
  327. warnings.filterwarnings("ignore", r"the 'vary_rounds' option is deprecated")
  328. #---------------------------------------------------------------
  329. # tweak message formatting so longMessage mode is only enabled
  330. # if msg ends with ":", and turn on longMessage by default.
  331. #---------------------------------------------------------------
  332. longMessage = True
  333. def _formatMessage(self, msg, std):
  334. if self.longMessage and msg and msg.rstrip().endswith(":"):
  335. return '%s %s' % (msg.rstrip(), std)
  336. else:
  337. return msg or std
  338. #---------------------------------------------------------------
  339. # override assertRaises() to support '__msg__' keyword,
  340. # and to return the caught exception for further examination
  341. #---------------------------------------------------------------
  342. def assertRaises(self, _exc_type, _callable=None, *args, **kwds):
  343. msg = kwds.pop("__msg__", None)
  344. if _callable is None:
  345. # FIXME: this ignores 'msg'
  346. return super(TestCase, self).assertRaises(_exc_type, None,
  347. *args, **kwds)
  348. try:
  349. result = _callable(*args, **kwds)
  350. except _exc_type as err:
  351. return err
  352. std = "function returned %r, expected it to raise %r" % (result,
  353. _exc_type)
  354. raise self.failureException(self._formatMessage(msg, std))
  355. #---------------------------------------------------------------
  356. # forbid a bunch of deprecated aliases so I stop using them
  357. #---------------------------------------------------------------
  358. def assertEquals(self, *a, **k):
  359. raise AssertionError("this alias is deprecated by unittest2")
  360. assertNotEquals = assertRegexMatches = assertEquals
  361. #===================================================================
  362. # custom methods for matching warnings
  363. #===================================================================
  364. def assertWarning(self, warning,
  365. message_re=None, message=None,
  366. category=None,
  367. filename_re=None, filename=None,
  368. lineno=None,
  369. msg=None,
  370. ):
  371. """check if warning matches specified parameters.
  372. 'warning' is the instance of Warning to match against;
  373. can also be instance of WarningMessage (as returned by catch_warnings).
  374. """
  375. # check input type
  376. if hasattr(warning, "category"):
  377. # resolve WarningMessage -> Warning, but preserve original
  378. wmsg = warning
  379. warning = warning.message
  380. else:
  381. # no original WarningMessage, passed raw Warning
  382. wmsg = None
  383. # tests that can use a warning instance or WarningMessage object
  384. if message:
  385. self.assertEqual(str(warning), message, msg)
  386. if message_re:
  387. self.assertRegex(str(warning), message_re, msg)
  388. if category:
  389. self.assertIsInstance(warning, category, msg)
  390. # tests that require a WarningMessage object
  391. if filename or filename_re:
  392. if not wmsg:
  393. raise TypeError("matching on filename requires a "
  394. "WarningMessage instance")
  395. real = wmsg.filename
  396. if real.endswith(".pyc") or real.endswith(".pyo"):
  397. # FIXME: should use a stdlib call to resolve this back
  398. # to module's original filename.
  399. real = real[:-1]
  400. if filename:
  401. self.assertEqual(real, filename, msg)
  402. if filename_re:
  403. self.assertRegex(real, filename_re, msg)
  404. if lineno:
  405. if not wmsg:
  406. raise TypeError("matching on lineno requires a "
  407. "WarningMessage instance")
  408. self.assertEqual(wmsg.lineno, lineno, msg)
  409. class _AssertWarningList(warnings.catch_warnings):
  410. """context manager for assertWarningList()"""
  411. def __init__(self, case, **kwds):
  412. self.case = case
  413. self.kwds = kwds
  414. self.__super = super(TestCase._AssertWarningList, self)
  415. self.__super.__init__(record=True)
  416. def __enter__(self):
  417. self.log = self.__super.__enter__()
  418. def __exit__(self, *exc_info):
  419. self.__super.__exit__(*exc_info)
  420. if exc_info[0] is None:
  421. self.case.assertWarningList(self.log, **self.kwds)
  422. def assertWarningList(self, wlist=None, desc=None, msg=None):
  423. """check that warning list (e.g. from catch_warnings) matches pattern"""
  424. if desc is None:
  425. assert wlist is not None
  426. return self._AssertWarningList(self, desc=wlist, msg=msg)
  427. # TODO: make this display better diff of *which* warnings did not match
  428. assert desc is not None
  429. if not isinstance(desc, (list,tuple)):
  430. desc = [desc]
  431. for idx, entry in enumerate(desc):
  432. if isinstance(entry, str):
  433. entry = dict(message_re=entry)
  434. elif isinstance(entry, type) and issubclass(entry, Warning):
  435. entry = dict(category=entry)
  436. elif not isinstance(entry, dict):
  437. raise TypeError("entry must be str, warning, or dict")
  438. try:
  439. data = wlist[idx]
  440. except IndexError:
  441. break
  442. self.assertWarning(data, msg=msg, **entry)
  443. else:
  444. if len(wlist) == len(desc):
  445. return
  446. std = "expected %d warnings, found %d: wlist=%s desc=%r" % \
  447. (len(desc), len(wlist), self._formatWarningList(wlist), desc)
  448. raise self.failureException(self._formatMessage(msg, std))
  449. def consumeWarningList(self, wlist, desc=None, *args, **kwds):
  450. """[deprecated] assertWarningList() variant that clears list afterwards"""
  451. if desc is None:
  452. desc = []
  453. self.assertWarningList(wlist, desc, *args, **kwds)
  454. del wlist[:]
  455. def _formatWarning(self, entry):
  456. tail = ""
  457. if hasattr(entry, "message"):
  458. # WarningMessage instance.
  459. tail = " filename=%r lineno=%r" % (entry.filename, entry.lineno)
  460. if entry.line:
  461. tail += " line=%r" % (entry.line,)
  462. entry = entry.message
  463. cls = type(entry)
  464. return "<%s.%s message=%r%s>" % (cls.__module__, cls.__name__,
  465. str(entry), tail)
  466. def _formatWarningList(self, wlist):
  467. return "[%s]" % ", ".join(self._formatWarning(entry) for entry in wlist)
  468. #===================================================================
  469. # capability tests
  470. #===================================================================
  471. def require_stringprep(self):
  472. """helper to skip test if stringprep is missing"""
  473. from passlib.utils import stringprep
  474. if not stringprep:
  475. from passlib.utils import _stringprep_missing_reason
  476. raise self.skipTest("not available - stringprep module is " +
  477. _stringprep_missing_reason)
  478. def require_TEST_MODE(self, level):
  479. """skip test for all PASSLIB_TEST_MODE values below <level>"""
  480. if not TEST_MODE(level):
  481. raise self.skipTest("requires >= %r test mode" % level)
  482. def require_writeable_filesystem(self):
  483. """skip test if writeable FS not available"""
  484. if GAE:
  485. return self.skipTest("GAE doesn't offer read/write filesystem access")
  486. #===================================================================
  487. # reproducible random helpers
  488. #===================================================================
  489. #: global thread lock for random state
  490. #: XXX: could split into global & per-instance locks if need be
  491. _random_global_lock = threading.Lock()
  492. #: cache of global seed value, initialized on first call to getRandom()
  493. _random_global_seed = None
  494. #: per-instance cache of name -> RNG
  495. _random_cache = None
  496. def getRandom(self, name="default", seed=None):
  497. """
  498. Return a :class:`random.Random` object for current test method to use.
  499. Within an instance, multiple calls with the same name will return
  500. the same object.
  501. When first created, each RNG will be seeded with value derived from
  502. a global seed, the test class module & name, the current test method name,
  503. and the **name** parameter.
  504. The global seed taken from the $RANDOM_TEST_SEED env var,
  505. the $PYTHONHASHSEED env var, or a randomly generated the
  506. first time this method is called. In all cases, the value
  507. is logged for reproducibility.
  508. :param name:
  509. name to uniquely identify separate RNGs w/in a test
  510. (e.g. for threaded tests).
  511. :param seed:
  512. override global seed when initialzing rng.
  513. :rtype: random.Random
  514. """
  515. # check cache
  516. cache = self._random_cache
  517. if cache and name in cache:
  518. return cache[name]
  519. with self._random_global_lock:
  520. # check cache again, and initialize it
  521. cache = self._random_cache
  522. if cache and name in cache:
  523. return cache[name]
  524. elif not cache:
  525. cache = self._random_cache = {}
  526. # init global seed
  527. global_seed = seed or TestCase._random_global_seed
  528. if global_seed is None:
  529. # NOTE: checking PYTHONHASHSEED, because if that's set,
  530. # the test runner wants something reproducible.
  531. global_seed = TestCase._random_global_seed = \
  532. int(os.environ.get("RANDOM_TEST_SEED") or
  533. os.environ.get("PYTHONHASHSEED") or
  534. sys_rng.getrandbits(32))
  535. # XXX: would it be better to print() this?
  536. log.info("using RANDOM_TEST_SEED=%d", global_seed)
  537. # create seed
  538. cls = type(self)
  539. source = "\n".join([str(global_seed), cls.__module__, cls.__name__,
  540. self._testMethodName, name])
  541. digest = hashlib.sha256(source.encode("utf-8")).hexdigest()
  542. seed = int(digest[:16], 16)
  543. # create rng
  544. value = cache[name] = random.Random(seed)
  545. return value
  546. #===================================================================
  547. # other
  548. #===================================================================
  549. _mktemp_queue = None
  550. def mktemp(self, *args, **kwds):
  551. """create temp file that's cleaned up at end of test"""
  552. self.require_writeable_filesystem()
  553. fd, path = tempfile.mkstemp(*args, **kwds)
  554. os.close(fd)
  555. queue = self._mktemp_queue
  556. if queue is None:
  557. queue = self._mktemp_queue = []
  558. def cleaner():
  559. for path in queue:
  560. if os.path.exists(path):
  561. os.remove(path)
  562. del queue[:]
  563. self.addCleanup(cleaner)
  564. queue.append(path)
  565. return path
  566. def patchAttr(self, obj, attr, value, require_existing=True, wrap=False):
  567. """monkeypatch object value, restoring original value on cleanup"""
  568. try:
  569. orig = getattr(obj, attr)
  570. except AttributeError:
  571. if require_existing:
  572. raise
  573. def cleanup():
  574. try:
  575. delattr(obj, attr)
  576. except AttributeError:
  577. pass
  578. self.addCleanup(cleanup)
  579. else:
  580. self.addCleanup(setattr, obj, attr, orig)
  581. if wrap:
  582. value = partial(value, orig)
  583. wraps(orig)(value)
  584. setattr(obj, attr, value)
  585. #===================================================================
  586. # eoc
  587. #===================================================================
  588. #=============================================================================
  589. # other unittest helpers
  590. #=============================================================================
  591. RESERVED_BACKEND_NAMES = ["any", "default"]
  592. class HandlerCase(TestCase):
  593. """base class for testing password hash handlers (esp passlib.utils.handlers subclasses)
  594. In order to use this to test a handler,
  595. create a subclass will all the appropriate attributes
  596. filled as listed in the example below,
  597. and run the subclass via unittest.
  598. .. todo::
  599. Document all of the options HandlerCase offers.
  600. .. note::
  601. This is subclass of :class:`unittest.TestCase`
  602. (or :class:`unittest2.TestCase` if available).
  603. """
  604. #===================================================================
  605. # class attrs - should be filled in by subclass
  606. #===================================================================
  607. #---------------------------------------------------------------
  608. # handler setup
  609. #---------------------------------------------------------------
  610. # handler class to test [required]
  611. handler = None
  612. # if set, run tests against specified backend
  613. backend = None
  614. #---------------------------------------------------------------
  615. # test vectors
  616. #---------------------------------------------------------------
  617. # list of (secret, hash) tuples which are known to be correct
  618. known_correct_hashes = []
  619. # list of (config, secret, hash) tuples are known to be correct
  620. known_correct_configs = []
  621. # list of (alt_hash, secret, hash) tuples, where alt_hash is a hash
  622. # using an alternate representation that should be recognized and verify
  623. # correctly, but should be corrected to match hash when passed through
  624. # genhash()
  625. known_alternate_hashes = []
  626. # hashes so malformed they aren't even identified properly
  627. known_unidentified_hashes = []
  628. # hashes which are identifiabled but malformed - they should identify()
  629. # as True, but cause an error when passed to genhash/verify.
  630. known_malformed_hashes = []
  631. # list of (handler name, hash) pairs for other algorithm's hashes that
  632. # handler shouldn't identify as belonging to it this list should generally
  633. # be sufficient (if handler name in list, that entry will be skipped)
  634. known_other_hashes = [
  635. ('des_crypt', '6f8c114b58f2c'),
  636. ('md5_crypt', '$1$dOHYPKoP$tnxS1T8Q6VVn3kpV8cN6o.'),
  637. ('sha512_crypt', "$6$rounds=123456$asaltof16chars..$BtCwjqMJGx5hrJhZywW"
  638. "vt0RLE8uZ4oPwcelCjmw2kSYu.Ec6ycULevoBK25fs2xXgMNrCzIMVcgEJAstJeonj1"),
  639. ]
  640. # passwords used to test basic hash behavior - generally
  641. # don't need to be overidden.
  642. stock_passwords = [
  643. u("test"),
  644. u("\u20AC\u00A5$"),
  645. b'\xe2\x82\xac\xc2\xa5$'
  646. ]
  647. #---------------------------------------------------------------
  648. # option flags
  649. #---------------------------------------------------------------
  650. # whether hash is case insensitive
  651. # True, False, or special value "verify-only" (which indicates
  652. # hash contains case-sensitive portion, but verifies is case-insensitive)
  653. secret_case_insensitive = False
  654. # flag if scheme accepts ALL hash strings (e.g. plaintext)
  655. accepts_all_hashes = False
  656. # flag if scheme has "is_disabled" set, and contains 'salted' data
  657. disabled_contains_salt = False
  658. # flag/hack to filter PasslibHashWarning issued by test_72_configs()
  659. filter_config_warnings = False
  660. # forbid certain characters in passwords
  661. @classproperty
  662. def forbidden_characters(cls):
  663. # anything that supports crypt() interface should forbid null chars,
  664. # since crypt() uses null-terminated strings.
  665. if 'os_crypt' in getattr(cls.handler, "backends", ()):
  666. return b"\x00"
  667. return None
  668. #===================================================================
  669. # internal class attrs
  670. #===================================================================
  671. __unittest_skip = True
  672. @property
  673. def descriptionPrefix(self):
  674. handler = self.handler
  675. name = handler.name
  676. if hasattr(handler, "get_backend"):
  677. name += " (%s backend)" % (handler.get_backend(),)
  678. return name
  679. #===================================================================
  680. # support methods
  681. #===================================================================
  682. #---------------------------------------------------------------
  683. # configuration helpers
  684. #---------------------------------------------------------------
  685. @classmethod
  686. def iter_known_hashes(cls):
  687. """iterate through known (secret, hash) pairs"""
  688. for secret, hash in cls.known_correct_hashes:
  689. yield secret, hash
  690. for config, secret, hash in cls.known_correct_configs:
  691. yield secret, hash
  692. for alt, secret, hash in cls.known_alternate_hashes:
  693. yield secret, hash
  694. def get_sample_hash(self):
  695. """test random sample secret/hash pair"""
  696. known = list(self.iter_known_hashes())
  697. return self.getRandom().choice(known)
  698. #---------------------------------------------------------------
  699. # test helpers
  700. #---------------------------------------------------------------
  701. def check_verify(self, secret, hash, msg=None, negate=False):
  702. """helper to check verify() outcome, honoring is_disabled_handler"""
  703. result = self.do_verify(secret, hash)
  704. self.assertTrue(result is True or result is False,
  705. "verify() returned non-boolean value: %r" % (result,))
  706. if self.handler.is_disabled or negate:
  707. if not result:
  708. return
  709. if not msg:
  710. msg = ("verify incorrectly returned True: secret=%r, hash=%r" %
  711. (secret, hash))
  712. raise self.failureException(msg)
  713. else:
  714. if result:
  715. return
  716. if not msg:
  717. msg = "verify failed: secret=%r, hash=%r" % (secret, hash)
  718. raise self.failureException(msg)
  719. def check_returned_native_str(self, result, func_name):
  720. self.assertIsInstance(result, str,
  721. "%s() failed to return native string: %r" % (func_name, result,))
  722. #---------------------------------------------------------------
  723. # PasswordHash helpers - wraps all calls to PasswordHash api,
  724. # so that subclasses can fill in defaults and account for other specialized behavior
  725. #---------------------------------------------------------------
  726. def populate_settings(self, kwds):
  727. """subclassable method to populate default settings"""
  728. # use lower rounds settings for certain test modes
  729. handler = self.handler
  730. if 'rounds' in handler.setting_kwds and 'rounds' not in kwds:
  731. mn = handler.min_rounds
  732. df = handler.default_rounds
  733. if TEST_MODE(max="quick"):
  734. # use minimum rounds for quick mode
  735. kwds['rounds'] = max(3, mn)
  736. else:
  737. # use default/16 otherwise
  738. factor = 3
  739. if getattr(handler, "rounds_cost", None) == "log2":
  740. df -= factor
  741. else:
  742. df //= (1<<factor)
  743. kwds['rounds'] = max(3, mn, df)
  744. def populate_context(self, secret, kwds):
  745. """subclassable method allowing 'secret' to be encode context kwds"""
  746. return secret
  747. # TODO: rename to do_hash() to match new API
  748. def do_encrypt(self, secret, use_encrypt=False, handler=None, context=None, **settings):
  749. """call handler's hash() method with specified options"""
  750. self.populate_settings(settings)
  751. if context is None:
  752. context = {}
  753. secret = self.populate_context(secret, context)
  754. if use_encrypt:
  755. # use legacy 1.6 api
  756. warnings = []
  757. if settings:
  758. context.update(**settings)
  759. warnings.append("passing settings to.*is deprecated")
  760. with self.assertWarningList(warnings):
  761. return (handler or self.handler).encrypt(secret, **context)
  762. else:
  763. # use 1.7 api
  764. return (handler or self.handler).using(**settings).hash(secret, **context)
  765. def do_verify(self, secret, hash, handler=None, **kwds):
  766. """call handler's verify method"""
  767. secret = self.populate_context(secret, kwds)
  768. return (handler or self.handler).verify(secret, hash, **kwds)
  769. def do_identify(self, hash):
  770. """call handler's identify method"""
  771. return self.handler.identify(hash)
  772. def do_genconfig(self, **kwds):
  773. """call handler's genconfig method with specified options"""
  774. self.populate_settings(kwds)
  775. return self.handler.genconfig(**kwds)
  776. def do_genhash(self, secret, config, **kwds):
  777. """call handler's genhash method with specified options"""
  778. secret = self.populate_context(secret, kwds)
  779. return self.handler.genhash(secret, config, **kwds)
  780. def do_stub_encrypt(self, handler=None, context=None, **settings):
  781. """
  782. return sample hash for handler, w/o caring if digest is valid
  783. (uses some monkeypatching to minimize digest calculation cost)
  784. """
  785. handler = (handler or self.handler).using(**settings)
  786. if context is None:
  787. context = {}
  788. secret = self.populate_context("", context)
  789. with patch_calc_min_rounds(handler):
  790. return handler.hash(secret, **context)
  791. #---------------------------------------------------------------
  792. # automatically generate subclasses for testing specific backends,
  793. # and other backend helpers
  794. #---------------------------------------------------------------
  795. BACKEND_NOT_AVAILABLE = "backend not available"
  796. @classmethod
  797. def _get_skip_backend_reason(cls, backend):
  798. """
  799. helper for create_backend_case() --
  800. returns reason to skip backend, or None if backend should be tested
  801. """
  802. handler = cls.handler
  803. if not is_default_backend(handler, backend) and not TEST_MODE("full"):
  804. return "only default backend is being tested"
  805. if handler.has_backend(backend):
  806. return None
  807. return cls.BACKEND_NOT_AVAILABLE
  808. @classmethod
  809. def create_backend_case(cls, backend):
  810. handler = cls.handler
  811. name = handler.name
  812. assert hasattr(handler, "backends"), "handler must support uh.HasManyBackends protocol"
  813. assert backend in handler.backends, "unknown backend: %r" % (backend,)
  814. bases = (cls,)
  815. if backend == "os_crypt":
  816. bases += (OsCryptMixin,)
  817. subcls = type(
  818. "%s_%s_test" % (name, backend),
  819. bases,
  820. dict(
  821. descriptionPrefix="%s (%s backend)" % (name, backend),
  822. backend=backend,
  823. __module__=cls.__module__,
  824. )
  825. )
  826. skip_reason = cls._get_skip_backend_reason(backend)
  827. if skip_reason:
  828. subcls = skip(skip_reason)(subcls)
  829. return subcls
  830. #===================================================================
  831. # setup
  832. #===================================================================
  833. def setUp(self):
  834. super(HandlerCase, self).setUp()
  835. # if needed, select specific backend for duration of test
  836. handler = self.handler
  837. backend = self.backend
  838. if backend:
  839. if not hasattr(handler, "set_backend"):
  840. raise RuntimeError("handler doesn't support multiple backends")
  841. self.addCleanup(handler.set_backend, handler.get_backend())
  842. handler.set_backend(backend)
  843. # patch some RNG references so they're reproducible.
  844. from passlib.utils import handlers
  845. self.patchAttr(handlers, "rng", self.getRandom("salt generator"))
  846. #===================================================================
  847. # basic tests
  848. #===================================================================
  849. def test_01_required_attributes(self):
  850. """validate required attributes"""
  851. handler = self.handler
  852. def ga(name):
  853. return getattr(handler, name, None)
  854. #
  855. # name should be a str, and valid
  856. #
  857. name = ga("name")
  858. self.assertTrue(name, "name not defined:")
  859. self.assertIsInstance(name, str, "name must be native str")
  860. self.assertTrue(name.lower() == name, "name not lower-case:")
  861. self.assertTrue(re.match("^[a-z0-9_]+$", name),
  862. "name must be alphanum + underscore: %r" % (name,))
  863. #
  864. # setting_kwds should be specified
  865. #
  866. settings = ga("setting_kwds")
  867. self.assertTrue(settings is not None, "setting_kwds must be defined:")
  868. self.assertIsInstance(settings, tuple, "setting_kwds must be a tuple:")
  869. #
  870. # context_kwds should be specified
  871. #
  872. context = ga("context_kwds")
  873. self.assertTrue(context is not None, "context_kwds must be defined:")
  874. self.assertIsInstance(context, tuple, "context_kwds must be a tuple:")
  875. # XXX: any more checks needed?
  876. def test_02_config_workflow(self):
  877. """test basic config-string workflow
  878. this tests that genconfig() returns the expected types,
  879. and that identify() and genhash() handle the result correctly.
  880. """
  881. #
  882. # genconfig() should return native string.
  883. # NOTE: prior to 1.7 could return None, but that's no longer allowed.
  884. #
  885. config = self.do_genconfig()
  886. self.check_returned_native_str(config, "genconfig")
  887. #
  888. # genhash() should always accept genconfig()'s output,
  889. # whether str OR None.
  890. #
  891. result = self.do_genhash('stub', config)
  892. self.check_returned_native_str(result, "genhash")
  893. #
  894. # verify() should never accept config strings
  895. #
  896. # NOTE: changed as of 1.7 -- previously, .verify() should have
  897. # rejected partial config strings returned by genconfig().
  898. # as of 1.7, that feature is deprecated, and genconfig()
  899. # always returns a hash (usually of the empty string)
  900. # so verify should always accept it's output
  901. self.do_verify('', config) # usually true, but not required by protocol
  902. #
  903. # identify() should positively identify config strings if not None.
  904. #
  905. # NOTE: changed as of 1.7 -- genconfig() previously might return None,
  906. # now must always return valid hash
  907. self.assertTrue(self.do_identify(config),
  908. "identify() failed to identify genconfig() output: %r" %
  909. (config,))
  910. def test_02_using_workflow(self):
  911. """test basic using() workflow"""
  912. handler = self.handler
  913. subcls = handler.using()
  914. self.assertIsNot(subcls, handler)
  915. self.assertEqual(subcls.name, handler.name)
  916. # NOTE: other info attrs should match as well, just testing basic behavior.
  917. # NOTE: mixin-specific args like using(min_rounds=xxx) tested later.
  918. def test_03_hash_workflow(self, use_16_legacy=False):
  919. """test basic hash-string workflow.
  920. this tests that hash()'s hashes are accepted
  921. by verify() and identify(), and regenerated correctly by genhash().
  922. the test is run against a couple of different stock passwords.
  923. """
  924. wrong_secret = 'stub'
  925. for secret in self.stock_passwords:
  926. #
  927. # hash() should generate native str hash
  928. #
  929. result = self.do_encrypt(secret, use_encrypt=use_16_legacy)
  930. self.check_returned_native_str(result, "hash")
  931. #
  932. # verify() should work only against secret
  933. #
  934. self.check_verify(secret, result)
  935. self.check_verify(wrong_secret, result, negate=True)
  936. #
  937. # genhash() should reproduce original hash
  938. #
  939. other = self.do_genhash(secret, result)
  940. self.check_returned_native_str(other, "genhash")
  941. if self.handler.is_disabled and self.disabled_contains_salt:
  942. self.assertNotEqual(other, result, "genhash() failed to salt result "
  943. "hash: secret=%r hash=%r: result=%r" %
  944. (secret, result, other))
  945. else:
  946. self.assertEqual(other, result, "genhash() failed to reproduce "
  947. "hash: secret=%r hash=%r: result=%r" %
  948. (secret, result, other))
  949. #
  950. # genhash() should NOT reproduce original hash for wrong password
  951. #
  952. other = self.do_genhash(wrong_secret, result)
  953. self.check_returned_native_str(other, "genhash")
  954. if self.handler.is_disabled and not self.disabled_contains_salt:
  955. self.assertEqual(other, result, "genhash() failed to reproduce "
  956. "disabled-hash: secret=%r hash=%r other_secret=%r: result=%r" %
  957. (secret, result, wrong_secret, other))
  958. else:
  959. self.assertNotEqual(other, result, "genhash() duplicated "
  960. "hash: secret=%r hash=%r wrong_secret=%r: result=%r" %
  961. (secret, result, wrong_secret, other))
  962. #
  963. # identify() should positively identify hash
  964. #
  965. self.assertTrue(self.do_identify(result))
  966. def test_03_legacy_hash_workflow(self):
  967. """test hash-string workflow with legacy .encrypt() & .genhash() methods"""
  968. self.test_03_hash_workflow(use_16_legacy=True)
  969. def test_04_hash_types(self):
  970. """test hashes can be unicode or bytes"""
  971. # this runs through workflow similar to 03, but wraps
  972. # everything using tonn() so we test unicode under py2,
  973. # and bytes under py3.
  974. # hash using non-native secret
  975. result = self.do_encrypt(tonn('stub'))
  976. self.check_returned_native_str(result, "hash")
  977. # verify using non-native hash
  978. self.check_verify('stub', tonn(result))
  979. # verify using non-native hash AND secret
  980. self.check_verify(tonn('stub'), tonn(result))
  981. # genhash using non-native hash
  982. other = self.do_genhash('stub', tonn(result))
  983. self.check_returned_native_str(other, "genhash")
  984. if self.handler.is_disabled and self.disabled_contains_salt:
  985. self.assertNotEqual(other, result)
  986. else:
  987. self.assertEqual(other, result)
  988. # genhash using non-native hash AND secret
  989. other = self.do_genhash(tonn('stub'), tonn(result))
  990. self.check_returned_native_str(other, "genhash")
  991. if self.handler.is_disabled and self.disabled_contains_salt:
  992. self.assertNotEqual(other, result)
  993. else:
  994. self.assertEqual(other, result)
  995. # identify using non-native hash
  996. self.assertTrue(self.do_identify(tonn(result)))
  997. def test_05_backends(self):
  998. """test multi-backend support"""
  999. # check that handler supports multiple backends
  1000. handler = self.handler
  1001. if not hasattr(handler, "set_backend"):
  1002. raise self.skipTest("handler only has one backend")
  1003. # add cleanup func to restore old backend
  1004. self.addCleanup(handler.set_backend, handler.get_backend())
  1005. # run through each backend, make sure it works
  1006. for backend in handler.backends:
  1007. #
  1008. # validate backend name
  1009. #
  1010. self.assertIsInstance(backend, str)
  1011. self.assertNotIn(backend, RESERVED_BACKEND_NAMES,
  1012. "invalid backend name: %r" % (backend,))
  1013. #
  1014. # ensure has_backend() returns bool value
  1015. #
  1016. ret = handler.has_backend(backend)
  1017. if ret is True:
  1018. # verify backend can be loaded
  1019. handler.set_backend(backend)
  1020. self.assertEqual(handler.get_backend(), backend)
  1021. elif ret is False:
  1022. # verify backend CAN'T be loaded
  1023. self.assertRaises(MissingBackendError, handler.set_backend,
  1024. backend)
  1025. else:
  1026. # didn't return boolean object. commonly fails due to
  1027. # use of 'classmethod' decorator instead of 'classproperty'
  1028. raise TypeError("has_backend(%r) returned invalid "
  1029. "value: %r" % (backend, ret))
  1030. #===================================================================
  1031. # salts
  1032. #===================================================================
  1033. def require_salt(self):
  1034. if 'salt' not in self.handler.setting_kwds:
  1035. raise self.skipTest("handler doesn't have salt")
  1036. def require_salt_info(self):
  1037. self.require_salt()
  1038. if not has_salt_info(self.handler):
  1039. raise self.skipTest("handler doesn't provide salt info")
  1040. def test_10_optional_salt_attributes(self):
  1041. """validate optional salt attributes"""
  1042. self.require_salt_info()
  1043. AssertionError = self.failureException
  1044. cls = self.handler
  1045. # check max_salt_size
  1046. mx_set = (cls.max_salt_size is not None)
  1047. if mx_set and cls.max_salt_size < 1:
  1048. raise AssertionError("max_salt_chars must be >= 1")
  1049. # check min_salt_size
  1050. if cls.min_salt_size < 0:
  1051. raise AssertionError("min_salt_chars must be >= 0")
  1052. if mx_set and cls.min_salt_size > cls.max_salt_size:
  1053. raise AssertionError("min_salt_chars must be <= max_salt_chars")
  1054. # check default_salt_size
  1055. if cls.default_salt_size < cls.min_salt_size:
  1056. raise AssertionError("default_salt_size must be >= min_salt_size")
  1057. if mx_set and cls.default_salt_size > cls.max_salt_size:
  1058. raise AssertionError("default_salt_size must be <= max_salt_size")
  1059. # check for 'salt_size' keyword
  1060. # NOTE: skipping warning if default salt size is already maxed out
  1061. # (might change that in future)
  1062. if 'salt_size' not in cls.setting_kwds and (not mx_set or cls.default_salt_size < cls.max_salt_size):
  1063. warn('%s: hash handler supports range of salt sizes, '
  1064. 'but doesn\'t offer \'salt_size\' setting' % (cls.name,))
  1065. # check salt_chars & default_salt_chars
  1066. if cls.salt_chars:
  1067. if not cls.default_salt_chars:
  1068. raise AssertionError("default_salt_chars must not be empty")
  1069. for c in cls.default_salt_chars:
  1070. if c not in cls.salt_chars:
  1071. raise AssertionError("default_salt_chars must be subset of salt_chars: %r not in salt_chars" % (c,))
  1072. else:
  1073. if not cls.default_salt_chars:
  1074. raise AssertionError("default_salt_chars MUST be specified if salt_chars is empty")
  1075. @property
  1076. def salt_bits(self):
  1077. """calculate number of salt bits in hash"""
  1078. # XXX: replace this with bitsize() method?
  1079. handler = self.handler
  1080. assert has_salt_info(handler), "need explicit bit-size for " + handler.name
  1081. from math import log
  1082. # FIXME: this may be off for case-insensitive hashes, but that accounts
  1083. # for ~1 bit difference, which is good enough for test_11()
  1084. return int(handler.default_salt_size *
  1085. log(len(handler.default_salt_chars), 2))
  1086. def test_11_unique_salt(self):
  1087. """test hash() / genconfig() creates new salt each time"""
  1088. self.require_salt()
  1089. # odds of picking 'n' identical salts at random is '(.5**salt_bits)**n'.
  1090. # we want to pick the smallest N needed s.t. odds are <1/10**d, just
  1091. # to eliminate false-positives. which works out to n>3.33+d-salt_bits.
  1092. # for 1/1e12 odds, n=1 is sufficient for most hashes, but a few border cases (e.g.
  1093. # cisco_type7) have < 16 bits of salt, requiring more.
  1094. samples = max(1, 4 + 12 - self.salt_bits)
  1095. def sampler(func):
  1096. value1 = func()
  1097. for _ in irange(samples):
  1098. value2 = func()
  1099. if value1 != value2:
  1100. return
  1101. raise self.failureException("failed to find different salt after "
  1102. "%d samples" % (samples,))
  1103. sampler(self.do_genconfig)
  1104. sampler(lambda: self.do_encrypt("stub"))
  1105. def test_12_min_salt_size(self):
  1106. """test hash() / genconfig() honors min_salt_size"""
  1107. self.require_salt_info()
  1108. handler = self.handler
  1109. salt_char = handler.salt_chars[0:1]
  1110. min_size = handler.min_salt_size
  1111. #
  1112. # check min is accepted
  1113. #
  1114. s1 = salt_char * min_size
  1115. self.do_genconfig(salt=s1)
  1116. self.do_encrypt('stub', salt_size=min_size)
  1117. #
  1118. # check min-1 is rejected
  1119. #
  1120. if min_size > 0:
  1121. self.assertRaises(ValueError, self.do_genconfig,
  1122. salt=s1[:-1])
  1123. self.assertRaises(ValueError, self.do_encrypt, 'stub',
  1124. salt_size=min_size-1)
  1125. def test_13_max_salt_size(self):
  1126. """test hash() / genconfig() honors max_salt_size"""
  1127. self.require_salt_info()
  1128. handler = self.handler
  1129. max_size = handler.max_salt_size
  1130. salt_char = handler.salt_chars[0:1]
  1131. # NOTE: skipping this for hashes like argon2 since max_salt_size takes WAY too much memory
  1132. if max_size is None or max_size > (1 << 20):
  1133. #
  1134. # if it's not set, salt should never be truncated; so test it
  1135. # with an unreasonably large salt.
  1136. #
  1137. s1 = salt_char * 1024
  1138. c1 = self.do_stub_encrypt(salt=s1)
  1139. c2 = self.do_stub_encrypt(salt=s1 + salt_char)
  1140. self.assertNotEqual(c1, c2)
  1141. self.do_stub_encrypt(salt_size=1024)
  1142. else:
  1143. #
  1144. # check max size is accepted
  1145. #
  1146. s1 = salt_char * max_size
  1147. c1 = self.do_stub_encrypt(salt=s1)
  1148. self.do_stub_encrypt(salt_size=max_size)
  1149. #
  1150. # check max size + 1 is rejected
  1151. #
  1152. s2 = s1 + salt_char
  1153. self.assertRaises(ValueError, self.do_stub_encrypt, salt=s2)
  1154. self.assertRaises(ValueError, self.do_stub_encrypt, salt_size=max_size + 1)
  1155. #
  1156. # should accept too-large salt in relaxed mode
  1157. #
  1158. if has_relaxed_setting(handler):
  1159. with warnings.catch_warnings(record=True): # issues passlibhandlerwarning
  1160. c2 = self.do_stub_encrypt(salt=s2, relaxed=True)
  1161. self.assertEqual(c2, c1)
  1162. #
  1163. # if min_salt supports it, check smaller than mx is NOT truncated
  1164. #
  1165. if handler.min_salt_size < max_size:
  1166. c3 = self.do_stub_encrypt(salt=s1[:-1])
  1167. self.assertNotEqual(c3, c1)
  1168. # whether salt should be passed through bcrypt repair function
  1169. fuzz_salts_need_bcrypt_repair = False
  1170. def prepare_salt(self, salt):
  1171. """prepare generated salt"""
  1172. if self.fuzz_salts_need_bcrypt_repair:
  1173. from passlib.utils.binary import bcrypt64
  1174. salt = bcrypt64.repair_unused(salt)
  1175. return salt
  1176. def test_14_salt_chars(self):
  1177. """test hash() honors salt_chars"""
  1178. self.require_salt_info()
  1179. handler = self.handler
  1180. mx = handler.max_salt_size
  1181. mn = handler.min_salt_size
  1182. cs = handler.salt_chars
  1183. raw = isinstance(cs, bytes)
  1184. # make sure all listed chars are accepted
  1185. for salt in batch(cs, mx or 32):
  1186. if len(salt) < mn:
  1187. salt = repeat_string(salt, mn)
  1188. salt = self.prepare_salt(salt)
  1189. self.do_stub_encrypt(salt=salt)
  1190. # check some invalid salt chars, make sure they're rejected
  1191. source = u('\x00\xff')
  1192. if raw:
  1193. source = source.encode("latin-1")
  1194. chunk = max(mn, 1)
  1195. for c in source:
  1196. if c not in cs:
  1197. self.assertRaises(ValueError, self.do_stub_encrypt, salt=c*chunk,
  1198. __msg__="invalid salt char %r:" % (c,))
  1199. @property
  1200. def salt_type(self):
  1201. """hack to determine salt keyword's datatype"""
  1202. # NOTE: cisco_type7 uses 'int'
  1203. if getattr(self.handler, "_salt_is_bytes", False):
  1204. return bytes
  1205. else:
  1206. return unicode
  1207. def test_15_salt_type(self):
  1208. """test non-string salt values"""
  1209. self.require_salt()
  1210. salt_type = self.salt_type
  1211. salt_size = getattr(self.handler, "min_salt_size", 0) or 8
  1212. # should always throw error for random class.
  1213. class fake(object):
  1214. pass
  1215. self.assertRaises(TypeError, self.do_encrypt, 'stub', salt=fake())
  1216. # unicode should be accepted only if salt_type is unicode.
  1217. if salt_type is not unicode:
  1218. self.assertRaises(TypeError, self.do_encrypt, 'stub', salt=u('x') * salt_size)
  1219. # bytes should be accepted only if salt_type is bytes,
  1220. # OR if salt type is unicode and running PY2 - to allow native strings.
  1221. if not (salt_type is bytes or (PY2 and salt_type is unicode)):
  1222. self.assertRaises(TypeError, self.do_encrypt, 'stub', salt=b'x' * salt_size)
  1223. def test_using_salt_size(self):
  1224. """Handler.using() -- default_salt_size"""
  1225. self.require_salt_info()
  1226. handler = self.handler
  1227. mn = handler.min_salt_size
  1228. mx = handler.max_salt_size
  1229. df = handler.default_salt_size
  1230. # should prevent setting below handler limit
  1231. self.assertRaises(ValueError, handler.using, default_salt_size=-1)
  1232. with self.assertWarningList([PasslibHashWarning]):
  1233. temp = handler.using(default_salt_size=-1, relaxed=True)
  1234. self.assertEqual(temp.default_salt_size, mn)
  1235. # should prevent setting above handler limit
  1236. if mx:
  1237. self.assertRaises(ValueError, handler.using, default_salt_size=mx+1)
  1238. with self.assertWarningList([PasslibHashWarning]):
  1239. temp = handler.using(default_salt_size=mx+1, relaxed=True)
  1240. self.assertEqual(temp.default_salt_size, mx)
  1241. # try setting to explicit value
  1242. if mn != mx:
  1243. temp = handler.using(default_salt_size=mn+1)
  1244. self.assertEqual(temp.default_salt_size, mn+1)
  1245. self.assertEqual(handler.default_salt_size, df)
  1246. temp = handler.using(default_salt_size=mn+2)
  1247. self.assertEqual(temp.default_salt_size, mn+2)
  1248. self.assertEqual(handler.default_salt_size, df)
  1249. # accept strings
  1250. if mn == mx:
  1251. ref = mn
  1252. else:
  1253. ref = mn + 1
  1254. temp = handler.using(default_salt_size=str(ref))
  1255. self.assertEqual(temp.default_salt_size, ref)
  1256. # reject invalid strings
  1257. self.assertRaises(ValueError, handler.using, default_salt_size=str(ref) + "xxx")
  1258. # honor 'salt_size' alias
  1259. temp = handler.using(salt_size=ref)
  1260. self.assertEqual(temp.default_salt_size, ref)
  1261. #===================================================================
  1262. # rounds
  1263. #===================================================================
  1264. def require_rounds_info(self):
  1265. if not has_rounds_info(self.handler):
  1266. raise self.skipTest("handler lacks rounds attributes")
  1267. def test_20_optional_rounds_attributes(self):
  1268. """validate optional rounds attributes"""
  1269. self.require_rounds_info()
  1270. cls = self.handler
  1271. AssertionError = self.failureException
  1272. # check max_rounds
  1273. if cls.max_rounds is None:
  1274. raise AssertionError("max_rounds not specified")
  1275. if cls.max_rounds < 1:
  1276. raise AssertionError("max_rounds must be >= 1")
  1277. # check min_rounds
  1278. if cls.min_rounds < 0:
  1279. raise AssertionError("min_rounds must be >= 0")
  1280. if cls.min_rounds > cls.max_rounds:
  1281. raise AssertionError("min_rounds must be <= max_rounds")
  1282. # check default_rounds
  1283. if cls.default_rounds is not None:
  1284. if cls.default_rounds < cls.min_rounds:
  1285. raise AssertionError("default_rounds must be >= min_rounds")
  1286. if cls.default_rounds > cls.max_rounds:
  1287. raise AssertionError("default_rounds must be <= max_rounds")
  1288. # check rounds_cost
  1289. if cls.rounds_cost not in rounds_cost_values:
  1290. raise AssertionError("unknown rounds cost constant: %r" % (cls.rounds_cost,))
  1291. def test_21_min_rounds(self):
  1292. """test hash() / genconfig() honors min_rounds"""
  1293. self.require_rounds_info()
  1294. handler = self.handler
  1295. min_rounds = handler.min_rounds
  1296. # check min is accepted
  1297. self.do_genconfig(rounds=min_rounds)
  1298. self.do_encrypt('stub', rounds=min_rounds)
  1299. # check min-1 is rejected
  1300. self.assertRaises(ValueError, self.do_genconfig, rounds=min_rounds-1)
  1301. self.assertRaises(ValueError, self.do_encrypt, 'stub', rounds=min_rounds-1)
  1302. # TODO: check relaxed mode clips min-1
  1303. def test_21b_max_rounds(self):
  1304. """test hash() / genconfig() honors max_rounds"""
  1305. self.require_rounds_info()
  1306. handler = self.handler
  1307. max_rounds = handler.max_rounds
  1308. if max_rounds is not None:
  1309. # check max+1 is rejected
  1310. self.assertRaises(ValueError, self.do_genconfig, rounds=max_rounds+1)
  1311. self.assertRaises(ValueError, self.do_encrypt, 'stub', rounds=max_rounds+1)
  1312. # handle max rounds
  1313. if max_rounds is None:
  1314. self.do_stub_encrypt(rounds=(1 << 31) - 1)
  1315. else:
  1316. self.do_stub_encrypt(rounds=max_rounds)
  1317. # TODO: check relaxed mode clips max+1
  1318. #--------------------------------------------------------------------------------------
  1319. # HasRounds.using() / .needs_update() -- desired rounds limits
  1320. #--------------------------------------------------------------------------------------
  1321. def _create_using_rounds_helper(self):
  1322. """
  1323. setup test helpers for testing handler.using()'s rounds parameters.
  1324. """
  1325. self.require_rounds_info()
  1326. handler = self.handler
  1327. if handler.name == "bsdi_crypt":
  1328. # hack to bypass bsdi-crypt's "odd rounds only" behavior, messes up this test
  1329. orig_handler = handler
  1330. handler = handler.using()
  1331. handler._generate_rounds = classmethod(lambda cls: super(orig_handler, cls)._generate_rounds())
  1332. # create some fake values to test with
  1333. orig_min_rounds = handler.min_rounds
  1334. orig_max_rounds = handler.max_rounds
  1335. orig_default_rounds = handler.default_rounds
  1336. medium = ((orig_max_rounds or 9999) + orig_min_rounds) // 2
  1337. if medium == orig_default_rounds:
  1338. medium += 1
  1339. small = (orig_min_rounds + medium) // 2
  1340. large = ((orig_max_rounds or 9999) + medium) // 2
  1341. if handler.name == "bsdi_crypt":
  1342. # hack to avoid even numbered rounds
  1343. small |= 1
  1344. medium |= 1
  1345. large |= 1
  1346. adj = 2
  1347. else:
  1348. adj = 1
  1349. # create a subclass with small/medium/large as new default desired values
  1350. with self.assertWarningList([]):
  1351. subcls = handler.using(
  1352. min_desired_rounds=small,
  1353. max_desired_rounds=large,
  1354. default_rounds=medium,
  1355. )
  1356. # return helpers
  1357. return handler, subcls, small, medium, large, adj
  1358. def test_has_rounds_using_harness(self):
  1359. """
  1360. HasRounds.using() -- sanity check test harness
  1361. """
  1362. # setup helpers
  1363. self.require_rounds_info()
  1364. handler = self.handler
  1365. orig_min_rounds = handler.min_rounds
  1366. orig_max_rounds = handler.max_rounds
  1367. orig_default_rounds = handler.default_rounds
  1368. handler, subcls, small, medium, large, adj = self._create_using_rounds_helper()
  1369. # shouldn't affect original handler at all
  1370. self.assertEqual(handler.min_rounds, orig_min_rounds)
  1371. self.assertEqual(handler.max_rounds, orig_max_rounds)
  1372. self.assertEqual(handler.min_desired_rounds, None)
  1373. self.assertEqual(handler.max_desired_rounds, None)
  1374. self.assertEqual(handler.default_rounds, orig_default_rounds)
  1375. # should affect subcls' desired value, but not hard min/max
  1376. self.assertEqual(subcls.min_rounds, orig_min_rounds)
  1377. self.assertEqual(subcls.max_rounds, orig_max_rounds)
  1378. self.assertEqual(subcls.default_rounds, medium)
  1379. self.assertEqual(subcls.min_desired_rounds, small)
  1380. self.assertEqual(subcls.max_desired_rounds, large)
  1381. def test_has_rounds_using_w_min_rounds(self):
  1382. """
  1383. HasRounds.using() -- min_rounds / min_desired_rounds
  1384. """
  1385. # setup helpers
  1386. handler, subcls, small, medium, large, adj = self._create_using_rounds_helper()
  1387. orig_min_rounds = handler.min_rounds
  1388. orig_max_rounds = handler.max_rounds
  1389. orig_default_rounds = handler.default_rounds
  1390. # .using() should clip values below valid minimum, w/ warning
  1391. if orig_min_rounds > 0:
  1392. self.assertRaises(ValueError, handler.using, min_desired_rounds=orig_min_rounds - adj)
  1393. with self.assertWarningList([PasslibHashWarning]):
  1394. temp = handler.using(min_desired_rounds=orig_min_rounds - adj, relaxed=True)
  1395. self.assertEqual(temp.min_desired_rounds, orig_min_rounds)
  1396. # .using() should clip values above valid maximum, w/ warning
  1397. if orig_max_rounds:
  1398. self.assertRaises(ValueError, handler.using, min_desired_rounds=orig_max_rounds + adj)
  1399. with self.assertWarningList([PasslibHashWarning]):
  1400. temp = handler.using(min_desired_rounds=orig_max_rounds + adj, relaxed=True)
  1401. self.assertEqual(temp.min_desired_rounds, orig_max_rounds)
  1402. # .using() should allow values below previous desired minimum, w/o warning
  1403. with self.assertWarningList([]):
  1404. temp = subcls.using(min_desired_rounds=small - adj)
  1405. self.assertEqual(temp.min_desired_rounds, small - adj)
  1406. # .using() should allow values w/in previous range
  1407. temp = subcls.using(min_desired_rounds=small + 2 * adj)
  1408. self.assertEqual(temp.min_desired_rounds, small + 2 * adj)
  1409. # .using() should allow values above previous desired maximum, w/o warning
  1410. with self.assertWarningList([]):
  1411. temp = subcls.using(min_desired_rounds=large + adj)
  1412. self.assertEqual(temp.min_desired_rounds, large + adj)
  1413. # hash() etc should allow explicit values below desired minimum
  1414. # NOTE: formerly issued a warning in passlib 1.6, now just a wrapper for .using()
  1415. self.assertEqual(get_effective_rounds(subcls, small + adj), small + adj)
  1416. self.assertEqual(get_effective_rounds(subcls, small), small)
  1417. with self.assertWarningList([]):
  1418. self.assertEqual(get_effective_rounds(subcls, small - adj), small - adj)
  1419. # 'min_rounds' should be treated as alias for 'min_desired_rounds'
  1420. temp = handler.using(min_rounds=small)
  1421. self.assertEqual(temp.min_desired_rounds, small)
  1422. # should be able to specify strings
  1423. temp = handler.using(min_rounds=str(small))
  1424. self.assertEqual(temp.min_desired_rounds, small)
  1425. # invalid strings should cause error
  1426. self.assertRaises(ValueError, handler.using, min_rounds=str(small) + "xxx")
  1427. def test_has_rounds_replace_w_max_rounds(self):
  1428. """
  1429. HasRounds.using() -- max_rounds / max_desired_rounds
  1430. """
  1431. # setup helpers
  1432. handler, subcls, small, medium, large, adj = self._create_using_rounds_helper()
  1433. orig_min_rounds = handler.min_rounds
  1434. orig_max_rounds = handler.max_rounds
  1435. # .using() should clip values below valid minimum w/ warning
  1436. if orig_min_rounds > 0:
  1437. self.assertRaises(ValueError, handler.using, max_desired_rounds=orig_min_rounds - adj)
  1438. with self.assertWarningList([PasslibHashWarning]):
  1439. temp = handler.using(max_desired_rounds=orig_min_rounds - adj, relaxed=True)
  1440. self.assertEqual(temp.max_desired_rounds, orig_min_rounds)
  1441. # .using() should clip values above valid maximum, w/ warning
  1442. if orig_max_rounds:
  1443. self.assertRaises(ValueError, handler.using, max_desired_rounds=orig_max_rounds + adj)
  1444. with self.assertWarningList([PasslibHashWarning]):
  1445. temp = handler.using(max_desired_rounds=orig_max_rounds + adj, relaxed=True)
  1446. self.assertEqual(temp.max_desired_rounds, orig_max_rounds)
  1447. # .using() should clip values below previous minimum, w/ warning
  1448. with self.assertWarningList([PasslibConfigWarning]):
  1449. temp = subcls.using(max_desired_rounds=small - adj)
  1450. self.assertEqual(temp.max_desired_rounds, small)
  1451. # .using() should reject explicit min > max
  1452. self.assertRaises(ValueError, subcls.using,
  1453. min_desired_rounds=medium+adj,
  1454. max_desired_rounds=medium-adj)
  1455. # .using() should allow values w/in previous range
  1456. temp = subcls.using(min_desired_rounds=large - 2 * adj)
  1457. self.assertEqual(temp.min_desired_rounds, large - 2 * adj)
  1458. # .using() should allow values above previous desired maximum, w/o warning
  1459. with self.assertWarningList([]):
  1460. temp = subcls.using(max_desired_rounds=large + adj)
  1461. self.assertEqual(temp.max_desired_rounds, large + adj)
  1462. # hash() etc should allow explicit values above desired minimum, w/o warning
  1463. # NOTE: formerly issued a warning in passlib 1.6, now just a wrapper for .using()
  1464. self.assertEqual(get_effective_rounds(subcls, large - adj), large - adj)
  1465. self.assertEqual(get_effective_rounds(subcls, large), large)
  1466. with self.assertWarningList([]):
  1467. self.assertEqual(get_effective_rounds(subcls, large + adj), large + adj)
  1468. # 'max_rounds' should be treated as alias for 'max_desired_rounds'
  1469. temp = handler.using(max_rounds=large)
  1470. self.assertEqual(temp.max_desired_rounds, large)
  1471. # should be able to specify strings
  1472. temp = handler.using(max_desired_rounds=str(large))
  1473. self.assertEqual(temp.max_desired_rounds, large)
  1474. # invalid strings should cause error
  1475. self.assertRaises(ValueError, handler.using, max_desired_rounds=str(large) + "xxx")
  1476. def test_has_rounds_using_w_default_rounds(self):
  1477. """
  1478. HasRounds.using() -- default_rounds
  1479. """
  1480. # setup helpers
  1481. handler, subcls, small, medium, large, adj = self._create_using_rounds_helper()
  1482. orig_max_rounds = handler.max_rounds
  1483. # XXX: are there any other cases that need testing?
  1484. # implicit default rounds -- increase to min_rounds
  1485. temp = subcls.using(min_rounds=medium+adj)
  1486. self.assertEqual(temp.default_rounds, medium+adj)
  1487. # implicit default rounds -- decrease to max_rounds
  1488. temp = subcls.using(max_rounds=medium-adj)
  1489. self.assertEqual(temp.default_rounds, medium-adj)
  1490. # explicit default rounds below desired minimum
  1491. # XXX: make this a warning if min is implicit?
  1492. self.assertRaises(ValueError, subcls.using, default_rounds=small-adj)
  1493. # explicit default rounds above desired maximum
  1494. # XXX: make this a warning if max is implicit?
  1495. if orig_max_rounds:
  1496. self.assertRaises(ValueError, subcls.using, default_rounds=large+adj)
  1497. # hash() etc should implicit default rounds, but get overridden
  1498. self.assertEqual(get_effective_rounds(subcls), medium)
  1499. self.assertEqual(get_effective_rounds(subcls, medium+adj), medium+adj)
  1500. # should be able to specify strings
  1501. temp = handler.using(default_rounds=str(medium))
  1502. self.assertEqual(temp.default_rounds, medium)
  1503. # invalid strings should cause error
  1504. self.assertRaises(ValueError, handler.using, default_rounds=str(medium) + "xxx")
  1505. def test_has_rounds_using_w_rounds(self):
  1506. """
  1507. HasRounds.using() -- rounds
  1508. """
  1509. # setup helpers
  1510. handler, subcls, small, medium, large, adj = self._create_using_rounds_helper()
  1511. orig_max_rounds = handler.max_rounds
  1512. # 'rounds' should be treated as fallback for min, max, and default
  1513. temp = subcls.using(rounds=medium+adj)
  1514. self.assertEqual(temp.min_desired_rounds, medium+adj)
  1515. self.assertEqual(temp.default_rounds, medium+adj)
  1516. self.assertEqual(temp.max_desired_rounds, medium+adj)
  1517. # 'rounds' should be treated as fallback for min, max, and default
  1518. temp = subcls.using(rounds=medium+1, min_rounds=small+adj,
  1519. default_rounds=medium, max_rounds=large-adj)
  1520. self.assertEqual(temp.min_desired_rounds, small+adj)
  1521. self.assertEqual(temp.default_rounds, medium)
  1522. self.assertEqual(temp.max_desired_rounds, large-adj)
  1523. def test_has_rounds_using_w_vary_rounds_parsing(self):
  1524. """
  1525. HasRounds.using() -- vary_rounds parsing
  1526. """
  1527. # setup helpers
  1528. handler, subcls, small, medium, large, adj = self._create_using_rounds_helper()
  1529. def parse(value):
  1530. return subcls.using(vary_rounds=value).vary_rounds
  1531. # floats should be preserved
  1532. self.assertEqual(parse(0.1), 0.1)
  1533. self.assertEqual(parse('0.1'), 0.1)
  1534. # 'xx%' should be converted to float
  1535. self.assertEqual(parse('10%'), 0.1)
  1536. # ints should be preserved
  1537. self.assertEqual(parse(1000), 1000)
  1538. self.assertEqual(parse('1000'), 1000)
  1539. # float bounds should be enforced
  1540. self.assertRaises(ValueError, parse, -0.1)
  1541. self.assertRaises(ValueError, parse, 1.1)
  1542. def test_has_rounds_using_w_vary_rounds_generation(self):
  1543. """
  1544. HasRounds.using() -- vary_rounds generation
  1545. """
  1546. handler, subcls, small, medium, large, adj = self._create_using_rounds_helper()
  1547. def get_effective_range(cls):
  1548. seen = set(get_effective_rounds(cls) for _ in irange(1000))
  1549. return min(seen), max(seen)
  1550. def assert_rounds_range(vary_rounds, lower, upper):
  1551. temp = subcls.using(vary_rounds=vary_rounds)
  1552. seen_lower, seen_upper = get_effective_range(temp)
  1553. self.assertEqual(seen_lower, lower, "vary_rounds had wrong lower limit:")
  1554. self.assertEqual(seen_upper, upper, "vary_rounds had wrong upper limit:")
  1555. # test static
  1556. assert_rounds_range(0, medium, medium)
  1557. assert_rounds_range("0%", medium, medium)
  1558. # test absolute
  1559. assert_rounds_range(adj, medium - adj, medium + adj)
  1560. assert_rounds_range(50, max(small, medium - 50), min(large, medium + 50))
  1561. # test relative - should shift over at 50% mark
  1562. if handler.rounds_cost == "log2":
  1563. # log rounds "50%" variance should only increase/decrease by 1 cost value
  1564. assert_rounds_range("1%", medium, medium)
  1565. assert_rounds_range("49%", medium, medium)
  1566. assert_rounds_range("50%", medium - adj, medium)
  1567. else:
  1568. # for linear rounds, range is frequently so huge, won't ever see ends.
  1569. # so we just check it's within an expected range.
  1570. lower, upper = get_effective_range(subcls.using(vary_rounds="50%"))
  1571. self.assertGreaterEqual(lower, max(small, medium * 0.5))
  1572. self.assertLessEqual(lower, max(small, medium * 0.8))
  1573. self.assertGreaterEqual(upper, min(large, medium * 1.2))
  1574. self.assertLessEqual(upper, min(large, medium * 1.5))
  1575. def test_has_rounds_using_and_needs_update(self):
  1576. """
  1577. HasRounds.using() -- desired_rounds + needs_update()
  1578. """
  1579. handler, subcls, small, medium, large, adj = self._create_using_rounds_helper()
  1580. temp = subcls.using(min_desired_rounds=small+2, max_desired_rounds=large-2)
  1581. # generate some sample hashes
  1582. small_hash = self.do_stub_encrypt(subcls, rounds=small)
  1583. medium_hash = self.do_stub_encrypt(subcls, rounds=medium)
  1584. large_hash = self.do_stub_encrypt(subcls, rounds=large)
  1585. # everything should be w/in bounds for original handler
  1586. self.assertFalse(subcls.needs_update(small_hash))
  1587. self.assertFalse(subcls.needs_update(medium_hash))
  1588. self.assertFalse(subcls.needs_update(large_hash))
  1589. # small & large should require update for temp handler
  1590. self.assertTrue(temp.needs_update(small_hash))
  1591. self.assertFalse(temp.needs_update(medium_hash))
  1592. self.assertTrue(temp.needs_update(large_hash))
  1593. #===================================================================
  1594. # idents
  1595. #===================================================================
  1596. def require_many_idents(self):
  1597. handler = self.handler
  1598. if not isinstance(handler, type) or not issubclass(handler, uh.HasManyIdents):
  1599. raise self.skipTest("handler doesn't derive from HasManyIdents")
  1600. def test_30_HasManyIdents(self):
  1601. """validate HasManyIdents configuration"""
  1602. cls = self.handler
  1603. self.require_many_idents()
  1604. # check settings
  1605. self.assertTrue('ident' in cls.setting_kwds)
  1606. # check ident_values list
  1607. for value in cls.ident_values:
  1608. self.assertIsInstance(value, unicode,
  1609. "cls.ident_values must be unicode:")
  1610. self.assertTrue(len(cls.ident_values)>1,
  1611. "cls.ident_values must have 2+ elements:")
  1612. # check default_ident value
  1613. self.assertIsInstance(cls.default_ident, unicode,
  1614. "cls.default_ident must be unicode:")
  1615. self.assertTrue(cls.default_ident in cls.ident_values,
  1616. "cls.default_ident must specify member of cls.ident_values")
  1617. # check optional aliases list
  1618. if cls.ident_aliases:
  1619. for alias, ident in iteritems(cls.ident_aliases):
  1620. self.assertIsInstance(alias, unicode,
  1621. "cls.ident_aliases keys must be unicode:") # XXX: allow ints?
  1622. self.assertIsInstance(ident, unicode,
  1623. "cls.ident_aliases values must be unicode:")
  1624. self.assertTrue(ident in cls.ident_values,
  1625. "cls.ident_aliases must map to cls.ident_values members: %r" % (ident,))
  1626. # check constructor validates ident correctly.
  1627. handler = cls
  1628. hash = self.get_sample_hash()[1]
  1629. kwds = handler.parsehash(hash)
  1630. del kwds['ident']
  1631. # ... accepts good ident
  1632. handler(ident=cls.default_ident, **kwds)
  1633. # ... requires ident w/o defaults
  1634. self.assertRaises(TypeError, handler, **kwds)
  1635. # ... supplies default ident
  1636. handler(use_defaults=True, **kwds)
  1637. # ... rejects bad ident
  1638. self.assertRaises(ValueError, handler, ident='xXx', **kwds)
  1639. # TODO: check various supported idents
  1640. def test_has_many_idents_using(self):
  1641. """HasManyIdents.using() -- 'default_ident' and 'ident' keywords"""
  1642. self.require_many_idents()
  1643. # pick alt ident to test with
  1644. handler = self.handler
  1645. orig_ident = handler.default_ident
  1646. for alt_ident in handler.ident_values:
  1647. if alt_ident != orig_ident:
  1648. break
  1649. else:
  1650. raise AssertionError("expected to find alternate ident: default=%r values=%r" %
  1651. (orig_ident, handler.ident_values))
  1652. def effective_ident(cls):
  1653. cls = unwrap_handler(cls)
  1654. return cls(use_defaults=True).ident
  1655. # keep default if nothing else specified
  1656. subcls = handler.using()
  1657. self.assertEqual(subcls.default_ident, orig_ident)
  1658. # accepts alt ident
  1659. subcls = handler.using(default_ident=alt_ident)
  1660. self.assertEqual(subcls.default_ident, alt_ident)
  1661. self.assertEqual(handler.default_ident, orig_ident)
  1662. # check subcls actually *generates* default ident,
  1663. # and that we didn't affect orig handler
  1664. self.assertEqual(effective_ident(subcls), alt_ident)
  1665. self.assertEqual(effective_ident(handler), orig_ident)
  1666. # rejects bad ident
  1667. self.assertRaises(ValueError, handler.using, default_ident='xXx')
  1668. # honor 'ident' alias
  1669. subcls = handler.using(ident=alt_ident)
  1670. self.assertEqual(subcls.default_ident, alt_ident)
  1671. self.assertEqual(handler.default_ident, orig_ident)
  1672. # forbid both at same time
  1673. self.assertRaises(TypeError, handler.using, default_ident=alt_ident, ident=alt_ident)
  1674. # check ident aliases are being honored
  1675. if handler.ident_aliases:
  1676. for alias, ident in handler.ident_aliases.items():
  1677. subcls = handler.using(ident=alias)
  1678. self.assertEqual(subcls.default_ident, ident, msg="alias %r:" % alias)
  1679. #===================================================================
  1680. # password size limits
  1681. #===================================================================
  1682. def test_truncate_error_setting(self):
  1683. """
  1684. validate 'truncate_error' setting & related attributes
  1685. """
  1686. # If it doesn't have truncate_size set,
  1687. # it shouldn't support truncate_error
  1688. hasher = self.handler
  1689. if hasher.truncate_size is None:
  1690. self.assertNotIn("truncate_error", hasher.setting_kwds)
  1691. return
  1692. # if hasher defaults to silently truncating,
  1693. # it MUST NOT use .truncate_verify_reject,
  1694. # because resulting hashes wouldn't verify!
  1695. if not hasher.truncate_error:
  1696. self.assertFalse(hasher.truncate_verify_reject)
  1697. # if hasher doesn't have configurable policy,
  1698. # it must throw error by default
  1699. if "truncate_error" not in hasher.setting_kwds:
  1700. self.assertTrue(hasher.truncate_error)
  1701. return
  1702. # test value parsing
  1703. def parse_value(value):
  1704. return hasher.using(truncate_error=value).truncate_error
  1705. self.assertEqual(parse_value(None), hasher.truncate_error)
  1706. self.assertEqual(parse_value(True), True)
  1707. self.assertEqual(parse_value("true"), True)
  1708. self.assertEqual(parse_value(False), False)
  1709. self.assertEqual(parse_value("false"), False)
  1710. self.assertRaises(ValueError, parse_value, "xxx")
  1711. def test_secret_wo_truncate_size(self):
  1712. """
  1713. test no password size limits enforced (if truncate_size=None)
  1714. """
  1715. # skip if hasher has a maximum password size
  1716. hasher = self.handler
  1717. if hasher.truncate_size is not None:
  1718. self.assertGreaterEqual(hasher.truncate_size, 1)
  1719. raise self.skipTest("truncate_size is set")
  1720. # NOTE: this doesn't do an exhaustive search to verify algorithm
  1721. # doesn't have some cutoff point, it just tries
  1722. # 1024-character string, and alters the last char.
  1723. # as long as algorithm doesn't clip secret at point <1024,
  1724. # the new secret shouldn't verify.
  1725. # hash a 1024-byte secret
  1726. secret = "too many secrets" * 16
  1727. alt = "x"
  1728. hash = self.do_encrypt(secret)
  1729. # check that verify doesn't silently reject secret
  1730. # (i.e. hasher mistakenly honors .truncate_verify_reject)
  1731. verify_success = not hasher.is_disabled
  1732. self.assertEqual(self.do_verify(secret, hash), verify_success,
  1733. msg="verify rejected correct secret")
  1734. # alter last byte, should get different hash, which won't verify
  1735. alt_secret = secret[:-1] + alt
  1736. self.assertFalse(self.do_verify(alt_secret, hash),
  1737. "full password not used in digest")
  1738. def test_secret_w_truncate_size(self):
  1739. """
  1740. test password size limits raise truncate_error (if appropriate)
  1741. """
  1742. #--------------------------------------------------
  1743. # check if test is applicable
  1744. #--------------------------------------------------
  1745. handler = self.handler
  1746. truncate_size = handler.truncate_size
  1747. if not truncate_size:
  1748. raise self.skipTest("truncate_size not set")
  1749. #--------------------------------------------------
  1750. # setup vars
  1751. #--------------------------------------------------
  1752. # try to get versions w/ and w/o truncate_error set.
  1753. # set to None if policy isn't configruable
  1754. size_error_type = exc.PasswordSizeError
  1755. if "truncate_error" in handler.setting_kwds:
  1756. without_error = handler.using(truncate_error=False)
  1757. with_error = handler.using(truncate_error=True)
  1758. size_error_type = exc.PasswordTruncateError
  1759. elif handler.truncate_error:
  1760. without_error = None
  1761. with_error = handler
  1762. else:
  1763. # NOTE: this mode is currently an error in test_truncate_error_setting()
  1764. without_error = handler
  1765. with_error = None
  1766. # create some test secrets
  1767. base = "too many secrets"
  1768. alt = "x" # char that's not in base, used to mutate test secrets
  1769. long_secret = repeat_string(base, truncate_size+1)
  1770. short_secret = long_secret[:-1]
  1771. alt_long_secret = long_secret[:-1] + alt
  1772. alt_short_secret = short_secret[:-1] + alt
  1773. # init flags
  1774. short_verify_success = not handler.is_disabled
  1775. long_verify_success = short_verify_success and \
  1776. not handler.truncate_verify_reject
  1777. #--------------------------------------------------
  1778. # do tests on <truncate_size> length secret, and resulting hash.
  1779. # should pass regardless of truncate_error policy.
  1780. #--------------------------------------------------
  1781. assert without_error or with_error
  1782. for cand_hasher in [without_error, with_error]:
  1783. # create & hash string that's exactly <truncate_size> chars.
  1784. short_hash = self.do_encrypt(short_secret, handler=cand_hasher)
  1785. # check hash verifies, regardless of .truncate_verify_reject
  1786. self.assertEqual(self.do_verify(short_secret, short_hash,
  1787. handler=cand_hasher),
  1788. short_verify_success)
  1789. # changing <truncate_size-1>'th char should invalidate hash
  1790. # if this fails, means (reported) truncate_size is too large.
  1791. self.assertFalse(self.do_verify(alt_short_secret, short_hash,
  1792. handler=with_error),
  1793. "truncate_size value is too large")
  1794. # verify should truncate long secret before comparing
  1795. # (unless truncate_verify_reject is set)
  1796. self.assertEqual(self.do_verify(long_secret, short_hash,
  1797. handler=cand_hasher),
  1798. long_verify_success)
  1799. #--------------------------------------------------
  1800. # do tests on <truncate_size+1> length secret,
  1801. # w/ truncate error disabled (should silently truncate)
  1802. #--------------------------------------------------
  1803. if without_error:
  1804. # create & hash string that's exactly truncate_size+1 chars
  1805. long_hash = self.do_encrypt(long_secret, handler=without_error)
  1806. # check verifies against secret (unless truncate_verify_reject=True)
  1807. self.assertEqual(self.do_verify(long_secret, long_hash,
  1808. handler=without_error),
  1809. short_verify_success)
  1810. # check mutating last char doesn't change outcome.
  1811. # if this fails, means (reported) truncate_size is too small.
  1812. self.assertEqual(self.do_verify(alt_long_secret, long_hash,
  1813. handler=without_error),
  1814. short_verify_success)
  1815. # check short_secret verifies against this hash
  1816. # if this fails, means (reported) truncate_size is too large.
  1817. self.assertTrue(self.do_verify(short_secret, long_hash,
  1818. handler=without_error))
  1819. #--------------------------------------------------
  1820. # do tests on <truncate_size+1> length secret,
  1821. # w/ truncate error
  1822. #--------------------------------------------------
  1823. if with_error:
  1824. # with errors enabled, should forbid truncation.
  1825. err = self.assertRaises(size_error_type, self.do_encrypt,
  1826. long_secret, handler=with_error)
  1827. self.assertEqual(err.max_size, truncate_size)
  1828. #===================================================================
  1829. # password contents
  1830. #===================================================================
  1831. def test_61_secret_case_sensitive(self):
  1832. """test password case sensitivity"""
  1833. hash_insensitive = self.secret_case_insensitive is True
  1834. verify_insensitive = self.secret_case_insensitive in [True,
  1835. "verify-only"]
  1836. # test hashing lower-case verifies against lower & upper
  1837. lower = 'test'
  1838. upper = 'TEST'
  1839. h1 = self.do_encrypt(lower)
  1840. if verify_insensitive and not self.handler.is_disabled:
  1841. self.assertTrue(self.do_verify(upper, h1),
  1842. "verify() should not be case sensitive")
  1843. else:
  1844. self.assertFalse(self.do_verify(upper, h1),
  1845. "verify() should be case sensitive")
  1846. # test hashing upper-case verifies against lower & upper
  1847. h2 = self.do_encrypt(upper)
  1848. if verify_insensitive and not self.handler.is_disabled:
  1849. self.assertTrue(self.do_verify(lower, h2),
  1850. "verify() should not be case sensitive")
  1851. else:
  1852. self.assertFalse(self.do_verify(lower, h2),
  1853. "verify() should be case sensitive")
  1854. # test genhash
  1855. # XXX: 2.0: what about 'verify-only' hashes once genhash() is removed?
  1856. # won't have easy way to recreate w/ same config to see if hash differs.
  1857. # (though only hash this applies to is mssql2000)
  1858. h2 = self.do_genhash(upper, h1)
  1859. if hash_insensitive or (self.handler.is_disabled and not self.disabled_contains_salt):
  1860. self.assertEqual(h2, h1,
  1861. "genhash() should not be case sensitive")
  1862. else:
  1863. self.assertNotEqual(h2, h1,
  1864. "genhash() should be case sensitive")
  1865. def test_62_secret_border(self):
  1866. """test non-string passwords are rejected"""
  1867. hash = self.get_sample_hash()[1]
  1868. # secret=None
  1869. self.assertRaises(TypeError, self.do_encrypt, None)
  1870. self.assertRaises(TypeError, self.do_genhash, None, hash)
  1871. self.assertRaises(TypeError, self.do_verify, None, hash)
  1872. # secret=int (picked as example of entirely wrong class)
  1873. self.assertRaises(TypeError, self.do_encrypt, 1)
  1874. self.assertRaises(TypeError, self.do_genhash, 1, hash)
  1875. self.assertRaises(TypeError, self.do_verify, 1, hash)
  1876. # xxx: move to password size limits section, above?
  1877. def test_63_large_secret(self):
  1878. """test MAX_PASSWORD_SIZE is enforced"""
  1879. from passlib.exc import PasswordSizeError
  1880. from passlib.utils import MAX_PASSWORD_SIZE
  1881. secret = '.' * (1+MAX_PASSWORD_SIZE)
  1882. hash = self.get_sample_hash()[1]
  1883. err = self.assertRaises(PasswordSizeError, self.do_genhash, secret, hash)
  1884. self.assertEqual(err.max_size, MAX_PASSWORD_SIZE)
  1885. self.assertRaises(PasswordSizeError, self.do_encrypt, secret)
  1886. self.assertRaises(PasswordSizeError, self.do_verify, secret, hash)
  1887. def test_64_forbidden_chars(self):
  1888. """test forbidden characters not allowed in password"""
  1889. chars = self.forbidden_characters
  1890. if not chars:
  1891. raise self.skipTest("none listed")
  1892. base = u('stub')
  1893. if isinstance(chars, bytes):
  1894. from passlib.utils.compat import iter_byte_chars
  1895. chars = iter_byte_chars(chars)
  1896. base = base.encode("ascii")
  1897. for c in chars:
  1898. self.assertRaises(ValueError, self.do_encrypt, base + c + base)
  1899. #===================================================================
  1900. # check identify(), verify(), genhash() against test vectors
  1901. #===================================================================
  1902. def is_secret_8bit(self, secret):
  1903. secret = self.populate_context(secret, {})
  1904. return not is_ascii_safe(secret)
  1905. def expect_os_crypt_failure(self, secret):
  1906. """
  1907. check if we're expecting potential verify failure due to crypt.crypt() encoding limitation
  1908. """
  1909. if PY3 and self.backend == "os_crypt" and isinstance(secret, bytes):
  1910. try:
  1911. secret.decode("utf-8")
  1912. except UnicodeDecodeError:
  1913. return True
  1914. return False
  1915. def test_70_hashes(self):
  1916. """test known hashes"""
  1917. # sanity check
  1918. self.assertTrue(self.known_correct_hashes or self.known_correct_configs,
  1919. "test must set at least one of 'known_correct_hashes' "
  1920. "or 'known_correct_configs'")
  1921. # run through known secret/hash pairs
  1922. saw8bit = False
  1923. for secret, hash in self.iter_known_hashes():
  1924. if self.is_secret_8bit(secret):
  1925. saw8bit = True
  1926. # hash should be positively identified by handler
  1927. self.assertTrue(self.do_identify(hash),
  1928. "identify() failed to identify hash: %r" % (hash,))
  1929. # check if what we're about to do is expected to fail due to crypt.crypt() limitation.
  1930. expect_os_crypt_failure = self.expect_os_crypt_failure(secret)
  1931. try:
  1932. # secret should verify successfully against hash
  1933. self.check_verify(secret, hash, "verify() of known hash failed: "
  1934. "secret=%r, hash=%r" % (secret, hash))
  1935. # genhash() should reproduce same hash
  1936. result = self.do_genhash(secret, hash)
  1937. self.assertIsInstance(result, str,
  1938. "genhash() failed to return native string: %r" % (result,))
  1939. if self.handler.is_disabled and self.disabled_contains_salt:
  1940. continue
  1941. self.assertEqual(result, hash, "genhash() failed to reproduce "
  1942. "known hash: secret=%r, hash=%r: result=%r" %
  1943. (secret, hash, result))
  1944. except MissingBackendError:
  1945. if not expect_os_crypt_failure:
  1946. raise
  1947. # would really like all handlers to have at least one 8-bit test vector
  1948. if not saw8bit:
  1949. warn("%s: no 8-bit secrets tested" % self.__class__)
  1950. def test_71_alternates(self):
  1951. """test known alternate hashes"""
  1952. if not self.known_alternate_hashes:
  1953. raise self.skipTest("no alternate hashes provided")
  1954. for alt, secret, hash in self.known_alternate_hashes:
  1955. # hash should be positively identified by handler
  1956. self.assertTrue(self.do_identify(hash),
  1957. "identify() failed to identify alternate hash: %r" %
  1958. (hash,))
  1959. # secret should verify successfully against hash
  1960. self.check_verify(secret, alt, "verify() of known alternate hash "
  1961. "failed: secret=%r, hash=%r" % (secret, alt))
  1962. # genhash() should reproduce canonical hash
  1963. result = self.do_genhash(secret, alt)
  1964. self.assertIsInstance(result, str,
  1965. "genhash() failed to return native string: %r" % (result,))
  1966. if self.handler.is_disabled and self.disabled_contains_salt:
  1967. continue
  1968. self.assertEqual(result, hash, "genhash() failed to normalize "
  1969. "known alternate hash: secret=%r, alt=%r, hash=%r: "
  1970. "result=%r" % (secret, alt, hash, result))
  1971. def test_72_configs(self):
  1972. """test known config strings"""
  1973. # special-case handlers without settings
  1974. if not self.handler.setting_kwds:
  1975. self.assertFalse(self.known_correct_configs,
  1976. "handler should not have config strings")
  1977. raise self.skipTest("hash has no settings")
  1978. if not self.known_correct_configs:
  1979. # XXX: make this a requirement?
  1980. raise self.skipTest("no config strings provided")
  1981. # make sure config strings work (hashes in list tested in test_70)
  1982. if self.filter_config_warnings:
  1983. warnings.filterwarnings("ignore", category=PasslibHashWarning)
  1984. for config, secret, hash in self.known_correct_configs:
  1985. # config should be positively identified by handler
  1986. self.assertTrue(self.do_identify(config),
  1987. "identify() failed to identify known config string: %r" %
  1988. (config,))
  1989. # verify() should throw error for config strings.
  1990. self.assertRaises(ValueError, self.do_verify, secret, config,
  1991. __msg__="verify() failed to reject config string: %r" %
  1992. (config,))
  1993. # genhash() should reproduce hash from config.
  1994. result = self.do_genhash(secret, config)
  1995. self.assertIsInstance(result, str,
  1996. "genhash() failed to return native string: %r" % (result,))
  1997. self.assertEqual(result, hash, "genhash() failed to reproduce "
  1998. "known hash from config: secret=%r, config=%r, hash=%r: "
  1999. "result=%r" % (secret, config, hash, result))
  2000. def test_73_unidentified(self):
  2001. """test known unidentifiably-mangled strings"""
  2002. if not self.known_unidentified_hashes:
  2003. raise self.skipTest("no unidentified hashes provided")
  2004. for hash in self.known_unidentified_hashes:
  2005. # identify() should reject these
  2006. self.assertFalse(self.do_identify(hash),
  2007. "identify() incorrectly identified known unidentifiable "
  2008. "hash: %r" % (hash,))
  2009. # verify() should throw error
  2010. self.assertRaises(ValueError, self.do_verify, 'stub', hash,
  2011. __msg__= "verify() failed to throw error for unidentifiable "
  2012. "hash: %r" % (hash,))
  2013. # genhash() should throw error
  2014. self.assertRaises(ValueError, self.do_genhash, 'stub', hash,
  2015. __msg__= "genhash() failed to throw error for unidentifiable "
  2016. "hash: %r" % (hash,))
  2017. def test_74_malformed(self):
  2018. """test known identifiable-but-malformed strings"""
  2019. if not self.known_malformed_hashes:
  2020. raise self.skipTest("no malformed hashes provided")
  2021. for hash in self.known_malformed_hashes:
  2022. # identify() should accept these
  2023. self.assertTrue(self.do_identify(hash),
  2024. "identify() failed to identify known malformed "
  2025. "hash: %r" % (hash,))
  2026. # verify() should throw error
  2027. self.assertRaises(ValueError, self.do_verify, 'stub', hash,
  2028. __msg__= "verify() failed to throw error for malformed "
  2029. "hash: %r" % (hash,))
  2030. # genhash() should throw error
  2031. self.assertRaises(ValueError, self.do_genhash, 'stub', hash,
  2032. __msg__= "genhash() failed to throw error for malformed "
  2033. "hash: %r" % (hash,))
  2034. def test_75_foreign(self):
  2035. """test known foreign hashes"""
  2036. if self.accepts_all_hashes:
  2037. raise self.skipTest("not applicable")
  2038. if not self.known_other_hashes:
  2039. raise self.skipTest("no foreign hashes provided")
  2040. for name, hash in self.known_other_hashes:
  2041. # NOTE: most tests use default list of foreign hashes,
  2042. # so they may include ones belonging to that hash...
  2043. # hence the 'own' logic.
  2044. if name == self.handler.name:
  2045. # identify should accept these
  2046. self.assertTrue(self.do_identify(hash),
  2047. "identify() failed to identify known hash: %r" % (hash,))
  2048. # verify & genhash should NOT throw error
  2049. self.do_verify('stub', hash)
  2050. result = self.do_genhash('stub', hash)
  2051. self.assertIsInstance(result, str,
  2052. "genhash() failed to return native string: %r" % (result,))
  2053. else:
  2054. # identify should reject these
  2055. self.assertFalse(self.do_identify(hash),
  2056. "identify() incorrectly identified hash belonging to "
  2057. "%s: %r" % (name, hash))
  2058. # verify should throw error
  2059. self.assertRaises(ValueError, self.do_verify, 'stub', hash,
  2060. __msg__= "verify() failed to throw error for hash "
  2061. "belonging to %s: %r" % (name, hash,))
  2062. # genhash() should throw error
  2063. self.assertRaises(ValueError, self.do_genhash, 'stub', hash,
  2064. __msg__= "genhash() failed to throw error for hash "
  2065. "belonging to %s: %r" % (name, hash))
  2066. def test_76_hash_border(self):
  2067. """test non-string hashes are rejected"""
  2068. #
  2069. # test hash=None is handled correctly
  2070. #
  2071. self.assertRaises(TypeError, self.do_identify, None)
  2072. self.assertRaises(TypeError, self.do_verify, 'stub', None)
  2073. # NOTE: changed in 1.7 -- previously 'None' would be accepted when config strings not supported.
  2074. self.assertRaises(TypeError, self.do_genhash, 'stub', None)
  2075. #
  2076. # test hash=int is rejected (picked as example of entirely wrong type)
  2077. #
  2078. self.assertRaises(TypeError, self.do_identify, 1)
  2079. self.assertRaises(TypeError, self.do_verify, 'stub', 1)
  2080. self.assertRaises(TypeError, self.do_genhash, 'stub', 1)
  2081. #
  2082. # test hash='' is rejected for all but the plaintext hashes
  2083. #
  2084. for hash in [u(''), b'']:
  2085. if self.accepts_all_hashes:
  2086. # then it accepts empty string as well.
  2087. self.assertTrue(self.do_identify(hash))
  2088. self.do_verify('stub', hash)
  2089. result = self.do_genhash('stub', hash)
  2090. self.check_returned_native_str(result, "genhash")
  2091. else:
  2092. # otherwise it should reject them
  2093. self.assertFalse(self.do_identify(hash),
  2094. "identify() incorrectly identified empty hash")
  2095. self.assertRaises(ValueError, self.do_verify, 'stub', hash,
  2096. __msg__="verify() failed to reject empty hash")
  2097. self.assertRaises(ValueError, self.do_genhash, 'stub', hash,
  2098. __msg__="genhash() failed to reject empty hash")
  2099. #
  2100. # test identify doesn't throw decoding errors on 8-bit input
  2101. #
  2102. self.do_identify('\xe2\x82\xac\xc2\xa5$') # utf-8
  2103. self.do_identify('abc\x91\x00') # non-utf8
  2104. #===================================================================
  2105. # fuzz testing
  2106. #===================================================================
  2107. def test_77_fuzz_input(self, threaded=False):
  2108. """fuzz testing -- random passwords and options
  2109. This test attempts to perform some basic fuzz testing of the hash,
  2110. based on whatever information can be found about it.
  2111. It does as much as it can within a fixed amount of time
  2112. (defaults to 1 second, but can be overridden via $PASSLIB_TEST_FUZZ_TIME).
  2113. It tests the following:
  2114. * randomly generated passwords including extended unicode chars
  2115. * randomly selected rounds values (if rounds supported)
  2116. * randomly selected salt sizes (if salts supported)
  2117. * randomly selected identifiers (if multiple found)
  2118. * runs output of selected backend against other available backends
  2119. (if any) to detect errors occurring between different backends.
  2120. * runs output against other "external" verifiers such as OS crypt()
  2121. :param report_thread_state:
  2122. if true, writes state of loop to current_thread().passlib_fuzz_state.
  2123. used to help debug multi-threaded fuzz test issues (below)
  2124. """
  2125. if self.handler.is_disabled:
  2126. raise self.skipTest("not applicable")
  2127. # gather info
  2128. from passlib.utils import tick
  2129. max_time = self.max_fuzz_time
  2130. if max_time <= 0:
  2131. raise self.skipTest("disabled by test mode")
  2132. verifiers = self.get_fuzz_verifiers(threaded=threaded)
  2133. def vname(v):
  2134. return (v.__doc__ or v.__name__).splitlines()[0]
  2135. # init rng -- using separate one for each thread
  2136. # so things are predictable for given RANDOM_TEST_SEED
  2137. # (relies on test_78_fuzz_threading() to give threads unique names)
  2138. if threaded:
  2139. thread_name = threading.current_thread().name
  2140. else:
  2141. thread_name = "fuzz test"
  2142. rng = self.getRandom(name=thread_name)
  2143. generator = self.FuzzHashGenerator(self, rng)
  2144. # do as many tests as possible for max_time seconds
  2145. log.debug("%s: %s: started; max_time=%r verifiers=%d (%s)",
  2146. self.descriptionPrefix, thread_name, max_time, len(verifiers),
  2147. ", ".join(vname(v) for v in verifiers))
  2148. start = tick()
  2149. stop = start + max_time
  2150. count = 0
  2151. while tick() <= stop:
  2152. # generate random password & options
  2153. opts = generator.generate()
  2154. secret = opts['secret']
  2155. other = opts['other']
  2156. settings = opts['settings']
  2157. ctx = opts['context']
  2158. if ctx:
  2159. settings['context'] = ctx
  2160. # create new hash
  2161. hash = self.do_encrypt(secret, **settings)
  2162. ##log.debug("fuzz test: hash=%r secret=%r other=%r",
  2163. ## hash, secret, other)
  2164. # run through all verifiers we found.
  2165. for verify in verifiers:
  2166. name = vname(verify)
  2167. result = verify(secret, hash, **ctx)
  2168. if result == "skip": # let verifiers signal lack of support
  2169. continue
  2170. assert result is True or result is False
  2171. if not result:
  2172. raise self.failureException("failed to verify against %r verifier: "
  2173. "secret=%r config=%r hash=%r" %
  2174. (name, secret, settings, hash))
  2175. # occasionally check that some other secrets WON'T verify
  2176. # against this hash.
  2177. if rng.random() < .1:
  2178. result = verify(other, hash, **ctx)
  2179. if result and result != "skip":
  2180. raise self.failureException("was able to verify wrong "
  2181. "password using %s: wrong_secret=%r real_secret=%r "
  2182. "config=%r hash=%r" % (name, other, secret, settings, hash))
  2183. count += 1
  2184. log.debug("%s: %s: done; elapsed=%r count=%r",
  2185. self.descriptionPrefix, thread_name, tick() - start, count)
  2186. def test_78_fuzz_threading(self):
  2187. """multithreaded fuzz testing -- random password & options using multiple threads
  2188. run test_77 simultaneously in multiple threads
  2189. in an attempt to detect any concurrency issues
  2190. (e.g. the bug fixed by pybcrypt 0.3)
  2191. """
  2192. self.require_TEST_MODE("full")
  2193. import threading
  2194. # check if this test should run
  2195. if self.handler.is_disabled:
  2196. raise self.skipTest("not applicable")
  2197. thread_count = self.fuzz_thread_count
  2198. if thread_count < 1 or self.max_fuzz_time <= 0:
  2199. raise self.skipTest("disabled by test mode")
  2200. # buffer to hold errors thrown by threads
  2201. failed_lock = threading.Lock()
  2202. failed = [0]
  2203. # launch <thread count> threads, all of which run
  2204. # test_77_fuzz_input(), and see if any errors get thrown.
  2205. # if hash has concurrency issues, this should reveal it.
  2206. def wrapper():
  2207. try:
  2208. self.test_77_fuzz_input(threaded=True)
  2209. except SkipTest:
  2210. pass
  2211. except:
  2212. with failed_lock:
  2213. failed[0] += 1
  2214. raise
  2215. def launch(n):
  2216. name = "Fuzz-Thread-%d" % (n,)
  2217. thread = threading.Thread(target=wrapper, name=name)
  2218. thread.setDaemon(True)
  2219. thread.start()
  2220. return thread
  2221. threads = [launch(n) for n in irange(thread_count)]
  2222. # wait until all threads exit
  2223. timeout = self.max_fuzz_time * thread_count * 4
  2224. stalled = 0
  2225. for thread in threads:
  2226. thread.join(timeout)
  2227. if not thread.is_alive():
  2228. continue
  2229. # XXX: not sure why this is happening, main one seems 1/4 times for sun_md5_crypt
  2230. log.error("%s timed out after %f seconds", thread.name, timeout)
  2231. stalled += 1
  2232. # if any thread threw an error, raise one ourselves.
  2233. if failed[0]:
  2234. raise self.fail("%d/%d threads failed concurrent fuzz testing "
  2235. "(see error log for details)" % (failed[0], thread_count))
  2236. if stalled:
  2237. raise self.fail("%d/%d threads stalled during concurrent fuzz testing "
  2238. "(see error log for details)" % (stalled, thread_count))
  2239. #---------------------------------------------------------------
  2240. # fuzz constants & helpers
  2241. #---------------------------------------------------------------
  2242. @property
  2243. def max_fuzz_time(self):
  2244. """amount of time to spend on fuzz testing"""
  2245. value = float(os.environ.get("PASSLIB_TEST_FUZZ_TIME") or 0)
  2246. if value:
  2247. return value
  2248. elif TEST_MODE(max="quick"):
  2249. return 0
  2250. elif TEST_MODE(max="default"):
  2251. return 1
  2252. else:
  2253. return 5
  2254. @property
  2255. def fuzz_thread_count(self):
  2256. """number of threads for threaded fuzz testing"""
  2257. value = int(os.environ.get("PASSLIB_TEST_FUZZ_THREADS") or 0)
  2258. if value:
  2259. return value
  2260. elif TEST_MODE(max="quick"):
  2261. return 0
  2262. else:
  2263. return 10
  2264. #---------------------------------------------------------------
  2265. # fuzz verifiers
  2266. #---------------------------------------------------------------
  2267. #: list of custom fuzz-test verifiers (in addition to hasher itself,
  2268. #: and backend-specific wrappers of hasher). each element is
  2269. #: name of method that will return None / a verifier callable.
  2270. fuzz_verifiers = ("fuzz_verifier_default",)
  2271. def get_fuzz_verifiers(self, threaded=False):
  2272. """return list of password verifiers (including external libs)
  2273. used by fuzz testing.
  2274. verifiers should be callable with signature
  2275. ``func(password: unicode, hash: ascii str) -> ok: bool``.
  2276. """
  2277. handler = self.handler
  2278. verifiers = []
  2279. # call all methods starting with prefix in order to create
  2280. for method_name in self.fuzz_verifiers:
  2281. func = getattr(self, method_name)()
  2282. if func is not None:
  2283. verifiers.append(func)
  2284. # create verifiers for any other available backends
  2285. # NOTE: skipping this under threading test,
  2286. # since backend switching isn't threadsafe (yet)
  2287. if hasattr(handler, "backends") and TEST_MODE("full") and not threaded:
  2288. def maker(backend):
  2289. def func(secret, hash):
  2290. orig_backend = handler.get_backend()
  2291. try:
  2292. handler.set_backend(backend)
  2293. return handler.verify(secret, hash)
  2294. finally:
  2295. handler.set_backend(orig_backend)
  2296. func.__name__ = "check_" + backend + "_backend"
  2297. func.__doc__ = backend + "-backend"
  2298. return func
  2299. for backend in iter_alt_backends(handler):
  2300. verifiers.append(maker(backend))
  2301. return verifiers
  2302. def fuzz_verifier_default(self):
  2303. # test against self
  2304. def check_default(secret, hash, **ctx):
  2305. return self.do_verify(secret, hash, **ctx)
  2306. if self.backend:
  2307. check_default.__doc__ = self.backend + "-backend"
  2308. else:
  2309. check_default.__doc__ = "self"
  2310. return check_default
  2311. #---------------------------------------------------------------
  2312. # fuzz settings generation
  2313. #---------------------------------------------------------------
  2314. class FuzzHashGenerator(object):
  2315. """
  2316. helper which takes care of generating random
  2317. passwords & configuration options to test hash with.
  2318. separate from test class so we can create one per thread.
  2319. """
  2320. #==========================================================
  2321. # class attrs
  2322. #==========================================================
  2323. # alphabet for randomly generated passwords
  2324. password_alphabet = u('qwertyASDF1234<>.@*#! \u00E1\u0259\u0411\u2113')
  2325. # encoding when testing bytes
  2326. password_encoding = "utf-8"
  2327. # map of setting kwd -> method name.
  2328. # will ignore setting if method returns None.
  2329. # subclasses should make copy of dict.
  2330. settings_map = dict(rounds="random_rounds",
  2331. salt_size="random_salt_size",
  2332. ident="random_ident")
  2333. # map of context kwd -> method name.
  2334. context_map = {}
  2335. #==========================================================
  2336. # init / generation
  2337. #==========================================================
  2338. def __init__(self, test, rng):
  2339. self.test = test
  2340. self.handler = test.handler
  2341. self.rng = rng
  2342. def generate(self):
  2343. """
  2344. generate random password and options for fuzz testing.
  2345. :returns:
  2346. `(secret, other_secret, settings_kwds, context_kwds)`
  2347. """
  2348. def gendict(map):
  2349. out = {}
  2350. for key, meth in map.items():
  2351. func = getattr(self, meth)
  2352. value = getattr(self, meth)()
  2353. if value is not None:
  2354. out[key] = value
  2355. return out
  2356. secret, other = self.random_password_pair()
  2357. return dict(secret=secret,
  2358. other=other,
  2359. settings=gendict(self.settings_map),
  2360. context=gendict(self.context_map),
  2361. )
  2362. #==========================================================
  2363. # helpers
  2364. #==========================================================
  2365. def randintgauss(self, lower, upper, mu, sigma):
  2366. """generate random int w/ gauss distirbution"""
  2367. value = self.rng.normalvariate(mu, sigma)
  2368. return int(limit(value, lower, upper))
  2369. #==========================================================
  2370. # settings generation
  2371. #==========================================================
  2372. def random_rounds(self):
  2373. handler = self.handler
  2374. if not has_rounds_info(handler):
  2375. return None
  2376. default = handler.default_rounds or handler.min_rounds
  2377. lower = handler.min_rounds
  2378. if handler.rounds_cost == "log2":
  2379. upper = default
  2380. else:
  2381. upper = min(default*2, handler.max_rounds)
  2382. return self.randintgauss(lower, upper, default, default*.5)
  2383. def random_salt_size(self):
  2384. handler = self.handler
  2385. if not (has_salt_info(handler) and 'salt_size' in handler.setting_kwds):
  2386. return None
  2387. default = handler.default_salt_size
  2388. lower = handler.min_salt_size
  2389. upper = handler.max_salt_size or default*4
  2390. return self.randintgauss(lower, upper, default, default*.5)
  2391. def random_ident(self):
  2392. rng = self.rng
  2393. handler = self.handler
  2394. if 'ident' not in handler.setting_kwds or not hasattr(handler, "ident_values"):
  2395. return None
  2396. if rng.random() < .5:
  2397. return None
  2398. # resolve wrappers before reading values
  2399. handler = getattr(handler, "wrapped", handler)
  2400. return rng.choice(handler.ident_values)
  2401. #==========================================================
  2402. # fuzz password generation
  2403. #==========================================================
  2404. def random_password_pair(self):
  2405. """generate random password, and non-matching alternate password"""
  2406. secret = self.random_password()
  2407. while True:
  2408. other = self.random_password()
  2409. if self.accept_password_pair(secret, other):
  2410. break
  2411. rng = self.rng
  2412. if rng.randint(0,1):
  2413. secret = secret.encode(self.password_encoding)
  2414. if rng.randint(0,1):
  2415. other = other.encode(self.password_encoding)
  2416. return secret, other
  2417. def random_password(self):
  2418. """generate random passwords for fuzz testing"""
  2419. # occasionally try an empty password
  2420. rng = self.rng
  2421. if rng.random() < .0001:
  2422. return u('')
  2423. # check if truncate size needs to be considered
  2424. handler = self.handler
  2425. truncate_size = handler.truncate_error and handler.truncate_size
  2426. max_size = truncate_size or 999999
  2427. # pick endpoint
  2428. if max_size < 50 or rng.random() < .5:
  2429. # chance of small password (~15 chars)
  2430. size = self.randintgauss(1, min(max_size, 50), 15, 15)
  2431. else:
  2432. # otherwise large password (~70 chars)
  2433. size = self.randintgauss(50, min(max_size, 99), 70, 20)
  2434. # generate random password
  2435. result = getrandstr(rng, self.password_alphabet, size)
  2436. # trim ones that encode past truncate point.
  2437. if truncate_size and isinstance(result, unicode):
  2438. while len(result.encode("utf-8")) > truncate_size:
  2439. result = result[:-1]
  2440. return result
  2441. def accept_password_pair(self, secret, other):
  2442. """verify fuzz pair contains different passwords"""
  2443. return secret != other
  2444. #==========================================================
  2445. # eoc FuzzGenerator
  2446. #==========================================================
  2447. #===================================================================
  2448. # "disabled hasher" api
  2449. #===================================================================
  2450. def test_disable_and_enable(self):
  2451. """.disable() / .enable() methods"""
  2452. #
  2453. # setup
  2454. #
  2455. handler = self.handler
  2456. if not handler.is_disabled:
  2457. self.assertFalse(hasattr(handler, "disable"))
  2458. self.assertFalse(hasattr(handler, "enable"))
  2459. self.assertFalse(self.disabled_contains_salt)
  2460. raise self.skipTest("not applicable")
  2461. #
  2462. # disable()
  2463. #
  2464. # w/o existing hash
  2465. disabled_default = handler.disable()
  2466. self.assertIsInstance(disabled_default, str,
  2467. msg="disable() must return native string")
  2468. self.assertTrue(handler.identify(disabled_default),
  2469. msg="identify() didn't recognize disable() result: %r" % (disabled_default))
  2470. # w/ existing hash
  2471. stub = self.getRandom().choice(self.known_other_hashes)[1]
  2472. disabled_stub = handler.disable(stub)
  2473. self.assertIsInstance(disabled_stub, str,
  2474. msg="disable() must return native string")
  2475. self.assertTrue(handler.identify(disabled_stub),
  2476. msg="identify() didn't recognize disable() result: %r" % (disabled_stub))
  2477. #
  2478. # enable()
  2479. #
  2480. # w/o original hash
  2481. self.assertRaisesRegex(ValueError, "cannot restore original hash",
  2482. handler.enable, disabled_default)
  2483. # w/ original hash
  2484. try:
  2485. result = handler.enable(disabled_stub)
  2486. error = None
  2487. except ValueError as e:
  2488. result = None
  2489. error = e
  2490. if error is None:
  2491. # if supports recovery, should have returned stub (e.g. unix_disabled);
  2492. self.assertIsInstance(result, str,
  2493. msg="enable() must return native string")
  2494. self.assertEqual(result, stub)
  2495. else:
  2496. # if doesn't, should have thrown appropriate error
  2497. self.assertIsInstance(error, ValueError)
  2498. self.assertRegex("cannot restore original hash", str(error))
  2499. #
  2500. # test repeating disable() & salting state
  2501. #
  2502. # repeating disabled
  2503. disabled_default2 = handler.disable()
  2504. if self.disabled_contains_salt:
  2505. # should return new salt for each call (e.g. django_disabled)
  2506. self.assertNotEqual(disabled_default2, disabled_default)
  2507. elif error is None:
  2508. # should return same result for each hash, but unique across hashes
  2509. self.assertEqual(disabled_default2, disabled_default)
  2510. # repeating same hash ...
  2511. disabled_stub2 = handler.disable(stub)
  2512. if self.disabled_contains_salt:
  2513. # ... should return different string (if salted)
  2514. self.assertNotEqual(disabled_stub2, disabled_stub)
  2515. else:
  2516. # ... should return same string
  2517. self.assertEqual(disabled_stub2, disabled_stub)
  2518. # using different hash ...
  2519. disabled_other = handler.disable(stub + 'xxx')
  2520. if self.disabled_contains_salt or error is None:
  2521. # ... should return different string (if salted or hash encoded)
  2522. self.assertNotEqual(disabled_other, disabled_stub)
  2523. else:
  2524. # ... should return same string
  2525. self.assertEqual(disabled_other, disabled_stub)
  2526. #===================================================================
  2527. # eoc
  2528. #===================================================================
  2529. #=============================================================================
  2530. # HandlerCase mixins providing additional tests for certain hashes
  2531. #=============================================================================
  2532. class OsCryptMixin(HandlerCase):
  2533. """helper used by create_backend_case() which adds additional features
  2534. to test the os_crypt backend.
  2535. * if crypt support is missing, inserts fake crypt support to simulate
  2536. a working safe_crypt, to test passlib's codepath as fully as possible.
  2537. * extra tests to verify non-conformant crypt implementations are handled
  2538. correctly.
  2539. * check that native crypt support is detected correctly for known platforms.
  2540. """
  2541. #===================================================================
  2542. # class attrs
  2543. #===================================================================
  2544. # platforms that are known to support / not support this hash natively.
  2545. # list of (platform_regex, True|False|None) entries.
  2546. platform_crypt_support = []
  2547. #: flag indicating backend provides a fallback when safe_crypt() can't handle password
  2548. has_os_crypt_fallback = True
  2549. #: alternate handler to use when searching for backend to fake safe_crypt() support.
  2550. alt_safe_crypt_handler = None
  2551. #===================================================================
  2552. # instance attrs
  2553. #===================================================================
  2554. __unittest_skip = True
  2555. # force this backend
  2556. backend = "os_crypt"
  2557. # flag read by HandlerCase to detect if fake os crypt is enabled.
  2558. using_patched_crypt = False
  2559. #===================================================================
  2560. # setup
  2561. #===================================================================
  2562. def setUp(self):
  2563. assert self.backend == "os_crypt"
  2564. if not self.handler.has_backend("os_crypt"):
  2565. self._patch_safe_crypt()
  2566. super(OsCryptMixin, self).setUp()
  2567. @classmethod
  2568. def _get_safe_crypt_handler_backend(cls):
  2569. """
  2570. return (handler, backend) pair to use for faking crypt.crypt() support for hash.
  2571. backend will be None if none availabe.
  2572. """
  2573. # find handler that generates safe_crypt() compatible hash
  2574. handler = cls.alt_safe_crypt_handler
  2575. if not handler:
  2576. handler = unwrap_handler(cls.handler)
  2577. # hack to prevent recursion issue when .has_backend() is called
  2578. handler.get_backend()
  2579. # find backend which isn't os_crypt
  2580. alt_backend = get_alt_backend(handler, "os_crypt")
  2581. return handler, alt_backend
  2582. def _patch_safe_crypt(self):
  2583. """if crypt() doesn't support current hash alg, this patches
  2584. safe_crypt() so that it transparently uses another one of the handler's
  2585. backends, so that we can go ahead and test as much of code path
  2586. as possible.
  2587. """
  2588. # find handler & backend
  2589. handler, alt_backend = self._get_safe_crypt_handler_backend()
  2590. if not alt_backend:
  2591. raise AssertionError("handler has no available alternate backends!")
  2592. # create subclass of handler, which we swap to an alternate backend
  2593. alt_handler = handler.using()
  2594. alt_handler.set_backend(alt_backend)
  2595. def crypt_stub(secret, hash):
  2596. hash = alt_handler.genhash(secret, hash)
  2597. assert isinstance(hash, str)
  2598. return hash
  2599. import passlib.utils as mod
  2600. self.patchAttr(mod, "_crypt", crypt_stub)
  2601. self.using_patched_crypt = True
  2602. @classmethod
  2603. def _get_skip_backend_reason(cls, backend):
  2604. """
  2605. make sure os_crypt backend is tested
  2606. when it's known os_crypt will be faked by _patch_safe_crypt()
  2607. """
  2608. assert backend == "os_crypt"
  2609. reason = super(OsCryptMixin, cls)._get_skip_backend_reason(backend)
  2610. from passlib.utils import has_crypt
  2611. if reason == cls.BACKEND_NOT_AVAILABLE and has_crypt:
  2612. if TEST_MODE("full") and cls._get_safe_crypt_handler_backend()[1]:
  2613. # in this case, _patch_safe_crypt() will monkeypatch os_crypt
  2614. # to use another backend, just so we can test os_crypt fully.
  2615. return None
  2616. else:
  2617. return "hash not supported by os crypt()"
  2618. return reason
  2619. #===================================================================
  2620. # custom tests
  2621. #===================================================================
  2622. # TODO: turn into decorator, and use mock library.
  2623. def _use_mock_crypt(self):
  2624. """
  2625. patch passlib.utils.safe_crypt() so it returns mock value for duration of test.
  2626. returns function whose .return_value controls what's returned.
  2627. this defaults to None.
  2628. """
  2629. import passlib.utils as mod
  2630. def mock_crypt(secret, config):
  2631. # let 'test' string through so _load_os_crypt_backend() will still work
  2632. if secret == "test":
  2633. return mock_crypt.__wrapped__(secret, config)
  2634. else:
  2635. return mock_crypt.return_value
  2636. mock_crypt.__wrapped__ = mod._crypt
  2637. mock_crypt.return_value = None
  2638. self.patchAttr(mod, "_crypt", mock_crypt)
  2639. return mock_crypt
  2640. def test_80_faulty_crypt(self):
  2641. """test with faulty crypt()"""
  2642. hash = self.get_sample_hash()[1]
  2643. exc_types = (AssertionError,)
  2644. mock_crypt = self._use_mock_crypt()
  2645. def test(value):
  2646. # set safe_crypt() to return specified value, and
  2647. # make sure assertion error is raised by handler.
  2648. mock_crypt.return_value = value
  2649. self.assertRaises(exc_types, self.do_genhash, "stub", hash)
  2650. self.assertRaises(exc_types, self.do_encrypt, "stub")
  2651. self.assertRaises(exc_types, self.do_verify, "stub", hash)
  2652. test('$x' + hash[2:]) # detect wrong prefix
  2653. test(hash[:-1]) # detect too short
  2654. test(hash + 'x') # detect too long
  2655. def test_81_crypt_fallback(self):
  2656. """test per-call crypt() fallback"""
  2657. # mock up safe_crypt to return None
  2658. mock_crypt = self._use_mock_crypt()
  2659. mock_crypt.return_value = None
  2660. if self.has_os_crypt_fallback:
  2661. # handler should have a fallback to use when os_crypt backend refuses to handle secret.
  2662. h1 = self.do_encrypt("stub")
  2663. h2 = self.do_genhash("stub", h1)
  2664. self.assertEqual(h2, h1)
  2665. self.assertTrue(self.do_verify("stub", h1))
  2666. else:
  2667. # handler should give up
  2668. from passlib.exc import MissingBackendError
  2669. hash = self.get_sample_hash()[1]
  2670. self.assertRaises(MissingBackendError, self.do_encrypt, 'stub')
  2671. self.assertRaises(MissingBackendError, self.do_genhash, 'stub', hash)
  2672. self.assertRaises(MissingBackendError, self.do_verify, 'stub', hash)
  2673. def test_82_crypt_support(self):
  2674. """test platform-specific crypt() support detection"""
  2675. # NOTE: this is mainly just a sanity check to ensure the runtime
  2676. # detection is functioning correctly on some known platforms,
  2677. # so that I can feel more confident it'll work right on unknown ones.
  2678. if hasattr(self.handler, "orig_prefix"):
  2679. raise self.skipTest("not applicable to wrappers")
  2680. platform = sys.platform
  2681. for pattern, state in self.platform_crypt_support:
  2682. if re.match(pattern, platform):
  2683. break
  2684. else:
  2685. raise self.skipTest("no data for %r platform" % platform)
  2686. if state is None:
  2687. # e.g. platform='freebsd8' ... sha256_crypt not added until 8.3
  2688. raise self.skipTest("varied support on %r platform" % platform)
  2689. elif state != self.using_patched_crypt:
  2690. return
  2691. elif state:
  2692. self.fail("expected %r platform would have native support "
  2693. "for %r" % (platform, self.handler.name))
  2694. else:
  2695. self.fail("did not expect %r platform would have native support "
  2696. "for %r" % (platform, self.handler.name))
  2697. #===================================================================
  2698. # fuzzy verified support -- add new verified that uses os crypt()
  2699. #===================================================================
  2700. def fuzz_verifier_crypt(self):
  2701. """test results against OS crypt()"""
  2702. # don't use this if we're faking safe_crypt (pointless test),
  2703. # or if handler is a wrapper (only original handler will be supported by os)
  2704. handler = self.handler
  2705. if self.using_patched_crypt or hasattr(handler, "wrapped"):
  2706. return None
  2707. # create a wrapper for fuzzy verified to use
  2708. from crypt import crypt
  2709. encoding = self.FuzzHashGenerator.password_encoding
  2710. def check_crypt(secret, hash):
  2711. """stdlib-crypt"""
  2712. if not self.crypt_supports_variant(hash):
  2713. return "skip"
  2714. secret = to_native_str(secret, encoding)
  2715. return crypt(secret, hash) == hash
  2716. return check_crypt
  2717. def crypt_supports_variant(self, hash):
  2718. """
  2719. fuzzy_verified_crypt() helper --
  2720. used to determine if os crypt() supports a particular hash variant.
  2721. """
  2722. return True
  2723. #===================================================================
  2724. # eoc
  2725. #===================================================================
  2726. class UserHandlerMixin(HandlerCase):
  2727. """helper for handlers w/ 'user' context kwd; mixin for HandlerCase
  2728. this overrides the HandlerCase test harness methods
  2729. so that a username is automatically inserted to hash/verify
  2730. calls. as well, passing in a pair of strings as the password
  2731. will be interpreted as (secret,user)
  2732. """
  2733. #===================================================================
  2734. # option flags
  2735. #===================================================================
  2736. default_user = "user"
  2737. requires_user = True
  2738. user_case_insensitive = False
  2739. #===================================================================
  2740. # instance attrs
  2741. #===================================================================
  2742. __unittest_skip = True
  2743. #===================================================================
  2744. # custom tests
  2745. #===================================================================
  2746. def test_80_user(self):
  2747. """test user context keyword"""
  2748. handler = self.handler
  2749. password = 'stub'
  2750. hash = handler.hash(password, user=self.default_user)
  2751. if self.requires_user:
  2752. self.assertRaises(TypeError, handler.hash, password)
  2753. self.assertRaises(TypeError, handler.genhash, password, hash)
  2754. self.assertRaises(TypeError, handler.verify, password, hash)
  2755. else:
  2756. # e.g. cisco_pix works with or without one.
  2757. handler.hash(password)
  2758. handler.genhash(password, hash)
  2759. handler.verify(password, hash)
  2760. def test_81_user_case(self):
  2761. """test user case sensitivity"""
  2762. lower = self.default_user.lower()
  2763. upper = lower.upper()
  2764. hash = self.do_encrypt('stub', context=dict(user=lower))
  2765. if self.user_case_insensitive:
  2766. self.assertTrue(self.do_verify('stub', hash, user=upper),
  2767. "user should not be case sensitive")
  2768. else:
  2769. self.assertFalse(self.do_verify('stub', hash, user=upper),
  2770. "user should be case sensitive")
  2771. def test_82_user_salt(self):
  2772. """test user used as salt"""
  2773. config = self.do_stub_encrypt()
  2774. h1 = self.do_genhash('stub', config, user='admin')
  2775. h2 = self.do_genhash('stub', config, user='admin')
  2776. self.assertEqual(h2, h1)
  2777. h3 = self.do_genhash('stub', config, user='root')
  2778. self.assertNotEqual(h3, h1)
  2779. # TODO: user size? kinda dicey, depends on algorithm.
  2780. #===================================================================
  2781. # override test helpers
  2782. #===================================================================
  2783. def populate_context(self, secret, kwds):
  2784. """insert username into kwds"""
  2785. if isinstance(secret, tuple):
  2786. secret, user = secret
  2787. elif not self.requires_user:
  2788. return secret
  2789. else:
  2790. user = self.default_user
  2791. if 'user' not in kwds:
  2792. kwds['user'] = user
  2793. return secret
  2794. #===================================================================
  2795. # modify fuzz testing
  2796. #===================================================================
  2797. class FuzzHashGenerator(HandlerCase.FuzzHashGenerator):
  2798. context_map = HandlerCase.FuzzHashGenerator.context_map.copy()
  2799. context_map.update(user="random_user")
  2800. user_alphabet = u("asdQWE123")
  2801. def random_user(self):
  2802. rng = self.rng
  2803. if not self.test.requires_user and rng.random() < .1:
  2804. return None
  2805. return getrandstr(rng, self.user_alphabet, rng.randint(2,10))
  2806. #===================================================================
  2807. # eoc
  2808. #===================================================================
  2809. class EncodingHandlerMixin(HandlerCase):
  2810. """helper for handlers w/ 'encoding' context kwd; mixin for HandlerCase
  2811. this overrides the HandlerCase test harness methods
  2812. so that an encoding can be inserted to hash/verify
  2813. calls by passing in a pair of strings as the password
  2814. will be interpreted as (secret,encoding)
  2815. """
  2816. #===================================================================
  2817. # instance attrs
  2818. #===================================================================
  2819. __unittest_skip = True
  2820. # restrict stock passwords & fuzz alphabet to latin-1,
  2821. # so different encodings can be tested safely.
  2822. stock_passwords = [
  2823. u("test"),
  2824. b"test",
  2825. u("\u00AC\u00BA"),
  2826. ]
  2827. class FuzzHashGenerator(HandlerCase.FuzzHashGenerator):
  2828. password_alphabet = u('qwerty1234<>.@*#! \u00AC')
  2829. def populate_context(self, secret, kwds):
  2830. """insert encoding into kwds"""
  2831. if isinstance(secret, tuple):
  2832. secret, encoding = secret
  2833. kwds.setdefault('encoding', encoding)
  2834. return secret
  2835. #===================================================================
  2836. # eoc
  2837. #===================================================================
  2838. #=============================================================================
  2839. # warnings helpers
  2840. #=============================================================================
  2841. class reset_warnings(warnings.catch_warnings):
  2842. """catch_warnings() wrapper which clears warning registry & filters"""
  2843. def __init__(self, reset_filter="always", reset_registry=".*", **kwds):
  2844. super(reset_warnings, self).__init__(**kwds)
  2845. self._reset_filter = reset_filter
  2846. self._reset_registry = re.compile(reset_registry) if reset_registry else None
  2847. def __enter__(self):
  2848. # let parent class archive filter state
  2849. ret = super(reset_warnings, self).__enter__()
  2850. # reset the filter to list everything
  2851. if self._reset_filter:
  2852. warnings.resetwarnings()
  2853. warnings.simplefilter(self._reset_filter)
  2854. # archive and clear the __warningregistry__ key for all modules
  2855. # that match the 'reset' pattern.
  2856. pattern = self._reset_registry
  2857. if pattern:
  2858. backup = self._orig_registry = {}
  2859. for name, mod in list(sys.modules.items()):
  2860. if mod is None or not pattern.match(name):
  2861. continue
  2862. reg = getattr(mod, "__warningregistry__", None)
  2863. if reg:
  2864. backup[name] = reg.copy()
  2865. reg.clear()
  2866. return ret
  2867. def __exit__(self, *exc_info):
  2868. # restore warning registry for all modules
  2869. pattern = self._reset_registry
  2870. if pattern:
  2871. # restore registry backup, clearing all registry entries that we didn't archive
  2872. backup = self._orig_registry
  2873. for name, mod in list(sys.modules.items()):
  2874. if mod is None or not pattern.match(name):
  2875. continue
  2876. reg = getattr(mod, "__warningregistry__", None)
  2877. if reg:
  2878. reg.clear()
  2879. orig = backup.get(name)
  2880. if orig:
  2881. if reg is None:
  2882. setattr(mod, "__warningregistry__", orig)
  2883. else:
  2884. reg.update(orig)
  2885. super(reset_warnings, self).__exit__(*exc_info)
  2886. #=============================================================================
  2887. # eof
  2888. #=============================================================================