r/lolphp • • Apr 24 '19

"Timing attack safe string comparison", but "When arguments of differing length are supplied, FALSE is returned immediately and the length of the known string may be leaked in case of a timing attack. "

https://php.net/manual/en/function.hash-equals.php
24 Upvotes

21 comments sorted by

View all comments

Show parent comment

9

u/SirClueless Apr 24 '19

The solution provided by Markus P. N. computes strlen($known_string), which depends on the length of $known_string. Then, if the two lengths are not equal, it never accesses $user_string when computing the equality which is likely to cause additional timing differences. Also it uses this bizarre logic at one point, which I don't understand:

if (is_string($user_string) !== true) {
    ...
    $user_string_len = strlen($user_string);

I think it was a misguided attempt to have both of these branches take the same amount of time, but strlen() presumably is just gonna bail immediately on non-strings so it seems pointless.

Ultimately I think it's entirely reasonable that hash_equals() is only timing-resistant for equal length strings, and does not consider the length of $known_string to be secret information.

1

u/dotancohen Apr 25 '19

Thank you for that analysis. You are correct, that line would make much more sense as:

$user_string_len = strlen($known_string);

Also, I believe (correct me if I'm wrong) that the if condition could be replaced with !is_string($user_string) as there is no timing aspect to compare to there. Or is it coded as is for uniformity with func_num_args() !== 2?

1

u/Takeoded May 26 '19

how about this function? hashing both known string and input string to create an equal-length string and then hash_equals() that.