Exemple #1
0
 def test_52_log2_vary_rounds(self):
     cc = CryptContext(schemes=['bcrypt'], bcrypt__min_rounds=15, bcrypt__max_rounds=25, bcrypt__default_rounds=20)
     self.assertRaises(ValueError, cc.copy, all__vary_rounds=-1)
     self.assertRaises(ValueError, cc.copy, all__vary_rounds='-1%')
     self.assertRaises(ValueError, cc.copy, all__vary_rounds='101%')
     c2 = cc.copy(all__vary_rounds=0)
     self.assertEqual(c2._get_record('bcrypt', None).vary_rounds, 0)
     self.assert_rounds_range(c2, 'bcrypt', 20, 20)
     c2 = cc.copy(all__vary_rounds='0%')
     self.assertEqual(c2._get_record('bcrypt', None).vary_rounds, 0)
     self.assert_rounds_range(c2, 'bcrypt', 20, 20)
     c2 = cc.copy(all__vary_rounds=1)
     self.assertEqual(c2._get_record('bcrypt', None).vary_rounds, 1)
     self.assert_rounds_range(c2, 'bcrypt', 19, 21)
     c2 = cc.copy(all__vary_rounds=100)
     self.assertEqual(c2._get_record('bcrypt', None).vary_rounds, 100)
     self.assert_rounds_range(c2, 'bcrypt', 15, 25)
     c2 = cc.copy(all__vary_rounds='1%')
     self.assertEqual(c2._get_record('bcrypt', None).vary_rounds, 0.01)
     self.assert_rounds_range(c2, 'bcrypt', 20, 20)
     c2 = cc.copy(all__vary_rounds='49%')
     self.assertEqual(c2._get_record('bcrypt', None).vary_rounds, 0.49)
     self.assert_rounds_range(c2, 'bcrypt', 20, 20)
     c2 = cc.copy(all__vary_rounds='50%')
     self.assertEqual(c2._get_record('bcrypt', None).vary_rounds, 0.5)
     self.assert_rounds_range(c2, 'bcrypt', 19, 20)
     c2 = cc.copy(all__vary_rounds='100%')
     self.assertEqual(c2._get_record('bcrypt', None).vary_rounds, 1.0)
     self.assert_rounds_range(c2, 'bcrypt', 15, 21)
     return
Exemple #2
0
    def test_20_options(self):

        def parse(**kwds):
            return CryptContext(**kwds).to_dict()

        self.assertRaises(TypeError, CryptContext, __=0.1)
        self.assertRaises(TypeError, CryptContext, default__scheme__='x')
        self.assertRaises(TypeError, CryptContext, __option='x')
        self.assertRaises(TypeError, CryptContext, default____option='x')
        self.assertRaises(TypeError, CryptContext, __scheme__option='x')
        self.assertRaises(TypeError, CryptContext, category__scheme__option__invalid=30000)
        self.assertRaises(KeyError, parse, **{'admin.context__schemes': 'md5_crypt'})
        ctx = CryptContext(**{'schemes': 'md5_crypt,des_crypt', 'admin.context__default': 'des_crypt'})
        self.assertEqual(ctx.default_scheme('admin'), 'des_crypt')
        result = dict(default='md5_crypt')
        self.assertEqual(parse(default='md5_crypt'), result)
        self.assertEqual(parse(context__default='md5_crypt'), result)
        self.assertEqual(parse(default__context__default='md5_crypt'), result)
        self.assertEqual(parse(**{'context.default': 'md5_crypt'}), result)
        self.assertEqual(parse(**{'default.context.default': 'md5_crypt'}), result)
        result = dict(admin__context__default='md5_crypt')
        self.assertEqual(parse(admin__context__default='md5_crypt'), result)
        self.assertEqual(parse(**{'admin.context.default': 'md5_crypt'}), result)
        result = dict(all__vary_rounds=0.1)
        self.assertEqual(parse(all__vary_rounds=0.1), result)
        self.assertEqual(parse(default__all__vary_rounds=0.1), result)
        self.assertEqual(parse(**{'all.vary_rounds': 0.1}), result)
        self.assertEqual(parse(**{'default.all.vary_rounds': 0.1}), result)
        result = dict(admin__all__vary_rounds=0.1)
        self.assertEqual(parse(admin__all__vary_rounds=0.1), result)
        self.assertEqual(parse(**{'admin.all.vary_rounds': 0.1}), result)
        ctx = CryptContext(['phpass', 'md5_crypt'], phpass__ident='P')
        self.assertRaises(KeyError, ctx.copy, md5_crypt__ident='P')
        self.assertRaises(KeyError, CryptContext, schemes=['des_crypt'], des_crypt__salt='xx')
        self.assertRaises(KeyError, CryptContext, schemes=['des_crypt'], all__salt='xx')
