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