/src/php-src/ext/random/csprng.c
Line | Count | Source |
1 | | /* |
2 | | +----------------------------------------------------------------------+ |
3 | | | Copyright © The PHP Group and Contributors. | |
4 | | +----------------------------------------------------------------------+ |
5 | | | This source file is subject to the Modified BSD License that is | |
6 | | | bundled with this package in the file LICENSE, and is available | |
7 | | | through the World Wide Web at <https://www.php.net/license/>. | |
8 | | | | |
9 | | | SPDX-License-Identifier: BSD-3-Clause | |
10 | | +----------------------------------------------------------------------+ |
11 | | | Authors: Tim Düsterhus <timwolla@php.net> | |
12 | | | Go Kudo <zeriyoshi@php.net> | |
13 | | +----------------------------------------------------------------------+ |
14 | | */ |
15 | | |
16 | | #ifdef HAVE_CONFIG_H |
17 | | # include "config.h" |
18 | | #endif |
19 | | |
20 | | #include <stdlib.h> |
21 | | #include <sys/stat.h> |
22 | | #include <fcntl.h> |
23 | | |
24 | | #include "php.h" |
25 | | |
26 | | #include "Zend/zend_exceptions.h" |
27 | | |
28 | | #include "php_random.h" |
29 | | #include "php_random_csprng.h" |
30 | | |
31 | | #ifdef HAVE_UNISTD_H |
32 | | # include <unistd.h> |
33 | | #endif |
34 | | |
35 | | #ifdef PHP_WIN32 |
36 | | # include "win32/time.h" |
37 | | # include "win32/winutil.h" |
38 | | # include <process.h> |
39 | | #endif |
40 | | |
41 | | #ifdef __linux__ |
42 | | # include <sys/syscall.h> |
43 | | #endif |
44 | | |
45 | | #ifdef HAVE_SYS_PARAM_H |
46 | | # include <sys/param.h> |
47 | | # if (defined(__FreeBSD__) && __FreeBSD_version > 1200000) || (defined(__DragonFly__) && __DragonFly_version >= 500700) || \ |
48 | | (defined(__sun) && defined(HAVE_GETRANDOM)) || (defined(__NetBSD__) && __NetBSD_Version__ >= 1000000000) || defined(__midipix__) |
49 | | # include <sys/random.h> |
50 | | # endif |
51 | | #endif |
52 | | |
53 | | #ifdef HAVE_COMMONCRYPTO_COMMONRANDOM_H |
54 | | # include <CommonCrypto/CommonCryptoError.h> |
55 | | # include <CommonCrypto/CommonRandom.h> |
56 | | #endif |
57 | | |
58 | | #if __has_feature(memory_sanitizer) |
59 | | # include <sanitizer/msan_interface.h> |
60 | | #endif |
61 | | |
62 | | #ifndef PHP_WIN32 |
63 | | static atomic_int random_fd = -1; |
64 | | #endif |
65 | | |
66 | | ZEND_ATTRIBUTE_NONNULL PHPAPI zend_result php_random_bytes_ex(void *bytes, size_t size, char *errstr, size_t errstr_size) |
67 | 2 | { |
68 | | #ifdef PHP_WIN32 |
69 | | /* Defer to CryptGenRandom on Windows */ |
70 | | if (php_win32_get_random_bytes(bytes, size) == FAILURE) { |
71 | | snprintf(errstr, errstr_size, "Failed to retrieve randomness from the operating system (BCryptGenRandom)"); |
72 | | return FAILURE; |
73 | | } |
74 | | #elif defined(HAVE_COMMONCRYPTO_COMMONRANDOM_H) |
75 | | /* |
76 | | * Purposely prioritized upon arc4random_buf for modern macOs releases |
77 | | * arc4random api on this platform uses `ccrng_generate` which returns |
78 | | * a status but silented to respect the "no fail" arc4random api interface |
79 | | * the vast majority of the time, it works fine ; but better make sure we catch failures |
80 | | */ |
81 | | if (CCRandomGenerateBytes(bytes, size) != kCCSuccess) { |
82 | | snprintf(errstr, errstr_size, "Failed to retrieve randomness from the operating system (CCRandomGenerateBytes)"); |
83 | | return FAILURE; |
84 | | } |
85 | | #elif defined(HAVE_ARC4RANDOM_BUF) && ((defined(__OpenBSD__) && OpenBSD >= 201405) || (defined(__NetBSD__) && __NetBSD_Version__ >= 700000001 && __NetBSD_Version__ < 1000000000) || \ |
86 | | defined(__APPLE__) || defined(__HAIKU__)) |
87 | | /* |
88 | | * OpenBSD until there is a valid equivalent |
89 | | * or NetBSD before the 10.x release |
90 | | * falls back to arc4random_buf |
91 | | * giving a decent output, the main benefit |
92 | | * is being (relatively) failsafe. |
93 | | * Older macOs releases fall also into this |
94 | | * category for reasons explained above. |
95 | | */ |
96 | | arc4random_buf(bytes, size); |
97 | | #else |
98 | 2 | size_t read_bytes = 0; |
99 | 2 | # if (defined(__linux__) && defined(SYS_getrandom)) || (defined(__FreeBSD__) && __FreeBSD_version >= 1200000) || (defined(__DragonFly__) && __DragonFly_version >= 500700) || \ |
100 | 2 | (defined(__sun) && defined(HAVE_GETRANDOM)) || (defined(__NetBSD__) && __NetBSD_Version__ >= 1000000000) || defined(__midipix__) |
101 | | /* Linux getrandom(2) syscall or FreeBSD/DragonFlyBSD/NetBSD getrandom(2) function |
102 | | * Being a syscall, implemented in the kernel, getrandom offers higher quality output |
103 | | * compared to the arc4random api albeit a fallback to /dev/urandom is considered. |
104 | | */ |
105 | 4 | while (read_bytes < size) { |
106 | | /* Below, (bytes + read_bytes) is pointer arithmetic. |
107 | | |
108 | | bytes read_bytes size |
109 | | | | | |
110 | | [#######=============] (we're going to write over the = region) |
111 | | \\\\\\\\\\\\\ |
112 | | amount_to_read |
113 | | */ |
114 | 2 | size_t amount_to_read = size - read_bytes; |
115 | 2 | ssize_t n; |
116 | | |
117 | 2 | errno = 0; |
118 | 2 | # if defined(__linux__) |
119 | 2 | n = syscall(SYS_getrandom, bytes + read_bytes, amount_to_read, 0); |
120 | | # else |
121 | | n = getrandom(bytes + read_bytes, amount_to_read, 0); |
122 | | # endif |
123 | | |
124 | 2 | if (n == -1) { |
125 | 0 | if (errno == ENOSYS) { |
126 | | /* This can happen if PHP was compiled against a newer kernel where getrandom() |
127 | | * is available, but then runs on an older kernel without getrandom(). If this |
128 | | * happens we simply fall back to reading from /dev/urandom. */ |
129 | 0 | ZEND_ASSERT(read_bytes == 0); |
130 | 0 | break; |
131 | 0 | } else if (errno == EINTR || errno == EAGAIN) { |
132 | | /* Try again */ |
133 | 0 | continue; |
134 | 0 | } else { |
135 | | /* If the syscall fails, fall back to reading from /dev/urandom */ |
136 | 0 | break; |
137 | 0 | } |
138 | 0 | } |
139 | | |
140 | | # if __has_feature(memory_sanitizer) |
141 | | /* MSan does not instrument manual syscall invocations. */ |
142 | | __msan_unpoison(bytes + read_bytes, n); |
143 | | # endif |
144 | 2 | read_bytes += (size_t) n; |
145 | 2 | } |
146 | 2 | # endif |
147 | 2 | if (read_bytes < size) { |
148 | 0 | int fd = atomic_load(&random_fd); |
149 | 0 | struct stat st; |
150 | |
|
151 | 0 | if (fd < 0) { |
152 | 0 | errno = 0; |
153 | 0 | fd = open("/dev/urandom", O_RDONLY); |
154 | 0 | if (fd < 0) { |
155 | 0 | if (errno != 0) { |
156 | 0 | snprintf(errstr, errstr_size, "Cannot open /dev/urandom: %s", strerror(errno)); |
157 | 0 | } else { |
158 | 0 | snprintf(errstr, errstr_size, "Cannot open /dev/urandom"); |
159 | 0 | } |
160 | 0 | return FAILURE; |
161 | 0 | } |
162 | | |
163 | 0 | errno = 0; |
164 | | /* Does the file exist and is it a character device? */ |
165 | 0 | if (fstat(fd, &st) != 0 || |
166 | | # ifdef S_ISNAM |
167 | | !(S_ISNAM(st.st_mode) || S_ISCHR(st.st_mode)) |
168 | | # else |
169 | 0 | !S_ISCHR(st.st_mode) |
170 | 0 | # endif |
171 | 0 | ) { |
172 | 0 | close(fd); |
173 | 0 | if (errno != 0) { |
174 | 0 | snprintf(errstr, errstr_size, "Error reading from /dev/urandom: %s", strerror(errno)); |
175 | 0 | } else { |
176 | 0 | snprintf(errstr, errstr_size, "Error reading from /dev/urandom"); |
177 | 0 | } |
178 | 0 | return FAILURE; |
179 | 0 | } |
180 | 0 | int expected = -1; |
181 | 0 | if (!atomic_compare_exchange_strong(&random_fd, &expected, fd)) { |
182 | 0 | close(fd); |
183 | | /* expected is now the actual value of random_fd */ |
184 | 0 | fd = expected; |
185 | 0 | } |
186 | 0 | } |
187 | | |
188 | 0 | read_bytes = 0; |
189 | 0 | while (read_bytes < size) { |
190 | 0 | errno = 0; |
191 | 0 | ssize_t n = read(fd, bytes + read_bytes, size - read_bytes); |
192 | |
|
193 | 0 | if (n <= 0) { |
194 | 0 | if (errno != 0) { |
195 | 0 | snprintf(errstr, errstr_size, "Could not gather sufficient random data: %s", strerror(errno)); |
196 | 0 | } else { |
197 | 0 | snprintf(errstr, errstr_size, "Could not gather sufficient random data"); |
198 | 0 | } |
199 | 0 | return FAILURE; |
200 | 0 | } |
201 | | |
202 | 0 | read_bytes += (size_t) n; |
203 | 0 | } |
204 | 0 | } |
205 | 2 | #endif |
206 | | |
207 | 2 | return SUCCESS; |
208 | 2 | } |
209 | | |
210 | | ZEND_ATTRIBUTE_NONNULL PHPAPI zend_result php_random_bytes(void *bytes, size_t size, bool should_throw) |
211 | 2 | { |
212 | 2 | char errstr[128]; |
213 | 2 | zend_result result = php_random_bytes_ex(bytes, size, errstr, sizeof(errstr)); |
214 | | |
215 | 2 | if (result == FAILURE && should_throw) { |
216 | 0 | zend_throw_exception(random_ce_Random_RandomException, errstr, 0); |
217 | 0 | } |
218 | | |
219 | 2 | return result; |
220 | 2 | } |
221 | | |
222 | | ZEND_ATTRIBUTE_NONNULL PHPAPI zend_result php_random_int(zend_long min, zend_long max, zend_long *result, bool should_throw) |
223 | 1 | { |
224 | 1 | zend_ulong umax; |
225 | 1 | zend_ulong trial; |
226 | | |
227 | 1 | if (min == max) { |
228 | 0 | *result = min; |
229 | 0 | return SUCCESS; |
230 | 0 | } |
231 | | |
232 | 1 | umax = (zend_ulong) max - (zend_ulong) min; |
233 | | |
234 | 1 | if (php_random_bytes(&trial, sizeof(trial), should_throw) == FAILURE) { |
235 | 0 | return FAILURE; |
236 | 0 | } |
237 | | |
238 | | /* Special case where no modulus is required */ |
239 | 1 | if (umax == ZEND_ULONG_MAX) { |
240 | 0 | *result = (zend_long)trial; |
241 | 0 | return SUCCESS; |
242 | 0 | } |
243 | | |
244 | | /* Increment the max so the range is inclusive of max */ |
245 | 1 | umax++; |
246 | | |
247 | | /* Powers of two are not biased */ |
248 | 1 | if ((umax & (umax - 1)) != 0) { |
249 | | /* Ceiling under which ZEND_LONG_MAX % max == 0 */ |
250 | 0 | zend_ulong limit = ZEND_ULONG_MAX - (ZEND_ULONG_MAX % umax) - 1; |
251 | | |
252 | | /* Discard numbers over the limit to avoid modulo bias */ |
253 | 0 | while (trial > limit) { |
254 | 0 | if (php_random_bytes(&trial, sizeof(trial), should_throw) == FAILURE) { |
255 | 0 | return FAILURE; |
256 | 0 | } |
257 | 0 | } |
258 | 0 | } |
259 | | |
260 | 1 | *result = (zend_long)((trial % umax) + min); |
261 | 1 | return SUCCESS; |
262 | 1 | } |
263 | | |
264 | | PHPAPI void php_random_csprng_shutdown(void) |
265 | 0 | { |
266 | 0 | #ifndef PHP_WIN32 |
267 | 0 | int fd = atomic_exchange(&random_fd, -1); |
268 | 0 | if (fd != -1) { |
269 | 0 | close(fd); |
270 | 0 | } |
271 | 0 | #endif |
272 | 0 | } |