Exemple #3
0
 def test_harden_verify_parsing(self):
     warnings.filterwarnings('ignore', '.*harden_verify.*', category=DeprecationWarning)
     ctx = CryptContext(schemes=['sha256_crypt'])
     self.assertEqual(ctx.harden_verify, None)
     self.assertEqual(ctx.using(harden_verify='').harden_verify, None)
     self.assertEqual(ctx.using(harden_verify='true').harden_verify, None)
     self.assertEqual(ctx.using(harden_verify='false').harden_verify, None)
     return
Exemple #4
0
 def test_01_replace(self):
     cc = CryptContext(['md5_crypt', 'bsdi_crypt', 'des_crypt'])
     self.assertIs(cc.policy.get_handler(), hash.md5_crypt)
     cc2 = cc.replace()
     self.assertIsNot(cc2, cc)
     cc3 = cc.replace(default='bsdi_crypt')
     self.assertIsNot(cc3, cc)
     self.assertIs(cc3.policy.get_handler(), hash.bsdi_crypt)
Exemple #5
0
 def test_dummy_verify(self):
     expected = 0.05
     accuracy = 0.2
     handler = DelayHash.using()
     handler.delay = expected
     ctx = CryptContext(schemes=[handler])
     ctx.dummy_verify()
     elapsed, _ = time_call(ctx.dummy_verify)
     self.assertAlmostEqual(elapsed, expected, delta=expected * accuracy)
Exemple #6
0
 def test_03_from_path(self):
     if not os.path.exists(self.sample_1_path):
         raise RuntimeError("can't find data file: %r" % self.sample_1_path)
     ctx = CryptContext.from_path(self.sample_1_path)
     self.assertEqual(ctx.to_dict(), self.sample_1_dict)
     ctx = CryptContext.from_path(self.sample_1b_path)
     self.assertEqual(ctx.to_dict(), self.sample_1_dict)
     ctx = CryptContext.from_path(self.sample_1c_path, section='mypolicy', encoding='utf-16')
     self.assertEqual(ctx.to_dict(), self.sample_1_dict)
     self.assertRaises(EnvironmentError, CryptContext.from_path, os.path.join(here, 'sample1xxx.cfg'))
     self.assertRaises(NoSectionError, CryptContext.from_path, self.sample_1_path, section='fakesection')
Exemple #7
0
 def test_02_no_handlers(self):
     cc = CryptContext()
     self.assertRaises(KeyError, cc.identify, 'hash', required=True)
     self.assertRaises(KeyError, cc.hash, 'secret')
     self.assertRaises(KeyError, cc.verify, 'secret', 'hash')
     cc = CryptContext(['md5_crypt'])
     p = CryptPolicy(schemes=[])
     cc.policy = p
     self.assertRaises(KeyError, cc.identify, 'hash', required=True)
     self.assertRaises(KeyError, cc.hash, 'secret')
     self.assertRaises(KeyError, cc.verify, 'secret', 'hash')
Exemple #8
0
    def test_30_nonstring_hash(self):
        warnings.filterwarnings(
            'ignore', ".*needs_update.*'scheme' keyword is deprecated.*")
        cc = CryptContext(['des_crypt'])
        for hash, kwds in [(None, {}), (None, {
                'scheme': 'des_crypt'
        }), (1, {}), ((), {})]:
            self.assertRaises(TypeError, cc.hash_needs_update, hash, **kwds)

        cc2 = CryptContext(['mysql323'])
        self.assertRaises(TypeError, cc2.hash_needs_update, None)
        return
Exemple #9
0
 def test_02_from_string(self):
     ctx = CryptContext.from_string(self.sample_1_unicode)
     self.assertEqual(ctx.to_dict(), self.sample_1_dict)
     ctx = CryptContext.from_string(self.sample_1_unnormalized)
     self.assertEqual(ctx.to_dict(), self.sample_1_dict)
     ctx = CryptContext.from_string(self.sample_1_unicode.encode('utf-8'))
     self.assertEqual(ctx.to_dict(), self.sample_1_dict)
     ctx = CryptContext.from_string(self.sample_1b_unicode)
     self.assertEqual(ctx.to_dict(), self.sample_1_dict)
     ctx = CryptContext.from_string(self.sample_1c_bytes, section='mypolicy', encoding='utf-16')
     self.assertEqual(ctx.to_dict(), self.sample_1_dict)
     self.assertRaises(TypeError, CryptContext.from_string, None)
     self.assertRaises(NoSectionError, CryptContext.from_string, self.sample_1_unicode, section='fakesection')
     return
