Skip to content

Fix reference type confusion and leak in user random engine #18718

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 6 commits into from
Closed
Show file tree
Hide file tree
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
12 changes: 9 additions & 3 deletions ext/random/engine_user.c
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,22 @@ static uint64_t generate(php_random_status *status)
uint64_t result = 0;
size_t size;
zval retval;
zend_string *zstr;

zend_call_known_instance_method_with_0_params(s->generate_method, s->object, &retval);

if (EG(exception)) {
return 0;
}

if (UNEXPECTED(Z_ISREF(retval))) {
zstr = Z_STR_P(Z_REFVAL(retval));
} else {
zstr = Z_STR(retval);
}

/* Store generated size in a state */
size = Z_STRLEN(retval);
size = ZSTR_LEN(zstr);

/* Guard for over 64-bit results */
if (size > sizeof(uint64_t)) {
Expand All @@ -46,11 +53,10 @@ static uint64_t generate(php_random_status *status)
if (size > 0) {
/* Endianness safe copy */
for (size_t i = 0; i < size; i++) {
result += ((uint64_t) (unsigned char) Z_STRVAL(retval)[i]) << (8 * i);
result += ((uint64_t) (unsigned char) ZSTR_VAL(zstr)[i]) << (8 * i);
}
} else {
zend_throw_error(random_ce_Random_BrokenRandomEngineError, "A random engine must return a non-empty string");
return 0;
}

zval_ptr_dtor(&retval);
Expand Down
25 changes: 25 additions & 0 deletions ext/random/tests/02_engine/user_reference_return.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
--TEST--
Random: Engine: User: Returning by reference works
--FILE--
<?php

use Random\Engine;
use Random\Randomizer;

final class ReferenceEngine implements Engine
{
private $field = 'abcdef';

public function &generate(): string
{
return $this->field;
}
}

$randomizer = new Randomizer(new ReferenceEngine());

var_dump($randomizer->getBytes(64));

?>
--EXPECT--
string(64) "abcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcd"
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ final class EmptyStringEngine implements Engine
{
public function generate(): string
{
return '';
// Create a non-interned empty string.
return preg_replace('/./', '', random_bytes(4));
}
}

Expand Down
Loading