diff options
-rw-r--r-- | cryptography/hazmat/primitives/twofactor/hotp.py | 15 | ||||
-rw-r--r-- | cryptography/hazmat/primitives/twofactor/totp.py | 33 | ||||
-rw-r--r-- | docs/hazmat/primitives/twofactor.rst | 102 | ||||
-rw-r--r-- | tests/hazmat/primitives/twofactor/test_hotp.py | 21 | ||||
-rw-r--r-- | tests/hazmat/primitives/twofactor/test_totp.py | 130 |
5 files changed, 268 insertions, 33 deletions
diff --git a/cryptography/hazmat/primitives/twofactor/hotp.py b/cryptography/hazmat/primitives/twofactor/hotp.py index 80e28820..e806c7ef 100644 --- a/cryptography/hazmat/primitives/twofactor/hotp.py +++ b/cryptography/hazmat/primitives/twofactor/hotp.py @@ -17,13 +17,13 @@ import struct import six -from cryptography.exceptions import InvalidToken +from cryptography.exceptions import InvalidToken, UnsupportedAlgorithm from cryptography.hazmat.primitives import constant_time, hmac -from cryptography.hazmat.primitives.hashes import SHA1 +from cryptography.hazmat.primitives.hashes import SHA1, SHA256, SHA512 class HOTP(object): - def __init__(self, key, length, backend): + def __init__(self, key, length, algorithm, backend): if len(key) < 16: raise ValueError("Key length has to be at least 128 bits.") @@ -31,8 +31,13 @@ class HOTP(object): if length < 6 or length > 8: raise ValueError("Length of HOTP has to be between 6 to 8.") + if not isinstance(algorithm, (SHA1, SHA256, SHA512)): + raise UnsupportedAlgorithm( + "Algorithm must be SHA1, SHA256 or SHA512") + self._key = key self._length = length + self._algorithm = algorithm self._backend = backend def generate(self, counter): @@ -45,11 +50,11 @@ class HOTP(object): raise InvalidToken("Supplied HOTP value does not match") def _dynamic_truncate(self, counter): - ctx = hmac.HMAC(self._key, SHA1(), self._backend) + ctx = hmac.HMAC(self._key, self._algorithm, self._backend) ctx.update(struct.pack(">Q", counter)) hmac_value = ctx.finalize() - offset_bits = six.indexbytes(hmac_value, 19) & 0b1111 + offset_bits = six.indexbytes(hmac_value, len(hmac_value) - 1) & 0b1111 offset = int(offset_bits) p = hmac_value[offset:offset + 4] diff --git a/cryptography/hazmat/primitives/twofactor/totp.py b/cryptography/hazmat/primitives/twofactor/totp.py new file mode 100644 index 00000000..be84b477 --- /dev/null +++ b/cryptography/hazmat/primitives/twofactor/totp.py @@ -0,0 +1,33 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +# implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import absolute_import, division, print_function + +from cryptography.exceptions import InvalidToken +from cryptography.hazmat.primitives import constant_time +from cryptography.hazmat.primitives.twofactor.hotp import HOTP + + +class TOTP(object): + def __init__(self, key, length, algorithm, time_step, backend): + + self._time_step = time_step + self._hotp = HOTP(key, length, algorithm, backend) + + def generate(self, time): + counter = int(time / self._time_step) + return self._hotp.generate(counter) + + def verify(self, totp, time): + if not constant_time.bytes_eq(self.generate(time), totp): + raise InvalidToken("Supplied TOTP value does not match") diff --git a/docs/hazmat/primitives/twofactor.rst b/docs/hazmat/primitives/twofactor.rst index 9d661612..06be151e 100644 --- a/docs/hazmat/primitives/twofactor.rst +++ b/docs/hazmat/primitives/twofactor.rst @@ -13,13 +13,13 @@ codes (HMAC). .. currentmodule:: cryptography.hazmat.primitives.twofactor.hotp -.. class:: HOTP(key, length, backend) +.. class:: HOTP(key, length, algorithm, backend) .. versionadded:: 0.3 - HOTP objects take a ``key`` and ``length`` parameter. The ``key`` - should be randomly generated bytes and is recommended to be 160 bits in - length. The ``length`` parameter controls the length of the generated + HOTP objects take a ``key``, ``length`` and ``algorithm`` parameter. The + ``key`` should be randomly generated bytes and is recommended to be 160 + bits in length. The ``length`` parameter controls the length of the generated one time password and must be >= 6 and <= 8. This is an implementation of :rfc:`4226`. @@ -29,23 +29,28 @@ codes (HMAC). >>> import os >>> from cryptography.hazmat.backends import default_backend >>> from cryptography.hazmat.primitives.twofactor.hotp import HOTP - - >>> key = b"12345678901234567890" - >>> hotp = HOTP(key, 6, backend=default_backend()) - >>> hotp.generate(0) - '755224' - >>> hotp.verify(b"755224", 0) - - :param bytes key: Secret key as ``bytes``. This value must be generated in a - cryptographically secure fashion and be at least 128 bits. - It is recommended that the key be 160 bits. + >>> from cryptography.hazmat.primitives.hashes import SHA1 + >>> key = os.urandom(16) + >>> hotp = HOTP(key, 6, SHA1(), backend=default_backend()) + >>> hotp_value = hotp.generate(0) + >>> hotp.verify(hotp_value, 0) + + :param bytes key: Per-user secret key. This value must be kept secret + and be at least 128 bits. It is recommended that the + key be 160 bits. :param int length: Length of generated one time password as ``int``. + :param HashAlgorithm algorithm: A + :class:`~cryptography.hazmat.primitives.hashes` + provider. :param backend: A :class:`~cryptography.hazmat.backends.interfaces.HMACBackend` provider. - :raises ValueError: This is raised if the provided ``key`` is shorter 128 bits - or if the ``length`` parameter is not between 6 to 8. - + :raises ValueError: This is raised if the provided ``key`` is shorter than 128 bits + or if the ``length`` parameter is not 6, 7 or 8. + :raises UnsupportedAlgorithm: This is raised if the provided ``algorithm`` is not + :class:`~cryptography.hazmat.primitives.hashes.SHA1()`, + :class:`~cryptography.hazmat.primitives.hashes.SHA256()` + or :class:`~cryptography.hazmat.primitives.hashes.SHA512()`. .. method:: generate(counter) @@ -55,12 +60,12 @@ codes (HMAC). .. method:: verify(hotp, counter) :param bytes hotp: The one time password value to validate. - :param bytes counter: The counter value to validate against. + :param int counter: The counter value to validate against. :raises cryptography.exceptions.InvalidToken: This is raised when the supplied HOTP does not match the expected HOTP. Throttling ----------- +~~~~~~~~~~ Due to the fact that the HOTP algorithm generates rather short tokens that are 6 - 8 digits long, brute force attacks are possible. It is highly recommended that the server that @@ -69,7 +74,7 @@ time after a number of failed attempts. The number of allowed attempts should be possible while still ensuring that usability is not significantly impacted. Re-synchronization of the Counter ---------------------------------- +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The server's counter value should only be incremented on a successful HOTP authentication. However, the counter on the client is incremented every time a new HOTP value is requested. @@ -93,4 +98,59 @@ This can be accomplished with something similar to the following code. except InvalidToken: pass - return correct_counter
\ No newline at end of file + return correct_counter + +.. currentmodule:: cryptography.hazmat.primitives.twofactor.totp + +.. class:: TOTP(key, length, algorithm, time_step, backend) + + TOTP objects take a ``key``, ``length``, ``algorithm`` and ``time_step`` + parameter. The ``key`` should be randomly generated bytes and is recommended + to be as long as your hash function's output (e.g 256-bit for SHA256). + The ``length`` parameter controls the length of the generated one time + password and must be >= 6 and <= 8. + + This is an implementation of :rfc:`6238`. + + .. doctest:: + + >>> import os + >>> import time + >>> from cryptography.hazmat.backends import default_backend + >>> from cryptography.hazmat.primitives.twofactor.totp import TOTP + >>> from cryptography.hazmat.primitives.hashes import SHA1 + >>> key = os.urandom(16) + >>> totp = TOTP(key, 8, SHA1(), 30, backend=default_backend()) + >>> time_value = time.time() + >>> totp_value = totp.generate(time_value) + >>> totp.verify(totp_value, time_value) + + :param bytes key: Per-user secret key. This value must be kept secret + and be at least 128 bits. It is recommended that the + key be 160 bits. + :param int length: Length of generated one time password as ``int``. + :param HashAlgorithm algorithm: A + :class:`~cryptography.hazmat.primitives.hashes` + provider. + :param int time_step: The time step size. The recommended size is 30. + :param backend: A + :class:`~cryptography.hazmat.backends.interfaces.HMACBackend` + provider. + :raises ValueError: This is raised if the provided ``key`` is shorter than 128 bits + or if the ``length`` parameter is not 6, 7 or 8. + :raises UnsupportedAlgorithm: This is raised if the provided ``algorithm`` is not + :class:`~cryptography.hazmat.primitives.hashes.SHA1()`, + :class:`~cryptography.hazmat.primitives.hashes.SHA256()` + or :class:`~cryptography.hazmat.primitives.hashes.SHA512()`. + + .. method:: generate(time) + + :param int time: The time value used to generate the one time password. + :return bytes: A one time password value. + + .. method:: verify(totp, time) + + :param bytes totp: The one time password value to validate. + :param int time: The time value to validate against. + :raises cryptography.exceptions.InvalidToken: This is raised when the supplied TOTP + does not match the expected TOTP. diff --git a/tests/hazmat/primitives/twofactor/test_hotp.py b/tests/hazmat/primitives/twofactor/test_hotp.py index ec619b55..8f687ebb 100644 --- a/tests/hazmat/primitives/twofactor/test_hotp.py +++ b/tests/hazmat/primitives/twofactor/test_hotp.py @@ -15,10 +15,11 @@ import os import pytest -from cryptography.exceptions import InvalidToken +from cryptography.exceptions import InvalidToken, UnsupportedAlgorithm from cryptography.hazmat.primitives.twofactor.hotp import HOTP from cryptography.hazmat.primitives import hashes from tests.utils import load_vectors_from_file, load_nist_vectors +from cryptography.hazmat.primitives.hashes import MD5, SHA1 vectors = load_vectors_from_file( "twofactor/rfc-4226.txt", load_nist_vectors) @@ -35,13 +36,19 @@ class TestHOTP(object): secret = os.urandom(10) with pytest.raises(ValueError): - HOTP(secret, 6, backend) + HOTP(secret, 6, SHA1(), backend) def test_invalid_hotp_length(self, backend): secret = os.urandom(16) with pytest.raises(ValueError): - HOTP(secret, 4, backend) + HOTP(secret, 4, SHA1(), backend) + + def test_invalid_algorithm(self, backend): + secret = os.urandom(16) + + with pytest.raises(UnsupportedAlgorithm): + HOTP(secret, 6, MD5(), backend) @pytest.mark.parametrize("params", vectors) def test_truncate(self, backend, params): @@ -49,7 +56,7 @@ class TestHOTP(object): counter = int(params["counter"]) truncated = params["truncated"] - hotp = HOTP(secret, 6, backend) + hotp = HOTP(secret, 6, SHA1(), backend) assert hotp._dynamic_truncate(counter) == int(truncated.decode(), 16) @@ -59,7 +66,7 @@ class TestHOTP(object): counter = int(params["counter"]) hotp_value = params["hotp"] - hotp = HOTP(secret, 6, backend) + hotp = HOTP(secret, 6, SHA1(), backend) assert hotp.generate(counter) == hotp_value @@ -69,7 +76,7 @@ class TestHOTP(object): counter = int(params["counter"]) hotp_value = params["hotp"] - hotp = HOTP(secret, 6, backend) + hotp = HOTP(secret, 6, SHA1(), backend) assert hotp.verify(hotp_value, counter) is None @@ -77,7 +84,7 @@ class TestHOTP(object): secret = b"12345678901234567890" counter = 0 - hotp = HOTP(secret, 6, backend) + hotp = HOTP(secret, 6, SHA1(), backend) with pytest.raises(InvalidToken): hotp.verify(b"123456", counter) diff --git a/tests/hazmat/primitives/twofactor/test_totp.py b/tests/hazmat/primitives/twofactor/test_totp.py new file mode 100644 index 00000000..8877a70a --- /dev/null +++ b/tests/hazmat/primitives/twofactor/test_totp.py @@ -0,0 +1,130 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +# implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pytest + +from cryptography.exceptions import InvalidToken +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.twofactor.totp import TOTP +from tests.utils import load_vectors_from_file, load_nist_vectors + +vectors = load_vectors_from_file( + "twofactor/rfc-6238.txt", load_nist_vectors) + + +@pytest.mark.hmac +class TestTOTP(object): + + @pytest.mark.supported( + only_if=lambda backend: backend.hmac_supported(hashes.SHA1()), + skip_message="Does not support HMAC-SHA1." + ) + @pytest.mark.parametrize( + "params", [i for i in vectors if i["mode"] == b"SHA1"]) + def test_generate_sha1(self, backend, params): + secret = params["secret"] + time = int(params["time"]) + totp_value = params["totp"] + + totp = TOTP(secret, 8, hashes.SHA1(), 30, backend) + assert totp.generate(time) == totp_value + + @pytest.mark.supported( + only_if=lambda backend: backend.hmac_supported(hashes.SHA256()), + skip_message="Does not support HMAC-SHA256." + ) + @pytest.mark.parametrize( + "params", [i for i in vectors if i["mode"] == b"SHA256"]) + def test_generate_sha256(self, backend, params): + secret = params["secret"] + time = int(params["time"]) + totp_value = params["totp"] + + totp = TOTP(secret, 8, hashes.SHA256(), 30, backend) + assert totp.generate(time) == totp_value + + @pytest.mark.supported( + only_if=lambda backend: backend.hmac_supported(hashes.SHA512()), + skip_message="Does not support HMAC-SHA512." + ) + @pytest.mark.parametrize( + "params", [i for i in vectors if i["mode"] == b"SHA512"]) + def test_generate_sha512(self, backend, params): + secret = params["secret"] + time = int(params["time"]) + totp_value = params["totp"] + + totp = TOTP(secret, 8, hashes.SHA512(), 30, backend) + assert totp.generate(time) == totp_value + + @pytest.mark.supported( + only_if=lambda backend: backend.hmac_supported(hashes.SHA1()), + skip_message="Does not support HMAC-SHA1." + ) + @pytest.mark.parametrize( + "params", [i for i in vectors if i["mode"] == b"SHA1"]) + def test_verify_sha1(self, backend, params): + secret = params["secret"] + time = int(params["time"]) + totp_value = params["totp"] + + totp = TOTP(secret, 8, hashes.SHA1(), 30, backend) + + assert totp.verify(totp_value, time) is None + + @pytest.mark.supported( + only_if=lambda backend: backend.hmac_supported(hashes.SHA256()), + skip_message="Does not support HMAC-SHA256." + ) + @pytest.mark.parametrize( + "params", [i for i in vectors if i["mode"] == b"SHA256"]) + def test_verify_sha256(self, backend, params): + secret = params["secret"] + time = int(params["time"]) + totp_value = params["totp"] + + totp = TOTP(secret, 8, hashes.SHA256(), 30, backend) + + assert totp.verify(totp_value, time) is None + + @pytest.mark.supported( + only_if=lambda backend: backend.hmac_supported(hashes.SHA512()), + skip_message="Does not support HMAC-SHA512." + ) + @pytest.mark.parametrize( + "params", [i for i in vectors if i["mode"] == b"SHA512"]) + def test_verify_sha512(self, backend, params): + secret = params["secret"] + time = int(params["time"]) + totp_value = params["totp"] + + totp = TOTP(secret, 8, hashes.SHA512(), 30, backend) + + assert totp.verify(totp_value, time) is None + + def test_invalid_verify(self, backend): + secret = b"12345678901234567890" + time = 59 + + totp = TOTP(secret, 8, hashes.SHA1(), 30, backend) + + with pytest.raises(InvalidToken): + totp.verify(b"12345678", time) + + def test_floating_point_time_generate(self, backend): + secret = b"12345678901234567890" + time = 59.1 + + totp = TOTP(secret, 8, hashes.SHA1(), 30, backend) + + assert totp.generate(time) == b"94287082" |