Exemple #10
0
 def test_13_config_defaults(self):
     from otp.ai.passlib.ext.django.utils import PASSLIB_DEFAULT
     default = CryptContext.from_string(PASSLIB_DEFAULT)
     self.load_extension()
     self.assert_patched(PASSLIB_DEFAULT)
     self.load_extension(PASSLIB_CONTEXT='passlib-default', check=False)
     self.assert_patched(PASSLIB_DEFAULT)
     self.load_extension(PASSLIB_CONTEXT=PASSLIB_DEFAULT, check=False)
     self.assert_patched(PASSLIB_DEFAULT)
Exemple #11
0
def _init_htpasswd_context():
    schemes = [
        'bcrypt', 'sha256_crypt', 'sha512_crypt', 'des_crypt', 'apr_md5_crypt',
        'ldap_sha1', 'plaintext'
    ]
    schemes.extend(registry.get_supported_os_crypt_schemes())
    preferred = schemes[:3] + ['apr_md5_crypt'] + schemes
    schemes = sorted(set(schemes), key=preferred.index)
    return CryptContext(schemes,
                        default=htpasswd_defaults['portable_apache_22'])
Exemple #12
0
 def test_35_to_string(self):
     ctx = CryptContext(**self.sample_1_dict)
     dump = ctx.to_string()
     if not PY26:
         self.assertEqual(dump, self.sample_1_unicode)
     ctx2 = CryptContext.from_string(dump)
     self.assertEqual(ctx2.to_dict(), self.sample_1_dict)
     other = ctx.to_string(section='password-security')
     self.assertEqual(other, dump.replace('[passlib]', '[password-security]'))
     from otp.ai.passlib.tests.test_utils_handlers import UnsaltedHash
     ctx3 = CryptContext([UnsaltedHash, 'md5_crypt'])
     dump = ctx3.to_string()
     self.assertRegex(dump, "# NOTE: the 'unsalted_test_hash' handler\\(s\\) are not registered with Passlib")
Exemple #13
0
    def test_43_hash(self):
        cc = CryptContext(**self.sample_4_dict)
        hash = cc.hash('password')
        self.assertTrue(hash.startswith('$5$rounds=3000$'))
        self.assertTrue(cc.verify('password', hash))
        self.assertFalse(cc.verify('passwordx', hash))
        self.assertRaises(ValueError, cc.copy, sha256_crypt__default_rounds=4000)
        cc = CryptContext(['des_crypt'])
        for secret, kwds in self.nonstring_vectors:
            self.assertRaises(TypeError, cc.hash, secret, **kwds)

        self.assertRaises(KeyError, CryptContext().hash, 'secret')
        self.assertRaises(TypeError, cc.hash, 'secret', category=1)
Exemple #14
0
 def test_41_genconfig(self):
     cc = CryptContext(schemes=['md5_crypt', 'phpass'], phpass__ident='H', phpass__default_rounds=7, admin__phpass__ident='P')
     self.assertTrue(cc.genconfig().startswith('$1$'))
     self.assertTrue(cc.genconfig(scheme='phpass').startswith('$H$5'))
     self.assertTrue(cc.genconfig(scheme='phpass', category='admin').startswith('$P$5'))
     self.assertTrue(cc.genconfig(scheme='phpass', category='staff').startswith('$H$5'))
     self.assertEqual(cc.genconfig(scheme='phpass', salt='........', rounds=8, ident='P'), '$P$6........22zGEuacuPOqEpYPDeR0R/')
     if PY2:
         c2 = cc.copy(default='phpass')
         self.assertTrue(c2.genconfig(category=u('admin')).startswith('$P$5'))
         self.assertTrue(c2.genconfig(category=u('staff')).startswith('$H$5'))
     self.assertRaises(KeyError, CryptContext().genconfig)
     self.assertRaises(KeyError, CryptContext().genconfig, scheme='md5_crypt')
     self.assertRaises(KeyError, cc.genconfig, scheme='fake')
     self.assertRaises(TypeError, cc.genconfig, scheme=1, category='staff')
     self.assertRaises(TypeError, cc.genconfig, scheme=1)
     self.assertRaises(TypeError, cc.genconfig, category=1)
Exemple #15
0
    def test_44_identify(self):
        handlers = [
         'md5_crypt', 'des_crypt', 'bsdi_crypt']
        cc = CryptContext(handlers, bsdi_crypt__default_rounds=5)
        self.assertEqual(cc.identify('$9$232323123$1287319827'), None)
        self.assertRaises(ValueError, cc.identify, '$9$232323123$1287319827', required=True)
        cc = CryptContext(['des_crypt'])
        for hash, kwds in self.nonstring_vectors:
            self.assertRaises(TypeError, cc.identify, hash, **kwds)

        cc = CryptContext()
        self.assertIs(cc.identify('hash'), None)
        self.assertRaises(KeyError, cc.identify, 'hash', required=True)
        self.assertRaises(TypeError, cc.identify, None, category=1)
        return
