Skip to content

Commit db44309

Browse files
committed
Improve openssl_random_pseudo_bytes()
CSPRNG implementations should always fail closed. Now openssl_random_pseudo_bytes() will fail closed by throwing an `\Exception` in fail conditions.
1 parent 0f7f149 commit db44309

File tree

3 files changed

+23
-7
lines changed

3 files changed

+23
-7
lines changed

ext/openssl/openssl.c

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
#include "php.h"
2929
#include "php_ini.h"
3030
#include "php_openssl.h"
31+
#include "zend_exceptions.h"
3132

3233
/* PHP Includes */
3334
#include "ext/standard/file.h"
@@ -6861,7 +6862,8 @@ PHP_FUNCTION(openssl_random_pseudo_bytes)
68616862
|| ZEND_LONG_INT_OVFL(buffer_length)
68626863
#endif
68636864
) {
6864-
RETURN_FALSE;
6865+
zend_throw_exception(zend_ce_error, "Length must be greater than 0", 0);
6866+
return;
68656867
}
68666868
buffer = zend_string_alloc(buffer_length, 0);
68676869

@@ -6872,7 +6874,8 @@ PHP_FUNCTION(openssl_random_pseudo_bytes)
68726874
if (zstrong_result_returned) {
68736875
ZVAL_FALSE(zstrong_result_returned);
68746876
}
6875-
RETURN_FALSE;
6877+
zend_throw_exception(zend_ce_exception, "Error reading from source device", 0);
6878+
return;
68766879
}
68776880
#else
68786881

@@ -6884,7 +6887,8 @@ PHP_FUNCTION(openssl_random_pseudo_bytes)
68846887
if (zstrong_result_returned) {
68856888
ZVAL_FALSE(zstrong_result_returned);
68866889
}
6887-
RETURN_FALSE;
6890+
zend_throw_exception(zend_ce_exception, "Error reading from source device", 0);
6891+
return;
68886892
} else {
68896893
php_openssl_store_errors();
68906894
}

ext/openssl/tests/openssl_random_pseudo_bytes_basic.phpt

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,11 @@ openssl_random_pseudo_bytes() tests
44
<?php if (!extension_loaded("openssl")) print "skip"; ?>
55
--FILE--
66
<?php
7-
for ($i = 0; $i < 10; $i++) {
8-
var_dump(bin2hex(openssl_random_pseudo_bytes($i, $strong)));
7+
for ($i = 1; $i < 10; $i++) {
8+
var_dump(bin2hex(openssl_random_pseudo_bytes($i)));
99
}
10-
1110
?>
1211
--EXPECTF--
13-
string(0) ""
1412
string(2) "%s"
1513
string(4) "%s"
1614
string(6) "%s"
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
--TEST--
2+
Test error operation of openssl_random_pseudo_bytes()
3+
--SKIPIF--
4+
<?php if (!extension_loaded("openssl")) print "skip"; ?>
5+
--FILE--
6+
<?php
7+
try {
8+
openssl_random_pseudo_bytes(0);
9+
} catch (Error $e) {
10+
echo $e->getMessage().PHP_EOL;
11+
}
12+
?>
13+
--EXPECTF--
14+
Length must be greater than 0

0 commit comments

Comments
 (0)