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/random.h>
52 #include <linux/sysctl.h>
59 #define min(a, b) (((a) < (b)) ? (a) : (b))
69 #define HR(x, l) (SHA512_Update(&ctx, (char *)(x), (l)))
70 #define HD(x) (SHA512_Update(&ctx, (char *)&(x), sizeof (x)))
71 #define HF(x) (SHA512_Update(&ctx, (char *)&(x), sizeof (void*)))
73 int getentropy(void *buf, size_t len);
75 #ifdef CAN_REFERENCE_MAIN
76 extern int main(int, char *argv[]);
78 static int gotdata(char *buf, size_t len);
79 static int getentropy_urandom(void *buf, size_t len);
81 static int getentropy_sysctl(void *buf, size_t len);
83 static int getentropy_fallback(void *buf, size_t len);
86 getentropy(void *buf, size_t len)
96 * Try to get entropy with /dev/urandom
98 * This can fail if the process is inside a chroot or if file
99 * descriptors are exhausted.
101 ret = getentropy_urandom(buf, len);
107 * Try to use sysctl CTL_KERN, KERN_RANDOM, RANDOM_UUID.
108 * sysctl is a failsafe API, so it guarantees a result. This
109 * should work inside a chroot, or when file descriptors are
112 * However this can fail if the Linux kernel removes support
113 * for sysctl. Starting in 2007, there have been efforts to
114 * deprecate the sysctl API/ABI, and push callers towards use
115 * of the chroot-unavailable fd-using /proc mechanism --
116 * essentially the same problems as /dev/urandom.
118 * Numerous setbacks have been encountered in their deprecation
119 * schedule, so as of June 2014 the kernel ABI still exists on
120 * most Linux architectures. The sysctl() stub in libc is missing
121 * on some systems. There are also reports that some kernels
122 * spew messages to the console.
124 ret = getentropy_sysctl(buf, len);
127 #endif /* CTL_MAXNAME */
130 * Entropy collection via /dev/urandom and sysctl have failed.
132 * No other API exists for collecting entropy. See the large
133 * comment block above.
135 * We have very few options:
136 * - Even syslog_r is unsafe to call at this low level, so
137 * there is no way to alert the user or program.
138 * - Cannot call abort() because some systems have unsafe
140 * - Could raise(SIGKILL) resulting in silent program termination.
141 * - Return EIO, to hint that arc4random's stir function
142 * should raise(SIGKILL)
143 * - Do the best under the circumstances....
145 * This code path exists to bring light to the issue that Linux
146 * does not provide a failsafe API for entropy collection.
148 * We hope this demonstrates that Linux should either retain their
149 * sysctl ABI, or consider providing a new failsafe API which
150 * works in a chroot or when file descriptors are exhausted.
152 #undef FAIL_INSTEAD_OF_TRYING_FALLBACK
153 #ifdef FAIL_INSTEAD_OF_TRYING_FALLBACK
156 ret = getentropy_fallback(buf, len);
165 * Basic sanity checking; wish we could do better.
168 gotdata(char *buf, size_t len)
173 for (i = 0; i < len; ++i)
181 getentropy_urandom(void *buf, size_t len)
186 int save_errno = errno;
197 fd = open("/dev/urandom", flags, 0);
204 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
207 /* Lightly verify that the device node looks sane */
208 if (fstat(fd, &st) == -1 || !S_ISCHR(st.st_mode)) {
212 if (ioctl(fd, RNDGETENTCNT, &cnt) == -1) {
216 for (i = 0; i < len; ) {
217 size_t wanted = len - i;
218 ssize_t ret = read(fd, (char*)buf + i, wanted);
221 if (errno == EAGAIN || errno == EINTR)
229 if (gotdata(buf, len) == 0) {
231 return 0; /* satisfied */
240 getentropy_sysctl(void *buf, size_t len)
242 static int mib[] = { CTL_KERN, KERN_RANDOM, RANDOM_UUID };
244 int save_errno = errno;
246 for (i = 0; i < len; ) {
247 size_t chunk = min(len - i, 16);
249 /* SYS__sysctl because some systems already removed sysctl() */
250 struct __sysctl_args args = {
256 if (syscall(SYS__sysctl, &args) != 0)
260 if (gotdata(buf, len) == 0) {
262 return (0); /* satisfied */
268 #endif /* CTL_MAXNAME */
272 #ifdef CLOCK_MONOTONIC
275 #ifdef CLOCK_MONOTONIC_RAW
287 #ifdef CLOCK_PROCESS_CPUTIME_ID
288 CLOCK_PROCESS_CPUTIME_ID,
290 #ifdef CLOCK_THREAD_CPUTIME_ID
291 CLOCK_THREAD_CPUTIME_ID,
296 getentropy_fallback(void *buf, size_t len)
298 uint8_t results[SHA512_DIGEST_LENGTH];
299 int save_errno = errno, e, pgs = getpagesize(), faster = 0, repeat;
307 static pid_t lastpid;
313 if (lastpid == pid) {
321 for (i = 0; i < len; ) {
324 for (j = 0; j < repeat; j++) {
325 HX((e = gettimeofday(&tv, NULL)) == -1, tv);
327 cnt += (int)tv.tv_sec;
328 cnt += (int)tv.tv_usec;
331 for (ii = 0; ii < sizeof(cl)/sizeof(cl[0]); ii++)
332 HX(clock_gettime(cl[ii], &ts) == -1, ts);
334 HX((pid = getpid()) == -1, pid);
335 HX((pid = getsid(pid)) == -1, pid);
336 HX((pid = getppid()) == -1, pid);
337 HX((pid = getpgid(0)) == -1, pid);
338 HX((e = getpriority(0, 0)) == -1, e);
343 (void) nanosleep(&ts, NULL);
346 HX(sigpending(&sigset) == -1, sigset);
347 HX(sigprocmask(SIG_BLOCK, NULL, &sigset) == -1,
350 #ifdef CAN_REFERENCE_MAIN
351 HF(main); /* an addr in program */
353 HF(getentropy); /* an addr in this library */
354 HF(printf); /* an addr in libc */
356 HD(p); /* an addr on stack */
358 HD(p); /* the addr of errno */
361 struct sockaddr_storage ss;
362 struct statvfs stvfs;
369 * Prime-sized mappings encourage fragmentation;
370 * thus exposing some address entropy.
376 { 17, MAP_FAILED }, { 3, MAP_FAILED },
377 { 11, MAP_FAILED }, { 2, MAP_FAILED },
378 { 5, MAP_FAILED }, { 3, MAP_FAILED },
379 { 7, MAP_FAILED }, { 1, MAP_FAILED },
380 { 57, MAP_FAILED }, { 3, MAP_FAILED },
381 { 131, MAP_FAILED }, { 1, MAP_FAILED },
384 for (m = 0; m < sizeof mm/sizeof(mm[0]); m++) {
385 HX(mm[m].p = mmap(NULL,
387 PROT_READ|PROT_WRITE,
388 MAP_PRIVATE|MAP_ANON, -1,
390 if (mm[m].p != MAP_FAILED) {
393 /* Touch some memory... */
396 (mm[m].npg * pgs - 1);
398 cnt += (int)((long)(mm[m].p)
402 /* Check cnts and times... */
403 for (ii = 0; ii < sizeof(cl)/sizeof(cl[0]);
405 HX((e = clock_gettime(cl[ii],
408 cnt += (int)ts.tv_nsec;
411 HX((e = getrusage(RUSAGE_SELF,
414 cnt += (int)ru.ru_utime.tv_sec;
415 cnt += (int)ru.ru_utime.tv_usec;
419 for (m = 0; m < sizeof mm/sizeof(mm[0]); m++) {
420 if (mm[m].p != MAP_FAILED)
421 munmap(mm[m].p, mm[m].npg * pgs);
422 mm[m].p = MAP_FAILED;
425 HX(stat(".", &st) == -1, st);
426 HX(statvfs(".", &stvfs) == -1, stvfs);
427 HX(statfs(".", &stfs) == -1, stfs);
429 HX(stat("/", &st) == -1, st);
430 HX(statvfs("/", &stvfs) == -1, stvfs);
431 HX(statfs("/", &stfs) == -1, stfs);
433 HX((e = fstat(0, &st)) == -1, st);
435 if (S_ISREG(st.st_mode) ||
436 S_ISFIFO(st.st_mode) ||
437 S_ISSOCK(st.st_mode)) {
438 HX(fstatvfs(0, &stvfs) == -1,
440 HX(fstatfs(0, &stfs) == -1,
442 HX((off = lseek(0, (off_t)0,
443 SEEK_CUR)) < 0, off);
445 if (S_ISCHR(st.st_mode)) {
446 HX(tcgetattr(0, &tios) == -1,
448 } else if (S_ISSOCK(st.st_mode)) {
449 memset(&ss, 0, sizeof ss);
452 (void *)&ss, &ssl) == -1,
457 HX((e = getrusage(RUSAGE_CHILDREN,
460 cnt += (int)ru.ru_utime.tv_sec;
461 cnt += (int)ru.ru_utime.tv_usec;
464 /* Subsequent hashes absorb previous result */
468 HX((e = gettimeofday(&tv, NULL)) == -1, tv);
470 cnt += (int)tv.tv_sec;
471 cnt += (int)tv.tv_usec;
477 /* Not as random as you think but we take what we are given */
478 p = (char *) getauxval(AT_RANDOM);
482 #ifdef AT_SYSINFO_EHDR
483 p = (char *) getauxval(AT_SYSINFO_EHDR);
488 p = (char *) getauxval(AT_BASE);
493 SHA512_Final(results, &ctx);
494 memcpy((char*)buf + i, results, min(sizeof(results), len - i));
495 i += min(sizeof(results), len - i);
497 memset(results, 0, sizeof results);
498 if (gotdata(buf, len) == 0) {
500 return 0; /* satisfied */