Exemple #16
0
 def test_11_load_rollback(self):
     cc = CryptContext(['des_crypt', 'sha256_crypt'], sha256_crypt__default_rounds=5000, all__vary_rounds=0.1)
     result = cc.to_string()
     self.assertRaises(TypeError, cc.update, too__many__key__parts=True)
     self.assertEqual(cc.to_string(), result)
     self.assertRaises(KeyError, cc.update, fake_context_option=True)
     self.assertEqual(cc.to_string(), result)
     self.assertRaises(ValueError, cc.update, sha256_crypt__min_rounds=10000)
     self.assertEqual(cc.to_string(), result)
Exemple #17
0
 def test_04_copy(self):
     cc1 = CryptContext(**self.sample_1_dict)
     cc2 = cc1.copy(**self.sample_2_dict)
     self.assertEqual(cc1.to_dict(), self.sample_1_dict)
     self.assertEqual(cc2.to_dict(), self.sample_12_dict)
     cc2b = cc2.copy(**self.sample_2_dict)
     self.assertEqual(cc1.to_dict(), self.sample_1_dict)
     self.assertEqual(cc2b.to_dict(), self.sample_12_dict)
     cc3 = cc2.copy(**self.sample_3_dict)
     self.assertEqual(cc3.to_dict(), self.sample_123_dict)
     cc4 = cc1.copy()
     self.assertIsNot(cc4, cc1)
     self.assertEqual(cc1.to_dict(), self.sample_1_dict)
     self.assertEqual(cc4.to_dict(), self.sample_1_dict)
     cc4.update(**self.sample_2_dict)
     self.assertEqual(cc1.to_dict(), self.sample_1_dict)
     self.assertEqual(cc4.to_dict(), self.sample_12_dict)
Exemple #18
0
    def assert_patched(self, context=None):
        mod = sys.modules.get('passlib.ext.django.models')
        self.assertTrue(mod and mod.adapter.patched, 'patch should have been enabled')
        for obj, attr, source, patched in self._iter_patch_candidates():
            if patched:
                self.assertTrue(source == 'passlib.ext.django.utils', 'obj=%r attr=%r should have been patched: %r' % (
                 obj, attr, source))
            else:
                self.assertFalse(source.startswith('passlib.'), 'obj=%r attr=%r should not have been patched: %r' % (
                 obj, attr, source))

        if context is not None:
            context = CryptContext._norm_source(context)
            self.assertEqual(mod.password_context.to_dict(resolve=True), context.to_dict(resolve=True))
        return
 def test_95_context_algs(self):
     handler = self.handler
     from otp.ai.passlib.context import CryptContext
     c1 = CryptContext(['scram'], scram__algs='sha1,md5')
     h = c1.hash('dummy')
     self.assertEqual(handler.extract_digest_algs(h), ['md5', 'sha-1'])
     self.assertFalse(c1.needs_update(h))
     c2 = c1.copy(scram__algs='sha1')
     self.assertFalse(c2.needs_update(h))
     c2 = c1.copy(scram__algs='sha1,sha256')
     self.assertTrue(c2.needs_update(h))
Exemple #20
0
    def test_42_genhash(self):
        cc = CryptContext(['des_crypt'])
        hash = cc.hash('stub')
        for secret, kwds in self.nonstring_vectors:
            self.assertRaises(TypeError, cc.genhash, secret, hash, **kwds)

        cc = CryptContext(['des_crypt'])
        for config, kwds in self.nonstring_vectors:
            if hash is None:
                continue
            self.assertRaises(TypeError, cc.genhash, 'secret', config, **kwds)

        cc = CryptContext(['mysql323'])
        self.assertRaises(TypeError, cc.genhash, 'stub', None)
        self.assertRaises(KeyError, CryptContext().genhash, 'secret', 'hash')
        self.assertRaises(KeyError, cc.genhash, 'secret', hash, scheme='fake')
        self.assertRaises(TypeError, cc.genhash, 'secret', hash, scheme=1)
        self.assertRaises(TypeError, cc.genconfig, 'secret', hash, category=1)
        return
Exemple #21
0
 def test_43_hash_legacy(self, use_16_legacy=False):
     cc = CryptContext(**self.sample_4_dict)
     with self.assertWarningList(['passing settings to.*is deprecated']):
         self.assertEqual(cc.hash('password', scheme='phpass', salt='........'), '$H$5........De04R5Egz0aq8Tf.1eVhY/')
     with self.assertWarningList(['passing settings to.*is deprecated']):
         self.assertEqual(cc.hash('password', scheme='phpass', salt='........', ident='P'), '$P$5........De04R5Egz0aq8Tf.1eVhY/')
     with self.assertWarningList(['passing settings to.*is deprecated']):
         self.assertEqual(cc.hash('password', rounds=1999, salt='nacl'), '$5$rounds=1999$nacl$nmfwJIxqj0csloAAvSER0B8LU0ERCAbhmMug4Twl609')
     with self.assertWarningList(['passing settings to.*is deprecated']):
         self.assertEqual(cc.hash('password', rounds=2001, salt='nacl'), '$5$rounds=2001$nacl$8PdeoPL4aXQnJ0woHhqgIw/efyfCKC2WHneOpnvF.31')
     self.assertRaises(KeyError, cc.hash, 'secret', scheme='fake')
     self.assertRaises(TypeError, cc.hash, 'secret', scheme=1)
