在 php.net 看到一個版本,然而卻有很多 downvotes,不知爲何。
<code>if(!function_exists('hash_equals')) { function hash_equals($str1, $str2) { if(strlen($str1) != strlen($str2)) { return false; } else { $res = $str1 ^ $str2; $ret = 0; for($i = strlen($res) - 1; $i >= 0; $i--) $ret |= ord($res[$i]); return !$ret; } }}</code>
如果這個函數真的不好,請說明原因,最好還能給出替代解決方案,謝謝。
從 stackoverflow 看到其實現如下:
<code>PHP_FUNCTION(hash_equals){ /* ... */ if (Z_STRLEN_P(known_zval) != Z_STRLEN_P(user_zval)) { RETURN_FALSE; } /* ... */ /* This is security sensitive code. Do not optimize this for speed. */ for (j = 0; j < Z_STRLEN_P(known_zval); j++) { result |= known_str[j] ^ user_str[j]; } RET<strong>*本文来源gaodai#ma#com搞@代~码^网+</strong><strong>搞代gaodaima码</strong>URN_BOOL(0 == result);}</code>
貌似和上面的 polyfill 沒什麼區別啊
回复内容:
在 php.net 看到一個版本,然而卻有很多 downvotes,不知爲何。
<code>if(!function_exists('hash_equals')) { function hash_equals($str1, $str2) { if(strlen($str1) != strlen($str2)) { return false; } else { $res = $str1 ^ $str2; $ret = 0; for($i = strlen($res) - 1; $i >= 0; $i--) $ret |= ord($res[$i]); return !$ret; } }}</code>
如果這個函數真的不好,請說明原因,最好還能給出替代解決方案,謝謝。
從 stackoverflow 看到其實現如下:
<code>PHP_FUNCTION(hash_equals){ /* ... */ if (Z_STRLEN_P(known_zval) != Z_STRLEN_P(user_zval)) { RETURN_FALSE; } /* ... */ /* This is security sensitive code. Do not optimize this for speed. */ for (j = 0; j < Z_STRLEN_P(known_zval); j++) { result |= known_str[j] ^ user_str[j]; } RETURN_BOOL(0 == result);}</code>
貌似和上面的 polyfill 沒什麼區別啊
因为类型不严格,导致如果攻击者能够通过某种方式控制入参的类型,可以攻击
<code>php</code><code>function bug_hash_equals($str1, $str2) { if(strlen($str1) != strlen($str2)) { return false; } else { $res = $str1 ^ $str2; $ret = 0; for($i = strlen($res) - 1; $i >= 0; $i--) $ret |= ord($res[$i]); return !$ret; }}var_dump(bug_hash_equals('aaabbb', 0.0001));//true</code>
http://sandbox.onlinephpfunctions.com/code/e7c978d047486534441403a88680cefb85b1a48c