xref: /freebsd/contrib/unbound/compat/getentropy_linux.c (revision 39ee7a7a6bdd1557b1c3532abf60d139798ac88b)
1 /*	$OpenBSD: getentropy_linux.c,v 1.20 2014/07/12 15:43:49 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 #include "config.h"
20 
21 /*
22 #define	_POSIX_C_SOURCE 199309L
23 #define	_GNU_SOURCE     1
24 */
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>
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 <termios.h>
43 #include <fcntl.h>
44 #include <signal.h>
45 #include <string.h>
46 #include <errno.h>
47 #include <unistd.h>
48 #include <time.h>
49 #include <openssl/sha.h>
50 
51 #include <linux/types.h>
52 #include <linux/random.h>
53 #include <linux/sysctl.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 #ifdef CAN_REFERENCE_MAIN
77 extern int main(int, char *argv[]);
78 #endif
79 static int gotdata(char *buf, size_t len);
80 #ifdef SYS_getrandom
81 static int getentropy_getrandom(void *buf, size_t len);
82 #endif
83 static int getentropy_urandom(void *buf, size_t len);
84 #ifdef SYS__sysctl
85 static int getentropy_sysctl(void *buf, size_t len);
86 #endif
87 static int getentropy_fallback(void *buf, size_t len);
88 
89 int
90 getentropy(void *buf, size_t len)
91 {
92 	int ret = -1;
93 
94 	if (len > 256) {
95 		errno = EIO;
96 		return -1;
97 	}
98 
99 #ifdef SYS_getrandom
100 	/*
101 	 * Try descriptor-less getrandom()
102 	 */
103 	ret = getentropy_getrandom(buf, len);
104 	if (ret != -1)
105 		return (ret);
106 	if (errno != ENOSYS)
107 		return (-1);
108 #endif
109 
110 	/*
111 	 * Try to get entropy with /dev/urandom
112 	 *
113 	 * This can fail if the process is inside a chroot or if file
114 	 * descriptors are exhausted.
115 	 */
116 	ret = getentropy_urandom(buf, len);
117 	if (ret != -1)
118 		return (ret);
119 
120 #ifdef SYS__sysctl
121 	/*
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
125 	 * exhuasted.
126 	 *
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.
132 	 *
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.
138 	 */
139 	ret = getentropy_sysctl(buf, len);
140 	if (ret != -1)
141 		return (ret);
142 #endif /* SYS__sysctl */
143 
144 	/*
145 	 * Entropy collection via /dev/urandom and sysctl have failed.
146 	 *
147 	 * No other API exists for collecting entropy.  See the large
148 	 * comment block above.
149 	 *
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
154 	 *	 corefiles.
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....
159 	 *
160 	 * This code path exists to bring light to the issue that Linux
161 	 * does not provide a failsafe API for entropy collection.
162 	 *
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.
166 	 */
167 #undef FAIL_INSTEAD_OF_TRYING_FALLBACK
168 #ifdef FAIL_INSTEAD_OF_TRYING_FALLBACK
169 	raise(SIGKILL);
170 #endif
171 	ret = getentropy_fallback(buf, len);
172 	if (ret != -1)
173 		return (ret);
174 
175 	errno = EIO;
176 	return (ret);
177 }
178 
179 /*
180  * Basic sanity checking; wish we could do better.
181  */
182 static int
183 gotdata(char *buf, size_t len)
184 {
185 	char	any_set = 0;
186 	size_t	i;
187 
188 	for (i = 0; i < len; ++i)
189 		any_set |= buf[i];
190 	if (any_set == 0)
191 		return -1;
192 	return 0;
193 }
194 
195 #ifdef SYS_getrandom
196 static int
197 getentropy_getrandom(void *buf, size_t len)
198 {
199 	int pre_errno = errno;
200 	int ret;
201 	if (len > 256)
202 		return (-1);
203 	do {
204 		ret = syscall(SYS_getrandom, buf, len, 0);
205 	} while (ret == -1 && errno == EINTR);
206 
207 	if (ret != (int)len)
208 		return (-1);
209 	errno = pre_errno;
210 	return (0);
211 }
212 #endif
213 
214 static int
215 getentropy_urandom(void *buf, size_t len)
216 {
217 	struct stat st;
218 	size_t i;
219 	int fd, cnt, flags;
220 	int save_errno = errno;
221 
222 start:
223 
224 	flags = O_RDONLY;
225 #ifdef O_NOFOLLOW
226 	flags |= O_NOFOLLOW;
227 #endif
228 #ifdef O_CLOEXEC
229 	flags |= O_CLOEXEC;
230 #endif
231 	fd = open("/dev/urandom", flags, 0);
232 	if (fd == -1) {
233 		if (errno == EINTR)
234 			goto start;
235 		goto nodevrandom;
236 	}
237 #ifndef O_CLOEXEC
238 	fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
239 #endif
240 
241 	/* Lightly verify that the device node looks sane */
242 	if (fstat(fd, &st) == -1 || !S_ISCHR(st.st_mode)) {
243 		close(fd);
244 		goto nodevrandom;
245 	}
246 	if (ioctl(fd, RNDGETENTCNT, &cnt) == -1) {
247 		close(fd);
248 		goto nodevrandom;
249 	}
250 	for (i = 0; i < len; ) {
251 		size_t wanted = len - i;
252 		ssize_t ret = read(fd, (char*)buf + i, wanted);
253 
254 		if (ret == -1) {
255 			if (errno == EAGAIN || errno == EINTR)
256 				continue;
257 			close(fd);
258 			goto nodevrandom;
259 		}
260 		i += ret;
261 	}
262 	close(fd);
263 	if (gotdata(buf, len) == 0) {
264 		errno = save_errno;
265 		return 0;		/* satisfied */
266 	}
267 nodevrandom:
268 	errno = EIO;
269 	return -1;
270 }
271 
272 #ifdef SYS__sysctl
273 static int
274 getentropy_sysctl(void *buf, size_t len)
275 {
276 	static int mib[] = { CTL_KERN, KERN_RANDOM, RANDOM_UUID };
277 	size_t i;
278 	int save_errno = errno;
279 
280 	for (i = 0; i < len; ) {
281 		size_t chunk = min(len - i, 16);
282 
283 		/* SYS__sysctl because some systems already removed sysctl() */
284 		struct __sysctl_args args = {
285 			.name = mib,
286 			.nlen = 3,
287 			.oldval = (char *)buf + i,
288 			.oldlenp = &chunk,
289 		};
290 		if (syscall(SYS__sysctl, &args) != 0)
291 			goto sysctlfailed;
292 		i += chunk;
293 	}
294 	if (gotdata(buf, len) == 0) {
295 		errno = save_errno;
296 		return (0);			/* satisfied */
297 	}
298 sysctlfailed:
299 	errno = EIO;
300 	return -1;
301 }
302 #endif /* SYS__sysctl */
303 
304 static int cl[] = {
305 	CLOCK_REALTIME,
306 #ifdef CLOCK_MONOTONIC
307 	CLOCK_MONOTONIC,
308 #endif
309 #ifdef CLOCK_MONOTONIC_RAW
310 	CLOCK_MONOTONIC_RAW,
311 #endif
312 #ifdef CLOCK_TAI
313 	CLOCK_TAI,
314 #endif
315 #ifdef CLOCK_VIRTUAL
316 	CLOCK_VIRTUAL,
317 #endif
318 #ifdef CLOCK_UPTIME
319 	CLOCK_UPTIME,
320 #endif
321 #ifdef CLOCK_PROCESS_CPUTIME_ID
322 	CLOCK_PROCESS_CPUTIME_ID,
323 #endif
324 #ifdef CLOCK_THREAD_CPUTIME_ID
325 	CLOCK_THREAD_CPUTIME_ID,
326 #endif
327 };
328 
329 static int
330 getentropy_fallback(void *buf, size_t len)
331 {
332 	uint8_t results[SHA512_DIGEST_LENGTH];
333 	int save_errno = errno, e, pgs = getpagesize(), faster = 0, repeat;
334 	static int cnt;
335 	struct timespec ts;
336 	struct timeval tv;
337 	struct rusage ru;
338 	sigset_t sigset;
339 	struct stat st;
340 	SHA512_CTX ctx;
341 	static pid_t lastpid;
342 	pid_t pid;
343 	size_t i, ii, m;
344 	char *p;
345 
346 	pid = getpid();
347 	if (lastpid == pid) {
348 		faster = 1;
349 		repeat = 2;
350 	} else {
351 		faster = 0;
352 		lastpid = pid;
353 		repeat = REPEAT;
354 	}
355 	for (i = 0; i < len; ) {
356 		int j;
357 		SHA512_Init(&ctx);
358 		for (j = 0; j < repeat; j++) {
359 			HX((e = gettimeofday(&tv, NULL)) == -1, tv);
360 			if (e != -1) {
361 				cnt += (int)tv.tv_sec;
362 				cnt += (int)tv.tv_usec;
363 			}
364 
365 			for (ii = 0; ii < sizeof(cl)/sizeof(cl[0]); ii++)
366 				HX(clock_gettime(cl[ii], &ts) == -1, ts);
367 
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);
373 
374 			if (!faster) {
375 				ts.tv_sec = 0;
376 				ts.tv_nsec = 1;
377 				(void) nanosleep(&ts, NULL);
378 			}
379 
380 			HX(sigpending(&sigset) == -1, sigset);
381 			HX(sigprocmask(SIG_BLOCK, NULL, &sigset) == -1,
382 			    sigset);
383 
384 #ifdef CAN_REFERENCE_MAIN
385 			HF(main);		/* an addr in program */
386 #endif
387 			HF(getentropy);	/* an addr in this library */
388 			HF(printf);		/* an addr in libc */
389 			p = (char *)&p;
390 			HD(p);		/* an addr on stack */
391 			p = (char *)&errno;
392 			HD(p);		/* the addr of errno */
393 
394 			if (i == 0) {
395 				struct sockaddr_storage ss;
396 				struct statvfs stvfs;
397 				struct termios tios;
398 				struct statfs stfs;
399 				socklen_t ssl;
400 				off_t off;
401 
402 				/*
403 				 * Prime-sized mappings encourage fragmentation;
404 				 * thus exposing some address entropy.
405 				 */
406 				struct mm {
407 					size_t	npg;
408 					void	*p;
409 				} mm[] =	 {
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 },
416 				};
417 
418 				for (m = 0; m < sizeof mm/sizeof(mm[0]); m++) {
419 					HX(mm[m].p = mmap(NULL,
420 					    mm[m].npg * pgs,
421 					    PROT_READ|PROT_WRITE,
422 					    MAP_PRIVATE|MAP_ANON, -1,
423 					    (off_t)0), mm[m].p);
424 					if (mm[m].p != MAP_FAILED) {
425 						size_t mo;
426 
427 						/* Touch some memory... */
428 						p = mm[m].p;
429 						mo = cnt %
430 						    (mm[m].npg * pgs - 1);
431 						p[mo] = 1;
432 						cnt += (int)((long)(mm[m].p)
433 						    / pgs);
434 					}
435 
436 					/* Check cnts and times... */
437 					for (ii = 0; ii < sizeof(cl)/sizeof(cl[0]);
438 					    ii++) {
439 						HX((e = clock_gettime(cl[ii],
440 						    &ts)) == -1, ts);
441 						if (e != -1)
442 							cnt += (int)ts.tv_nsec;
443 					}
444 
445 					HX((e = getrusage(RUSAGE_SELF,
446 					    &ru)) == -1, ru);
447 					if (e != -1) {
448 						cnt += (int)ru.ru_utime.tv_sec;
449 						cnt += (int)ru.ru_utime.tv_usec;
450 					}
451 				}
452 
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;
457 				}
458 
459 				HX(stat(".", &st) == -1, st);
460 				HX(statvfs(".", &stvfs) == -1, stvfs);
461 				HX(statfs(".", &stfs) == -1, stfs);
462 
463 				HX(stat("/", &st) == -1, st);
464 				HX(statvfs("/", &stvfs) == -1, stvfs);
465 				HX(statfs("/", &stfs) == -1, stfs);
466 
467 				HX((e = fstat(0, &st)) == -1, st);
468 				if (e == -1) {
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,
473 						    stvfs);
474 						HX(fstatfs(0, &stfs) == -1,
475 						    stfs);
476 						HX((off = lseek(0, (off_t)0,
477 						    SEEK_CUR)) < 0, off);
478 					}
479 					if (S_ISCHR(st.st_mode)) {
480 						HX(tcgetattr(0, &tios) == -1,
481 						    tios);
482 					} else if (S_ISSOCK(st.st_mode)) {
483 						memset(&ss, 0, sizeof ss);
484 						ssl = sizeof(ss);
485 						HX(getpeername(0,
486 						    (void *)&ss, &ssl) == -1,
487 						    ss);
488 					}
489 				}
490 
491 				HX((e = getrusage(RUSAGE_CHILDREN,
492 				    &ru)) == -1, ru);
493 				if (e != -1) {
494 					cnt += (int)ru.ru_utime.tv_sec;
495 					cnt += (int)ru.ru_utime.tv_usec;
496 				}
497 			} else {
498 				/* Subsequent hashes absorb previous result */
499 				HD(results);
500 			}
501 
502 			HX((e = gettimeofday(&tv, NULL)) == -1, tv);
503 			if (e != -1) {
504 				cnt += (int)tv.tv_sec;
505 				cnt += (int)tv.tv_usec;
506 			}
507 
508 			HD(cnt);
509 		}
510 #ifdef HAVE_GETAUXVAL
511 #  ifdef AT_RANDOM
512 		/* Not as random as you think but we take what we are given */
513 		p = (char *) getauxval(AT_RANDOM);
514 		if (p)
515 			HR(p, 16);
516 #  endif
517 #  ifdef AT_SYSINFO_EHDR
518 		p = (char *) getauxval(AT_SYSINFO_EHDR);
519 		if (p)
520 			HR(p, pgs);
521 #  endif
522 #  ifdef AT_BASE
523 		p = (char *) getauxval(AT_BASE);
524 		if (p)
525 			HD(p);
526 #  endif
527 #endif /* HAVE_GETAUXVAL */
528 
529 		SHA512_Final(results, &ctx);
530 		memcpy((char*)buf + i, results, min(sizeof(results), len - i));
531 		i += min(sizeof(results), len - i);
532 	}
533 	memset(results, 0, sizeof results);
534 	if (gotdata(buf, len) == 0) {
535 		errno = save_errno;
536 		return 0;		/* satisfied */
537 	}
538 	errno = EIO;
539 	return -1;
540 }
541