Exemple #22
0
 def __init__(self, context=None, get_user_category=None, **kwds):
     self.log = logging.getLogger(__name__ + '.DjangoContextAdapter')
     if context is None:
         context = CryptContext()
     super(DjangoContextAdapter, self).__init__(context=context, **kwds)
     if get_user_category:
         self.get_user_category = get_user_category
     from django.utils.lru_cache import lru_cache
     self.get_hashers = lru_cache()(self.get_hashers)
     from django.contrib.auth.hashers import make_password
     if make_password.__module__.startswith('passlib.'):
         make_password = _PatchManager.peek_unpatched_func(make_password)
     self._orig_make_password = make_password
     from django.contrib.auth.hashers import is_password_usable
     self.is_password_usable = is_password_usable
     mlog = logging.getLogger(__name__ + '.DjangoContextAdapter._manager')
     self._manager = _PatchManager(log=mlog)
     return
Exemple #23
0
    def test_61_autodeprecate(self):

        def getstate(ctx, category=None):
            return [ ctx.handler(scheme, category).deprecated for scheme in ctx.schemes() ]

        ctx = CryptContext('sha256_crypt,md5_crypt,des_crypt', deprecated='auto')
        self.assertEqual(getstate(ctx, None), [False, True, True])
        self.assertEqual(getstate(ctx, 'admin'), [False, True, True])
        ctx.update(default='md5_crypt')
        self.assertEqual(getstate(ctx, None), [True, False, True])
        self.assertEqual(getstate(ctx, 'admin'), [True, False, True])
        ctx.update(admin__context__default='des_crypt')
        self.assertEqual(getstate(ctx, None), [True, False, True])
        self.assertEqual(getstate(ctx, 'admin'), [True, True, False])
        ctx = CryptContext(['sha256_crypt'], deprecated='auto')
        self.assertEqual(getstate(ctx, None), [False])
        self.assertEqual(getstate(ctx, 'admin'), [False])
        self.assertRaises(ValueError, CryptContext, 'sha256_crypt,md5_crypt', deprecated='auto,md5_crypt')
        self.assertRaises(ValueError, CryptContext, 'sha256_crypt,md5_crypt', deprecated='md5_crypt,auto')
        return
Exemple #24
0
 def test_12_hash_needs_update(self):
     cc = CryptContext(**self.sample_policy_1)
     self.assertTrue(cc.hash_needs_update('9XXD4trGYeGJA'))
     self.assertFalse(
         cc.hash_needs_update('$1$J8HC2RCr$HcmM.7NxB2weSvlw2FgzU0'))
     self.assertTrue(
         cc.hash_needs_update(
             '$5$rounds=1999$jD81UCoo.zI.UETs$Y7qSTQ6mTiU9qZB4fRr43wRgQq4V.5AAf7F97Pzxey/'
         ))
     self.assertFalse(
         cc.hash_needs_update(
             '$5$rounds=2000$228SSRje04cnNCaQ$YGV4RYu.5sNiBvorQDlO0WWQjyJVGKBcJXz3OtyQ2u8'
         ))
     self.assertFalse(
         cc.hash_needs_update(
             '$5$rounds=3000$fS9iazEwTKi7QPW4$VasgBC8FqlOvD7x2HhABaMXCTh9jwHclPA9j5YQdns.'
         ))
     self.assertTrue(
         cc.hash_needs_update(
             '$5$rounds=3001$QlFHHifXvpFX4PLs$/0ekt7lSs/lOikSerQ0M/1porEHxYq7W/2hdFpxA3fA'
         ))
