1 | /* |
2 | * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. |
3 | * |
4 | * Licensed under the Apache License 2.0 (the "License"). You may not use |
5 | * this file except in compliance with the License. You can obtain a copy |
6 | * in the file LICENSE in the source distribution or at |
7 | * https://www.openssl.org/source/license.html |
8 | */ |
9 | |
10 | #ifndef _GNU_SOURCE |
11 | # define _GNU_SOURCE |
12 | #endif |
13 | #include "e_os.h" |
14 | #include <stdio.h> |
15 | #include "internal/cryptlib.h" |
16 | #include <openssl/rand.h> |
17 | #include <openssl/crypto.h> |
18 | #include "rand_local.h" |
19 | #include "crypto/rand.h" |
20 | #include <stdio.h> |
21 | #include "internal/dso.h" |
22 | |
23 | /* |
24 | * Defines related to seed sources |
25 | */ |
26 | #ifndef DEVRANDOM |
27 | /* |
28 | * set this to a comma-separated list of 'random' device files to try out. By |
29 | * default, we will try to read at least one of these files |
30 | */ |
31 | # define DEVRANDOM "/dev/urandom", "/dev/random", "/dev/hwrng", "/dev/srandom" |
32 | # if defined(__linux) && !defined(__ANDROID__) |
33 | # ifndef DEVRANDOM_WAIT |
34 | # define DEVRANDOM_WAIT "/dev/random" |
35 | # endif |
36 | /* |
37 | * Linux kernels 4.8 and later changes how their random device works and there |
38 | * is no reliable way to tell that /dev/urandom has been seeded -- getentropy(2) |
39 | * should be used instead. |
40 | */ |
41 | # ifndef DEVRANDOM_SAFE_KERNEL |
42 | # define DEVRANDOM_SAFE_KERNEL 4, 8 |
43 | # endif |
44 | /* |
45 | * Some operating systems do not permit select(2) on their random devices, |
46 | * defining this to zero will force the use of read(2) to extract one byte |
47 | * from /dev/random. |
48 | */ |
49 | # ifndef DEVRANDM_WAIT_USE_SELECT |
50 | # define DEVRANDM_WAIT_USE_SELECT 1 |
51 | # endif |
52 | /* |
53 | * Define the shared memory identifier used to indicate if the operating |
54 | * system has properly seeded the DEVRANDOM source. |
55 | */ |
56 | # ifndef OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID |
57 | # define OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID 114 |
58 | # endif |
59 | |
60 | # endif |
61 | #endif |
62 | |
63 | #if !defined(OPENSSL_NO_EGD) && !defined(DEVRANDOM_EGD) |
64 | /* |
65 | * set this to a comma-separated list of 'egd' sockets to try out. These |
66 | * sockets will be tried in the order listed in case accessing the device |
67 | * files listed in DEVRANDOM did not return enough randomness. |
68 | */ |
69 | # define DEVRANDOM_EGD "/var/run/egd-pool", "/dev/egd-pool", "/etc/egd-pool", "/etc/entropy" |
70 | #endif |
71 | |
72 | #ifdef __linux |
73 | # include <sys/syscall.h> |
74 | # ifdef DEVRANDOM_WAIT |
75 | # include <sys/shm.h> |
76 | # include <sys/utsname.h> |
77 | # endif |
78 | #endif |
79 | #if defined(__FreeBSD__) && !defined(OPENSSL_SYS_UEFI) |
80 | # include <sys/types.h> |
81 | # include <sys/sysctl.h> |
82 | # include <sys/param.h> |
83 | #endif |
84 | #if defined(__OpenBSD__) || defined(__NetBSD__) |
85 | # include <sys/param.h> |
86 | #endif |
87 | |
88 | #if (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS)) \ |
89 | || defined(__DJGPP__) |
90 | # include <sys/types.h> |
91 | # include <sys/stat.h> |
92 | # include <fcntl.h> |
93 | # include <unistd.h> |
94 | # include <sys/time.h> |
95 | |
96 | static uint64_t get_time_stamp(void); |
97 | static uint64_t get_timer_bits(void); |
98 | |
99 | /* Macro to convert two thirty two bit values into a sixty four bit one */ |
100 | # define TWO32TO64(a, b) ((((uint64_t)(a)) << 32) + (b)) |
101 | |
102 | /* |
103 | * Check for the existence and support of POSIX timers. The standard |
104 | * says that the _POSIX_TIMERS macro will have a positive value if they |
105 | * are available. |
106 | * |
107 | * However, we want an additional constraint: that the timer support does |
108 | * not require an extra library dependency. Early versions of glibc |
109 | * require -lrt to be specified on the link line to access the timers, |
110 | * so this needs to be checked for. |
111 | * |
112 | * It is worse because some libraries define __GLIBC__ but don't |
113 | * support the version testing macro (e.g. uClibc). This means |
114 | * an extra check is needed. |
115 | * |
116 | * The final condition is: |
117 | * "have posix timers and either not glibc or glibc without -lrt" |
118 | * |
119 | * The nested #if sequences are required to avoid using a parameterised |
120 | * macro that might be undefined. |
121 | */ |
122 | # undef OSSL_POSIX_TIMER_OKAY |
123 | # if defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0 |
124 | # if defined(__GLIBC__) |
125 | # else |
126 | # define OSSL_POSIX_TIMER_OKAY |
127 | # endif |
128 | # endif |
129 | #endif /* (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS)) |
130 | || defined(__DJGPP__) */ |
131 | |
132 | #if defined(OPENSSL_RAND_SEED_NONE) |
133 | /* none means none. this simplifies the following logic */ |
134 | # undef OPENSSL_RAND_SEED_OS |
135 | # undef OPENSSL_RAND_SEED_GETRANDOM |
136 | # undef OPENSSL_RAND_SEED_LIBRANDOM |
137 | # undef OPENSSL_RAND_SEED_DEVRANDOM |
138 | # undef OPENSSL_RAND_SEED_RDTSC |
139 | # undef OPENSSL_RAND_SEED_RDCPU |
140 | # undef OPENSSL_RAND_SEED_EGD |
141 | #endif |
142 | |
143 | #if defined(OPENSSL_SYS_UEFI) && !defined(OPENSSL_RAND_SEED_NONE) |
144 | # error "UEFI only supports seeding NONE" |
145 | #endif |
146 | |
147 | #if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) \ |
148 | || defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_VXWORKS) \ |
149 | || defined(OPENSSL_SYS_UEFI)) |
150 | |
151 | # if defined(OPENSSL_SYS_VOS) |
152 | |
153 | # ifndef OPENSSL_RAND_SEED_OS |
154 | # error "Unsupported seeding method configured; must be os" |
155 | # endif |
156 | |
157 | # if defined(OPENSSL_SYS_VOS_HPPA) && defined(OPENSSL_SYS_VOS_IA32) |
158 | # error "Unsupported HP-PA and IA32 at the same time." |
159 | # endif |
160 | # if !defined(OPENSSL_SYS_VOS_HPPA) && !defined(OPENSSL_SYS_VOS_IA32) |
161 | # error "Must have one of HP-PA or IA32" |
162 | # endif |
163 | |
164 | /* |
165 | * The following algorithm repeatedly samples the real-time clock (RTC) to |
166 | * generate a sequence of unpredictable data. The algorithm relies upon the |
167 | * uneven execution speed of the code (due to factors such as cache misses, |
168 | * interrupts, bus activity, and scheduling) and upon the rather large |
169 | * relative difference between the speed of the clock and the rate at which |
170 | * it can be read. If it is ported to an environment where execution speed |
171 | * is more constant or where the RTC ticks at a much slower rate, or the |
172 | * clock can be read with fewer instructions, it is likely that the results |
173 | * would be far more predictable. This should only be used for legacy |
174 | * platforms. |
175 | * |
176 | * As a precaution, we assume only 2 bits of entropy per byte. |
177 | */ |
178 | size_t rand_pool_acquire_entropy(RAND_POOL *pool) |
179 | { |
180 | short int code; |
181 | int i, k; |
182 | size_t bytes_needed; |
183 | struct timespec ts; |
184 | unsigned char v; |
185 | # ifdef OPENSSL_SYS_VOS_HPPA |
186 | long duration; |
187 | extern void s$sleep(long *_duration, short int *_code); |
188 | # else |
189 | long long duration; |
190 | extern void s$sleep2(long long *_duration, short int *_code); |
191 | # endif |
192 | |
193 | bytes_needed = rand_pool_bytes_needed(pool, 4 /*entropy_factor*/); |
194 | |
195 | for (i = 0; i < bytes_needed; i++) { |
196 | /* |
197 | * burn some cpu; hope for interrupts, cache collisions, bus |
198 | * interference, etc. |
199 | */ |
200 | for (k = 0; k < 99; k++) |
201 | ts.tv_nsec = random(); |
202 | |
203 | # ifdef OPENSSL_SYS_VOS_HPPA |
204 | /* sleep for 1/1024 of a second (976 us). */ |
205 | duration = 1; |
206 | s$sleep(&duration, &code); |
207 | # else |
208 | /* sleep for 1/65536 of a second (15 us). */ |
209 | duration = 1; |
210 | s$sleep2(&duration, &code); |
211 | # endif |
212 | |
213 | /* Get wall clock time, take 8 bits. */ |
214 | clock_gettime(CLOCK_REALTIME, &ts); |
215 | v = (unsigned char)(ts.tv_nsec & 0xFF); |
216 | rand_pool_add(pool, arg, &v, sizeof(v) , 2); |
217 | } |
218 | return rand_pool_entropy_available(pool); |
219 | } |
220 | |
221 | void rand_pool_cleanup(void) |
222 | { |
223 | } |
224 | |
225 | void rand_pool_keep_random_devices_open(int keep) |
226 | { |
227 | } |
228 | |
229 | # else |
230 | |
231 | # if defined(OPENSSL_RAND_SEED_EGD) && \ |
232 | (defined(OPENSSL_NO_EGD) || !defined(DEVRANDOM_EGD)) |
233 | # error "Seeding uses EGD but EGD is turned off or no device given" |
234 | # endif |
235 | |
236 | # if defined(OPENSSL_RAND_SEED_DEVRANDOM) && !defined(DEVRANDOM) |
237 | # error "Seeding uses urandom but DEVRANDOM is not configured" |
238 | # endif |
239 | |
240 | # if defined(OPENSSL_RAND_SEED_OS) |
241 | # if !defined(DEVRANDOM) |
242 | # error "OS seeding requires DEVRANDOM to be configured" |
243 | # endif |
244 | # define OPENSSL_RAND_SEED_GETRANDOM |
245 | # define OPENSSL_RAND_SEED_DEVRANDOM |
246 | # endif |
247 | |
248 | # if defined(OPENSSL_RAND_SEED_LIBRANDOM) |
249 | # error "librandom not (yet) supported" |
250 | # endif |
251 | |
252 | # if (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND) |
253 | /* |
254 | * sysctl_random(): Use sysctl() to read a random number from the kernel |
255 | * Returns the number of bytes returned in buf on success, -1 on failure. |
256 | */ |
257 | static ssize_t sysctl_random(char *buf, size_t buflen) |
258 | { |
259 | int mib[2]; |
260 | size_t done = 0; |
261 | size_t len; |
262 | |
263 | /* |
264 | * Note: sign conversion between size_t and ssize_t is safe even |
265 | * without a range check, see comment in syscall_random() |
266 | */ |
267 | |
268 | /* |
269 | * On FreeBSD old implementations returned longs, newer versions support |
270 | * variable sizes up to 256 byte. The code below would not work properly |
271 | * when the sysctl returns long and we want to request something not a |
272 | * multiple of longs, which should never be the case. |
273 | */ |
274 | if (!ossl_assert(buflen % sizeof(long) == 0)) { |
275 | errno = EINVAL; |
276 | return -1; |
277 | } |
278 | |
279 | /* |
280 | * On NetBSD before 4.0 KERN_ARND was an alias for KERN_URND, and only |
281 | * filled in an int, leaving the rest uninitialized. Since NetBSD 4.0 |
282 | * it returns a variable number of bytes with the current version supporting |
283 | * up to 256 bytes. |
284 | * Just return an error on older NetBSD versions. |
285 | */ |
286 | #if defined(__NetBSD__) && __NetBSD_Version__ < 400000000 |
287 | errno = ENOSYS; |
288 | return -1; |
289 | #endif |
290 | |
291 | mib[0] = CTL_KERN; |
292 | mib[1] = KERN_ARND; |
293 | |
294 | do { |
295 | len = buflen; |
296 | if (sysctl(mib, 2, buf, &len, NULL, 0) == -1) |
297 | return done > 0 ? done : -1; |
298 | done += len; |
299 | buf += len; |
300 | buflen -= len; |
301 | } while (buflen > 0); |
302 | |
303 | return done; |
304 | } |
305 | # endif |
306 | |
307 | # if defined(OPENSSL_RAND_SEED_GETRANDOM) |
308 | |
309 | # if defined(__linux) && !defined(__NR_getrandom) |
310 | # if defined(__arm__) |
311 | # define __NR_getrandom (__NR_SYSCALL_BASE+384) |
312 | # elif defined(__i386__) |
313 | # define __NR_getrandom 355 |
314 | # elif defined(__x86_64__) |
315 | # if defined(__ILP32__) |
316 | # define __NR_getrandom (__X32_SYSCALL_BIT + 318) |
317 | # else |
318 | # define __NR_getrandom 318 |
319 | # endif |
320 | # elif defined(__xtensa__) |
321 | # define __NR_getrandom 338 |
322 | # elif defined(__s390__) || defined(__s390x__) |
323 | # define __NR_getrandom 349 |
324 | # elif defined(__bfin__) |
325 | # define __NR_getrandom 389 |
326 | # elif defined(__powerpc__) |
327 | # define __NR_getrandom 359 |
328 | # elif defined(__mips__) || defined(__mips64) |
329 | # if _MIPS_SIM == _MIPS_SIM_ABI32 |
330 | # define __NR_getrandom (__NR_Linux + 353) |
331 | # elif _MIPS_SIM == _MIPS_SIM_ABI64 |
332 | # define __NR_getrandom (__NR_Linux + 313) |
333 | # elif _MIPS_SIM == _MIPS_SIM_NABI32 |
334 | # define __NR_getrandom (__NR_Linux + 317) |
335 | # endif |
336 | # elif defined(__hppa__) |
337 | # define __NR_getrandom (__NR_Linux + 339) |
338 | # elif defined(__sparc__) |
339 | # define __NR_getrandom 347 |
340 | # elif defined(__ia64__) |
341 | # define __NR_getrandom 1339 |
342 | # elif defined(__alpha__) |
343 | # define __NR_getrandom 511 |
344 | # elif defined(__sh__) |
345 | # if defined(__SH5__) |
346 | # define __NR_getrandom 373 |
347 | # else |
348 | # define __NR_getrandom 384 |
349 | # endif |
350 | # elif defined(__avr32__) |
351 | # define __NR_getrandom 317 |
352 | # elif defined(__microblaze__) |
353 | # define __NR_getrandom 385 |
354 | # elif defined(__m68k__) |
355 | # define __NR_getrandom 352 |
356 | # elif defined(__cris__) |
357 | # define __NR_getrandom 356 |
358 | # elif defined(__aarch64__) |
359 | # define __NR_getrandom 278 |
360 | # else /* generic */ |
361 | # define __NR_getrandom 278 |
362 | # endif |
363 | # endif |
364 | |
365 | /* |
366 | * syscall_random(): Try to get random data using a system call |
367 | * returns the number of bytes returned in buf, or < 0 on error. |
368 | */ |
369 | static ssize_t syscall_random(void *buf, size_t buflen) |
370 | { |
371 | /* |
372 | * Note: 'buflen' equals the size of the buffer which is used by the |
373 | * get_entropy() callback of the RAND_DRBG. It is roughly bounded by |
374 | * |
375 | * 2 * RAND_POOL_FACTOR * (RAND_DRBG_STRENGTH / 8) = 2^14 |
376 | * |
377 | * which is way below the OSSL_SSIZE_MAX limit. Therefore sign conversion |
378 | * between size_t and ssize_t is safe even without a range check. |
379 | */ |
380 | |
381 | /* |
382 | * Do runtime detection to find getentropy(). |
383 | * |
384 | * Known OSs that should support this: |
385 | * - Darwin since 16 (OSX 10.12, IOS 10.0). |
386 | * - Solaris since 11.3 |
387 | * - OpenBSD since 5.6 |
388 | * - Linux since 3.17 with glibc 2.25 |
389 | * - FreeBSD since 12.0 (1200061) |
390 | */ |
391 | # if defined(__GNUC__) && __GNUC__>=2 && defined(__ELF__) && !defined(__hpux) |
392 | extern int getentropy(void *buffer, size_t length) __attribute__((weak)); |
393 | |
394 | if (getentropy != NULL) |
395 | return getentropy(buf, buflen) == 0 ? (ssize_t)buflen : -1; |
396 | # elif !defined(FIPS_MODE) |
397 | union { |
398 | void *p; |
399 | int (*f)(void *buffer, size_t length); |
400 | } p_getentropy; |
401 | |
402 | /* |
403 | * We could cache the result of the lookup, but we normally don't |
404 | * call this function often. |
405 | */ |
406 | ERR_set_mark(); |
407 | p_getentropy.p = DSO_global_lookup("getentropy" ); |
408 | ERR_pop_to_mark(); |
409 | if (p_getentropy.p != NULL) |
410 | return p_getentropy.f(buf, buflen) == 0 ? (ssize_t)buflen : -1; |
411 | # endif |
412 | |
413 | /* Linux supports this since version 3.17 */ |
414 | # if defined(__linux) && defined(__NR_getrandom) |
415 | return syscall(__NR_getrandom, buf, buflen, 0); |
416 | # elif (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND) |
417 | return sysctl_random(buf, buflen); |
418 | # else |
419 | errno = ENOSYS; |
420 | return -1; |
421 | # endif |
422 | } |
423 | # endif /* defined(OPENSSL_RAND_SEED_GETRANDOM) */ |
424 | |
425 | # if defined(OPENSSL_RAND_SEED_DEVRANDOM) |
426 | static const char *random_device_paths[] = { DEVRANDOM }; |
427 | static struct random_device { |
428 | int fd; |
429 | dev_t dev; |
430 | ino_t ino; |
431 | mode_t mode; |
432 | dev_t rdev; |
433 | } random_devices[OSSL_NELEM(random_device_paths)]; |
434 | static int keep_random_devices_open = 1; |
435 | |
436 | # if defined(__linux) && defined(DEVRANDOM_WAIT) |
437 | static void *shm_addr; |
438 | |
439 | # if !defined(FIPS_MODE) |
440 | static void cleanup_shm(void) |
441 | { |
442 | shmdt(shm_addr); |
443 | } |
444 | # endif |
445 | |
446 | /* |
447 | * Ensure that the system randomness source has been adequately seeded. |
448 | * This is done by having the first start of libcrypto, wait until the device |
449 | * /dev/random becomes able to supply a byte of entropy. Subsequent starts |
450 | * of the library and later reseedings do not need to do this. |
451 | */ |
452 | static int wait_random_seeded(void) |
453 | { |
454 | static int seeded = OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID < 0; |
455 | static const int kernel_version[] = { DEVRANDOM_SAFE_KERNEL }; |
456 | int kernel[2]; |
457 | int shm_id, fd, r; |
458 | char c, *p; |
459 | struct utsname un; |
460 | fd_set fds; |
461 | |
462 | if (!seeded) { |
463 | /* See if anything has created the global seeded indication */ |
464 | if ((shm_id = shmget(OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID, 1, 0)) == -1) { |
465 | /* |
466 | * Check the kernel's version and fail if it is too recent. |
467 | * |
468 | * Linux kernels from 4.8 onwards do not guarantee that |
469 | * /dev/urandom is properly seeded when /dev/random becomes |
470 | * readable. However, such kernels support the getentropy(2) |
471 | * system call and this should always succeed which renders |
472 | * this alternative but essentially identical source moot. |
473 | */ |
474 | if (uname(&un) == 0) { |
475 | kernel[0] = atoi(un.release); |
476 | p = strchr(un.release, '.'); |
477 | kernel[1] = p == NULL ? 0 : atoi(p + 1); |
478 | if (kernel[0] > kernel_version[0] |
479 | || (kernel[0] == kernel_version[0] |
480 | && kernel[1] >= kernel_version[1])) { |
481 | return 0; |
482 | } |
483 | } |
484 | /* Open /dev/random and wait for it to be readable */ |
485 | if ((fd = open(DEVRANDOM_WAIT, O_RDONLY)) != -1) { |
486 | if (DEVRANDM_WAIT_USE_SELECT && fd < FD_SETSIZE) { |
487 | FD_ZERO(&fds); |
488 | FD_SET(fd, &fds); |
489 | while ((r = select(fd + 1, &fds, NULL, NULL, NULL)) < 0 |
490 | && errno == EINTR); |
491 | } else { |
492 | while ((r = read(fd, &c, 1)) < 0 && errno == EINTR); |
493 | } |
494 | close(fd); |
495 | if (r == 1) { |
496 | seeded = 1; |
497 | /* Create the shared memory indicator */ |
498 | shm_id = shmget(OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID, 1, |
499 | IPC_CREAT | S_IRUSR | S_IRGRP | S_IROTH); |
500 | } |
501 | } |
502 | } |
503 | if (shm_id != -1) { |
504 | seeded = 1; |
505 | /* |
506 | * Map the shared memory to prevent its premature destruction. |
507 | * If this call fails, it isn't a big problem. |
508 | */ |
509 | shm_addr = shmat(shm_id, NULL, SHM_RDONLY); |
510 | # ifndef FIPS_MODE |
511 | /* TODO 3.0: The FIPS provider doesn't have OPENSSL_atexit */ |
512 | if (shm_addr != (void *)-1) |
513 | OPENSSL_atexit(&cleanup_shm); |
514 | # endif |
515 | } |
516 | } |
517 | return seeded; |
518 | } |
519 | # else /* defined __linux */ |
520 | static int wait_random_seeded(void) |
521 | { |
522 | return 1; |
523 | } |
524 | # endif |
525 | |
526 | /* |
527 | * Verify that the file descriptor associated with the random source is |
528 | * still valid. The rationale for doing this is the fact that it is not |
529 | * uncommon for daemons to close all open file handles when daemonizing. |
530 | * So the handle might have been closed or even reused for opening |
531 | * another file. |
532 | */ |
533 | static int check_random_device(struct random_device * rd) |
534 | { |
535 | struct stat st; |
536 | |
537 | return rd->fd != -1 |
538 | && fstat(rd->fd, &st) != -1 |
539 | && rd->dev == st.st_dev |
540 | && rd->ino == st.st_ino |
541 | && ((rd->mode ^ st.st_mode) & ~(S_IRWXU | S_IRWXG | S_IRWXO)) == 0 |
542 | && rd->rdev == st.st_rdev; |
543 | } |
544 | |
545 | /* |
546 | * Open a random device if required and return its file descriptor or -1 on error |
547 | */ |
548 | static int get_random_device(size_t n) |
549 | { |
550 | struct stat st; |
551 | struct random_device * rd = &random_devices[n]; |
552 | |
553 | /* reuse existing file descriptor if it is (still) valid */ |
554 | if (check_random_device(rd)) |
555 | return rd->fd; |
556 | |
557 | /* open the random device ... */ |
558 | if ((rd->fd = open(random_device_paths[n], O_RDONLY)) == -1) |
559 | return rd->fd; |
560 | |
561 | /* ... and cache its relevant stat(2) data */ |
562 | if (fstat(rd->fd, &st) != -1) { |
563 | rd->dev = st.st_dev; |
564 | rd->ino = st.st_ino; |
565 | rd->mode = st.st_mode; |
566 | rd->rdev = st.st_rdev; |
567 | } else { |
568 | close(rd->fd); |
569 | rd->fd = -1; |
570 | } |
571 | |
572 | return rd->fd; |
573 | } |
574 | |
575 | /* |
576 | * Close a random device making sure it is a random device |
577 | */ |
578 | static void close_random_device(size_t n) |
579 | { |
580 | struct random_device * rd = &random_devices[n]; |
581 | |
582 | if (check_random_device(rd)) |
583 | close(rd->fd); |
584 | rd->fd = -1; |
585 | } |
586 | |
587 | int rand_pool_init(void) |
588 | { |
589 | size_t i; |
590 | |
591 | for (i = 0; i < OSSL_NELEM(random_devices); i++) |
592 | random_devices[i].fd = -1; |
593 | |
594 | return 1; |
595 | } |
596 | |
597 | void rand_pool_cleanup(void) |
598 | { |
599 | size_t i; |
600 | |
601 | for (i = 0; i < OSSL_NELEM(random_devices); i++) |
602 | close_random_device(i); |
603 | } |
604 | |
605 | void rand_pool_keep_random_devices_open(int keep) |
606 | { |
607 | if (!keep) |
608 | rand_pool_cleanup(); |
609 | |
610 | keep_random_devices_open = keep; |
611 | } |
612 | |
613 | # else /* !defined(OPENSSL_RAND_SEED_DEVRANDOM) */ |
614 | |
615 | int rand_pool_init(void) |
616 | { |
617 | return 1; |
618 | } |
619 | |
620 | void rand_pool_cleanup(void) |
621 | { |
622 | } |
623 | |
624 | void rand_pool_keep_random_devices_open(int keep) |
625 | { |
626 | } |
627 | |
628 | # endif /* defined(OPENSSL_RAND_SEED_DEVRANDOM) */ |
629 | |
630 | /* |
631 | * Try the various seeding methods in turn, exit when successful. |
632 | * |
633 | * TODO(DRBG): If more than one entropy source is available, is it |
634 | * preferable to stop as soon as enough entropy has been collected |
635 | * (as favored by @rsalz) or should one rather be defensive and add |
636 | * more entropy than requested and/or from different sources? |
637 | * |
638 | * Currently, the user can select multiple entropy sources in the |
639 | * configure step, yet in practice only the first available source |
640 | * will be used. A more flexible solution has been requested, but |
641 | * currently it is not clear how this can be achieved without |
642 | * overengineering the problem. There are many parameters which |
643 | * could be taken into account when selecting the order and amount |
644 | * of input from the different entropy sources (trust, quality, |
645 | * possibility of blocking). |
646 | */ |
647 | size_t rand_pool_acquire_entropy(RAND_POOL *pool) |
648 | { |
649 | # if defined(OPENSSL_RAND_SEED_NONE) |
650 | return rand_pool_entropy_available(pool); |
651 | # else |
652 | size_t entropy_available; |
653 | |
654 | # if defined(OPENSSL_RAND_SEED_GETRANDOM) |
655 | { |
656 | size_t bytes_needed; |
657 | unsigned char *buffer; |
658 | ssize_t bytes; |
659 | /* Maximum allowed number of consecutive unsuccessful attempts */ |
660 | int attempts = 3; |
661 | |
662 | bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/); |
663 | while (bytes_needed != 0 && attempts-- > 0) { |
664 | buffer = rand_pool_add_begin(pool, bytes_needed); |
665 | bytes = syscall_random(buffer, bytes_needed); |
666 | if (bytes > 0) { |
667 | rand_pool_add_end(pool, bytes, 8 * bytes); |
668 | bytes_needed -= bytes; |
669 | attempts = 3; /* reset counter after successful attempt */ |
670 | } else if (bytes < 0 && errno != EINTR) { |
671 | break; |
672 | } |
673 | } |
674 | } |
675 | entropy_available = rand_pool_entropy_available(pool); |
676 | if (entropy_available > 0) |
677 | return entropy_available; |
678 | # endif |
679 | |
680 | # if defined(OPENSSL_RAND_SEED_LIBRANDOM) |
681 | { |
682 | /* Not yet implemented. */ |
683 | } |
684 | # endif |
685 | |
686 | # if defined(OPENSSL_RAND_SEED_DEVRANDOM) |
687 | if (wait_random_seeded()) { |
688 | size_t bytes_needed; |
689 | unsigned char *buffer; |
690 | size_t i; |
691 | |
692 | bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/); |
693 | for (i = 0; bytes_needed > 0 && i < OSSL_NELEM(random_device_paths); |
694 | i++) { |
695 | ssize_t bytes = 0; |
696 | /* Maximum number of consecutive unsuccessful attempts */ |
697 | int attempts = 3; |
698 | const int fd = get_random_device(i); |
699 | |
700 | if (fd == -1) |
701 | continue; |
702 | |
703 | while (bytes_needed != 0 && attempts-- > 0) { |
704 | buffer = rand_pool_add_begin(pool, bytes_needed); |
705 | bytes = read(fd, buffer, bytes_needed); |
706 | |
707 | if (bytes > 0) { |
708 | rand_pool_add_end(pool, bytes, 8 * bytes); |
709 | bytes_needed -= bytes; |
710 | attempts = 3; /* reset counter on successful attempt */ |
711 | } else if (bytes < 0 && errno != EINTR) { |
712 | break; |
713 | } |
714 | } |
715 | if (bytes < 0 || !keep_random_devices_open) |
716 | close_random_device(i); |
717 | |
718 | bytes_needed = rand_pool_bytes_needed(pool, 1); |
719 | } |
720 | entropy_available = rand_pool_entropy_available(pool); |
721 | if (entropy_available > 0) |
722 | return entropy_available; |
723 | } |
724 | # endif |
725 | |
726 | # if defined(OPENSSL_RAND_SEED_RDTSC) |
727 | entropy_available = rand_acquire_entropy_from_tsc(pool); |
728 | if (entropy_available > 0) |
729 | return entropy_available; |
730 | # endif |
731 | |
732 | # if defined(OPENSSL_RAND_SEED_RDCPU) |
733 | entropy_available = rand_acquire_entropy_from_cpu(pool); |
734 | if (entropy_available > 0) |
735 | return entropy_available; |
736 | # endif |
737 | |
738 | # if defined(OPENSSL_RAND_SEED_EGD) |
739 | { |
740 | static const char *paths[] = { DEVRANDOM_EGD, NULL }; |
741 | size_t bytes_needed; |
742 | unsigned char *buffer; |
743 | int i; |
744 | |
745 | bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/); |
746 | for (i = 0; bytes_needed > 0 && paths[i] != NULL; i++) { |
747 | size_t bytes = 0; |
748 | int num; |
749 | |
750 | buffer = rand_pool_add_begin(pool, bytes_needed); |
751 | num = RAND_query_egd_bytes(paths[i], |
752 | buffer, (int)bytes_needed); |
753 | if (num == (int)bytes_needed) |
754 | bytes = bytes_needed; |
755 | |
756 | rand_pool_add_end(pool, bytes, 8 * bytes); |
757 | bytes_needed = rand_pool_bytes_needed(pool, 1); |
758 | } |
759 | entropy_available = rand_pool_entropy_available(pool); |
760 | if (entropy_available > 0) |
761 | return entropy_available; |
762 | } |
763 | # endif |
764 | |
765 | return rand_pool_entropy_available(pool); |
766 | # endif |
767 | } |
768 | # endif |
769 | #endif |
770 | |
771 | #if (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS)) \ |
772 | || defined(__DJGPP__) |
773 | int rand_pool_add_nonce_data(RAND_POOL *pool) |
774 | { |
775 | struct { |
776 | pid_t pid; |
777 | CRYPTO_THREAD_ID tid; |
778 | uint64_t time; |
779 | } data; |
780 | |
781 | /* Erase the entire structure including any padding */ |
782 | memset(&data, 0, sizeof(data)); |
783 | |
784 | /* |
785 | * Add process id, thread id, and a high resolution timestamp to |
786 | * ensure that the nonce is unique with high probability for |
787 | * different process instances. |
788 | */ |
789 | data.pid = getpid(); |
790 | data.tid = CRYPTO_THREAD_get_current_id(); |
791 | data.time = get_time_stamp(); |
792 | |
793 | return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0); |
794 | } |
795 | |
796 | int rand_pool_add_additional_data(RAND_POOL *pool) |
797 | { |
798 | struct { |
799 | int fork_id; |
800 | CRYPTO_THREAD_ID tid; |
801 | uint64_t time; |
802 | } data; |
803 | |
804 | /* Erase the entire structure including any padding */ |
805 | memset(&data, 0, sizeof(data)); |
806 | |
807 | /* |
808 | * Add some noise from the thread id and a high resolution timer. |
809 | * The fork_id adds some extra fork-safety. |
810 | * The thread id adds a little randomness if the drbg is accessed |
811 | * concurrently (which is the case for the <master> drbg). |
812 | */ |
813 | data.fork_id = openssl_get_fork_id(); |
814 | data.tid = CRYPTO_THREAD_get_current_id(); |
815 | data.time = get_timer_bits(); |
816 | |
817 | return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0); |
818 | } |
819 | |
820 | |
821 | /* |
822 | * Get the current time with the highest possible resolution |
823 | * |
824 | * The time stamp is added to the nonce, so it is optimized for not repeating. |
825 | * The current time is ideal for this purpose, provided the computer's clock |
826 | * is synchronized. |
827 | */ |
828 | static uint64_t get_time_stamp(void) |
829 | { |
830 | # if defined(OSSL_POSIX_TIMER_OKAY) |
831 | { |
832 | struct timespec ts; |
833 | |
834 | if (clock_gettime(CLOCK_REALTIME, &ts) == 0) |
835 | return TWO32TO64(ts.tv_sec, ts.tv_nsec); |
836 | } |
837 | # endif |
838 | # if defined(__unix__) \ |
839 | || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L) |
840 | { |
841 | struct timeval tv; |
842 | |
843 | if (gettimeofday(&tv, NULL) == 0) |
844 | return TWO32TO64(tv.tv_sec, tv.tv_usec); |
845 | } |
846 | # endif |
847 | return time(NULL); |
848 | } |
849 | |
850 | /* |
851 | * Get an arbitrary timer value of the highest possible resolution |
852 | * |
853 | * The timer value is added as random noise to the additional data, |
854 | * which is not considered a trusted entropy sourec, so any result |
855 | * is acceptable. |
856 | */ |
857 | static uint64_t get_timer_bits(void) |
858 | { |
859 | uint64_t res = OPENSSL_rdtsc(); |
860 | |
861 | if (res != 0) |
862 | return res; |
863 | |
864 | # if defined(__sun) || defined(__hpux) |
865 | return gethrtime(); |
866 | # elif defined(_AIX) |
867 | { |
868 | timebasestruct_t t; |
869 | |
870 | read_wall_time(&t, TIMEBASE_SZ); |
871 | return TWO32TO64(t.tb_high, t.tb_low); |
872 | } |
873 | # elif defined(OSSL_POSIX_TIMER_OKAY) |
874 | { |
875 | struct timespec ts; |
876 | |
877 | # ifdef CLOCK_BOOTTIME |
878 | # define CLOCK_TYPE CLOCK_BOOTTIME |
879 | # elif defined(_POSIX_MONOTONIC_CLOCK) |
880 | # define CLOCK_TYPE CLOCK_MONOTONIC |
881 | # else |
882 | # define CLOCK_TYPE CLOCK_REALTIME |
883 | # endif |
884 | |
885 | if (clock_gettime(CLOCK_TYPE, &ts) == 0) |
886 | return TWO32TO64(ts.tv_sec, ts.tv_nsec); |
887 | } |
888 | # endif |
889 | # if defined(__unix__) \ |
890 | || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L) |
891 | { |
892 | struct timeval tv; |
893 | |
894 | if (gettimeofday(&tv, NULL) == 0) |
895 | return TWO32TO64(tv.tv_sec, tv.tv_usec); |
896 | } |
897 | # endif |
898 | return time(NULL); |
899 | } |
900 | #endif /* (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS)) |
901 | || defined(__DJGPP__) */ |
902 | |