Skip to content

Commit

Permalink
Handle exceptions from __toString in XXH3's initialization
Browse files Browse the repository at this point in the history
The initialization routine for XXH3 was not prepared for exceptions from seed.
Fix this by using try_convert_to_string.

For discussion, please see: GH-10305

Closes GH-10352

Signed-off-by: George Peter Banyard <girgias@php.net>
  • Loading branch information
nielsdos authored and Girgias committed Jan 17, 2023
1 parent 398a10a commit 7463e70
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
3 changes: 3 additions & 0 deletions NEWS
Expand Up @@ -26,6 +26,9 @@ PHP NEWS
. Fixed bug #67244 (Wrong owner:group for listening unix socket).
(Jakub Zelenka)

- Hash:
. Handle exceptions from __toString in XXH3's initialization (nielsdos)

- LDAP:
. Fixed bug GH-10112 (LDAP\Connection::__construct() refers to ldap_create()).
(cmb)
Expand Down
4 changes: 3 additions & 1 deletion ext/hash/hash_xxhash.c
Expand Up @@ -174,7 +174,9 @@ zend_always_inline static void _PHP_XXH3_Init(PHP_XXH3_64_CTX *ctx, HashTable *a
func_init_seed(&ctx->s, (XXH64_hash_t)Z_LVAL_P(_seed));
return;
} else if (_secret) {
convert_to_string(_secret);
if (!try_convert_to_string(_secret)) {
return;
}
size_t len = Z_STRLEN_P(_secret);
if (len < PHP_XXH3_SECRET_SIZE_MIN) {
zend_throw_error(NULL, "%s: Secret length must be >= %u bytes, %zu bytes passed", algo_name, XXH3_SECRET_SIZE_MIN, len);
Expand Down
15 changes: 15 additions & 0 deletions ext/hash/tests/xxhash_secret.phpt
Expand Up @@ -3,6 +3,13 @@ Hash: xxHash secret
--FILE--
<?php

class StringableThrowingClass {
public function __toString(): string {
throw new Exception('exception in __toString');
return '';
}
}

foreach (["xxh3", "xxh128"] as $a) {

//$secret = random_bytes(256);
Expand All @@ -14,6 +21,12 @@ foreach (["xxh3", "xxh128"] as $a) {
var_dump($e->getMessage());
}

try {
$ctx = hash_init($a, options: ["secret" => new StringableThrowingClass()]);
} catch (Throwable $e) {
var_dump($e->getMessage());
}

try {
$ctx = hash_init($a, options: ["secret" => str_repeat('a', 17)]);
} catch (Throwable $e) {
Expand All @@ -35,8 +48,10 @@ foreach (["xxh3", "xxh128"] as $a) {
?>
--EXPECT--
string(67) "xxh3: Only one of seed or secret is to be passed for initialization"
string(23) "exception in __toString"
string(57) "xxh3: Secret length must be >= 136 bytes, 17 bytes passed"
8028aa834c03557a == 8028aa834c03557a == true
string(69) "xxh128: Only one of seed or secret is to be passed for initialization"
string(23) "exception in __toString"
string(59) "xxh128: Secret length must be >= 136 bytes, 17 bytes passed"
54279097795e7218093a05d4d781cbb9 == 54279097795e7218093a05d4d781cbb9 == true

0 comments on commit 7463e70

Please sign in to comment.