Exemple #25
0
    def test_33_options(self):

        def options(ctx, scheme, category=None):
            return ctx._config._get_record_options_with_flag(scheme, category)[0]

        cc4 = CryptContext(truncate_error=True, schemes=[
         'sha512_crypt', 'des_crypt', 'bsdi_crypt'], deprecated=[
         'sha512_crypt', 'des_crypt'], all__vary_rounds=0.1, bsdi_crypt__vary_rounds=0.2, sha512_crypt__max_rounds=20000, admin__context__deprecated=[
         'des_crypt', 'bsdi_crypt'], admin__all__vary_rounds=0.05, admin__bsdi_crypt__vary_rounds=0.3, admin__sha512_crypt__max_rounds=40000)
        self.assertEqual(cc4._config.categories, ('admin', ))
        self.assertEqual(options(cc4, 'sha512_crypt'), dict(deprecated=True, vary_rounds=0.1, max_rounds=20000))
        self.assertEqual(options(cc4, 'sha512_crypt', 'user'), dict(deprecated=True, vary_rounds=0.1, max_rounds=20000))
        self.assertEqual(options(cc4, 'sha512_crypt', 'admin'), dict(vary_rounds=0.05, max_rounds=40000))
        self.assertEqual(options(cc4, 'des_crypt'), dict(deprecated=True, truncate_error=True))
        self.assertEqual(options(cc4, 'des_crypt', 'user'), dict(deprecated=True, truncate_error=True))
        self.assertEqual(options(cc4, 'des_crypt', 'admin'), dict(deprecated=True, truncate_error=True))
        self.assertEqual(options(cc4, 'bsdi_crypt'), dict(vary_rounds=0.2))
        self.assertEqual(options(cc4, 'bsdi_crypt', 'user'), dict(vary_rounds=0.2))
        self.assertEqual(options(cc4, 'bsdi_crypt', 'admin'), dict(vary_rounds=0.3, deprecated=True))
        return
Exemple #26
0
 def test_51_linear_vary_rounds(self):
     cc = CryptContext(schemes=['sha256_crypt'], sha256_crypt__min_rounds=1995, sha256_crypt__max_rounds=2005, sha256_crypt__default_rounds=2000)
     self.assertRaises(ValueError, cc.copy, all__vary_rounds=-1)
     self.assertRaises(ValueError, cc.copy, all__vary_rounds='-1%')
     self.assertRaises(ValueError, cc.copy, all__vary_rounds='101%')
     c2 = cc.copy(all__vary_rounds=0)
     self.assertEqual(c2._get_record('sha256_crypt', None).vary_rounds, 0)
     self.assert_rounds_range(c2, 'sha256_crypt', 2000, 2000)
     c2 = cc.copy(all__vary_rounds='0%')
     self.assertEqual(c2._get_record('sha256_crypt', None).vary_rounds, 0)
     self.assert_rounds_range(c2, 'sha256_crypt', 2000, 2000)
     c2 = cc.copy(all__vary_rounds=1)
     self.assertEqual(c2._get_record('sha256_crypt', None).vary_rounds, 1)
     self.assert_rounds_range(c2, 'sha256_crypt', 1999, 2001)
     c2 = cc.copy(all__vary_rounds=100)
     self.assertEqual(c2._get_record('sha256_crypt', None).vary_rounds, 100)
     self.assert_rounds_range(c2, 'sha256_crypt', 1995, 2005)
     c2 = cc.copy(all__vary_rounds='0.1%')
     self.assertEqual(c2._get_record('sha256_crypt', None).vary_rounds, 0.001)
     self.assert_rounds_range(c2, 'sha256_crypt', 1998, 2002)
     c2 = cc.copy(all__vary_rounds='100%')
     self.assertEqual(c2._get_record('sha256_crypt', None).vary_rounds, 1.0)
     self.assert_rounds_range(c2, 'sha256_crypt', 1995, 2005)
     return
