1 /* $OpenBSD: getentropy_linux.c,v 1.20 2014/07/12 15:43:49 beck Exp $ */
4 * Copyright (c) 2014 Theo de Raadt <deraadt@openbsd.org>
5 * Copyright (c) 2014 Bob Beck <beck@obtuse.com>
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
22 #define _POSIX_C_SOURCE 199309L
25 #include <sys/types.h>
26 #include <sys/param.h>
27 #include <sys/ioctl.h>
28 #include <sys/resource.h>
29 #include <sys/syscall.h>
30 #ifdef HAVE_SYS_SYSCTL_H
31 #include <sys/sysctl.h>
33 #include <sys/statvfs.h>
34 #include <sys/socket.h>
35 #include <sys/mount.h>
49 #include <openssl/sha.h>
51 #include <linux/types.h>
52 #include <linux/random.h>
53 #include <linux/sysctl.h>
60 #define min(a, b) (((a) < (b)) ? (a) : (b))
70 #define HR(x, l) (SHA512_Update(&ctx, (char *)(x), (l)))
71 #define HD(x) (SHA512_Update(&ctx, (char *)&(x), sizeof (x)))
72 #define HF(x) (SHA512_Update(&ctx, (char *)&(x), sizeof (void*)))
74 int getentropy(void *buf, size_t len);
76 #ifdef CAN_REFERENCE_MAIN
77 extern int main(int, char *argv[]);
79 static int gotdata(char *buf, size_t len);
81 static int getentropy_getrandom(void *buf, size_t len);
83 static int getentropy_urandom(void *buf, size_t len);
85 static int getentropy_sysctl(void *buf, size_t len);
87 static int getentropy_fallback(void *buf, size_t len);
90 getentropy(void *buf, size_t len)
101 * Try descriptor-less getrandom()
103 ret = getentropy_getrandom(buf, len);
111 * Try to get entropy with /dev/urandom
113 * This can fail if the process is inside a chroot or if file
114 * descriptors are exhausted.
116 ret = getentropy_urandom(buf, len);
122 * Try to use sysctl CTL_KERN, KERN_RANDOM, RANDOM_UUID.
123 * sysctl is a failsafe API, so it guarantees a result. This
124 * should work inside a chroot, or when file descriptors are
127 * However this can fail if the Linux kernel removes support
128 * for sysctl. Starting in 2007, there have been efforts to
129 * deprecate the sysctl API/ABI, and push callers towards use
130 * of the chroot-unavailable fd-using /proc mechanism --
131 * essentially the same problems as /dev/urandom.
133 * Numerous setbacks have been encountered in their deprecation
134 * schedule, so as of June 2014 the kernel ABI still exists on
135 * most Linux architectures. The sysctl() stub in libc is missing
136 * on some systems. There are also reports that some kernels
137 * spew messages to the console.
139 ret = getentropy_sysctl(buf, len);
142 #endif /* SYS__sysctl */
145 * Entropy collection via /dev/urandom and sysctl have failed.
147 * No other API exists for collecting entropy. See the large
148 * comment block above.
150 * We have very few options:
151 * - Even syslog_r is unsafe to call at this low level, so
152 * there is no way to alert the user or program.
153 * - Cannot call abort() because some systems have unsafe
155 * - Could raise(SIGKILL) resulting in silent program termination.
156 * - Return EIO, to hint that arc4random's stir function
157 * should raise(SIGKILL)
158 * - Do the best under the circumstances....
160 * This code path exists to bring light to the issue that Linux
161 * does not provide a failsafe API for entropy collection.
163 * We hope this demonstrates that Linux should either retain their
164 * sysctl ABI, or consider providing a new failsafe API which
165 * works in a chroot or when file descriptors are exhausted.
167 #undef FAIL_INSTEAD_OF_TRYING_FALLBACK
168 #ifdef FAIL_INSTEAD_OF_TRYING_FALLBACK
171 ret = getentropy_fallback(buf, len);
180 * Basic sanity checking; wish we could do better.
183 gotdata(char *buf, size_t len)
188 for (i = 0; i < len; ++i)
197 getentropy_getrandom(void *buf, size_t len)
199 int pre_errno = errno;
204 ret = syscall(SYS_getrandom, buf, len, 0);
205 } while (ret == -1 && errno == EINTR);
215 getentropy_urandom(void *buf, size_t len)
220 int save_errno = errno;
231 fd = open("/dev/urandom", flags, 0);
238 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
241 /* Lightly verify that the device node looks sane */
242 if (fstat(fd, &st) == -1 || !S_ISCHR(st.st_mode)) {
246 if (ioctl(fd, RNDGETENTCNT, &cnt) == -1) {
250 for (i = 0; i < len; ) {
251 size_t wanted = len - i;
252 ssize_t ret = read(fd, (char*)buf + i, wanted);
255 if (errno == EAGAIN || errno == EINTR)
263 if (gotdata(buf, len) == 0) {
265 return 0; /* satisfied */
274 getentropy_sysctl(void *buf, size_t len)
276 static int mib[] = { CTL_KERN, KERN_RANDOM, RANDOM_UUID };
278 int save_errno = errno;
280 for (i = 0; i < len; ) {
281 size_t chunk = min(len - i, 16);
283 /* SYS__sysctl because some systems already removed sysctl() */
284 struct __sysctl_args args = {
287 .oldval = (char *)buf + i,
290 if (syscall(SYS__sysctl, &args) != 0)
294 if (gotdata(buf, len) == 0) {
296 return (0); /* satisfied */
302 #endif /* SYS__sysctl */
306 #ifdef CLOCK_MONOTONIC
309 #ifdef CLOCK_MONOTONIC_RAW
321 #ifdef CLOCK_PROCESS_CPUTIME_ID
322 CLOCK_PROCESS_CPUTIME_ID,
324 #ifdef CLOCK_THREAD_CPUTIME_ID
325 CLOCK_THREAD_CPUTIME_ID,
330 getentropy_fallback(void *buf, size_t len)
332 uint8_t results[SHA512_DIGEST_LENGTH];
333 int save_errno = errno, e, pgs = getpagesize(), faster = 0, repeat;
341 static pid_t lastpid;
347 if (lastpid == pid) {
355 for (i = 0; i < len; ) {
358 for (j = 0; j < repeat; j++) {
359 HX((e = gettimeofday(&tv, NULL)) == -1, tv);
361 cnt += (int)tv.tv_sec;
362 cnt += (int)tv.tv_usec;
365 for (ii = 0; ii < sizeof(cl)/sizeof(cl[0]); ii++)
366 HX(clock_gettime(cl[ii], &ts) == -1, ts);
368 HX((pid = getpid()) == -1, pid);
369 HX((pid = getsid(pid)) == -1, pid);
370 HX((pid = getppid()) == -1, pid);
371 HX((pid = getpgid(0)) == -1, pid);
372 HX((e = getpriority(0, 0)) == -1, e);
377 (void) nanosleep(&ts, NULL);
380 HX(sigpending(&sigset) == -1, sigset);
381 HX(sigprocmask(SIG_BLOCK, NULL, &sigset) == -1,
384 #ifdef CAN_REFERENCE_MAIN
385 HF(main); /* an addr in program */
387 HF(getentropy); /* an addr in this library */
388 HF(printf); /* an addr in libc */
390 HD(p); /* an addr on stack */
392 HD(p); /* the addr of errno */
395 struct sockaddr_storage ss;
396 struct statvfs stvfs;
403 * Prime-sized mappings encourage fragmentation;
404 * thus exposing some address entropy.
410 { 17, MAP_FAILED }, { 3, MAP_FAILED },
411 { 11, MAP_FAILED }, { 2, MAP_FAILED },
412 { 5, MAP_FAILED }, { 3, MAP_FAILED },
413 { 7, MAP_FAILED }, { 1, MAP_FAILED },
414 { 57, MAP_FAILED }, { 3, MAP_FAILED },
415 { 131, MAP_FAILED }, { 1, MAP_FAILED },
418 for (m = 0; m < sizeof mm/sizeof(mm[0]); m++) {
419 HX(mm[m].p = mmap(NULL,
421 PROT_READ|PROT_WRITE,
422 MAP_PRIVATE|MAP_ANON, -1,
424 if (mm[m].p != MAP_FAILED) {
427 /* Touch some memory... */
430 (mm[m].npg * pgs - 1);
432 cnt += (int)((long)(mm[m].p)
436 /* Check cnts and times... */
437 for (ii = 0; ii < sizeof(cl)/sizeof(cl[0]);
439 HX((e = clock_gettime(cl[ii],
442 cnt += (int)ts.tv_nsec;
445 HX((e = getrusage(RUSAGE_SELF,
448 cnt += (int)ru.ru_utime.tv_sec;
449 cnt += (int)ru.ru_utime.tv_usec;
453 for (m = 0; m < sizeof mm/sizeof(mm[0]); m++) {
454 if (mm[m].p != MAP_FAILED)
455 munmap(mm[m].p, mm[m].npg * pgs);
456 mm[m].p = MAP_FAILED;
459 HX(stat(".", &st) == -1, st);
460 HX(statvfs(".", &stvfs) == -1, stvfs);
461 HX(statfs(".", &stfs) == -1, stfs);
463 HX(stat("/", &st) == -1, st);
464 HX(statvfs("/", &stvfs) == -1, stvfs);
465 HX(statfs("/", &stfs) == -1, stfs);
467 HX((e = fstat(0, &st)) == -1, st);
469 if (S_ISREG(st.st_mode) ||
470 S_ISFIFO(st.st_mode) ||
471 S_ISSOCK(st.st_mode)) {
472 HX(fstatvfs(0, &stvfs) == -1,
474 HX(fstatfs(0, &stfs) == -1,
476 HX((off = lseek(0, (off_t)0,
477 SEEK_CUR)) < 0, off);
479 if (S_ISCHR(st.st_mode)) {
480 HX(tcgetattr(0, &tios) == -1,
482 } else if (S_ISSOCK(st.st_mode)) {
483 memset(&ss, 0, sizeof ss);
486 (void *)&ss, &ssl) == -1,
491 HX((e = getrusage(RUSAGE_CHILDREN,
494 cnt += (int)ru.ru_utime.tv_sec;
495 cnt += (int)ru.ru_utime.tv_usec;
498 /* Subsequent hashes absorb previous result */
502 HX((e = gettimeofday(&tv, NULL)) == -1, tv);
504 cnt += (int)tv.tv_sec;
505 cnt += (int)tv.tv_usec;
510 #ifdef HAVE_GETAUXVAL
512 /* Not as random as you think but we take what we are given */
513 p = (char *) getauxval(AT_RANDOM);
517 # ifdef AT_SYSINFO_EHDR
518 p = (char *) getauxval(AT_SYSINFO_EHDR);
523 p = (char *) getauxval(AT_BASE);
527 #endif /* HAVE_GETAUXVAL */
529 SHA512_Final(results, &ctx);
530 memcpy((char*)buf + i, results, min(sizeof(results), len - i));
531 i += min(sizeof(results), len - i);
533 memset(results, 0, sizeof results);
534 if (gotdata(buf, len) == 0) {
536 return 0; /* satisfied */