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