Created
December 27, 2023 02:34
-
-
Save heathhenley/eb695717f7eb5172f63c165e72c91d4a to your computer and use it in GitHub Desktop.
Timing leak example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import timeit | |
TOKEN = b"super_secret_token" | |
# Which one is better? | |
def is_authorized_one(provided_token: bytes, expected_token: bytes) -> bool: | |
return provided_token == expected_token | |
def is_authorized_two(provided_token: bytes, expected_token: bytes) -> bool: | |
if len(provided_token) != len(expected_token): | |
return False | |
result = 0 | |
for i in range(len(provided_token)): | |
result |= provided_token[i] ^ expected_token[i] | |
return result == 0 | |
# check they're working when correct | |
assert is_authorized_one(TOKEN, TOKEN) == True | |
assert is_authorized_two(TOKEN, TOKEN) == True | |
# check they're working when incorrect | |
assert is_authorized_one(b'bad_token', TOKEN) == False | |
assert is_authorized_two(b'bad_token', TOKEN) == False | |
# time the function calls | |
print("Same length, bad token:") | |
normal_compare = timeit.timeit( | |
stmt="is_authorized_one(b'SuPeR_SeCrEt_ToKen', TOKEN)", | |
setup="from __main__ import is_authorized_one, TOKEN", | |
number=1000 | |
) | |
print(f" Normal: {normal_compare}") | |
constant_time = timeit.timeit( | |
stmt="is_authorized_two(b'SuPeR_SeCrEt_ToKen', TOKEN)", | |
setup="from __main__ import is_authorized_two, TOKEN", | |
number=1000) | |
print(f" Constant time: {constant_time}") | |
print(normal_compare / constant_time) | |
print() | |
print("Same length, good token:") | |
normal_compare = timeit.timeit( | |
stmt="is_authorized_one(b'super_secret_token', TOKEN)", | |
setup="from __main__ import is_authorized_one, TOKEN", | |
number=1000 | |
) | |
print(f" Normal: {normal_compare}") | |
constant_time = timeit.timeit( | |
stmt="is_authorized_two(b'super_secret_token', TOKEN)", | |
setup="from __main__ import is_authorized_two, TOKEN", | |
number=1000) | |
print(f" Constant time: {constant_time}") | |
print(normal_compare / constant_time) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment