This is a bit of a technical security detail post, but I found it extremely interesting because it probably affects 99% of the code out there.
If you have ever done something like the following
if password == “hunter2”
# The user is logged in! :D
# The user got the password wrong
then your code is vulnerable to this timing attack!
You can read more about it in the article above, and also I found this
article with a more in-depth explanation and the following two papers.
Essentially the problem is that most of the string comparison algorithms will loop through the strings and check character by character if they are the same. If not they return False, otherwise if the loop completes successfully it would return True.
This has the disadvantage that the time of completion of the algorithm is not fixed, so timing how long it took for the function to return, an attacker can understand how much of the password they got right, and this means that it would take fewer requests to guess the password (more measurements examples are shown in the article).
To solve this problem you need a string comparison algorithm that would always complete in a constant time, and most of the programming languages available have one in their standard library.
I found a very simple implementation here
, in the source code of OpenSSL, which for security reason they implemented a secure memcmp() function called CRYPTO_memcmp(), and they are using it in critical parts of their code.
To sum it up, the following is a very good advice.
Every time you compare two values, ask yourself: what could someone do if they knew either of these values? If the answer is at all meaningful, use a constant-time algorithm to compare them.