x509/x509name.c: fix potential crash in X509_NAME_get_text_by_OBJ.
[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 int syscall_random(void *buf, size_t buflen);
81
82 #if (defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_UEFI)) && \
83         !defined(OPENSSL_RAND_SEED_NONE)
84 # error "UEFI and VXWorks only support seeding NONE"
85 #endif
86
87 #if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) \
88     || defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_VXWORKS) \
89     || defined(OPENSSL_SYS_UEFI))
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 size on success, 0 on failure.
196  */
197 static size_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      * On FreeBSD old implementations returned longs, newer versions support
205      * variable sizes up to 256 byte. The code below would not work properly
206      * when the sysctl returns long and we want to request something not a
207      * multiple of longs, which should never be the case.
208      */
209     if (!ossl_assert(buflen % sizeof(long) == 0))
210         return 0;
211
212     /*
213      * On NetBSD before 4.0 KERN_ARND was an alias for KERN_URND, and only
214      * filled in an int, leaving the rest uninitialized. Since NetBSD 4.0
215      * it returns a variable number of bytes with the current version supporting
216      * up to 256 bytes.
217      * Just return an error on older NetBSD versions.
218      */
219 #if   defined(__NetBSD__) && __NetBSD_Version__ < 400000000
220     return 0;
221 #endif
222
223     mib[0] = CTL_KERN;
224     mib[1] = KERN_ARND;
225
226     do {
227         len = buflen;
228         if (sysctl(mib, 2, buf, &len, NULL, 0) == -1)
229             return done;
230         done += len;
231         buf += len;
232         buflen -= len;
233     } while (buflen > 0);
234
235     return done;
236 }
237 #  endif
238
239 /*
240  * syscall_random(): Try to get random data using a system call
241  * returns the number of bytes returned in buf, or <= 0 on error.
242  */
243 int syscall_random(void *buf, size_t buflen)
244 {
245     /*
246      * Do runtime detection to find getentropy().
247      *
248      * Known OSs that should support this:
249      * - Darwin since 16 (OSX 10.12, IOS 10.0).
250      * - Solaris since 11.3
251      * - OpenBSD since 5.6
252      * - Linux since 3.17 with glibc 2.25
253      * - FreeBSD since 12.0 (1200061)
254      */
255 #  if defined(__GNUC__) && __GNUC__>=2 && defined(__ELF__) && !defined(__hpux)
256     extern int getentropy(void *bufer, size_t length) __attribute__((weak));
257
258     if (getentropy != NULL)
259         return getentropy(buf, buflen) == 0 ? buflen : 0;
260 #  else
261     union {
262         void *p;
263         int (*f)(void *buffer, size_t length);
264     } p_getentropy;
265
266     /*
267      * We could cache the result of the lookup, but we normally don't
268      * call this function often.
269      */
270     ERR_set_mark();
271     p_getentropy.p = DSO_global_lookup("getentropy");
272     ERR_pop_to_mark();
273     if (p_getentropy.p != NULL)
274         return p_getentropy.f(buf, buflen) == 0 ? buflen : 0;
275 #  endif
276
277     /* Linux supports this since version 3.17 */
278 #  if defined(__linux) && defined(SYS_getrandom)
279     return (int)syscall(SYS_getrandom, buf, buflen, 0);
280 #  endif
281
282 #  if (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
283     return (int)sysctl_random(buf, buflen);
284 #  endif
285
286     return -1;
287 }
288
289 #if  !defined(OPENSSL_RAND_SEED_NONE) && defined(OPENSSL_RAND_SEED_DEVRANDOM)
290 static const char *random_device_paths[] = { DEVRANDOM };
291 static struct random_device {
292     int fd;
293     dev_t dev;
294     ino_t ino;
295     mode_t mode;
296     dev_t rdev;
297 } random_devices[OSSL_NELEM(random_device_paths)];
298 static int keep_random_devices_open = 1;
299
300 /*
301  * Verify that the file descriptor associated with the random source is
302  * still valid. The rationale for doing this is the fact that it is not
303  * uncommon for daemons to close all open file handles when daemonizing.
304  * So the handle might have been closed or even reused for opening
305  * another file.
306  */
307 static int check_random_device(struct random_device * rd)
308 {
309     struct stat st;
310
311     return rd->fd != -1
312            && fstat(rd->fd, &st) != -1
313            && rd->dev == st.st_dev
314            && rd->ino == st.st_ino
315            && ((rd->mode ^ st.st_mode) & ~(S_IRWXU | S_IRWXG | S_IRWXO)) == 0
316            && rd->rdev == st.st_rdev;
317 }
318
319 /*
320  * Open a random device if required and return its file descriptor or -1 on error
321  */
322 static int get_random_device(size_t n)
323 {
324     struct stat st;
325     struct random_device * rd = &random_devices[n];
326
327     /* reuse existing file descriptor if it is (still) valid */
328     if (check_random_device(rd))
329         return rd->fd;
330
331     /* open the random device ... */
332     if ((rd->fd = open(random_device_paths[n], O_RDONLY)) == -1)
333         return rd->fd;
334
335     /* ... and cache its relevant stat(2) data */
336     if (fstat(rd->fd, &st) != -1) {
337         rd->dev = st.st_dev;
338         rd->ino = st.st_ino;
339         rd->mode = st.st_mode;
340         rd->rdev = st.st_rdev;
341     } else {
342         close(rd->fd);
343         rd->fd = -1;
344     }
345
346     return rd->fd;
347 }
348
349 /*
350  * Close a random device making sure it is a random device
351  */
352 static void close_random_device(size_t n)
353 {
354     struct random_device * rd = &random_devices[n];
355
356     if (check_random_device(rd))
357         close(rd->fd);
358     rd->fd = -1;
359 }
360
361 static void open_random_devices(void)
362 {
363     size_t i;
364
365     for (i = 0; i < OSSL_NELEM(random_devices); i++)
366         (void)get_random_device(i);
367 }
368
369 int rand_pool_init(void)
370 {
371     size_t i;
372
373     for (i = 0; i < OSSL_NELEM(random_devices); i++)
374         random_devices[i].fd = -1;
375     open_random_devices();
376     return 1;
377 }
378
379 void rand_pool_cleanup(void)
380 {
381     size_t i;
382
383     for (i = 0; i < OSSL_NELEM(random_devices); i++)
384         close_random_device(i);
385 }
386
387 void rand_pool_keep_random_devices_open(int keep)
388 {
389     if (keep)
390         open_random_devices();
391     else
392         rand_pool_cleanup();
393     keep_random_devices_open = keep;
394 }
395
396 #  else     /* defined(OPENSSL_RAND_SEED_NONE)
397              * || !defined(OPENSSL_RAND_SEED_DEVRANDOM)
398              */
399
400 int rand_pool_init(void)
401 {
402     return 1;
403 }
404
405 void rand_pool_cleanup(void)
406 {
407 }
408
409 void rand_pool_keep_random_devices_open(int keep)
410 {
411 }
412
413 #  endif    /* !defined(OPENSSL_RAND_SEED_NONE)
414              * && defined(OPENSSL_RAND_SEED_DEVRANDOM)
415              */
416
417 /*
418  * Try the various seeding methods in turn, exit when successful.
419  *
420  * TODO(DRBG): If more than one entropy source is available, is it
421  * preferable to stop as soon as enough entropy has been collected
422  * (as favored by @rsalz) or should one rather be defensive and add
423  * more entropy than requested and/or from different sources?
424  *
425  * Currently, the user can select multiple entropy sources in the
426  * configure step, yet in practice only the first available source
427  * will be used. A more flexible solution has been requested, but
428  * currently it is not clear how this can be achieved without
429  * overengineering the problem. There are many parameters which
430  * could be taken into account when selecting the order and amount
431  * of input from the different entropy sources (trust, quality,
432  * possibility of blocking).
433  */
434 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
435 {
436 #  ifdef OPENSSL_RAND_SEED_NONE
437     return rand_pool_entropy_available(pool);
438 #  else
439     size_t bytes_needed;
440     size_t entropy_available = 0;
441     unsigned char *buffer;
442
443 #   ifdef OPENSSL_RAND_SEED_GETRANDOM
444     bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
445     buffer = rand_pool_add_begin(pool, bytes_needed);
446     if (buffer != NULL) {
447         size_t bytes = 0;
448
449         if (syscall_random(buffer, bytes_needed) == (int)bytes_needed)
450             bytes = bytes_needed;
451
452         rand_pool_add_end(pool, bytes, 8 * bytes);
453         entropy_available = rand_pool_entropy_available(pool);
454     }
455     if (entropy_available > 0)
456         return entropy_available;
457 #   endif
458
459 #   if defined(OPENSSL_RAND_SEED_LIBRANDOM)
460     {
461         /* Not yet implemented. */
462     }
463 #   endif
464
465 #   ifdef OPENSSL_RAND_SEED_DEVRANDOM
466     bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
467     {
468         size_t i;
469
470         for (i = 0; bytes_needed > 0 && i < OSSL_NELEM(random_device_paths); i++) {
471             const int fd = get_random_device(i);
472
473             if (fd == -1)
474                 continue;
475             buffer = rand_pool_add_begin(pool, bytes_needed);
476             if (buffer != NULL) {
477                 const ssize_t n = read(fd, buffer, bytes_needed);
478
479                 if (n <= 0) {
480                     close_random_device(i);
481                     continue;
482                 }
483
484                 rand_pool_add_end(pool, n, 8 * n);
485             }
486             if (!keep_random_devices_open)
487                 close_random_device(i);
488
489             bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
490         }
491         entropy_available = rand_pool_entropy_available(pool);
492         if (entropy_available > 0)
493             return entropy_available;
494     }
495 #   endif
496
497 #   ifdef OPENSSL_RAND_SEED_RDTSC
498     entropy_available = rand_acquire_entropy_from_tsc(pool);
499     if (entropy_available > 0)
500         return entropy_available;
501 #   endif
502
503 #   ifdef OPENSSL_RAND_SEED_RDCPU
504     entropy_available = rand_acquire_entropy_from_cpu(pool);
505     if (entropy_available > 0)
506         return entropy_available;
507 #   endif
508
509 #   ifdef OPENSSL_RAND_SEED_EGD
510     bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
511     if (bytes_needed > 0) {
512         static const char *paths[] = { DEVRANDOM_EGD, NULL };
513         int i;
514
515         for (i = 0; paths[i] != NULL; i++) {
516             buffer = rand_pool_add_begin(pool, bytes_needed);
517             if (buffer != NULL) {
518                 size_t bytes = 0;
519                 int num = RAND_query_egd_bytes(paths[i],
520                                                buffer, (int)bytes_needed);
521                 if (num == (int)bytes_needed)
522                     bytes = bytes_needed;
523
524                 rand_pool_add_end(pool, bytes, 8 * bytes);
525                 entropy_available = rand_pool_entropy_available(pool);
526             }
527             if (entropy_available > 0)
528                 return entropy_available;
529         }
530     }
531 #   endif
532
533     return rand_pool_entropy_available(pool);
534 #  endif
535 }
536 # endif
537 #endif
538
539 #if defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__)
540 int rand_pool_add_nonce_data(RAND_POOL *pool)
541 {
542     struct {
543         pid_t pid;
544         CRYPTO_THREAD_ID tid;
545         uint64_t time;
546     } data = { 0 };
547
548     /*
549      * Add process id, thread id, and a high resolution timestamp to
550      * ensure that the nonce is unique whith high probability for
551      * different process instances.
552      */
553     data.pid = getpid();
554     data.tid = CRYPTO_THREAD_get_current_id();
555     data.time = get_time_stamp();
556
557     return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
558 }
559
560 int rand_pool_add_additional_data(RAND_POOL *pool)
561 {
562     struct {
563         CRYPTO_THREAD_ID tid;
564         uint64_t time;
565     } data = { 0 };
566
567     /*
568      * Add some noise from the thread id and a high resolution timer.
569      * The thread id adds a little randomness if the drbg is accessed
570      * concurrently (which is the case for the <master> drbg).
571      */
572     data.tid = CRYPTO_THREAD_get_current_id();
573     data.time = get_timer_bits();
574
575     return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
576 }
577
578
579 /*
580  * Get the current time with the highest possible resolution
581  *
582  * The time stamp is added to the nonce, so it is optimized for not repeating.
583  * The current time is ideal for this purpose, provided the computer's clock
584  * is synchronized.
585  */
586 static uint64_t get_time_stamp(void)
587 {
588 # if defined(OSSL_POSIX_TIMER_OKAY)
589     {
590         struct timespec ts;
591
592         if (clock_gettime(CLOCK_REALTIME, &ts) == 0)
593             return TWO32TO64(ts.tv_sec, ts.tv_nsec);
594     }
595 # endif
596 # if defined(__unix__) \
597      || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
598     {
599         struct timeval tv;
600
601         if (gettimeofday(&tv, NULL) == 0)
602             return TWO32TO64(tv.tv_sec, tv.tv_usec);
603     }
604 # endif
605     return time(NULL);
606 }
607
608 /*
609  * Get an arbitrary timer value of the highest possible resolution
610  *
611  * The timer value is added as random noise to the additional data,
612  * which is not considered a trusted entropy sourec, so any result
613  * is acceptable.
614  */
615 static uint64_t get_timer_bits(void)
616 {
617     uint64_t res = OPENSSL_rdtsc();
618
619     if (res != 0)
620         return res;
621
622 # if defined(__sun) || defined(__hpux)
623     return gethrtime();
624 # elif defined(_AIX)
625     {
626         timebasestruct_t t;
627
628         read_wall_time(&t, TIMEBASE_SZ);
629         return TWO32TO64(t.tb_high, t.tb_low);
630     }
631 # elif defined(OSSL_POSIX_TIMER_OKAY)
632     {
633         struct timespec ts;
634
635 #  ifdef CLOCK_BOOTTIME
636 #   define CLOCK_TYPE CLOCK_BOOTTIME
637 #  elif defined(_POSIX_MONOTONIC_CLOCK)
638 #   define CLOCK_TYPE CLOCK_MONOTONIC
639 #  else
640 #   define CLOCK_TYPE CLOCK_REALTIME
641 #  endif
642
643         if (clock_gettime(CLOCK_TYPE, &ts) == 0)
644             return TWO32TO64(ts.tv_sec, ts.tv_nsec);
645     }
646 # endif
647 # if defined(__unix__) \
648      || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
649     {
650         struct timeval tv;
651
652         if (gettimeofday(&tv, NULL) == 0)
653             return TWO32TO64(tv.tv_sec, tv.tv_usec);
654     }
655 # endif
656     return time(NULL);
657 }
658 #endif /* defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__) */