Exemple #27
0
 def test_disabled_hashes(self):
     from otp.ai.passlib.hash import md5_crypt, unix_disabled
     ctx = CryptContext(['des_crypt'])
     ctx2 = CryptContext(['des_crypt', 'unix_disabled'])
     h_ref = ctx.hash('foo')
     h_other = md5_crypt.hash('foo')
     self.assertRaisesRegex(RuntimeError, 'no disabled hasher present', ctx.disable)
     self.assertRaisesRegex(RuntimeError, 'no disabled hasher present', ctx.disable, h_ref)
     self.assertRaisesRegex(RuntimeError, 'no disabled hasher present', ctx.disable, h_other)
     h_dis = ctx2.disable()
     self.assertEqual(h_dis, unix_disabled.default_marker)
     h_dis_ref = ctx2.disable(h_ref)
     self.assertEqual(h_dis_ref, unix_disabled.default_marker + h_ref)
     h_dis_other = ctx2.disable(h_other)
     self.assertEqual(h_dis_other, unix_disabled.default_marker + h_other)
     self.assertEqual(ctx2.disable(h_dis_ref), h_dis_ref)
     self.assertTrue(ctx.is_enabled(h_ref))
     HASH_NOT_IDENTIFIED = 'hash could not be identified'
     self.assertRaisesRegex(ValueError, HASH_NOT_IDENTIFIED, ctx.is_enabled, h_other)
     self.assertRaisesRegex(ValueError, HASH_NOT_IDENTIFIED, ctx.is_enabled, h_dis)
     self.assertRaisesRegex(ValueError, HASH_NOT_IDENTIFIED, ctx.is_enabled, h_dis_ref)
     self.assertTrue(ctx2.is_enabled(h_ref))
     self.assertRaisesRegex(ValueError, HASH_NOT_IDENTIFIED, ctx.is_enabled, h_other)
     self.assertFalse(ctx2.is_enabled(h_dis))
     self.assertFalse(ctx2.is_enabled(h_dis_ref))
     self.assertRaisesRegex(ValueError, HASH_NOT_IDENTIFIED, ctx.enable, '')
     self.assertRaises(TypeError, ctx.enable, None)
     self.assertEqual(ctx.enable(h_ref), h_ref)
     self.assertRaisesRegex(ValueError, HASH_NOT_IDENTIFIED, ctx.enable, h_other)
     self.assertRaisesRegex(ValueError, HASH_NOT_IDENTIFIED, ctx.enable, h_dis)
     self.assertRaisesRegex(ValueError, HASH_NOT_IDENTIFIED, ctx.enable, h_dis_ref)
     self.assertRaisesRegex(ValueError, HASH_NOT_IDENTIFIED, ctx.enable, '')
     self.assertRaises(TypeError, ctx2.enable, None)
     self.assertEqual(ctx2.enable(h_ref), h_ref)
     self.assertRaisesRegex(ValueError, HASH_NOT_IDENTIFIED, ctx2.enable, h_other)
     self.assertRaisesRegex(ValueError, 'cannot restore original hash', ctx2.enable, h_dis)
     self.assertEqual(ctx2.enable(h_dis_ref), h_ref)
     return
Exemple #28
0
 def test_50_rounds_limits(self):
     cc = CryptContext(schemes=['sha256_crypt'], sha256_crypt__min_rounds=2000, sha256_crypt__max_rounds=3000, sha256_crypt__default_rounds=2500)
     STUB = '...........................................'
     custom_handler = cc._get_record('sha256_crypt', None)
     self.assertEqual(custom_handler.min_desired_rounds, 2000)
     self.assertEqual(custom_handler.max_desired_rounds, 3000)
     self.assertEqual(custom_handler.default_rounds, 2500)
     with self.assertWarningList([PasslibHashWarning] * 2):
         c2 = cc.copy(sha256_crypt__min_rounds=500, sha256_crypt__max_rounds=None, sha256_crypt__default_rounds=500)
     self.assertEqual(c2.genconfig(salt='nacl'), '$5$rounds=1000$nacl$' + STUB)
     with self.assertWarningList([]):
         self.assertEqual(cc.genconfig(rounds=1999, salt='nacl'), '$5$rounds=1999$nacl$' + STUB)
     self.assertEqual(cc.genconfig(rounds=2000, salt='nacl'), '$5$rounds=2000$nacl$' + STUB)
     self.assertEqual(cc.genconfig(rounds=2001, salt='nacl'), '$5$rounds=2001$nacl$' + STUB)
     with self.assertWarningList([PasslibHashWarning] * 2):
         c2 = cc.copy(sha256_crypt__max_rounds=int(1000000000.0) + 500, sha256_crypt__min_rounds=None, sha256_crypt__default_rounds=int(1000000000.0) + 500)
     self.assertEqual(c2.genconfig(salt='nacl'), '$5$rounds=999999999$nacl$' + STUB)
     with self.assertWarningList([]):
         self.assertEqual(cc.genconfig(rounds=3001, salt='nacl'), '$5$rounds=3001$nacl$' + STUB)
     self.assertEqual(cc.genconfig(rounds=3000, salt='nacl'), '$5$rounds=3000$nacl$' + STUB)
     self.assertEqual(cc.genconfig(rounds=2999, salt='nacl'), '$5$rounds=2999$nacl$' + STUB)
     self.assertEqual(cc.genconfig(salt='nacl'), '$5$rounds=2500$nacl$' + STUB)
     df = hash.sha256_crypt.default_rounds
     c2 = cc.copy(sha256_crypt__default_rounds=None, sha256_crypt__max_rounds=df << 1)
     self.assertEqual(c2.genconfig(salt='nacl'), '$5$rounds=%d$nacl$%s' % (df, STUB))
     c2 = cc.copy(sha256_crypt__default_rounds=None, sha256_crypt__max_rounds=3000)
     self.assertEqual(c2.genconfig(salt='nacl'), '$5$rounds=3000$nacl$' + STUB)
     self.assertRaises(ValueError, cc.copy, sha256_crypt__default_rounds=1999)
     cc.copy(sha256_crypt__default_rounds=2000)
     cc.copy(sha256_crypt__default_rounds=3000)
     self.assertRaises(ValueError, cc.copy, sha256_crypt__default_rounds=3001)
     c2 = CryptContext(schemes=['sha256_crypt'])
     self.assertRaises(ValueError, c2.copy, sha256_crypt__min_rounds=2000, sha256_crypt__max_rounds=1999)
     self.assertRaises(ValueError, CryptContext, sha256_crypt__min_rounds='x')
     self.assertRaises(ValueError, CryptContext, sha256_crypt__max_rounds='x')
     self.assertRaises(ValueError, CryptContext, all__vary_rounds='x')
     self.assertRaises(ValueError, CryptContext, sha256_crypt__default_rounds='x')
     bad = datetime.datetime.now()
     self.assertRaises(TypeError, CryptContext, 'sha256_crypt', sha256_crypt__min_rounds=bad)
     self.assertRaises(TypeError, CryptContext, 'sha256_crypt', sha256_crypt__max_rounds=bad)
     self.assertRaises(TypeError, CryptContext, 'sha256_crypt', all__vary_rounds=bad)
     self.assertRaises(TypeError, CryptContext, 'sha256_crypt', sha256_crypt__default_rounds=bad)
     return
