A plain string comparison stops at the first different byte. So the time it takes depends on how many leading bytes were correct. That is a side channel: information leaking through something other than the output.
def check(token, expected):
return token == expected # time depends on the matching prefix
Over a noisy network the difference is nanoseconds, but with enough samples and statistics it can be measured, and in setups where the attacker is close (same machine, same cloud host) it gets easier. The defence is old and simple: take the same time for every input of the same length.
import hmac
def check(token: bytes, expected: bytes) -> bool:
return hmac.compare_digest(token, expected)
And the idea in C, for the curious:
int ct_equal(const unsigned char *a, const unsigned char *b, size_t n) {
unsigned char diff = 0;
for (size_t i = 0; i < n; i++)
diff |= a[i] ^ b[i]; /* never exits early */
return diff == 0;
}
Caveats: the length still leaks unless it is fixed, and you should use the vetted function from your crypto library instead of your own loop, because a compiler is free to be clever.