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