Skip to content

Instantly share code, notes, and snippets.

@dionyziz
Last active June 5, 2016 19:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dionyziz/8120620 to your computer and use it in GitHub Desktop.
Save dionyziz/8120620 to your computer and use it in GitHub Desktop.
Difficulty of a security timing attack against an insecure PHP hash equality comparison, indicated by a local measure of timing deltas. Example finds a difference of 10x in total time requiring 1,000,000 requests.
<?php
define('N', 1000000);
define('HASH', '0000000000000000000000');
define('MATCH', '0000000000000000000001');
define('MISMATCH', '1000000000000000000000');
function insecure_check_equality($expected, $actual) {
if (strlen($expected) != strlen($actual)) {
return false;
}
for ($i = 0; $i < strlen($expected); ++$i) {
if ($expected[$i] != $actual[$i]) {
return false;
}
}
return true;
}
$t = microtime(true);
for ($repeat = 0; $repeat < N; ++$repeat) {
insecure_check_equality(HASH, MATCH);
}
$dt_match = microtime(true) - $t;
$t = microtime(true);
for ($repeat = 0; $repeat < N; ++$repeat) {
insecure_check_equality(HASH, MISMATCH);
}
$dt_mismatch = microtime(true) - $t;
echo N . " requests took:\n";
echo $dt_match . " s for hash matching almost-everywhere.\n";
echo $dt_mismatch . " s for hash not matching anywhere.\n";
?>
@dionyziz
Copy link
Author

dionyziz@erdos ~ % php test.php
1000000 requests took:
7.5622079372406 s for hash matching almost-everywhere.
0.80904006958008 s for hash not matching anywhere.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment