diff options
| author | Eli Collins <elic@assurancetechnologies.com> | 2016-11-07 21:38:37 -0500 |
|---|---|---|
| committer | Eli Collins <elic@assurancetechnologies.com> | 2016-11-07 21:38:37 -0500 |
| commit | c9f0d96ffb0c86013cfb5920fd8184ea40baf1ef (patch) | |
| tree | 09338eb0646c0028266dbb9abaed953fa697464c /passlib | |
| parent | d5566625e9ef818665c5a7f73ce7c5872e2b2879 (diff) | |
| download | passlib-c9f0d96ffb0c86013cfb5920fd8184ea40baf1ef.tar.gz | |
totp: no functional code changes, just combined the BaseOTP and TOTP classes,
since there's no need for the subdivision.
Diffstat (limited to 'passlib')
| -rw-r--r-- | passlib/tests/test_totp.py | 3 | ||||
| -rw-r--r-- | passlib/totp.py | 980 |
2 files changed, 453 insertions, 530 deletions
diff --git a/passlib/tests/test_totp.py b/passlib/tests/test_totp.py index c2629fd..b31356e 100644 --- a/passlib/tests/test_totp.py +++ b/passlib/tests/test_totp.py @@ -397,6 +397,9 @@ RFC_KEY_BYTES_20 = "12345678901234567890".encode("ascii") RFC_KEY_BYTES_32 = (RFC_KEY_BYTES_20*2)[:32] RFC_KEY_BYTES_64 = (RFC_KEY_BYTES_20*4)[:64] +# TODO: this class is separate from TotpTest due to historical issue, +# when there was a base class, and a separate HOTP class. +# these test case classes should probably be combined. class _BaseOTPTest(TestCase): """ common code shared by TotpTest & HotpTest diff --git a/passlib/totp.py b/passlib/totp.py index 8e93223..845bda3 100644 --- a/passlib/totp.py +++ b/passlib/totp.py @@ -54,7 +54,6 @@ __all__ = [ "UsedTokenError", # internal helper classes - "BaseOTP", "TotpToken", "TotpMatch", ] @@ -142,7 +141,7 @@ def b32decode(key): def _decode_bytes(key, format): """ - internal _BaseOTP() helper -- + internal TOTP() helper -- decodes key according to specified format. """ if format == "raw": @@ -433,7 +432,7 @@ class OTPContext(object): return TOTP.from_json(source, context=self) #======================================================================== - # encrypted key helpers -- used internally by BaseOTP + # encrypted key helpers -- used internally by TOTP #======================================================================== @staticmethod @@ -554,25 +553,22 @@ class OTPContext(object): #============================================================================= #============================================================================= -# common code shared by TOTP & HOTP +# TOTP class #============================================================================= AUTO = "auto" -class BaseOTP(object): - """ - Base class for generating and verifying OTP codes. - - .. rst-class:: inline-title - .. note:: +class TOTP(object): + """ + Helper for generating and verifying TOTP codes. - **This class shouldn't be used directly.** - It's here to provide & document common functionality - shared by the :class:`TOTP` class. - See those classes for usage instructions. + Given a secret key and set of configuration options, this object + offers methods for token generation, token validation, and serialization. + It can also be used to track important persistent TOTP state, + such as the last counter used. - :class:`TOTP` accepts the following common options + This class accepts the following options (only **key** and **format** may be specified as positional arguments). :arg str key: @@ -611,7 +607,7 @@ class BaseOTP(object): .. warning:: - Overriding the default values for ``digits`` or ``alg`` (below) may + Overriding the default values for ``digits``, ``period``, or ``alg`` (below) may cause problems with some OTP client programs (such as Google Authenticator), which may have these defaults hardcoded. @@ -628,11 +624,19 @@ class BaseOTP(object): Name of hash algorithm to use. Defaults to ``"sha1"``. ``"sha256"`` and ``"sha512"`` are also accepted, per :rfc:`6238`. + :param int period: + The time-step period to use, in integer seconds. Defaults to ``30``. + :param OTPContext context: Optional :class:`OTPContext` instance to bind this object to. If set, and application secrets are present, they will be used to encrypt the OTP key when :meth:`to_json` is invoked. + :param now: + Optional callable that should return current time for generator to use. + Default to :func:`time.time`. This optional is generally not needed, + and is mainly present for examples & unit-testing. + .. See the passlib documentation for list of attributes & methods. """ @@ -673,10 +677,23 @@ class BaseOTP(object): #: default issuer for :meth:`to_uri` issuer = None + #: number of seconds per counter step. + #: *(TOTP uses an internal time-derived counter which + #: increments by 1 every* :attr:`!period` *seconds)*. + period = 30 + + #: function to get system time in seconds, as needed by :meth:`generate` and :meth:`verify`. + #: defaults to :func:`time.time`, but can be overridden on a per-instance basis. + now = _time.time + #--------------------------------------------------------------------------- # state attrs #--------------------------------------------------------------------------- + #: counter value of last token generated by :meth:`advance` *(client-side)*, + #: or validated by :meth:`consume` *(server-side)*. + last_counter = 0 + #: flag set if internal state is modified changed = False @@ -686,13 +703,11 @@ class BaseOTP(object): def __init__(self, key=None, format="base32", # keyword only... - new=False, digits=None, alg=None, size=None, + new=False, digits=None, alg=None, size=None, period=None, label=None, issuer=None, context=None, changed=False, - **kwds): - if type(self) is BaseOTP: - raise RuntimeError("BaseOTP() shouldn't be invoked directly -- " - "use TOTP() instead") - super(BaseOTP, self).__init__(**kwds) + now=None, # NOTE: mainly used for unittesting + last_counter=0, **kwds): + super(TOTP, self).__init__(**kwds) self.changed = changed self.context = context @@ -762,6 +777,26 @@ class BaseOTP(object): self._check_issuer(issuer) self.issuer = issuer + # init period + if period is not None: + self._check_serial(period, "period", minval=1) + self.period = period + + # use custom timer -- + # intended for examples & unittests, not real-world use. + if now: + assert isinstance(now(), num_types) and now() >= 0, \ + "now() function must return non-negative int/float" + self.now = now + + # init last counter value + self._check_serial(last_counter, "last_counter") + self.last_counter = last_counter + + #============================================================================= + # helpers to verify value types & ranges + #============================================================================= + def _check_serial(self, value, param, minval=0): """ check that serial value (e.g. 'counter') is non-negative integer @@ -837,9 +872,185 @@ class BaseOTP(object): return key #============================================================================= - # token helpers + # time & token parsing + #============================================================================= + + # XXX: could be class/static method if not for the .now parameter + def normalize_time(self, time): + """ + Normalize time value to unix epoch seconds. + + :arg time: + Can be ``None``, :class:`!datetime`, + or unix epoch timestamp as :class:`!float` or :class:`!int`. + If ``None``, uses current system time. + Naive datetimes are treated as UTC. + + :returns: + unix epoch timestamp as :class:`int`. + """ + if isinstance(time, int_types): + return time + elif isinstance(time, float): + return int(time) + elif time is None: + return int(self.now()) + elif hasattr(time, "utctimetuple"): + # coerce datetime to UTC timestamp + # NOTE: utctimetuple() assumes naive datetimes are in UTC + # NOTE: we explicitly *don't* want microseconds. + return calendar.timegm(time.utctimetuple()) + else: + raise exc.ExpectedTypeError(time, "int, float, or datetime", "time") + + def _time_to_counter(self, time): + """ + convert timestamp to HOTP counter using :attr:`period`. + input is passed through :meth:`normalize_time`. + """ + if time < 0: + raise ValueError("time must be >= 0") + return time // self.period + + def normalize_token(self, token): + """ + normalize OTP token representation: + strips whitespace, converts integers to zero-padded string, + validates token content & number of digits. + + :arg token: + token as ascii bytes, unicode, or an integer. + + :raises ValueError: + if token has wrong number of digits, or contains non-numeric characters. + + :returns: + token as unicode string containing only digits 0-9. + """ + digits = self.digits + if isinstance(token, int_types): + token = u("%0*d") % (digits, token) + else: + token = to_unicode(token, param="token") + token = _clean_re.sub(u(""), token) + if not token.isdigit(): + raise MalformedTokenError("Token must contain only the digits 0-9") + if len(token) != digits: + raise MalformedTokenError("Token must have exactly %d digits" % digits) + return token + + #============================================================================= + # token generation #============================================================================= +# # debug helper +# def generate_range(self, size, time=None): +# counter = self._time_to_counter(time) - (size + 1) // 2 +# end = counter + size +# while counter <= end: +# token = self._generate(counter) +# yield TotpToken(self, token, counter) +# counter += 1 + + def generate(self, time=None): + """ + Low-level method to generate token for specified time. + + :arg time: + Can be ``None``, :class:`!datetime`, + or unix epoch timestamp as :class:`!float` or :class:`!int`. + If ``None`` (the default), uses current system time. + Naive datetimes are treated as UTC. + + :returns: + + sequence of ``(token, expire_time)`` (actually a :class:`TotpToken` instance): + + * ``token`` -- decimal-formatted token as a (unicode) string + * ``expire_time`` -- unix epoch time when token will expire + + Usage example:: + + >>> # generate a new token, wrapped in a TotpToken instance... + >>> otp = TOTP('s3jdvb7qd2r7jpxx') + >>> otp.generate(1419622739) + <TotpToken token='897212' expire_time=1419622740> + + >>> # when you just need the token... + >>> otp.generate(1419622739).token + '897212' + + .. seealso:: + This is a lowlevel method, which doesn't read or modify any state-dependant values + (such as the :attr:`last_counter` value). + """ + time = self.normalize_time(time) + counter = self._time_to_counter(time) + token = self._generate(counter) + return TotpToken(self, token, counter) + + def advance(self, reuse=False): + """ + High-level method to generate TOTP token for current time. + Unlike :meth:`generate`, this method takes into account the :attr:`last_counter` value, + and updates that attribute to match the returned token. + + :param reuse: + Controls whether a token can be issued twice within the same time :attr:`period`. + + By default (``False``), calling this method twice within the same time :attr:`period` + will result in a :exc:`~passlib.exc.UsedTokenError`, since once a token has gone across the wire, + it should be considered insecure. + + Setting this to ``True`` will allow multiple uses of the token within the same time period. + + :raises ~passlib.exc.UsedTokenError: + + if an attempt is made to generate a token within the same time :attr:`period` + (suppressed by ``reuse=True``). + + :returns: + + sequence of ``(token, expire_time)`` (actually a :class:`TotpToken` instance): + + * ``token`` -- decimal-formatted token as a (unicode) string + * ``expire_time`` -- unix epoch time when token will expire + + Usage example:: + + >>> # IMPORTANT: THE 'now' PARAMETER SHOULD NOT BE USED IN PRODUCTION. + >>> # It's only used here to fix the totp generator's clock, so that + >>> # this example can be reproduced regardless of the actual system time. + + >>> # generate new token, wrapped in a TotpToken instance... + >>> totp = TOTP('s3jdvb7qd2r7jpxx', now=lambda : 1419622739) + >>> totp.advance() + <TotpToken token='897212' expire_time=1419622740> + + >>> # or use attr access when you just need the token ... + >>> totp.advance().token + '897212' + """ + time = self.normalize_time(None) + result = self.generate(time) + + if result.counter < self.last_counter: + # NOTE: this usually means system time has jumped back since last call. + # this will occasionally happen, so not throwing an error, + # but definitely worth issuing a warning. + warn("TOTP.advance(): current time (%r) earlier than last-used time (%r); " + "did system clock change?" % (int(time), self.last_counter * self.period), + exc.PasslibSecurityWarning, stacklevel=1) + + elif result.counter == self.last_counter and not reuse: + raise UsedTokenError("Token already generated in this time period, " + "please wait %d seconds for another." % result.remaining, + expire_time=result.expire_time) + + self.last_counter = result.counter + self.changed = True + return result + def _generate(self, counter): """ base implementation of HOTP token generation algorithm. @@ -867,32 +1078,208 @@ class BaseOTP(object): assert 0 < digits < 11, "digits: sanity check failed" return (u("%0*d") % (digits, value))[-digits:] - def normalize_token(self, token): + #============================================================================= + # token verification + #============================================================================= + + def verify(self, token, time=None, window=30, skew=0, last_counter=-1, reuse=False): """ - normalize OTP token representation: - strips whitespace, converts integers to zero-padded string, - validates token content & number of digits. + Low-level method to validate TOTP token against specified timestamp. + Searches within a window before & after the provided time, + in order to account for transmission delay and small amounts of skew in the client's clock. :arg token: - token as ascii bytes, unicode, or an integer. + Token to validate. + may be integer or string (whitespace and hyphens are ignored). - :raises ValueError: - if token has wrong number of digits, or contains non-numeric characters. + :param time: + Unix epoch timestamp, can be any of :class:`!float`, :class:`!int`, or :class:`!datetime`. + if ``None`` (the default), uses current system time. + *this should correspond to the time the token was received from the client*. + + :param int window: + How far backward and forward in time to search for a match. + Measured in seconds. Defaults to ``30``. Typically only useful if set + to multiples of :attr:`period`. + + :param int skew: + Adjust timestamp by specified value, to account for excessive + client clock skew. Measured in seconds. Defaults to ``0``. + + Negative skew (the common case) indicates transmission delay, + and/or that the client clock is running behind the server. + + Positive skew indicates the client clock is running ahead of the server + (and by enough that it cancels out any negative skew added by + the transmission delay). + + You should ensure the server clock uses a reliable time source such as NTP, + so that only the client clock's inaccuracy needs to be accounted for. + + This is an advanced parameter that should usually be left at ``0``; + The **window** parameter is usually enough to account + for any observed transmission delay. + + :param last_counter: + Optional value of last counter value that was successfully used. + If specified, verify will never search earlier counters, + no matter how large the window is. + + Useful when client has previously authenticated, + and thus should never provide a token older than previously + verified value. + + :param bool reuse: + Controls whether a token can be issued twice within the same time :attr:`period`. + + By default (``False``), attempting to verify the same token twice within the same time :attr:`period` + will result in a :exc:`~passlib.exc.TokenReuseError`. + Setting this to ``True`` will silently allow multiple uses of the token within the same time period. + + Note that enabling this exposes your application to a replay attack: + if an attacker is able to read the token (whether physically + as the user types it, or going across the wire), the attacker + will be able to re-use any time over the next <period> seconds. + + :raises ~passlib.exc.TokenError: + + If the token is malformed, or fails to verify. + + :returns TotpMatch: + + Returns a :class:`TotpMatch` instance on successful match. + Can be treated as tuple of ``(counter, time)``. + Raises error if token is malformed / can't be verified. + + Usage example:: + + >>> totp = TOTP('s3jdvb7qd2r7jpxx') + + >>> # valid token for this time period + >>> totp.verify('897212', 1419622729) + <TotpMatch counter=47320757 time=1419622729> + + >>> # token from counter step 30 sec ago (within allowed window) + >>> totp.verify('000492', 1419622729) + <TotpMatch counter=47320756 time=1419622729> + + >>> # invalid token -- token from 60 sec ago (outside of window) + >>> totp.verify('760389', 1419622729) + Traceback: + ... + InvalidTokenError: Token did not match + + .. seealso:: + This is a low-level method, which doesn't read or modify any state-dependant values + (such as the :attr:`last_counter` value). + For a version which does, see :meth:`consume`. + """ + time = self.normalize_time(time) + self._check_serial(window, "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) + 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, 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, + and updates that attribute if a match is found. + + :arg token: + token to validate. + may be integer or string (whitespace and hyphens are ignored). + + :param bool reuse: + Controls whether a token can be issued twice within the same time :attr:`period`. + + By default (``False``), attempting to verify the same token twice within the same time :attr:`period` + will result in a :exc:`~passlib.exc.TokenReuseError`. + Setting this to ``True`` will silently allow multiple uses of the token within the same time period. + + Note that enabling this exposes your application to a replay attack: + if an attacker is able to read the token (whether physically + as the user types it, or going across the wire), the attacker + will be able to re-use any time over the next <period> seconds. + + :param int window: + How far backward and forward in time to search for a match. + Measured in seconds. Defaults to ``30``. Typically only useful if set + to multiples of :attr:`period`. + + :raises ~passlib.exc.TokenError: + + If the token is malformed, fails to verify, + or an attempt is made to re-use the current time period's token + (this last check can be suppressed by ``reuse=True``) :returns: - token as unicode string containing only digits 0-9. + If token validated, returns the :class:`HotpMatch` instance from the underlying :meth:`verify` call. + Raise errors on invalid/malformed tokens. + + May set the :attr:`changed` attribute if the internal state was updated, + and needs to be re-persisted by the application (see :meth:`to_json`). + + Usage example:: + + >>> # IMPORTANT: THE 'now' PARAMETER SHOULD NOT BE USED IN PRODUCTION. + >>> # It's only used here to fix the totp generator's clock, so that + >>> # this example can be reproduced regardless of the actual system time. + >>> totp = TOTP('s3jdvb7qd2r7jpxx', now = lambda: 1419622739) + + >>> # wrong token + >>> totp.consume('123456') + Traceback: + ... + InvalidTokenError: Token did not match + + >>> # token from 30 sec ago (w/ window, will be accepted) + >>> totp.consume('000492') + <TotpMatch counter=47320756 time=1419622729> + + >>> # token from current period + >>> totp.consume('897212') + <TotpMatch counter=47320757 time=1419622729> + + >>> # token from 30 sec ago will now be rejected + >>> totp.consume('000492') + Traceback: + ... + InvalidTokenError: Token did not match """ - digits = self.digits - if isinstance(token, int_types): - token = u("%0*d") % (digits, token) + time = self.normalize_time(None) + # 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. + 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 match.counter != self.last_counter: + # accept new token, update internal state + self.last_counter = match.counter + self.changed = True else: - token = to_unicode(token, param="token") - token = _clean_re.sub(u(""), token) - if not token.isdigit(): - raise MalformedTokenError("Token must contain only the digits 0-9") - if len(token) != digits: - raise MalformedTokenError("Token must have exactly %d digits" % digits) - return token + assert reuse, "sanity check failed" + # XXX: return the match instead? + return match def _find_match(self, token, start, end, expected=None): """ @@ -938,6 +1325,14 @@ class BaseOTP(object): counter += 1 raise InvalidTokenError() + #------------------------------------------------------------------------- + # TODO: resync(self, tokens, time=None, min_tokens=10, window=100) + # helper to re-synchronize using series of sequential tokens, + # all of which must validate; per RFC recommendation. + # NOTE: need to make sure this function is constant time + # (i.e. scans ALL tokens, and doesn't short-circuit after first mismatch) + #------------------------------------------------------------------------- + #============================================================================= # uri parsing #============================================================================= @@ -1020,7 +1415,7 @@ class BaseOTP(object): @classmethod def _adapt_uri_params(cls, label=None, secret=None, issuer=None, - digits=None, algorithm=None, + digits=None, algorithm=None, period=None, **extra): """ from_uri() helper -- @@ -1034,6 +1429,8 @@ class BaseOTP(object): kwds['digits'] = cls._uri_parse_int(digits, "digits") if algorithm: kwds['alg'] = algorithm + if period: + kwds['period'] = cls._uri_parse_int(period, "period") if extra: # malicious uri, deviation from spec, or newer revision of spec? # in either case, we issue warning and ignore extra params. @@ -1142,6 +1539,8 @@ class BaseOTP(object): args.append(("algorithm", self.alg.upper())) if self.digits != 6: args.append(("digits", str(self.digits))) + if self.period != 30: + args.append(("period", str(self.period))) return args #============================================================================= @@ -1266,6 +1665,14 @@ class BaseOTP(object): state['enckey'] = enckey else: state['key'] = self.base32_key + if self.period != 30: + state['period'] = self.period + if self.last_counter: + state['last_counter'] = self.last_counter + # 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 #============================================================================= @@ -1273,7 +1680,7 @@ class BaseOTP(object): #============================================================================= #============================================================================= -# TOTP helper +# TOTP helpers #============================================================================= class TotpToken(SequenceMixin): """ @@ -1396,493 +1803,6 @@ class TotpMatch(SequenceMixin): def __repr__(self): return "<TotpMatch counter=%d time=%d>" % self._as_tuple() -class TOTP(BaseOTP): - """Helper for generating and verifying TOTP codes. - - Given a secret key and set of configuration options, this object - offers methods for token generation, token validation, and serialization. - It can also be used to track important persistent TOTP state, - such as the last counter used. - - In addition to the :ref:`BaseOTP Constructor Options <baseotp-constructor-options>`, - this class accepts the following extra parameters: - - :param int period: - The time-step period to use, in integer seconds. Defaults to ``30``. - - :param now: - Optional callable that should return current time for generator to use. - Default to :func:`time.time`. This optional is generally not needed, - and is mainly present for examples & unit-testing. - - .. warning:: - - Overriding the default values for ``digits``, ``period``, or ``alg`` may - cause problems with some OTP client programs. For instance, Google Authenticator - claims it's defaults are hard-coded. - - .. - See the passlib documentation for a full list of attributes & methods. - """ - #============================================================================= - # instance attrs - #============================================================================= - - #: function to get system time in seconds, as needed by :meth:`generate` and :meth:`verify`. - #: defaults to :func:`time.time`, but can be overridden on a per-instance basis. - now = _time.time - - #: number of seconds per counter step. - #: *(TOTP uses an internal time-derived counter which - #: increments by 1 every* :attr:`!period` *seconds)*. - period = 30 - - #--------------------------------------------------------------------------- - # state attrs - #--------------------------------------------------------------------------- - - #: counter value of last token generated by :meth:`advance` *(client-side)*, - #: or validated by :meth:`consume` *(server-side)*. - last_counter = 0 - - #============================================================================= - # init - #============================================================================= - def __init__(self, key=None, format="base32", - # keyword only... - period=None, - last_counter=0, - now=None, # NOTE: mainly used for unittesting - **kwds): - # call BaseOTP to handle common options - super(TOTP, self).__init__(key, format, **kwds) - - # use custom timer -- - # intended for examples & unittests, not real-world use. - if now: - assert isinstance(now(), num_types) and now() >= 0, \ - "now() function must return non-negative int/float" - self.now = now - - # init period - if period is not None: - self._check_serial(period, "period", minval=1) - self.period = period - - # init last counter value - self._check_serial(last_counter, "last_counter") - self.last_counter = last_counter - - #============================================================================= - # token management - #============================================================================= - - #------------------------------------------------------------------------- - # internal helpers - #------------------------------------------------------------------------- - # XXX: could be class/static method if not for the .now parameter - def normalize_time(self, time): - """ - Normalize time value to unix epoch seconds. - - :arg time: - Can be ``None``, :class:`!datetime`, - or unix epoch timestamp as :class:`!float` or :class:`!int`. - If ``None``, uses current system time. - Naive datetimes are treated as UTC. - - :returns: - unix epoch timestamp as :class:`int`. - """ - if isinstance(time, int_types): - return time - elif isinstance(time, float): - return int(time) - elif time is None: - return int(self.now()) - elif hasattr(time, "utctimetuple"): - # coerce datetime to UTC timestamp - # NOTE: utctimetuple() assumes naive datetimes are in UTC - # NOTE: we explicitly *don't* want microseconds. - return calendar.timegm(time.utctimetuple()) - else: - raise exc.ExpectedTypeError(time, "int, float, or datetime", "time") - - def _time_to_counter(self, time): - """ - convert timestamp to HOTP counter using :attr:`period`. - input is passed through :meth:`normalize_time`. - """ - if time < 0: - raise ValueError("time must be >= 0") - return time // self.period - - #------------------------------------------------------------------------- - # token generation - #------------------------------------------------------------------------- - def generate(self, time=None): - """ - Low-level method to generate token for specified time. - - :arg time: - Can be ``None``, :class:`!datetime`, - or unix epoch timestamp as :class:`!float` or :class:`!int`. - If ``None`` (the default), uses current system time. - Naive datetimes are treated as UTC. - - :returns: - - sequence of ``(token, expire_time)`` (actually a :class:`TotpToken` instance): - - * ``token`` -- decimal-formatted token as a (unicode) string - * ``expire_time`` -- unix epoch time when token will expire - - Usage example:: - - >>> # generate a new token, wrapped in a TotpToken instance... - >>> otp = TOTP('s3jdvb7qd2r7jpxx') - >>> otp.generate(1419622739) - <TotpToken token='897212' expire_time=1419622740> - - >>> # when you just need the token... - >>> otp.generate(1419622739).token - '897212' - - .. seealso:: - This is a lowlevel method, which doesn't read or modify any state-dependant values - (such as the :attr:`last_counter` value). - """ - time = self.normalize_time(time) - counter = self._time_to_counter(time) - token = self._generate(counter) - return TotpToken(self, token, counter) - -# # debug helper -# def generate_range(self, size, time=None): -# counter = self._time_to_counter(time) - (size + 1) // 2 -# end = counter + size -# while counter <= end: -# token = self._generate(counter) -# yield TotpToken(self, token, counter) -# counter += 1 - - def advance(self, reuse=False): - """ - High-level method to generate TOTP token for current time. - Unlike :meth:`generate`, this method takes into account the :attr:`last_counter` value, - and updates that attribute to match the returned token. - - :param reuse: - Controls whether a token can be issued twice within the same time :attr:`period`. - - By default (``False``), calling this method twice within the same time :attr:`period` - will result in a :exc:`~passlib.exc.UsedTokenError`, since once a token has gone across the wire, - it should be considered insecure. - - Setting this to ``True`` will allow multiple uses of the token within the same time period. - - :raises ~passlib.exc.UsedTokenError: - - if an attempt is made to generate a token within the same time :attr:`period` - (suppressed by ``reuse=True``). - - :returns: - - sequence of ``(token, expire_time)`` (actually a :class:`TotpToken` instance): - - * ``token`` -- decimal-formatted token as a (unicode) string - * ``expire_time`` -- unix epoch time when token will expire - - Usage example:: - - >>> # IMPORTANT: THE 'now' PARAMETER SHOULD NOT BE USED IN PRODUCTION. - >>> # It's only used here to fix the totp generator's clock, so that - >>> # this example can be reproduced regardless of the actual system time. - - >>> # generate new token, wrapped in a TotpToken instance... - >>> totp = TOTP('s3jdvb7qd2r7jpxx', now=lambda : 1419622739) - >>> totp.advance() - <TotpToken token='897212' expire_time=1419622740> - - >>> # or use attr access when you just need the token ... - >>> totp.advance().token - '897212' - """ - time = self.normalize_time(None) - result = self.generate(time) - - if result.counter < self.last_counter: - # NOTE: this usually means system time has jumped back since last call. - # this will occasionally happen, so not throwing an error, - # but definitely worth issuing a warning. - warn("TOTP.advance(): current time (%r) earlier than last-used time (%r); " - "did system clock change?" % (int(time), self.last_counter * self.period), - exc.PasslibSecurityWarning, stacklevel=1) - - elif result.counter == self.last_counter and not reuse: - raise UsedTokenError("Token already generated in this time period, " - "please wait %d seconds for another." % result.remaining, - expire_time=result.expire_time) - - self.last_counter = result.counter - self.changed = True - return result - - #------------------------------------------------------------------------- - # token verification - #------------------------------------------------------------------------- - - 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, - in order to account for transmission delay and small amounts of skew in the client's clock. - - :arg token: - Token to validate. - may be integer or string (whitespace and hyphens are ignored). - - :param time: - Unix epoch timestamp, can be any of :class:`!float`, :class:`!int`, or :class:`!datetime`. - if ``None`` (the default), uses current system time. - *this should correspond to the time the token was received from the client*. - - :param int window: - How far backward and forward in time to search for a match. - Measured in seconds. Defaults to ``30``. Typically only useful if set - to multiples of :attr:`period`. - - :param int skew: - Adjust timestamp by specified value, to account for excessive - client clock skew. Measured in seconds. Defaults to ``0``. - - Negative skew (the common case) indicates transmission delay, - and/or that the client clock is running behind the server. - - Positive skew indicates the client clock is running ahead of the server - (and by enough that it cancels out any negative skew added by - the transmission delay). - - You should ensure the server clock uses a reliable time source such as NTP, - so that only the client clock's inaccuracy needs to be accounted for. - - This is an advanced parameter that should usually be left at ``0``; - The **window** parameter is usually enough to account - for any observed transmission delay. - - :param last_counter: - Optional value of last counter value that was successfully used. - If specified, verify will never search earlier counters, - no matter how large the window is. - - Useful when client has previously authenticated, - and thus should never provide a token older than previously - verified value. - - :param bool reuse: - Controls whether a token can be issued twice within the same time :attr:`period`. - - By default (``False``), attempting to verify the same token twice within the same time :attr:`period` - will result in a :exc:`~passlib.exc.TokenReuseError`. - Setting this to ``True`` will silently allow multiple uses of the token within the same time period. - - Note that enabling this exposes your application to a replay attack: - if an attacker is able to read the token (whether physically - as the user types it, or going across the wire), the attacker - will be able to re-use any time over the next <period> seconds. - - :raises ~passlib.exc.TokenError: - - If the token is malformed, or fails to verify. - - :returns TotpMatch: - - Returns a :class:`TotpMatch` instance on successful match. - Can be treated as tuple of ``(counter, time)``. - Raises error if token is malformed / can't be verified. - - Usage example:: - - >>> totp = TOTP('s3jdvb7qd2r7jpxx') - - >>> # valid token for this time period - >>> totp.verify('897212', 1419622729) - <TotpMatch counter=47320757 time=1419622729> - - >>> # token from counter step 30 sec ago (within allowed window) - >>> totp.verify('000492', 1419622729) - <TotpMatch counter=47320756 time=1419622729> - - >>> # invalid token -- token from 60 sec ago (outside of window) - >>> totp.verify('760389', 1419622729) - Traceback: - ... - InvalidTokenError: Token did not match - - .. seealso:: - This is a low-level method, which doesn't read or modify any state-dependant values - (such as the :attr:`last_counter` value). - For a version which does, see :meth:`consume`. - """ - time = self.normalize_time(time) - self._check_serial(window, "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) - 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, 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, - and updates that attribute if a match is found. - - :arg token: - token to validate. - may be integer or string (whitespace and hyphens are ignored). - - :param bool reuse: - Controls whether a token can be issued twice within the same time :attr:`period`. - - By default (``False``), attempting to verify the same token twice within the same time :attr:`period` - will result in a :exc:`~passlib.exc.TokenReuseError`. - Setting this to ``True`` will silently allow multiple uses of the token within the same time period. - - Note that enabling this exposes your application to a replay attack: - if an attacker is able to read the token (whether physically - as the user types it, or going across the wire), the attacker - will be able to re-use any time over the next <period> seconds. - - :param int window: - How far backward and forward in time to search for a match. - Measured in seconds. Defaults to ``30``. Typically only useful if set - to multiples of :attr:`period`. - - :raises ~passlib.exc.TokenError: - - If the token is malformed, fails to verify, - or an attempt is made to re-use the current time period's token - (this last check can be suppressed by ``reuse=True``) - - :returns: - If token validated, returns the :class:`HotpMatch` instance from the underlying :meth:`verify` call. - Raise errors on invalid/malformed tokens. - - May set the :attr:`changed` attribute if the internal state was updated, - and needs to be re-persisted by the application (see :meth:`to_json`). - - Usage example:: - - >>> # IMPORTANT: THE 'now' PARAMETER SHOULD NOT BE USED IN PRODUCTION. - >>> # It's only used here to fix the totp generator's clock, so that - >>> # this example can be reproduced regardless of the actual system time. - >>> totp = TOTP('s3jdvb7qd2r7jpxx', now = lambda: 1419622739) - - >>> # wrong token - >>> totp.consume('123456') - Traceback: - ... - InvalidTokenError: Token did not match - - >>> # token from 30 sec ago (w/ window, will be accepted) - >>> totp.consume('000492') - <TotpMatch counter=47320756 time=1419622729> - - >>> # token from current period - >>> totp.consume('897212') - <TotpMatch counter=47320757 time=1419622729> - - >>> # token from 30 sec ago will now be rejected - >>> totp.consume('000492') - Traceback: - ... - InvalidTokenError: Token did not match - """ - time = self.normalize_time(None) - # 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. - 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 match.counter != self.last_counter: - # accept new token, update internal state - self.last_counter = match.counter - self.changed = True - else: - assert reuse, "sanity check failed" - # XXX: return the match instead? - return match - - #------------------------------------------------------------------------- - # TODO: resync(self, tokens, time=None, min_tokens=10, window=100) - # helper to re-synchronize using series of sequential tokens, - # all of which must validate; per RFC recommendation. - # NOTE: need to make sure this function is constant time - # (i.e. scans ALL tokens, and doesn't short-circuit after first mismatch) - #------------------------------------------------------------------------- - - #============================================================================= - # uri parsing - #============================================================================= - @classmethod - def _adapt_uri_params(cls, period=None, **kwds): - """ - parse TOTP specific params, and let _BaseOTP handle rest. - """ - kwds = super(TOTP, cls)._adapt_uri_params(**kwds) - if period: - kwds['period'] = cls._uri_parse_int(period, "period") - return kwds - - #============================================================================= - # uri rendering - #============================================================================= - def _to_uri_params(self): - """ - add TOTP specific arguments to URI, and let _BaseOTP handle rest. - """ - args = super(TOTP, self)._to_uri_params() - if self.period != 30: - args.append(("period", str(self.period))) - return args - - #============================================================================= - # json rendering - #============================================================================= - def to_dict(self, **kwds): - state = super(TOTP, self).to_dict(**kwds) - if self.period != 30: - state['period'] = self.period - if self.last_counter: - state['last_counter'] = self.last_counter - # 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 - - #============================================================================= - # eoc - #============================================================================= - #============================================================================= # convenience helpers #============================================================================= |
