xref: /openbsd-src/lib/libcrypto/arc4random/getentropy_linux.c (revision ae3cb403620ab940fbaabb3055fac045a63d56b7)
1 /*	$OpenBSD: getentropy_linux.c,v 1.44 2017/04/29 18:43:31 beck Exp $	*/
2 
3 /*
4  * Copyright (c) 2014 Theo de Raadt <deraadt@openbsd.org>
5  * Copyright (c) 2014 Bob Beck <beck@obtuse.com>
6  *
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.
10  *
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.
18  *
19  * Emulation of getentropy(2) as documented at:
20  * http://man.openbsd.org/getentropy.2
21  */
22 
23 #define	_POSIX_C_SOURCE	199309L
24 #define	_GNU_SOURCE	1
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 SYS__sysctl
31 #include <linux/sysctl.h>
32 #endif
33 #include <sys/statvfs.h>
34 #include <sys/socket.h>
35 #include <sys/mount.h>
36 #include <sys/mman.h>
37 #include <sys/stat.h>
38 #include <sys/time.h>
39 #include <stdlib.h>
40 #include <stdint.h>
41 #include <stdio.h>
42 #include <link.h>
43 #include <termios.h>
44 #include <fcntl.h>
45 #include <signal.h>
46 #include <string.h>
47 #include <errno.h>
48 #include <unistd.h>
49 #include <time.h>
50 #include <openssl/sha.h>
51 
52 #include <linux/types.h>
53 #include <linux/random.h>
54 #ifdef HAVE_GETAUXVAL
55 #include <sys/auxv.h>
56 #endif
57 #include <sys/vfs.h>
58 
59 #define REPEAT 5
60 #define min(a, b) (((a) < (b)) ? (a) : (b))
61 
62 #define HX(a, b) \
63 	do { \
64 		if ((a)) \
65 			HD(errno); \
66 		else \
67 			HD(b); \
68 	} while (0)
69 
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*)))
73 
74 int	getentropy(void *buf, size_t len);
75 
76 static int gotdata(char *buf, size_t len);
77 #ifdef SYS_getrandom
78 static int getentropy_getrandom(void *buf, size_t len);
79 #endif
80 static int getentropy_urandom(void *buf, size_t len);
81 #ifdef SYS__sysctl
82 static int getentropy_sysctl(void *buf, size_t len);
83 #endif
84 static int getentropy_fallback(void *buf, size_t len);
85 static int getentropy_phdr(struct dl_phdr_info *info, size_t size, void *data);
86 
87 int
88 getentropy(void *buf, size_t len)
89 {
90 	int ret = -1;
91 
92 	if (len > 256) {
93 		errno = EIO;
94 		return (-1);
95 	}
96 
97 #ifdef SYS_getrandom
98 	/*
99 	 * Try descriptor-less getrandom(), in non-blocking mode.
100 	 *
101 	 * The design of Linux getrandom is broken.  It has an
102 	 * uninitialized phase coupled with blocking behaviour, which
103 	 * is unacceptable from within a library at boot time without
104 	 * possible recovery. See http://bugs.python.org/issue26839#msg267745
105 	 */
106 	ret = getentropy_getrandom(buf, len);
107 	if (ret != -1)
108 		return (ret);
109 #endif
110 
111 	/*
112 	 * Try to get entropy with /dev/urandom
113 	 *
114 	 * This can fail if the process is inside a chroot or if file
115 	 * descriptors are exhausted.
116 	 */
117 	ret = getentropy_urandom(buf, len);
118 	if (ret != -1)
119 		return (ret);
120 
121 #ifdef SYS__sysctl
122 	/*
123 	 * Try to use sysctl CTL_KERN, KERN_RANDOM, RANDOM_UUID.
124 	 * sysctl is a failsafe API, so it guarantees a result.  This
125 	 * should work inside a chroot, or when file descriptors are
126 	 * exhausted.
127 	 *
128 	 * However this can fail if the Linux kernel removes support
129 	 * for sysctl.  Starting in 2007, there have been efforts to
130 	 * deprecate the sysctl API/ABI, and push callers towards use
131 	 * of the chroot-unavailable fd-using /proc mechanism --
132 	 * essentially the same problems as /dev/urandom.
133 	 *
134 	 * Numerous setbacks have been encountered in their deprecation
135 	 * schedule, so as of June 2014 the kernel ABI still exists on
136 	 * most Linux architectures. The sysctl() stub in libc is missing
137 	 * on some systems.  There are also reports that some kernels
138 	 * spew messages to the console.
139 	 */
140 	ret = getentropy_sysctl(buf, len);
141 	if (ret != -1)
142 		return (ret);
143 #endif /* SYS__sysctl */
144 
145 	/*
146 	 * Entropy collection via /dev/urandom and sysctl have failed.
147 	 *
148 	 * No other API exists for collecting entropy.  See the large
149 	 * comment block above.
150 	 *
151 	 * We have very few options:
152 	 *     - Even syslog_r is unsafe to call at this low level, so
153 	 *	 there is no way to alert the user or program.
154 	 *     - Cannot call abort() because some systems have unsafe
155 	 *	 corefiles.
156 	 *     - Could raise(SIGKILL) resulting in silent program termination.
157 	 *     - Return EIO, to hint that arc4random's stir function
158 	 *       should raise(SIGKILL)
159 	 *     - Do the best under the circumstances....
160 	 *
161 	 * This code path exists to bring light to the issue that Linux
162 	 * still does not provide a failsafe API for entropy collection.
163 	 *
164 	 * We hope this demonstrates that Linux should either retain their
165 	 * sysctl ABI, or consider providing a new failsafe API which
166 	 * works in a chroot or when file descriptors are exhausted.
167 	 */
168 #undef FAIL_INSTEAD_OF_TRYING_FALLBACK
169 #ifdef FAIL_INSTEAD_OF_TRYING_FALLBACK
170 	raise(SIGKILL);
171 #endif
172 	ret = getentropy_fallback(buf, len);
173 	if (ret != -1)
174 		return (ret);
175 
176 	errno = EIO;
177 	return (ret);
178 }
179 
180 /*
181  * Basic sanity checking; wish we could do better.
182  */
183 static int
184 gotdata(char *buf, size_t len)
185 {
186 	char	any_set = 0;
187 	size_t	i;
188 
189 	for (i = 0; i < len; ++i)
190 		any_set |= buf[i];
191 	if (any_set == 0)
192 		return (-1);
193 	return (0);
194 }
195 
196 #ifdef SYS_getrandom
197 static int
198 getentropy_getrandom(void *buf, size_t len)
199 {
200 	int pre_errno = errno;
201 	int ret;
202 	if (len > 256)
203 		return (-1);
204 	do {
205 		ret = syscall(SYS_getrandom, buf, len, GRND_NONBLOCK);
206 	} while (ret == -1 && errno == EINTR);
207 
208 	if (ret != len)
209 		return (-1);
210 	errno = pre_errno;
211 	return (0);
212 }
213 #endif
214 
215 static int
216 getentropy_urandom(void *buf, size_t len)
217 {
218 	struct stat st;
219 	size_t i;
220 	int fd, cnt, flags;
221 	int save_errno = errno;
222 
223 start:
224 
225 	flags = O_RDONLY;
226 #ifdef O_NOFOLLOW
227 	flags |= O_NOFOLLOW;
228 #endif
229 #ifdef O_CLOEXEC
230 	flags |= O_CLOEXEC;
231 #endif
232 	fd = open("/dev/urandom", flags, 0);
233 	if (fd == -1) {
234 		if (errno == EINTR)
235 			goto start;
236 		goto nodevrandom;
237 	}
238 #ifndef O_CLOEXEC
239 	fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
240 #endif
241 
242 	/* Lightly verify that the device node looks sane */
243 	if (fstat(fd, &st) == -1 || !S_ISCHR(st.st_mode)) {
244 		close(fd);
245 		goto nodevrandom;
246 	}
247 	if (ioctl(fd, RNDGETENTCNT, &cnt) == -1) {
248 		close(fd);
249 		goto nodevrandom;
250 	}
251 	for (i = 0; i < len; ) {
252 		size_t wanted = len - i;
253 		ssize_t ret = read(fd, (char *)buf + i, wanted);
254 
255 		if (ret == -1) {
256 			if (errno == EAGAIN || errno == EINTR)
257 				continue;
258 			close(fd);
259 			goto nodevrandom;
260 		}
261 		i += ret;
262 	}
263 	close(fd);
264 	if (gotdata(buf, len) == 0) {
265 		errno = save_errno;
266 		return (0);		/* satisfied */
267 	}
268 nodevrandom:
269 	errno = EIO;
270 	return (-1);
271 }
272 
273 #ifdef SYS__sysctl
274 static int
275 getentropy_sysctl(void *buf, size_t len)
276 {
277 	static int mib[] = { CTL_KERN, KERN_RANDOM, RANDOM_UUID };
278 	size_t i;
279 	int save_errno = errno;
280 
281 	for (i = 0; i < len; ) {
282 		size_t chunk = min(len - i, 16);
283 
284 		/* SYS__sysctl because some systems already removed sysctl() */
285 		struct __sysctl_args args = {
286 			.name = mib,
287 			.nlen = 3,
288 			.oldval = (char *)buf + i,
289 			.oldlenp = &chunk,
290 		};
291 		if (syscall(SYS__sysctl, &args) != 0)
292 			goto sysctlfailed;
293 		i += chunk;
294 	}
295 	if (gotdata(buf, len) == 0) {
296 		errno = save_errno;
297 		return (0);			/* satisfied */
298 	}
299 sysctlfailed:
300 	errno = EIO;
301 	return (-1);
302 }
303 #endif /* SYS__sysctl */
304 
305 static const int cl[] = {
306 	CLOCK_REALTIME,
307 #ifdef CLOCK_MONOTONIC
308 	CLOCK_MONOTONIC,
309 #endif
310 #ifdef CLOCK_MONOTONIC_RAW
311 	CLOCK_MONOTONIC_RAW,
312 #endif
313 #ifdef CLOCK_TAI
314 	CLOCK_TAI,
315 #endif
316 #ifdef CLOCK_VIRTUAL
317 	CLOCK_VIRTUAL,
318 #endif
319 #ifdef CLOCK_UPTIME
320 	CLOCK_UPTIME,
321 #endif
322 #ifdef CLOCK_PROCESS_CPUTIME_ID
323 	CLOCK_PROCESS_CPUTIME_ID,
324 #endif
325 #ifdef CLOCK_THREAD_CPUTIME_ID
326 	CLOCK_THREAD_CPUTIME_ID,
327 #endif
328 };
329 
330 static int
331 getentropy_phdr(struct dl_phdr_info *info, size_t size, void *data)
332 {
333 	SHA512_CTX *ctx = data;
334 
335 	SHA512_Update(ctx, &info->dlpi_addr, sizeof (info->dlpi_addr));
336 	return (0);
337 }
338 
339 static int
340 getentropy_fallback(void *buf, size_t len)
341 {
342 	uint8_t results[SHA512_DIGEST_LENGTH];
343 	int save_errno = errno, e, pgs = getpagesize(), faster = 0, repeat;
344 	static int cnt;
345 	struct timespec ts;
346 	struct timeval tv;
347 	struct rusage ru;
348 	sigset_t sigset;
349 	struct stat st;
350 	SHA512_CTX ctx;
351 	static pid_t lastpid;
352 	pid_t pid;
353 	size_t i, ii, m;
354 	char *p;
355 
356 	pid = getpid();
357 	if (lastpid == pid) {
358 		faster = 1;
359 		repeat = 2;
360 	} else {
361 		faster = 0;
362 		lastpid = pid;
363 		repeat = REPEAT;
364 	}
365 	for (i = 0; i < len; ) {
366 		int j;
367 		SHA512_Init(&ctx);
368 		for (j = 0; j < repeat; j++) {
369 			HX((e = gettimeofday(&tv, NULL)) == -1, tv);
370 			if (e != -1) {
371 				cnt += (int)tv.tv_sec;
372 				cnt += (int)tv.tv_usec;
373 			}
374 
375 			dl_iterate_phdr(getentropy_phdr, &ctx);
376 
377 			for (ii = 0; ii < sizeof(cl)/sizeof(cl[0]); ii++)
378 				HX(clock_gettime(cl[ii], &ts) == -1, ts);
379 
380 			HX((pid = getpid()) == -1, pid);
381 			HX((pid = getsid(pid)) == -1, pid);
382 			HX((pid = getppid()) == -1, pid);
383 			HX((pid = getpgid(0)) == -1, pid);
384 			HX((e = getpriority(0, 0)) == -1, e);
385 
386 			if (!faster) {
387 				ts.tv_sec = 0;
388 				ts.tv_nsec = 1;
389 				(void) nanosleep(&ts, NULL);
390 			}
391 
392 			HX(sigpending(&sigset) == -1, sigset);
393 			HX(sigprocmask(SIG_BLOCK, NULL, &sigset) == -1,
394 			    sigset);
395 
396 			HF(getentropy);	/* an addr in this library */
397 			HF(printf);		/* an addr in libc */
398 			p = (char *)&p;
399 			HD(p);		/* an addr on stack */
400 			p = (char *)&errno;
401 			HD(p);		/* the addr of errno */
402 
403 			if (i == 0) {
404 				struct sockaddr_storage ss;
405 				struct statvfs stvfs;
406 				struct termios tios;
407 				struct statfs stfs;
408 				socklen_t ssl;
409 				off_t off;
410 
411 				/*
412 				 * Prime-sized mappings encourage fragmentation;
413 				 * thus exposing some address entropy.
414 				 */
415 				struct mm {
416 					size_t	npg;
417 					void	*p;
418 				} mm[] =	 {
419 					{ 17, MAP_FAILED }, { 3, MAP_FAILED },
420 					{ 11, MAP_FAILED }, { 2, MAP_FAILED },
421 					{ 5, MAP_FAILED }, { 3, MAP_FAILED },
422 					{ 7, MAP_FAILED }, { 1, MAP_FAILED },
423 					{ 57, MAP_FAILED }, { 3, MAP_FAILED },
424 					{ 131, MAP_FAILED }, { 1, MAP_FAILED },
425 				};
426 
427 				for (m = 0; m < sizeof mm/sizeof(mm[0]); m++) {
428 					HX(mm[m].p = mmap(NULL,
429 					    mm[m].npg * pgs,
430 					    PROT_READ|PROT_WRITE,
431 					    MAP_PRIVATE|MAP_ANON, -1,
432 					    (off_t)0), mm[m].p);
433 					if (mm[m].p != MAP_FAILED) {
434 						size_t mo;
435 
436 						/* Touch some memory... */
437 						p = mm[m].p;
438 						mo = cnt %
439 						    (mm[m].npg * pgs - 1);
440 						p[mo] = 1;
441 						cnt += (int)((long)(mm[m].p)
442 						    / pgs);
443 					}
444 
445 					/* Check cnts and times... */
446 					for (ii = 0; ii < sizeof(cl)/sizeof(cl[0]);
447 					    ii++) {
448 						HX((e = clock_gettime(cl[ii],
449 						    &ts)) == -1, ts);
450 						if (e != -1)
451 							cnt += (int)ts.tv_nsec;
452 					}
453 
454 					HX((e = getrusage(RUSAGE_SELF,
455 					    &ru)) == -1, ru);
456 					if (e != -1) {
457 						cnt += (int)ru.ru_utime.tv_sec;
458 						cnt += (int)ru.ru_utime.tv_usec;
459 					}
460 				}
461 
462 				for (m = 0; m < sizeof mm/sizeof(mm[0]); m++) {
463 					if (mm[m].p != MAP_FAILED)
464 						munmap(mm[m].p, mm[m].npg * pgs);
465 					mm[m].p = MAP_FAILED;
466 				}
467 
468 				HX(stat(".", &st) == -1, st);
469 				HX(statvfs(".", &stvfs) == -1, stvfs);
470 				HX(statfs(".", &stfs) == -1, stfs);
471 
472 				HX(stat("/", &st) == -1, st);
473 				HX(statvfs("/", &stvfs) == -1, stvfs);
474 				HX(statfs("/", &stfs) == -1, stfs);
475 
476 				HX((e = fstat(0, &st)) == -1, st);
477 				if (e == -1) {
478 					if (S_ISREG(st.st_mode) ||
479 					    S_ISFIFO(st.st_mode) ||
480 					    S_ISSOCK(st.st_mode)) {
481 						HX(fstatvfs(0, &stvfs) == -1,
482 						    stvfs);
483 						HX(fstatfs(0, &stfs) == -1,
484 						    stfs);
485 						HX((off = lseek(0, (off_t)0,
486 						    SEEK_CUR)) < 0, off);
487 					}
488 					if (S_ISCHR(st.st_mode)) {
489 						HX(tcgetattr(0, &tios) == -1,
490 						    tios);
491 					} else if (S_ISSOCK(st.st_mode)) {
492 						memset(&ss, 0, sizeof ss);
493 						ssl = sizeof(ss);
494 						HX(getpeername(0,
495 						    (void *)&ss, &ssl) == -1,
496 						    ss);
497 					}
498 				}
499 
500 				HX((e = getrusage(RUSAGE_CHILDREN,
501 				    &ru)) == -1, ru);
502 				if (e != -1) {
503 					cnt += (int)ru.ru_utime.tv_sec;
504 					cnt += (int)ru.ru_utime.tv_usec;
505 				}
506 			} else {
507 				/* Subsequent hashes absorb previous result */
508 				HD(results);
509 			}
510 
511 			HX((e = gettimeofday(&tv, NULL)) == -1, tv);
512 			if (e != -1) {
513 				cnt += (int)tv.tv_sec;
514 				cnt += (int)tv.tv_usec;
515 			}
516 
517 			HD(cnt);
518 		}
519 #ifdef HAVE_GETAUXVAL
520 #ifdef AT_RANDOM
521 		/* Not as random as you think but we take what we are given */
522 		p = (char *) getauxval(AT_RANDOM);
523 		if (p)
524 			HR(p, 16);
525 #endif
526 #ifdef AT_SYSINFO_EHDR
527 		p = (char *) getauxval(AT_SYSINFO_EHDR);
528 		if (p)
529 			HR(p, pgs);
530 #endif
531 #ifdef AT_BASE
532 		p = (char *) getauxval(AT_BASE);
533 		if (p)
534 			HD(p);
535 #endif
536 #endif
537 
538 		SHA512_Final(results, &ctx);
539 		memcpy((char *)buf + i, results, min(sizeof(results), len - i));
540 		i += min(sizeof(results), len - i);
541 	}
542 	explicit_bzero(&ctx, sizeof ctx);
543 	explicit_bzero(results, sizeof results);
544 	if (gotdata(buf, len) == 0) {
545 		errno = save_errno;
546 		return (0);		/* satisfied */
547 	}
548 	errno = EIO;
549 	return (-1);
550 }
551