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