Exemple #29
0
 def test_01_constructor(self):
     ctx = CryptContext()
     self.assertEqual(ctx.to_dict(), {})
     ctx = CryptContext(**self.sample_1_dict)
     self.assertEqual(ctx.to_dict(), self.sample_1_dict)
     ctx = CryptContext(**self.sample_1_resolved_dict)
     self.assertEqual(ctx.to_dict(), self.sample_1_dict)
     ctx = CryptContext(**self.sample_2_dict)
     self.assertEqual(ctx.to_dict(), self.sample_2_dict)
     ctx = CryptContext(**self.sample_3_dict)
     self.assertEqual(ctx.to_dict(), self.sample_3_dict)
     ctx = CryptContext(schemes=[u('sha256_crypt')])
     self.assertEqual(ctx.schemes(), ('sha256_crypt', ))
Exemple #30
0
 def test_48_context_kwds(self):
     from otp.ai.passlib.hash import des_crypt, md5_crypt, postgres_md5
     des_hash = des_crypt.hash('stub')
     pg_root_hash = postgres_md5.hash('stub', user='******')
     pg_admin_hash = postgres_md5.hash('stub', user='******')
     cc1 = CryptContext([des_crypt, md5_crypt])
     self.assertEqual(cc1.context_kwds, set())
     self.assertTrue(des_crypt.identify(cc1.hash('stub')), 'des_crypt')
     self.assertTrue(cc1.verify('stub', des_hash))
     self.assertEqual(cc1.verify_and_update('stub', des_hash), (True, None))
     with self.assertWarningList(['passing settings to.*is deprecated']):
         self.assertRaises(TypeError, cc1.hash, 'stub', user='******')
     self.assertRaises(TypeError, cc1.verify, 'stub', des_hash, user='******')
     self.assertRaises(TypeError, cc1.verify_and_update, 'stub', des_hash, user='******')
     cc2 = CryptContext([des_crypt, postgres_md5])
     self.assertEqual(cc2.context_kwds, set(['user']))
     self.assertTrue(des_crypt.identify(cc2.hash('stub')), 'des_crypt')
     self.assertTrue(cc2.verify('stub', des_hash))
     self.assertEqual(cc2.verify_and_update('stub', des_hash), (True, None))
     self.assertTrue(des_crypt.identify(cc2.hash('stub', user='******')), 'des_crypt')
     self.assertTrue(cc2.verify('stub', des_hash, user='******'))
     self.assertEqual(cc2.verify_and_update('stub', des_hash, user='******'), (True, None))
     with self.assertWarningList(['passing settings to.*is deprecated']):
         self.assertRaises(TypeError, cc2.hash, 'stub', badkwd='root')
     self.assertRaises(TypeError, cc2.verify, 'stub', des_hash, badkwd='root')
     self.assertRaises(TypeError, cc2.verify_and_update, 'stub', des_hash, badkwd='root')
     cc3 = CryptContext([postgres_md5, des_crypt], deprecated='auto')
     self.assertEqual(cc3.context_kwds, set(['user']))
     self.assertRaises(TypeError, cc3.hash, 'stub')
     self.assertRaises(TypeError, cc3.verify, 'stub', pg_root_hash)
     self.assertRaises(TypeError, cc3.verify_and_update, 'stub', pg_root_hash)
     self.assertEqual(cc3.hash('stub', user='******'), pg_root_hash)
     self.assertTrue(cc3.verify('stub', pg_root_hash, user='******'))
     self.assertEqual(cc3.verify_and_update('stub', pg_root_hash, user='******'), (True, None))
     self.assertEqual(cc3.verify_and_update('stub', pg_root_hash, user='******'), (False, None))
     self.assertEqual(cc3.verify_and_update('stub', des_hash, user='******'), (
      True, pg_root_hash))
     return