summaryrefslogtreecommitdiff
path: root/passlib
diff options
context:
space:
mode:
authorEli Collins <elic@assurancetechnologies.com>2016-10-03 18:02:24 -0400
committerEli Collins <elic@assurancetechnologies.com>2016-10-03 18:02:24 -0400
commit09525db16e8eeb58786ce80f18f0be6ef31e9a8e (patch)
tree1eb0631776be73d8d661cd6b4cd34da04600bf1f /passlib
parent1cf93dd95dd31fdc6cc9034deba36ce31cd58671 (diff)
downloadpasslib-09525db16e8eeb58786ce80f18f0be6ef31e9a8e.tar.gz
totp: large cleanup of the API: removed skew prediction, tweaked structure
of the verify() return types, other related changes. This commit updates a bunch of the TOTP API, in an attempt to finalize it for release. TOTP ---- * The client clock-skew prediction code was stripped out from TOTP.consume() and elsewhere, along with the internal "history" attribute. This code wasn't going to be much use unless much better statistical analysis was added, so stripping out the non-functional code that was present. All that's left is the ability to pass an externally calculated 'skew' value into TOTP.verify() / .consume() (keyword previously named 'offset', which was deemed too ambigious). * TOTP.verify() / TotpMatch: Iterable signature changed from (matched_counter, estimated_skew) to (matched_counter, time). This reflects the underlying source data, eliminating the need to needlessly calculate derived values. It also aligns better with HotpMatch, and removes the 'skew' parameter (which has been stripped out). '.counter_skipped' attribute was renamed to '.skipped' * TOTP.verify() now handles token-reuse detection: Relocated code handling this from TOTP.consume(), renamed 'min_start' renamed to 'last_counter', and added 'reuse=False' keyword. This makes it easier to test & use independantly, as well as making TOTP.consume() more of just a wrapper for .verify(). * TOTP.consume() now returns TotpMatch() object from .verify(), rather than just "True"; more consistent as just a wrapper for .verify() * internal TOTP._time_to_counter() no longer passing input through normalize_time(), removing some redundant calls. HOTP ---- * HOTP.verify() / HotpMatch: Iterable content changed from (next_counter, skipped) to (matched_counter, expected_counter). This reflects the underlying source data, eliminating the need to needlessly calculate derived values. It also aligns better with TotpMatch. '.counter_skipped' attribute was renamed to '.skipped' * HTOP.verify(): now compares token against last counter value, so that it can raise a UsedTokenError() when appropriate. * HOTP.consume() now returns HotpMatch() object from .verify(), rather than just "True"; more consistent as just a wrapper for .verify() Other ----- * OTPContext: stripped out support for XOR-based encryption scheme (only used during alpha development) * HotpMatch, TotpToken, and TotpMatch now have custom reprs, to highlight that they aren't just tuples. Tests ----- * removed clock-skew prediction tests * removed legacy XOR-based encryption tests * consolidated some boilerplate arrays of tests into some helper methods. this includes .assertHotpMatch(), .assertTotpMatch(), .assertVerifyMatches(), .assertVerifyRaises() * added tests for TOTP.verify()/.consume()'s "skew" and "reuse" parameters * various updates to account for call signature changes above
Diffstat (limited to 'passlib')
-rw-r--r--passlib/tests/test_totp.py475
-rw-r--r--passlib/totp.py367
2 files changed, 316 insertions, 526 deletions
diff --git a/passlib/tests/test_totp.py b/passlib/tests/test_totp.py
index bdaa28b..53b0016 100644
--- a/passlib/tests/test_totp.py
+++ b/passlib/tests/test_totp.py
@@ -81,63 +81,8 @@ class UtilsTest(TestCase):
descriptionPrefix = "passlib.totp"
#=============================================================================
- # client offset helpers
- #=============================================================================
-
- # sample history used by suggest_offset() test
- history1 = [
- (1420563115, 0), # -25
- (1420563140, 0), # -20
- (1420563246, 0), # -6
- (1420563363, -1), # -33
- (1420563681, 0), # -21
- (1420569854, 0), # -14
- (1420571296, 0), # -16
- (1420579589, 0), # -29
- (1420580848, 0), # -28
- (1420580989, 0), # -19
- (1420581126, -1), # -36
- (1420582973, 0), # -23
- (1420583342, -1), # -32
- ]
-
- def test_suggest_offset(self):
- """suggest_offset()"""
- from passlib.totp import suggest_offset, DEFAULT_OFFSET
-
- # test reference sample
- history1 = self.history1
- result1 = suggest_offset(history1, 30)
- self.assertAlmostEqual(result1, -9, delta=10)
-
- # translation by multiple of period should have no effect
- for diff in range(-3, 4):
- translate = diff * 30
- history2 = [(time + translate, diff) for time, diff in history1]
- self.assertEqual(suggest_offset(history2, 30), result1,
- msg="history1 translated by %ds: " % translate)
-
- # in general, translations shouldn't send value too far away from original
- # (may relax this for new situations)
- for translate in range(-30, 30):
- history2 = [(time + translate, diff) for time, diff in history1]
- self.assertAlmostEqual(suggest_offset(history2, 30), result1, delta=10,
- msg="history1 translated by %ds: " % translate)
-
- # handle 2 element history
- self.assertAlmostEqual(suggest_offset(history1[:2]), -9, delta=10)
-
- # handle 1 element history
- self.assertAlmostEqual(suggest_offset(history1[:1]), -9, delta=10)
-
- # empty history should use default
- self.assertAlmostEqual(suggest_offset([]), DEFAULT_OFFSET)
- self.assertAlmostEqual(suggest_offset([], default=-10), -10)
-
- # fuzz test on random values
- size = random.randint(0, 16)
- elems = [ (randtime(), random.randint(-2,3)) for _ in range(size)]
- suggest_offset(elems)
+ #
+ #=============================================================================
#=============================================================================
# eoc
@@ -348,24 +293,6 @@ class OTPContextTest(TestCase):
temp.update(v=999)
self.assertRaises(ValueError, context.decrypt_key, temp)
- def test_decrypt_key_xor(self):
- """.decrypt_key() -- legacy xor format"""
- self.require_aes_support()
-
- # XOR encoding of KEY1
- CIPHER = dict(v=0, t="1", c=12, s='EISCJBCQVL2V4C7B', k='KTTAWJP2RT4MYGWR')
- context = OTPContext({1: PASS1})
- key, needs_recrypt = context.decrypt_key(CIPHER)
- self.assertEqual(key, KEY1_RAW)
- self.assertTrue(needs_recrypt)
-
- # XOR encoding of KEY2
- CIPHER = dict(v=0, t="2", c=8, s='5HOZXE2SVJ2Q5QPY', k='ZI2WYDXLIMTPU5UIMFSJJOEPJLSI2Q6Q')
- context = OTPContext({2: PASS2})
- key, needs_recrypt = context.decrypt_key(CIPHER)
- self.assertEqual(key, KEY2_RAW)
- self.assertTrue(needs_recrypt)
-
def test_decrypt_key_needs_recrypt(self):
""".decrypt_key() -- needs_recrypt flag"""
self.require_aes_support()
@@ -878,7 +805,7 @@ class TotpTest(_BaseOTPTest):
# require returns non-negative value
self.assertRaisesRegex(AssertionError, msg_re, self.randotp, now=lambda : -1)
- # NOTE: 'last_counter', '_history' are internal parameters,
+ # NOTE: 'last_counter' is an internal parameter,
# tested by from_json() / to_json().
#=============================================================================
@@ -1074,35 +1001,38 @@ class TotpTest(_BaseOTPTest):
# TotpMatch() -- verify()'s return value
#=============================================================================
- def test_totp_match_w_valid_token(self):
- """verify() -- valid TotpMatch object"""
+ def assertTotpMatch(self, match, time, skipped, period=30, msg=''):
from passlib.totp import TotpMatch
- time = 141230981
- token = '781501'
- otp = TOTP(KEY3, now=lambda : time + 24 * 3600)
- result = otp.verify(token, time)
-
# test type
- self.assertIsInstance(result, TotpMatch)
+ self.assertIsInstance(match, TotpMatch)
# test attrs
- self.assertAlmostEqual(result.next_offset, 0, delta=10) # xxx: alter this if suggest_offset() is updated?
- self.assertEqual(result.time, time)
- self.assertEqual(result.counter, time // 30)
- self.assertEqual(result.counter_skipped, 0)
- self.assertEqual(result.previous_offset, 0)
+ self.assertEqual(match.time, time, msg=msg + " matched time:")
+ expected = time // period
+ counter = expected + skipped
+ self.assertEqual(match.counter, counter, msg=msg + " matched counter:")
+ self.assertEqual(match.expected_counter, expected, msg=msg + " expected counter:")
+ self.assertEqual(match.skipped, skipped, msg=msg + " skipped:")
# test tuple
- self.assertEqual(len(result), 2)
- self.assertEqual(result, (result.counter, result.next_offset))
- self.assertRaises(IndexError, result.__getitem__, -3)
- self.assertEqual(result[0], result.counter)
- self.assertEqual(result[1], result.next_offset)
- self.assertRaises(IndexError, result.__getitem__, 2)
+ self.assertEqual(len(match), 2)
+ self.assertEqual(match, (counter, time))
+ self.assertRaises(IndexError, match.__getitem__, -3)
+ self.assertEqual(match[0], counter)
+ self.assertEqual(match[1], time)
+ self.assertRaises(IndexError, match.__getitem__, 2)
# test bool
- self.assertTrue(result)
+ self.assertTrue(match)
+
+ def test_totp_match_w_valid_token(self):
+ """verify() -- valid TotpMatch object"""
+ time = 141230981
+ token = '781501'
+ otp = TOTP(KEY3, now=lambda : time + 24 * 3600)
+ result = otp.verify(token, time)
+ self.assertTotpMatch(result, time=time, skipped=0)
def test_totp_match_w_older_token(self):
"""verify() -- valid TotpMatch object with future token"""
@@ -1110,29 +1040,9 @@ class TotpTest(_BaseOTPTest):
time = 141230981
token = '781501'
- otp = TOTP(KEY3, now=lambda : time + 24 * 3600)
+ otp = TOTP(KEY3, now=lambda: time + 24 * 3600)
result = otp.verify(token, time - 30)
-
- # test type
- self.assertIsInstance(result, TotpMatch)
-
- # test attrs
- self.assertAlmostEqual(result.next_offset, 30, delta=10) # xxx: alter this if suggest_offset() is updated?
- self.assertEqual(result.time, time - 30)
- self.assertEqual(result.counter, time // 30)
- self.assertEqual(result.counter_skipped, 1)
- self.assertEqual(result.previous_offset, 0)
-
- # test tuple
- self.assertEqual(len(result), 2)
- self.assertEqual(result, (result.counter, result.next_offset))
- self.assertRaises(IndexError, result.__getitem__, -3)
- self.assertEqual(result[0], result.counter)
- self.assertEqual(result[1], result.next_offset)
- self.assertRaises(IndexError, result.__getitem__, 2)
-
- # test bool
- self.assertTrue(result)
+ self.assertTotpMatch(result, time=time - 30, skipped=1)
def test_totp_match_w_new_token(self):
"""verify() -- valid TotpMatch object with past token"""
@@ -1142,28 +1052,7 @@ class TotpTest(_BaseOTPTest):
token = '781501'
otp = TOTP(KEY3, now=lambda : time + 24 * 3600)
result = otp.verify(token, time + 30)
-
- # test type
- self.assertIsInstance(result, TotpMatch)
-
- # test attrs
- # NOTE: may need to alter this next line if suggest_offset() is updated ...
- self.assertAlmostEqual(result.next_offset, -20, delta=10)
- self.assertEqual(result.time, time + 30)
- self.assertEqual(result.counter, time // 30)
- self.assertEqual(result.counter_skipped, -1)
- self.assertEqual(result.previous_offset, 0)
-
- # test tuple
- self.assertEqual(len(result), 2)
- self.assertEqual(result, (result.counter, result.next_offset))
- self.assertRaises(IndexError, result.__getitem__, -3)
- self.assertEqual(result[0], result.counter)
- self.assertEqual(result[1], result.next_offset)
- self.assertRaises(IndexError, result.__getitem__, 2)
-
- # test bool
- self.assertTrue(result)
+ self.assertTotpMatch(result, time=time + 30, skipped=-1)
def test_totp_match_w_invalid_token(self):
"""verify() -- invalid TotpMatch object"""
@@ -1178,77 +1067,156 @@ class TotpTest(_BaseOTPTest):
# verify()
#=============================================================================
+ def assertVerifyMatches(self, expect_skipped, token, time, # *
+ otp, check_consume=False, gen_time=None, **kwds):
+ """helper to test otp.verify() output is correct"""
+ # NOTE: TotpMatch return type tested more throughly above ^^^
+ msg = "key=%r alg=%r period=%r token=%r gen_time=%r time=%r:" % \
+ (otp.base32_key, otp.alg, otp.period, token, gen_time, time)
+ if check_consume:
+ verify = self._create_consume_wrapper(otp)
+ else:
+ verify = otp.verify
+ result = verify(token, time, **kwds)
+ self.assertTotpMatch(result,
+ time=otp.normalize_time(time),
+ period=otp.period,
+ skipped=expect_skipped,
+ msg=msg)
+
+ def assertVerifyRaises(self, exc_class, token, time, # *
+ otp, check_consume=False, gen_time=None,
+ **kwds):
+ """helper to test otp.verify() throws correct error"""
+ # NOTE: TotpMatch return type tested more throughly above ^^^
+ msg = "key=%r alg=%r period=%r token=%r gen_time=%r time=%r:" % \
+ (otp.base32_key, otp.alg, otp.period, token, gen_time, time)
+ if check_consume:
+ verify = self._create_consume_wrapper(otp)
+ else:
+ verify = otp.verify
+ return self.assertRaises(exc_class, verify, token, time,
+ __msg__=msg, **kwds)
+
def test_verify_w_window(self, for_consume=False):
"""verify() -- 'time' and 'window' parameters"""
- # init generator
- time = orig_time = randtime()
+ # init generator & helper
otp = self.randotp()
period = otp.period
- if for_consume:
- verify = self._create_consume_wrapper(otp)
- else:
- verify = otp.verify
+ time = randtime()
token = otp.generate(time).token
-
- # init test helper
- def test(correct_valid, correct_counter_offset, token, time, **kwds):
- """helper to test verify() output"""
- # NOTE: TotpMatch return type tested more throughly above ^^^
- msg = "key=%r alg=%r period=%r token=%r orig_time=%r time=%r:" % \
- (otp.base32_key, otp.alg, otp.period, token, orig_time, time)
- if correct_valid:
- result = verify(token, time, **kwds)
- self.assertTrue(result)
- self.assertEqual(result.counter_skipped, correct_counter_offset)
- self.assertEqual(otp.normalize_time(result.time), otp.normalize_time(time))
- else:
- self.assertRaises(exc.InvalidTokenError, verify, token, time,
- __msg__=msg, **kwds)
+ common = dict(otp=otp, gen_time=time, check_consume=for_consume)
+ assertMatches = partial(self.assertVerifyMatches, **common)
+ assertRaises = partial(self.assertVerifyRaises, **common)
#-------------------------------
# basic validation, and 'window' parameter
#-------------------------------
# validate against previous counter (passes if window >= period)
- test(False, 0, token, time - period, window=0)
- test(True, 1, token, time - period, window=period)
- test(True, 1, token, time - period, window=2 * period)
+ assertRaises(exc.InvalidTokenError, token, time - period, window=0)
+ assertMatches(+1, token, time - period, window=period)
+ assertMatches(+1, token, time - period, window=2 * period)
# validate against current counter
- test(True, 0, token, time, window=0)
+ assertMatches(0, token, time, window=0)
# validate against next counter (passes if window >= period)
- test(False, 0, token, time + period, window=0)
- test(True, -1, token, time + period, window=period)
- test(True, -1, token, time + period, window=2 * period)
+ assertRaises(exc.InvalidTokenError, token, time + period, window=0)
+ assertMatches(-1, token, time + period, window=period)
+ assertMatches(-1, token, time + period, window=2 * period)
# validate against two time steps later (should never pass)
- test(False, 0, token, time + 2 * period, window=0)
- test(False, 0, token, time + 2 * period, window=period)
- test(True, -2, token, time + 2 * period, window=2 * period)
+ assertRaises(exc.InvalidTokenError, token, time + 2 * period, window=0)
+ assertRaises(exc.InvalidTokenError, token, time + 2 * period, window=period)
+ assertMatches(-2, token, time + 2 * period, window=2 * period)
# TODO: test window values that aren't multiples of period
# (esp ensure counter rounding works correctly)
#-------------------------------
- # offset param
- #-------------------------------
-
- # TODO: test offset param
-
- # TODO: test offset + window
-
- #-------------------------------
# time normalization
#-------------------------------
# handle datetimes
dt = datetime.datetime.utcfromtimestamp(time)
- test(True, 0, token, dt, window=0)
+ assertMatches(0, token, dt, window=0)
# reject invalid time
- self.assertRaises(ValueError, otp.verify, token, -1)
+ assertRaises(ValueError, token, -1)
+
+ def test_verify_w_skew(self, for_consume=False):
+ """verify() -- 'skew' parameters"""
+ # init generator & helper
+ otp = self.randotp()
+ period = otp.period
+ time = randtime()
+ common = dict(otp=otp, gen_time=time, check_consume=for_consume)
+ assertMatches = partial(self.assertVerifyMatches, **common)
+ assertRaises = partial(self.assertVerifyRaises, **common)
+
+ # assume client is running far behind server / has excessive transmission delay
+ skew = 3 * period
+ behind_token = otp.generate(time - skew).token
+ assertRaises(exc.InvalidTokenError, behind_token, time, window=0)
+ assertMatches(-3, behind_token, time, window=0, skew=-skew)
+
+ # assume client is running far ahead of server
+ ahead_token = otp.generate(time + skew).token
+ assertRaises(exc.InvalidTokenError, ahead_token, time, window=0)
+ assertMatches(+3, ahead_token, time, window=0, skew=skew)
+
+ # TODO: test skew + larger window
+
+ def test_verify_w_reuse(self, for_consume=False):
+ """verify() -- 'reuse' and 'last_counter' parameters"""
+
+ # init generator & helper
+ otp = self.randotp()
+ period = otp.period
+ time = randtime()
+ tdata = otp.generate(time)
+ token = tdata.token
+ counter = tdata.counter
+ expire_time = tdata.expire_time
+ common = dict(otp=otp, gen_time=time, check_consume=for_consume)
+ assertMatches = partial(self.assertVerifyMatches, **common)
+ assertRaises = partial(self.assertVerifyRaises, **common)
+
+ # last counter unset --
+ # previous period's token should count as valid
+ assertMatches(-1, token, time + period, window=period)
+
+ # last counter set 2 periods ago --
+ # previous period's token should count as valid
+ assertMatches(-1, token, time + period, last_counter=counter-1,
+ window=period)
+
+ # last counter set 2 periods ago --
+ # 2 periods ago's token should NOT count as valid, even if reuse=True
+ assertRaises(exc.InvalidTokenError, token, time + 2 * period,
+ last_counter=counter, window=period, reuse=True)
+
+ # last counter set 1 period ago --
+ # previous period's token should now be rejected as 'used'
+ err = assertRaises(exc.UsedTokenError, token, time + period,
+ last_counter=counter, window=period)
+ self.assertEqual(err.expire_time, expire_time)
+
+ # last counter set 1 period ago, reuse allowed
+ assertMatches(-1, token, time + period, last_counter=counter,
+ window=period, reuse=True)
+
+ # last counter set to current period --
+ # current period's token should be rejected
+ err = assertRaises(exc.UsedTokenError, token, time,
+ last_counter=counter, window=0)
+ self.assertEqual(err.expire_time, expire_time)
+
+ # last counter set to current period, reuse allowed
+ assertMatches(0, token, time, last_counter=counter,
+ window=0, reuse=True)
def test_verify_w_token_normalization(self, for_consume=False):
"""verify() -- token normalization"""
@@ -1286,9 +1254,8 @@ class TotpTest(_BaseOTPTest):
# token should verify against time
if for_consume:
- real_offset = -divmod(time, otp.period)[1]
- msg = "%s(with next_offset=%r, real_offset=%r):" % (msg, otp._next_offset(time),
- real_offset)
+ real_skew = -divmod(time, otp.period)[1]
+ msg = "%s(with real_skew=%r):" % (msg, real_skew)
result = verify(token, time)
self.assertTrue(result)
self.assertEqual(result.counter, time // otp.period, msg=msg)
@@ -1305,39 +1272,41 @@ class TotpTest(_BaseOTPTest):
which makes it's signature & return match verify(),
to helper out shared test code.
"""
- from passlib.totp import TotpMatch
- def wrapper(token, time, **kwds):
+ def wrapper(token, time, last_counter=0, **kwds):
# reset internal state
time = otp.normalize_time(time)
- otp.last_counter = 0
- otp._history = None
- # fix current time
+ otp.last_counter = last_counter
+ otp.changed = False
+
+ # monkeypatch current time, and run consume() w/in our sandbox
orig = otp.now
try:
otp.now = lambda: time
- # run verify next w/in our sandbox
- offset = otp._next_offset(time)
- valid = otp.consume(token, **kwds)
- self.assertIs(valid, True)
+ return otp.consume(token, **kwds)
finally:
otp.now = orig
- # create fake TotpMatch instance to return
- result = TotpMatch(time, otp.last_counter, offset, otp.period)
- # check that history was populated correctly
- self.assertEqual(otp._history[0][1], result.counter_skipped)
- return result
+
return wrapper
def test_consume_w_window(self):
"""consume() -- 'window' parameter"""
self.test_verify_w_window(for_consume=True)
+ def test_consume_w_skew(self):
+ """consume() -- 'skew' parameter"""
+ self.test_verify_w_skew(for_consume=True)
+
+ def test_consume_w_reuse(self, for_consume=False):
+ """consume() -- 'reuse' parameter & 'last_counter' attribute"""
+ self.test_verify_w_reuse(for_consume=True)
+
def test_consume_w_token_normalization(self):
"""consume() -- token normalization"""
self.test_verify_w_token_normalization(for_consume=True)
+ # TODO: roll this into test_consume_w_reuse(), above
def test_consume_w_last_counter(self):
- """consume() -- 'last_counter' and '_history' attributes"""
+ """consume() -- 'last_counter' attribute"""
from passlib.exc import UsedTokenError
# init generator
@@ -1376,8 +1345,6 @@ class TotpTest(_BaseOTPTest):
self.assertTrue(otp.consume(token2))
self.assertEqual(otp.last_counter, counter + 1)
- # TODO: test history & suggested offset for next time.
-
# TODO: test 'changed flag' behavior
def test_consume_w_reference_vectors(self):
@@ -1582,7 +1549,7 @@ class TotpTest(_BaseOTPTest):
# with encrypt=True + context + no secrets
# with encrypt=True + no context
- # TODO: check history, last_counter are preserved
+ # TODO: last_counter is preserved
#=============================================================================
# eoc
@@ -1854,66 +1821,51 @@ class HotpTest(_BaseOTPTest):
#=============================================================================
# HotpMatch() -- verify()'s return value
#=============================================================================
- def test_hotp_match_w_valid_token(self):
- """verify() -- valid HotpMatch object"""
+ def assertHotpMatch(self, result, matched, expected, msg=None):
from passlib.totp import HotpMatch
- otp = HOTP(KEY3)
- counter = 41230981
- token = '775167'
- result = otp.verify(token, counter)
-
# test type
- self.assertIsInstance(result, HotpMatch)
+ self.assertIsInstance(result, HotpMatch, msg=msg)
# test attrs
- self.assertEqual(result.next_counter, counter+1)
- self.assertEqual(result.counter_skipped, 0)
+ self.assertEqual(result.counter, matched, msg=msg)
+ self.assertEqual(result.expected_counter, expected, msg=msg)
+ self.assertEqual(result.next_counter, matched+1, msg=msg)
+ self.assertEqual(result.skipped, matched - expected, msg=msg)
# test tuple
self.assertEqual(len(result), 2)
- self.assertEqual(result, (counter+1,0))
+ self.assertEqual(result, (matched, expected))
self.assertRaises(IndexError, result.__getitem__, -3)
- self.assertEqual(result[0], counter+1)
- self.assertEqual(result[1], 0)
+ self.assertEqual(result[0], matched)
+ self.assertEqual(result[1], expected)
self.assertRaises(IndexError, result.__getitem__, 2)
# test bool
self.assertTrue(result)
+ def test_hotp_match_w_valid_token(self):
+ """verify() -- valid HotpMatch object"""
+ otp = HOTP(KEY3)
+ counter = 41230981
+ token = '775167'
+ result = otp.verify(token, counter)
+ self.assertHotpMatch(result, counter, counter)
+
def test_hotp_match_w_skipped_counter(self):
"""verify() -- valid HotpMatch object w/ skipped counter"""
- from passlib.totp import HotpMatch
-
otp = HOTP(KEY3)
counter = 41230981
token = '775167'
result = otp.verify(token, counter-1)
-
- # test type
- self.assertIsInstance(result, HotpMatch)
-
- # test attrs
- self.assertEqual(result.next_counter, counter + 1)
- self.assertEqual(result.counter_skipped, 1)
-
- # test tuple
- self.assertEqual(len(result), 2)
- self.assertEqual(result, (counter + 1, 1))
- self.assertRaises(IndexError, result.__getitem__, -3)
- self.assertEqual(result[0], counter + 1)
- self.assertEqual(result[1], 1)
- self.assertRaises(IndexError, result.__getitem__, 2)
-
- # test bool
- self.assertTrue(result)
+ self.assertHotpMatch(result, counter, counter-1)
def test_hotp_match_w_invalid_token(self):
"""verify() -- invalid HotpMatch object"""
otp = HOTP(KEY3)
counter = 41230981
token = '775167'
- self.assertRaises(exc.InvalidTokenError, otp.verify, token, counter+1)
+ self.assertRaises(exc.UsedTokenError, otp.verify, token, counter+1)
#=============================================================================
# verify()
@@ -1921,38 +1873,40 @@ class HotpTest(_BaseOTPTest):
def test_verify_w_window(self, for_consume=False):
"""verify() -- 'counter' & 'window' parameters"""
# init generator
- counter = randcounter()
otp = self.randotp()
if for_consume:
verify = self._create_consume_wrapper(otp)
else:
verify = otp.verify
+ counter = randcounter()
token = otp.generate(counter)
# init test helper
- def test(valid, counter_offset, token, counter, **kwds):
+ def assertMatched(matched, token, counter, **kwds):
"""helper to test verify() output"""
# NOTE: HotpMatch return type tested more throughly above ^^^
- if valid:
- result = verify(token, counter, **kwds)
- self.assertTrue(result)
- self.assertEqual(result.next_counter, counter + 1 + counter_offset)
- self.assertEqual(result.counter_skipped, counter_offset)
- else:
- self.assertRaises(exc.InvalidTokenError, verify, token, counter, **kwds)
+ result = verify(token, counter, **kwds)
+ self.assertHotpMatch(result, matched=matched, expected=counter)
# validate against previous counter step (passes if window >= 1)
- test(False, 0, token, counter-1, window=0)
- test(True, 1, token, counter-1) # window=1 is default
- test(True, 1, token, counter-1, window=2)
+ self.assertRaises(exc.InvalidTokenError, verify, token, counter - 1, window=0)
+ assertMatched(counter, token, counter - 1) # window=1 is default
+ assertMatched(counter, token, counter - 1, window=2)
# validate against current counter step
- test(True, 0, token, counter, window=0)
+ assertMatched(counter, token, counter, window=0)
+
+ # validate against next counter step --
+ # should never pass; should detect token as recently 'used'
+ self.assertRaises(exc.UsedTokenError, verify, token, counter + 1, window=0)
+ self.assertRaises(exc.UsedTokenError, verify, token, counter + 1) # window=1 is default
+ self.assertRaises(exc.UsedTokenError, verify, token, counter + 1, window=2)
- # validate against next counter step (should never pass)
- test(False, 0, token, counter+1, window=0)
- test(False, 0, token, counter+1) # window=1 is default
- test(False, 0, token, counter+1, window=2)
+ # validate against counter step + 2 --
+ # should never pass; but not detect token was recently 'used'
+ self.assertRaises(exc.InvalidTokenError, verify, token, counter + 2, window=0)
+ self.assertRaises(exc.InvalidTokenError, verify, token, counter + 2) # window=1 is default
+ self.assertRaises(exc.InvalidTokenError, verify, token, counter + 2, window=2)
def test_verify_w_token_normalization(self, for_consume=False):
"""verify() -- token normalization"""
@@ -1965,7 +1919,7 @@ class HotpTest(_BaseOTPTest):
# separators / spaces should be stripped (orig token '049644')
counter = 2889830
- correct = (counter + 1, 0)
+ correct = (counter, counter)
self.assertEqual(verify(' 0 49-644 ', counter), correct)
# ascii bytes
@@ -1994,9 +1948,7 @@ class HotpTest(_BaseOTPTest):
# token should match counter *exactly*
result = verify(token, counter, window=0)
- self.assertTrue(result)
- self.assertEqual(result.next_counter, counter+1, msg=msg) # NOTE: will report *next* counter valid
- self.assertEqual(result.counter_skipped, 0, msg=msg)
+ self.assertHotpMatch(result, counter, counter, msg=msg)
# should NOT verify against another counter
self.assertRaises(exc.InvalidTokenError, verify, token, counter + 100, window=0)
@@ -2010,12 +1962,9 @@ class HotpTest(_BaseOTPTest):
which makes it's signature & return match verify(),
to helper out shared test code.
"""
- from passlib.totp import HotpMatch
- def wrapper(token, counter=None, **kwds):
+ def wrapper(token, counter, **kwds):
otp.counter = counter
- valid = otp.consume(token, **kwds)
- self.assertIs(valid, True)
- return HotpMatch(otp.counter, counter)
+ return otp.consume(token, **kwds)
return wrapper
def test_consume_w_window(self):
@@ -2044,7 +1993,7 @@ class HotpTest(_BaseOTPTest):
# reverify should reject token, leaving counter & dirty flag alone.
otp.counter = counter + 1
otp.changed = False
- self.assertRaises(exc.InvalidTokenError, otp.consume, token)
+ self.assertRaises(exc.UsedTokenError, otp.consume, token)
self.assertEqual(otp.counter, counter + 1)
self.assertFalse(otp.changed)
diff --git a/passlib/totp.py b/passlib/totp.py
index d918569..f8f2b4d 100644
--- a/passlib/totp.py
+++ b/passlib/totp.py
@@ -163,132 +163,6 @@ def _decode_bytes(key, format):
else:
raise ValueError("unknown byte-encoding format: %r" % (format,))
-#-----------------------------------------------------------------------------
-# offset / clock drift helpers
-#-----------------------------------------------------------------------------
-
-#: default offset preferred by suggest_offset()
-#: attempts to account for time taken for user to enter token + transmission delay.
-#: value is avg of 'history1' sample in the unittests.
-DEFAULT_OFFSET = 0
-
-def suggest_offset(history, period=30, target=None, default=None):
- """
- Given a history of previous verification offsets,
- calculate offset that should be used for specified timestamp.
- This is used by :meth:`verify` and :meth:`consume`.
-
- :param history:
- List of 0+ ``(timestamp, counter_offset)`` entries.
-
- :param period:
- Counter period in seconds (defaults to 30).
-
- :param target:
- Timestamp that resulting offset should target (defaults to the current time).
-
- :param default:
- Default offset if there are no history entries;
- also used as starting seed. for calculations.
-
- :returns:
- Suggested offset to use when verifying at specified time.
- """
- # NOTE: ``target`` param currently unused, reserved for future algorithm
- # which might attempt to utilize timestamp data to account for client clock drift.
-
- # XXX: This function could use a lot of improvement.
- #
- # The Problem
- # -----------
- # The problem this function is trying to solve is to find an estimate for the client
- # offset at time <target>, given a list of known (time, counter_skipped) values from previously
- # successful authentications. An ideal solution would use some method (e.g. linear regression)
- # to estimate the client clock drift and skew, and correctly predict the offset
- # we need for the target timestamp.
- #
- # However, all we know for each (time, counter_skipped) pair is that the actual offset at that
- # point in time lies somewhere in the half-closed interval:
- # ``[counter_start - time, counter_end - time)``
- # ... which can be reduced to:
- # ``[min_offset, min_offset + period)``
- # .. where min_offset is:
- # ``counter = time // period``,
- # ``min_offset = (counter + counter_skipped) * period - time``
- #
- # Further complicating things, the actual offset is not just a function of the client clock skew,
- # but also includes a random amount of transmission delay (including time taken by the user
- # to enter the token).
- #
- # Thus any proper solution would need to predict a best fit line across a set of intervals,
- # not just datapoints, minimizing drift, while ignoring outliers.
- #
- # Current Algorithm
- # -----------------
- # For now, mostly punting on this problem.
- # Current code just takes the average & stddev of the intervals,
- # and returns value in interval ``avg +- sigma`` which is nearest ``default``.
-
- # use default offset
- if default is None:
- default = DEFAULT_OFFSET
-
- # fallback for empty list
- if not history:
- return default
-
- # helpers
- def calc_min_offset(time, counter_skipped):
- return counter_skipped * period - divmod(int(time), period)[1]
-
- # convert to list of min_offset values -- more useful for current algorithm
- half_period = period // 2
- min_offsets = [calc_min_offset(time, diff) for time, diff in history]
- ##log.debug("suggest_offsets(): midpoints=%r",
- ## [min_offset+half_period for min_offset in min_offsets])
-
- # calc average & stddev of min_offset values
- hsize = len(history)
- avg = sum(min_offsets) // hsize
- if hsize > 2:
- _total = sum((min_offset - avg) ** 2 for min_offset in min_offsets)
- sigma = int((_total // (hsize - 1)) ** 0.5)
- else:
- # too few samples for stddev to be reliable
- # (*need* at least 2, but < 3 seems to fluctuate too much for this purpose)
- sigma = half_period
-
- # add half period so that avg of min_offset is now
- # avg midpoint of the [min_offset, max_offset) intervals
- avg += half_period
-
- # keep result within 1/2 of sigma or interval size, whichever is smaller.
- # using full sigma or interval size seems to add too much variability in output.
- bounds = min(sigma, half_period)//2
-
- # use default if within bounds of avg,
- # otherwise use whichever of ``avg +- bounds`` is closest to default.
- ##log.debug("suggest_offsets(): avg=%r, radius=%r, sigma=%r, bound=%r",
- ## avg, half_period, sigma, bounds)
- if abs(default - avg) <= bounds:
- return default
- elif avg < default:
- return avg + bounds
- else:
- return avg - bounds
-
-# def _debug_suggested_offset(data, default=None):
-# """dev helper for debugging suggested_offset() behavior"""
-# from crowbar.math import analyze_values
-# for window in range(1, len(data)+1):
-# result = []
-# offset = default # simulate offset being carried through a rolling window
-# for idx in range(len(data)-window+1):
-# offset = suggest_offset(data[idx:idx+window], default=offset)
-# result.append(offset)
-# stats = analyze_values(result)
-# print "{:2d} {:2.0f} {:2.2f} {!r}".format(window, stats.mean, stats.stdev, result)
-
#=============================================================================
# OTP management
#=============================================================================
@@ -386,7 +260,7 @@ class OTPContext(object):
salt_size = 12
#: default cost (log2 of pbkdf2 rounds) for encrypt_key() output
- cost = 13
+ cost = 14
#: map of secret tag -> secret bytes
_secrets = None
@@ -565,25 +439,6 @@ class OTPContext(object):
#========================================================================
@staticmethod
- def _cipher_xor_key(value, secret, salt, cost, decrypt=False):
- """
- Internal helper that handles lowlevel encryption/decryption.
-
- This uses PBKDF2-HMAC-SHA256 to generate <value> bytes of data,
- which are XORed against <value> to encrypt/decrypt it.
-
- This scheme was originally present to act as a fallback when AES
- wasn't available, but was disabled before the 1.7 release due to
- concerns with the construction (e.g. http://crypto.stackexchange.com/questions/1957/can-pbkdf2-be-used-to-create-an-xor-cipher-key-to-encrypt-random-plaintext),
- and a wish to strongly encourage AES use.
-
- It's only present for backward compatibility with some beta deployments.
- """
- mask = pbkdf2_hmac("sha256", secret, salt=salt, rounds=(1 << cost),
- keylen=len(value))
- return xor_bytes(value, mask)
-
- @staticmethod
def _cipher_aes_key(value, secret, salt, cost, decrypt=False):
"""
Internal helper that handles lowlevel encryption/decryption.
@@ -681,9 +536,6 @@ class OTPContext(object):
needs_recrypt = False
if version == 1:
_cipher_key = self._cipher_aes_key
- elif version == 0:
- _cipher_key = self._cipher_xor_key
- needs_recrypt = AES_SUPPORT
else:
raise ValueError("missing / unrecognized 'enckey' version: %r" % (version,))
tag = enckey['t']
@@ -1488,36 +1340,52 @@ class HotpMatch(SequenceMixin):
"""
Object returned by :meth:`HOTP.verify` on a successful match.
- It can be treated as a tuple of ``(next_counter, counter_skipped)``,
+ It can be treated as a tuple of ``(counter, expected_counter)``,
or accessed via the following attributes:
+ .. autoattribute:: counter
+ :annotation: = 0
+
+ .. autoattribute:: expected_counter
+ :annotation: = 0
+
.. autoattribute:: next_counter
- .. autoattribute:: counter_skipped
- .. autoattribute:: previous_counter
+ :annotation: = .counter + 1
- It will always have a ``True`` boolean value.
+ .. autoattribute:: skipped
+ :annotation: = 0
"""
- #: new HOTP counter value (1 + matched counter value)
- next_counter = 0
+ #: HOTP counter value that matched token
+ counter = 0
+
+ #: Previous HOTP counter value
+ expected_counter = 0
- #: previous HOTP counter value
- previous_counter = 0
+ def __init__(self, counter, expected_counter):
+ self.counter = counter
+ self.expected_counter = expected_counter
- def __init__(self, next_counter, previous_counter):
- self.next_counter = next_counter
- self.previous_counter = previous_counter
+ @memoized_property
+ def next_counter(self):
+ """
+ New HOTP counter value.
+ """
+ return self.counter + 1
@memoized_property
- def counter_skipped(self):
+ def skipped(self):
"""
- how many steps were skipped between expected
- and actual matched counter values
+ How many steps between expected and matched counter values.
+ Always >= 0.
"""
- return self.next_counter - 1 - self.previous_counter
+ return self.counter - self.expected_counter
def _as_tuple(self):
- return self.next_counter, self.counter_skipped
+ return self.counter, self.expected_counter
+
+ def __repr__(self):
+ return "<HotpMatch counter=%d expected_counter=%d>" % self._as_tuple()
class HOTP(BaseOTP):
"""Helper for generating and verifying HOTP codes.
@@ -1732,8 +1600,13 @@ class HOTP(BaseOTP):
"""
counter = self._normalize_counter(counter)
self._check_serial(window, "window")
- match = self._find_match(token, counter, counter + window + 1)
- return HotpMatch(match + 1, counter)
+ last_counter = counter - 1
+ matched = self._find_match(token, last_counter, counter + window + 1,
+ expected=counter)
+ if matched == last_counter:
+ raise UsedTokenError("Token has already been used, please generate for another.")
+ assert matched > last_counter, "sanity check failed: counter went backward"
+ return HotpMatch(matched, counter)
def consume(self, token, window=1):
"""
@@ -1781,11 +1654,10 @@ class HOTP(BaseOTP):
1000
"""
counter = self.counter
- result = self.verify(token, counter, window=window)
- self.counter = result.next_counter
+ match = self.verify(token, counter, window=window)
+ self.counter = match.next_counter
self.changed = True
- # XXX: return result instead? would only provide .skipped as extra data.
- return True
+ return match
# TODO: resync(self, tokens, counter, window=100)
# helper to re-synchronize using series of sequential tokens,
@@ -1870,9 +1742,6 @@ class TotpToken(SequenceMixin):
self.token = token
self.counter = counter
- def _as_tuple(self):
- return self.token, self.expire_time
-
# @memoized_property
# def start_time(self):
# """Timestamp marking beginning of period when token is valid"""
@@ -1893,6 +1762,14 @@ class TotpToken(SequenceMixin):
"""whether token is still valid"""
return bool(self.remaining)
+ def _as_tuple(self):
+ return self.token, self.expire_time
+
+ def __repr__(self):
+ expired = "" if self.remaining else " expired"
+ return "<TotpToken token='%s' expire_time=%d%s>" % \
+ (self.token, self.expire_time, expired)
+
class TotpMatch(SequenceMixin):
"""
Object returned by :meth:`TOTP.verify` on a successful match.
@@ -1912,50 +1789,47 @@ class TotpMatch(SequenceMixin):
It will always have a ``True`` boolean value.
"""
- #: TOTP counter value which token matched against.
- #: (Best practice it to subsequently ignore tokens for this counter
- #: and earlier)
+ #: TOTP counter value which matched token.
+ #: (Best practice is to subsequently ignore tokens matching this counter
+ #: or earlier)
counter = 0
#: Timestamp when verification was performed.
time = 0
- #: Previous offset value provided when verify() was called.
- previous_offset = 0
-
#: TOTP period (needed internally to calculate min_offset, etc).
- _period = 30
+ period = 30
- def __init__(self, time, counter, previous_offset, period):
+ def __init__(self, counter, time, # *
+ period=30):
"""
.. warning::
the constructor signature is an internal detail, and is subject to change.
"""
- self.time = time
self.counter = counter
- self.previous_offset = previous_offset
- self._period = period
+ self.time = time
+ self.period = period
@memoized_property
- def counter_skipped(self):
+ def expected_counter(self):
"""
- How many steps were skipped between expected and actual matched counter
- value.
-
- Expected value is the counter step at :attr:`time`.
+ Counter value expected for timestamp.
"""
- return self.counter - self.time // self._period
+ return self.time // self.period
@memoized_property
- def next_offset(self):
+ def skipped(self):
"""
- Suggested offset value for next time a token is verified from this client.
+ How many steps were skipped between expected and actual matched counter
+ value (may be positive, zero, or negative).
"""
- return suggest_offset(history=[(self.time, self.counter_skipped)],
- period=self._period, default=self.previous_offset)
+ return self.counter - self.expected_counter
def _as_tuple(self):
- return self.counter, self.next_offset
+ return self.counter, self.time
+
+ def __repr__(self):
+ return "<TotpMatch counter=%d time=%d>" % self._as_tuple()
class TOTP(BaseOTP):
"""Helper for generating and verifying TOTP codes.
@@ -2046,11 +1920,6 @@ class TOTP(BaseOTP):
#: otpauth type this class implements
type = "totp"
- #: max history buffer size
- # NOTE: picked based on average size that suggest_offset() algorithm
- # needs to settle down on predicted value, using `history1` from unittest as reference.
- MAX_HISTORY_SIZE = 8
-
#=============================================================================
# instance attrs
#=============================================================================
@@ -2072,21 +1941,13 @@ class TOTP(BaseOTP):
#: or validated by :meth:`consume` *(server-side)*.
last_counter = 0
- #: *(server-side only)* history of previous verifications performed by :meth:`consume`,
- #: and is used to estimate the **delay** parameter on a per-client basis.
- #:
- #: this is an internal attribute whose structure is subject to change,
- #: but currently is a list of 1 or more ``(timestamp, counter_skipped)`` entries.
- #: it's maximum size is controlled by the class attribute ``TOTP.MAX_HISTORY_SIZE``.
- _history = None
-
#=============================================================================
# init
#=============================================================================
def __init__(self, key=None, format="base32",
# keyword only...
period=None,
- last_counter=0, _history=None,
+ last_counter=0,
now=None, # NOTE: mainly used for unittesting
**kwds):
# call BaseOTP to handle common options
@@ -2108,11 +1969,6 @@ class TOTP(BaseOTP):
self._check_serial(last_counter, "last_counter")
self.last_counter = last_counter
- # init history
- if _history:
- # TODO: run sanity check on structure of history object
- self._history = _history
-
#=============================================================================
# token management
#=============================================================================
@@ -2152,7 +2008,6 @@ class TOTP(BaseOTP):
convert timestamp to HOTP counter using :attr:`period`.
input is passed through :meth:`normalize_time`.
"""
- time = self.normalize_time(time)
if time < 0:
raise ValueError("time must be >= 0")
return time // self.period
@@ -2192,6 +2047,7 @@ class TOTP(BaseOTP):
(such as the :attr:`last_counter` value).
For a version which does, see :meth:`advance`.
"""
+ time = self.normalize_time(time)
counter = self._time_to_counter(time)
token = self._generate(counter)
return TotpToken(self, token, counter)
@@ -2269,7 +2125,7 @@ class TOTP(BaseOTP):
# token verification
#-------------------------------------------------------------------------
- def verify(self, token, time=None, window=30, offset=0, min_start=0):
+ def verify(self, token, time=None, window=30, skew=0, last_counter=-1, reuse=False):
"""
Low-level method to validate TOTP token against specified timestamp.
Searches within a window before & after the provided time,
@@ -2336,16 +2192,26 @@ class TOTP(BaseOTP):
time = self.normalize_time(time)
self._check_serial(window, "window")
- # NOTE: 'min_start' is internal parameter used by consume() to
- # skip searching any counter values before last confirmed verification.
- client_time = time + offset
- start = max(min_start, self._time_to_counter(client_time - window))
+ client_time = time + skew
+ start = max(last_counter, self._time_to_counter(client_time - window))
end = self._time_to_counter(client_time + window) + 1
+ # XXX: could pass 'expected = _time_to_counter(client_time + TRANSMISSION_DELAY)'
+ # to the _find_match() method, would help if window set large.
counter = self._find_match(token, start, end)
- return TotpMatch(time, counter, offset, self.period)
+ assert counter >= last_counter, "sanity check failed: counter went backward"
+
+ if not reuse and counter == last_counter:
+ raise UsedTokenError("Token has already been used, please wait for another.",
+ expire_time=(last_counter + 1) * self.period)
+
+ # NOTE: By returning match tied to <time>, not <client_time>, we're
+ # causing .skipped to reflect the observed skew, independent of
+ # the 'skew' param. This is deliberately done so that caller
+ # can use historical .skipped values to estimate future skew.
+ return TotpMatch(counter, time, self.period)
- def consume(self, token, reuse=False, window=30, offset=None):
+ def consume(self, token, reuse=False, window=30, skew=0):
"""
High-level method to validate TOTP token against current system time.
Unlike :meth:`verify`, this method takes into account the :attr:`last_counter` value,
@@ -2417,49 +2283,22 @@ class TOTP(BaseOTP):
InvalidTokenError: Token did not match
"""
time = self.normalize_time(None)
- if offset is None:
- offset = self._next_offset(time)
# NOTE: setting min_start so verify() doesn't even bother checking
# points before the last verified counter, no matter what offset or window is set to.
- result = self.verify(token, time, window=window, offset=offset, min_start=self.last_counter)
- assert result.time == time, "sanity check failed: verify().time didn't match input time"
- assert result.counter >= self.last_counter, "sanity check failed: 'min_start' not honored"
+ match = self.verify(token, time, window=window, skew=skew, last_counter=self.last_counter,
+ reuse=reuse)
+ assert match.time == time, "sanity check failed: verify().time didn't match input time"
+ assert match.counter >= self.last_counter, "sanity check failed: verify() didn't honor last_counter"
+ assert reuse or match.counter != self.last_counter
- if result.counter > self.last_counter:
+ if match.counter != self.last_counter:
# accept new token, update internal state
- self.last_counter = result.counter
- self._add_sample(result.time, result.counter_skipped)
+ self.last_counter = match.counter
self.changed = True
- elif not reuse:
- # re-used current period's token
- raise UsedTokenError("Token has already been used, please wait for another.",
- expire_time=(self.last_counter + 1) * self.period)
- return True
-
- def _next_offset(self, time):
- """
- internal helper for :meth:`consume` --
- return suggested offset for specified time, based on history.
- """
- return suggest_offset(self._history, self.period, time)
-
- def _add_sample(self, time, counter_skipped):
- """
- internal helper for :meth:`consume` --
- appends an entry to the verification history.
- """
- history = self._history
- if history:
- # add entry to history
- history.append((time, counter_skipped))
-
- # remove old entries
- while len(history) > self.MAX_HISTORY_SIZE:
- history.pop(0)
-
- elif self.MAX_HISTORY_SIZE > 0:
- # initialize history (if it hasn't been disabled)
- self._history = [(time, counter_skipped)]
+ else:
+ assert reuse, "sanity check failed"
+ # XXX: return the match instead?
+ return match
#-------------------------------------------------------------------------
# TODO: resync(self, tokens, time=None, min_tokens=10, window=100)
@@ -2503,8 +2342,10 @@ class TOTP(BaseOTP):
state['period'] = self.period
if self.last_counter:
state['last_counter'] = self.last_counter
- if self._history:
- state['_history'] = self._history
+ # NOTE: in the future, may add a "history" parameter
+ # containing a list of (time, skipped) pairs, encoding
+ # the last X successful verifications, to allow persisting
+ # & estimating client clock skew over time.
return state
#=============================================================================