Skip to content

hash_equals: Don't leak length difference. (Bug 67939) #791

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 11 additions & 9 deletions ext/hash/hash.c
Original file line number Diff line number Diff line change
Expand Up @@ -729,13 +729,12 @@ PHP_FUNCTION(hash_pbkdf2)
/* }}} */

/* {{{ proto bool hash_equals(string known_string, string user_string)
Compares two strings using the same time whether they're equal or not.
A difference in length will leak */
Compares two strings using the same time whether they're equal or not. */
PHP_FUNCTION(hash_equals)
{
zval *known_zval, *user_zval;
char *known_str, *user_str;
int result = 0, j;
int known_len, user_len, result, j;

if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &known_zval, &user_zval) == FAILURE) {
return;
Expand All @@ -752,16 +751,19 @@ PHP_FUNCTION(hash_equals)
RETURN_FALSE;
}

if (Z_STRLEN_P(known_zval) != Z_STRLEN_P(user_zval)) {
RETURN_FALSE;
}
known_len = Z_STRLEN_P(known_zval);
user_len = Z_STRLEN_P(user_zval);

known_str = Z_STRVAL_P(known_zval);
user_str = Z_STRVAL_P(user_zval);

/* 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];
/* Set result as different of 0 if strings have a different length. */
result = known_len - user_len;

/* This is security sensitive code. Do not optimize this for speed.
Always iterate on \0 to avoid issues with empty strings. */
for (j = 0; j < user_len + 1; j++) {
result |= known_str[j % (known_len + 1)] ^ user_str[j];
}

RETURN_BOOL(0 == result);
Expand Down