Skip to content

Commit e6cf7d7

Browse files
committed
Fix some lengths in crypt()
Use salt_len_in instead of strlen(salt) or PHP_MAX_SALT_LEN, otherwise too much memory will be allocated. sha512 has a 86 character checksum, not 43. That probably was a copy&paste from the sha256 code which indeed has 43. The allocation also was using sizeof(char *), thus allocating 4 or 8 times as much memory as necessary. The sizeof(char *) was removed in the 5.4 branch in b7a92c9 but forgotten on 5.3. The memset 0 call was using PHP_MAX_SALT_LEN which can be smaller than the output buffer and thus not zeroing out everything. Use the size of the output buffer (needed) instead.
1 parent 7e8276c commit e6cf7d7

File tree

1 file changed

+6
-6
lines changed

1 file changed

+6
-6
lines changed

ext/standard/crypt.c

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -199,8 +199,8 @@ PHP_FUNCTION(crypt)
199199
char *output;
200200
int needed = (sizeof(sha512_salt_prefix) - 1
201201
+ sizeof(sha512_rounds_prefix) + 9 + 1
202-
+ PHP_MAX_SALT_LEN + 1 + 43 + 1);
203-
output = emalloc(needed * sizeof(char *));
202+
+ salt_in_len + 1 + 86 + 1);
203+
output = emalloc(needed);
204204
salt[salt_in_len] = '\0';
205205

206206
crypt_res = php_sha512_crypt_r(str, salt, output, needed);
@@ -214,16 +214,16 @@ PHP_FUNCTION(crypt)
214214
RETVAL_STRING(output, 1);
215215
}
216216

217-
memset(output, 0, PHP_MAX_SALT_LEN + 1);
217+
memset(output, 0, needed);
218218
efree(output);
219219
} else if (salt[0]=='$' && salt[1]=='5' && salt[2]=='$') {
220220
const char sha256_salt_prefix[] = "$5$";
221221
const char sha256_rounds_prefix[] = "rounds=";
222222
char *output;
223223
int needed = (sizeof(sha256_salt_prefix) - 1
224224
+ sizeof(sha256_rounds_prefix) + 9 + 1
225-
+ PHP_MAX_SALT_LEN + 1 + 43 + 1);
226-
output = emalloc(needed * sizeof(char *));
225+
+ salt_in_len + 1 + 43 + 1);
226+
output = emalloc(needed);
227227
salt[salt_in_len] = '\0';
228228

229229
crypt_res = php_sha256_crypt_r(str, salt, output, needed);
@@ -237,7 +237,7 @@ PHP_FUNCTION(crypt)
237237
RETVAL_STRING(output, 1);
238238
}
239239

240-
memset(output, 0, PHP_MAX_SALT_LEN + 1);
240+
memset(output, 0, needed);
241241
efree(output);
242242
} else if (
243243
salt[0] == '$' &&

0 commit comments

Comments
 (0)