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