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