diff --git a/core/modules/user.py b/core/modules/user.py index 57a2a4fd5..757295a7d 100644 --- a/core/modules/user.py +++ b/core/modules/user.py @@ -7,7 +7,9 @@ import logging import secrets import warnings -from typing import Optional +from typing import Optional, Union, Any +import pyotp +import base64 import time from google.auth.transport import requests @@ -661,38 +663,6 @@ def startProcessing(self, user_key): return self.userModule.render.edit(self.OtpSkel(), action="otp", tpl=self.otpTemplate) - def generateOtps(self, secret, timeDrift): - """ - Generates all valid tokens for the given secret - """ - - # fixme: Use pyotp for this! - def asBytes(valIn): - """ - Returns the integer in binary representation - """ - hexStr = hex(valIn)[2:] - # Maybe uneven length - if len(hexStr) % 2 == 1: - hexStr = "0" + hexStr - return bytes.fromhex("00" * int(8 - (len(hexStr) / 2)) + hexStr) - - idx = int(time.time() / 60.0) # Current time index - idx += int(timeDrift) - res = [] - - for slot in range(idx - self.windowSize, idx + self.windowSize): - currHash = hmac.new(bytes.fromhex(secret), asBytes(slot), hashlib.sha1).digest() - # Magic code from https://tools.ietf.org/html/rfc4226 :) - offset = currHash[19] & 0xf - code = ((currHash[offset] & 0x7f) << 24 | - (currHash[offset + 1] & 0xff) << 16 | - (currHash[offset + 2] & 0xff) << 8 | - (currHash[offset + 3] & 0xff)) - res.append(int(str(code)[-6:])) # We use only the last 6 digits - - return res - @exposed @forceSSL def otp(self, skey: str = None, *args, **kwargs): @@ -715,12 +685,18 @@ def otp(self, skey: str = None, *args, **kwargs): elif len(otp_user_conf["otpkey"]) % 2 == 1: raise errors.PreconditionFailed("The otp secret stored for this user is invalid (uneven length)") - # Generate a batch of tokens for given time window size - valid_tokens = self.generateOtps(otp_user_conf["otpkey"], otp_user_conf["otptimedrift"]) - - # If token is not in generated token set, token is invalid - # logging.debug(f"{skel['otptoken']=}, {valid_tokens=}") - if skel["otptoken"] not in valid_tokens: + # Verify the otptoken. If valid, this returns the current timedrift index for this hardware OTP. + verifyIndex = self.verify( + otp=skel["otptoken"], + secret=otp_user_conf["otpkey"], + algorithm=otp_user_conf["algorithm"], + timedrift=otp_user_conf["otptimedrift"], + valid_window=self.windowSize + ) + logging.debug(f"TimeBasedOTP:otp: {verifyIndex=}.") + + # Check if Token is invalid. Caution: 'if not verifyIndex' gets false positive for verifyIndex === 0! + if verifyIndex is False: otp_user_conf["failures"] += 1 session.markChanged() return self.userModule.render.edit(self.OtpSkel(), action="otp", tpl=self.otpTemplate, loginFailed=True) @@ -731,15 +707,69 @@ def otp(self, skey: str = None, *args, **kwargs): session.markChanged() # Check if the OTP device has a time drift - idx = valid_tokens.index(skel["otptoken"]) - if abs(idx - self.windowSize) > 2: - # The time-drift accumulates to more than 2 minutes, update clock-drift value accordingly - self.updateTimeDrift(user_key, idx - self.windowSize) + timedriftchange = float(verifyIndex) - otp_user_conf["otptimedrift"] + if abs(timedriftchange) > 2: + # The time-drift change accumulates to more than 2 minutes (for interval==60): + # update clock-drift value accordingly + self.updateTimeDrift(user_key, timedriftchange) # Continue with authentication return self.userModule.secondFactorSucceeded(self, user_key) + @staticmethod + def verify( + otp: str, + secret: str = "", + algorithm: Any = None, + interval: int = 60, + timedrift: float = 0, + for_time: Optional[datetime.datetime] = None, + valid_window: int = 0, + ) -> Union[int, bool]: + """ + Verifies the OTP passed in against the current time OTP. + + This is a fork of pyotp.verify. Rather than true/false, if valid_window > 0, it returns the index for which + the OTP value obtained by pyotp.at(for_time=time.time(), counter_offset=index) equals the current value shown + on the hardware token generator. This can be used to store the time drift of a given token generator. + + :param otp: the OTP token to check against + :param secret: The OTP secret + :param algorithm: digest function to use in the HMAC (expected to be sha1 or sha256) + :param interval: the time interval in seconds for OTP. This defaults to 60 (old OTP c200 Generators). In + pyotp, default is 30! + :param timedrift: The known timedrift (old index) of the hardware OTP generator + :param for_time: Time to check OTP at (defaults to now) + :param valid_window: extends the validity to this many counter ticks before and after the current one + :returns: The index where verification succeeded, None otherwise + """ + + if for_time is None: + for_time = datetime.datetime.now() + + # Timedrift is updated only in fractions in order to prevent problems, but we need an integer index + timedrift = round(timedrift) + + secret = bytes.decode(base64.b32encode(bytes.fromhex(secret))) + digest = { + "sha1": hashlib.sha1, + "sha256": hashlib.sha256, + }[algorithm] + logging.debug(f"TimeBasedOTP:verify: {digest=}, {interval=}, {valid_window=}") + + totp = pyotp.TOTP(secret, digest=digest, interval=interval) + + if valid_window: + for i in range(timedrift - valid_window, timedrift + valid_window + 1): + token = str(totp.at(for_time, i)) + logging.debug(f"TimeBasedOTP:verify: {i=}, {token=}") + if utils.strings_equal(str(otp), token): + return i + return False + + return utils.strings_equal(str(otp), str(totp.at(for_time, timedrift))) + def updateTimeDrift(self, user_key, idx): """ Updates the clock-drift value. diff --git a/core/utils.py b/core/utils.py index c8b87a06b..d2661a0d6 100644 --- a/core/utils.py +++ b/core/utils.py @@ -3,6 +3,7 @@ import logging import secrets import string +import unicodedata from base64 import urlsafe_b64encode from datetime import datetime, timedelta, timezone from typing import Any, Union, Optional @@ -272,6 +273,22 @@ def normalizeKey(key: Union[None, 'db.KeyClass']) -> Union[None, 'db.KeyClass']: return db.Key(key.kind, key.id_or_name, parent=parent) +def strings_equal(s1: str, s2: str) -> bool: + """ + Timing-attack resistant string comparison. + + Taken from pyotp. + + Normal comparison using == will short-circuit on the first mismatching + character. This avoids that by scanning the whole string, though we + still reveal to a timing attack whether the strings are the same + length. + """ + s1 = unicodedata.normalize("NFKC", s1) + s2 = unicodedata.normalize("NFKC", s2) + return hmac.compare_digest(s1.encode("utf-8"), s2.encode("utf-8")) + + # DEPRECATED ATTRIBUTES HANDLING __utils_conf_replacement = { "projectID": "viur.instance.project_id", diff --git a/requirements.txt b/requirements.txt index 724f6a257..ac46bf835 100644 --- a/requirements.txt +++ b/requirements.txt @@ -31,6 +31,7 @@ proto-plus==1.22.3 ; python_version >= '3.6' --hash=sha256:a49cd903bc0b6ab41f76b protobuf==4.23.4 ; python_version >= '3.7' --hash=sha256:0a5759f5696895de8cc913f084e27fd4125e8fb0914bb729a17816a33819f474 --hash=sha256:351cc90f7d10839c480aeb9b870a211e322bf05f6ab3f55fcb2f51331f80a7d2 --hash=sha256:5fea3c64d41ea5ecf5697b83e41d09b9589e6f20b677ab3c48e5f242d9b7897b --hash=sha256:6dd9b9940e3f17077e820b75851126615ee38643c2c5332aa7a359988820c720 --hash=sha256:7b19b6266d92ca6a2a87effa88ecc4af73ebc5cfde194dc737cf8ef23a9a3b12 --hash=sha256:8547bf44fe8cec3c69e3042f5c4fb3e36eb2a7a013bb0a44c018fc1e427aafbd --hash=sha256:9053df6df8e5a76c84339ee4a9f5a2661ceee4a0dab019e8663c50ba324208b0 --hash=sha256:c3e0939433c40796ca4cfc0fac08af50b00eb66a40bbbc5dee711998fb0bbc1e --hash=sha256:ccd9430c0719dce806b93f89c91de7977304729e55377f872a92465d548329a9 --hash=sha256:e1c915778d8ced71e26fcf43c0866d7499891bca14c4368448a82edc61fdbc70 --hash=sha256:e9d0be5bf34b275b9f87ba7407796556abeeba635455d036c7351f7c183ef8ff --hash=sha256:effeac51ab79332d44fba74660d40ae79985901ac21bca408f8dc335a81aa597 --hash=sha256:fee88269a090ada09ca63551bf2f573eb2424035bcf2cb1b121895b01a46594a pyasn1==0.5.0 ; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4, 3.5' --hash=sha256:87a2121042a1ac9358cabcaf1d07680ff97ee6404333bacca15f76aa8ad01a57 --hash=sha256:97b7290ca68e62a832558ec3976f15cbf911bf5d7c7039d8b861c2a0ece69fde pyasn1-modules==0.3.0 ; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4, 3.5' --hash=sha256:5bd01446b736eb9d31512a30d46c1ac3395d676c6f3cafa4c03eb54b9925631c --hash=sha256:d3ccd6ed470d9ffbc716be08bd90efbd44d0734bc9303818f7336070984a162d +pyotp==2.8.0 --hash=sha256:889d037fdde6accad28531fc62a790f089e5dfd5b638773e9ee004cce074a2e5 --hash=sha256:c2f5e17d9da92d8ec1f7de6331ab08116b9115adbabcba6e208d46fc49a98c5a pytz==2023.3 --hash=sha256:1d8ce29db189191fb55338ee6d0387d82ab59f3d00eac103412d64e0ebd0c588 --hash=sha256:a151b3abb88eda1d4e34a9814df37de2a80e301e68ba0fd856fb9b46bfbbbffb pyyaml==6.0.1 --hash=sha256:062582fca9fabdd2c8b54a3ef1c978d786e0f6b3a1510e0ac93ef59e0ddae2bc --hash=sha256:1635fd110e8d85d55237ab316b5b011de701ea0f29d07611174a1b42f1444741 --hash=sha256:184c5108a2aca3c5b3d3bf9395d50893a7ab82a38004c8f61c258d4428e80206 --hash=sha256:18aeb1bf9a78867dc38b259769503436b7c72f7a1f1f4c93ff9a17de54319b27 --hash=sha256:1d4c7e777c441b20e32f52bd377e0c409713e8bb1386e1099c2415f26e479595 --hash=sha256:1e2722cc9fbb45d9b87631ac70924c11d3a401b2d7f410cc0e3bbf249f2dca62 --hash=sha256:1fe35611261b29bd1de0070f0b2f47cb6ff71fa6595c077e42bd0c419fa27b98 --hash=sha256:28c119d996beec18c05208a8bd78cbe4007878c6dd15091efb73a30e90539696 --hash=sha256:42f8152b8dbc4fe7d96729ec2b99c7097d656dc1213a3229ca5383f973a5ed6d --hash=sha256:4fb147e7a67ef577a588a0e2c17b6db51dda102c71de36f8549b6816a96e1867 --hash=sha256:50550eb667afee136e9a77d6dc71ae76a44df8b3e51e41b77f6de2932bfe0f47 --hash=sha256:510c9deebc5c0225e8c96813043e62b680ba2f9c50a08d3724c7f28a747d1486 --hash=sha256:5773183b6446b2c99bb77e77595dd486303b4faab2b086e7b17bc6bef28865f6 --hash=sha256:596106435fa6ad000c2991a98fa58eeb8656ef2325d7e158344fb33864ed87e3 --hash=sha256:6965a7bc3cf88e5a1c3bd2e0b5c22f8d677dc88a455344035f03399034eb3007 --hash=sha256:69b023b2b4daa7548bcfbd4aa3da05b3a74b772db9e23b982788168117739938 --hash=sha256:704219a11b772aea0d8ecd7058d0082713c3562b4e271b849ad7dc4a5c90c13c --hash=sha256:7e07cbde391ba96ab58e532ff4803f79c4129397514e1413a7dc761ccd755735 --hash=sha256:81e0b275a9ecc9c0c0c07b4b90ba548307583c125f54d5b6946cfee6360c733d --hash=sha256:9046c58c4395dff28dd494285c82ba00b546adfc7ef001486fbf0324bc174fba --hash=sha256:9eb6caa9a297fc2c2fb8862bc5370d0303ddba53ba97e71f08023b6cd73d16a8 --hash=sha256:a0cd17c15d3bb3fa06978b4e8958dcdc6e0174ccea823003a106c7d4d7899ac5 --hash=sha256:afd7e57eddb1a54f0f1a974bc4391af8bcce0b444685d936840f125cf046d5bd --hash=sha256:b1275ad35a5d18c62a7220633c913e1b42d44b46ee12554e5fd39c70a243d6a3 --hash=sha256:b786eecbdf8499b9ca1d697215862083bd6d2a99965554781d0d8d1ad31e13a0 --hash=sha256:ba336e390cd8e4d1739f42dfe9bb83a3cc2e80f567d8805e11b46f4a943f5515 --hash=sha256:baa90d3f661d43131ca170712d903e6295d1f7a0f595074f151c0aed377c9b9c --hash=sha256:bc1bf2925a1ecd43da378f4db9e4f799775d6367bdb94671027b73b393a7c42c --hash=sha256:bd4af7373a854424dabd882decdc5579653d7868b8fb26dc7d0e99f823aa5924 --hash=sha256:bf07ee2fef7014951eeb99f56f39c9bb4af143d8aa3c21b1677805985307da34 --hash=sha256:bfdf460b1736c775f2ba9f6a92bca30bc2095067b8a9d77876d1fad6cc3b4a43 --hash=sha256:c8098ddcc2a85b61647b2590f825f3db38891662cfc2fc776415143f599bb859 --hash=sha256:d2b04aac4d386b172d5b9692e2d2da8de7bfb6c387fa4f801fbf6fb2e6ba4673 --hash=sha256:d858aa552c999bc8a8d57426ed01e40bef403cd8ccdd0fc5f6f04a00414cac2a --hash=sha256:f003ed9ad21d6a4713f0a9b5a7a0a79e08dd0f221aff4525a2be4c346ee60aab --hash=sha256:f22ac1c3cac4dbc50079e965eba2c1058622631e526bd9afd45fedd49ba781fa --hash=sha256:faca3bdcf85b2fc05d06ff3fbc1f83e1391b3e724afa3feba7d13eeab355484c --hash=sha256:fca0e3a251908a499833aa292323f32437106001d436eca0e6e7833256674585 --hash=sha256:fd1592b3fdf65fff2ad0004b5e363300ef59ced41c2e6b3a99d4089fa8c5435d --hash=sha256:fd66fc5d0da6d9815ba2cebeb4205f95818ff4b79c3ebe268e75d961704af52f referencing==0.30.0 ; python_version >= '3.8' --hash=sha256:47237742e990457f7512c7d27486394a9aadaf876cbfaa4be65b27b4f4d47c6b --hash=sha256:c257b08a399b6c2f5a3510a50d28ab5dbc7bbde049bcaf954d43c446f83ab548