xref: /freebsd/contrib/unbound/compat/getentropy_solaris.c (revision 1719886f6d08408b834d270c59ffcfd821c8f63a)
1 /*	$OpenBSD: getentropy_solaris.c,v 1.4 2014/07/12 20:41:47 wouter 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 #include <sys/types.h>
22 #include <sys/param.h>
23 #include <sys/ioctl.h>
24 #include <sys/resource.h>
25 #include <sys/syscall.h>
26 #include <sys/statvfs.h>
27 #include <sys/socket.h>
28 #include <sys/mount.h>
29 #include <sys/mman.h>
30 #include <sys/stat.h>
31 #include <sys/time.h>
32 #include <stdlib.h>
33 #ifdef HAVE_STDINT_H
34 #include <stdint.h>
35 #endif
36 #include <stdio.h>
37 #include <termios.h>
38 #include <fcntl.h>
39 #include <signal.h>
40 #include <string.h>
41 #include <errno.h>
42 #include <unistd.h>
43 #include <time.h>
44 #ifdef HAVE_SYS_SHA2_H
45 #include <sys/sha2.h>
46 #define SHA512_Init SHA512Init
47 #define SHA512_Update SHA512Update
48 #define SHA512_Final SHA512Final
49 #else
50 #include <openssl/sha.h>
51 #endif
52 
53 #include <sys/vfs.h>
54 #include <sys/statfs.h>
55 #include <sys/loadavg.h>
56 
57 #define REPEAT 5
58 #define min(a, b) (((a) < (b)) ? (a) : (b))
59 
60 #define HX(a, b) \
61 	do { \
62 		if ((a)) \
63 			HD(errno); \
64 		else \
65 			HD(b); \
66 	} while (0)
67 
68 #define HR(x, l) (SHA512_Update(&ctx, (char *)(x), (l)))
69 #define HD(x)	 (SHA512_Update(&ctx, (char *)&(x), sizeof (x)))
70 #define HF(x)	 (SHA512_Update(&ctx, (char *)&(x), sizeof (void*)))
71 
72 int	getentropy(void *buf, size_t len);
73 
74 #ifdef CAN_REFERENCE_MAIN
75 extern int main(int, char *argv[]);
76 #endif
77 static int gotdata(char *buf, size_t len);
78 static int getentropy_urandom(void *buf, size_t len, const char *path,
79     int devfscheck);
80 static int getentropy_fallback(void *buf, size_t len);
81 
82 int
83 getentropy(void *buf, size_t len)
84 {
85 	int ret = -1;
86 
87 	if (len > 256) {
88 		errno = EIO;
89 		return -1;
90 	}
91 
92 	/*
93 	 * Try to get entropy with /dev/urandom
94 	 *
95 	 * Solaris provides /dev/urandom as a symbolic link to
96 	 * /devices/pseudo/random@0:urandom which is provided by
97 	 * a devfs filesystem.  Best practice is to use O_NOFOLLOW,
98 	 * so we must try the unpublished name directly.
99 	 *
100 	 * This can fail if the process is inside a chroot which lacks
101 	 * the devfs mount, or if file descriptors are exhausted.
102 	 */
103 	ret = getentropy_urandom(buf, len,
104 	    "/devices/pseudo/random@0:urandom", 1);
105 	if (ret != -1)
106 		return (ret);
107 
108 	/*
109 	 * Unfortunately, chroot spaces on Solaris are sometimes setup
110 	 * with direct device node of the well-known /dev/urandom name
111 	 * (perhaps to avoid dragging all of devfs into the space).
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, "/dev/urandom", 0);
117 	if (ret != -1)
118 		return (ret);
119 
120 	/*
121 	 * Entropy collection via /dev/urandom has failed.
122 	 *
123 	 * No other API exists for collecting entropy, and we have
124 	 * no failsafe way to get it on Solaris that is not sensitive
125 	 * to resource exhaustion.
126 	 *
127 	 * We have very few options:
128 	 *     - Even syslog_r is unsafe to call at this low level, so
129 	 *	 there is no way to alert the user or program.
130 	 *     - Cannot call abort() because some systems have unsafe
131 	 *	 corefiles.
132 	 *     - Could raise(SIGKILL) resulting in silent program termination.
133 	 *     - Return EIO, to hint that arc4random's stir function
134 	 *       should raise(SIGKILL)
135 	 *     - Do the best under the circumstances....
136 	 *
137 	 * This code path exists to bring light to the issue that Solaris
138 	 * does not provide a failsafe API for entropy collection.
139 	 *
140 	 * We hope this demonstrates that Solaris should consider
141 	 * providing a new failsafe API which works in a chroot or
142 	 * when file descriptors are exhausted.
143 	 */
144 #undef FAIL_INSTEAD_OF_TRYING_FALLBACK
145 #ifdef FAIL_INSTEAD_OF_TRYING_FALLBACK
146 	raise(SIGKILL);
147 #endif
148 	ret = getentropy_fallback(buf, len);
149 	if (ret != -1)
150 		return (ret);
151 
152 	errno = EIO;
153 	return (ret);
154 }
155 
156 /*
157  * Basic sanity checking; wish we could do better.
158  */
159 static int
160 gotdata(char *buf, size_t len)
161 {
162 	char	any_set = 0;
163 	size_t	i;
164 
165 	for (i = 0; i < len; ++i)
166 		any_set |= buf[i];
167 	if (any_set == 0)
168 		return -1;
169 	return 0;
170 }
171 
172 static int
173 getentropy_urandom(void *buf, size_t len, const char *path, int devfscheck)
174 {
175 	struct stat st;
176 	size_t i;
177 	int fd, flags;
178 	int save_errno = errno;
179 
180 start:
181 
182 	flags = O_RDONLY;
183 #ifdef O_NOFOLLOW
184 	flags |= O_NOFOLLOW;
185 #endif
186 #ifdef O_CLOEXEC
187 	flags |= O_CLOEXEC;
188 #endif
189 	fd = open(path, flags, 0);
190 	if (fd == -1) {
191 		if (errno == EINTR)
192 			goto start;
193 		goto nodevrandom;
194 	}
195 #ifndef O_CLOEXEC
196 	fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
197 #endif
198 
199 	/* Lightly verify that the device node looks sane */
200 	if (fstat(fd, &st) == -1 || !S_ISCHR(st.st_mode) ||
201 	    (devfscheck && (strcmp(st.st_fstype, "devfs") != 0))) {
202 		close(fd);
203 		goto nodevrandom;
204 	}
205 	for (i = 0; i < len; ) {
206 		size_t wanted = len - i;
207 		ssize_t ret = read(fd, (char *)buf + i, wanted);
208 
209 		if (ret == -1) {
210 			if (errno == EAGAIN || errno == EINTR)
211 				continue;
212 			close(fd);
213 			goto nodevrandom;
214 		}
215 		i += ret;
216 	}
217 	close(fd);
218 	if (gotdata(buf, len) == 0) {
219 		errno = save_errno;
220 		return 0;		/* satisfied */
221 	}
222 nodevrandom:
223 	errno = EIO;
224 	return -1;
225 }
226 
227 static const int cl[] = {
228 	CLOCK_REALTIME,
229 #ifdef CLOCK_MONOTONIC
230 	CLOCK_MONOTONIC,
231 #endif
232 #ifdef CLOCK_MONOTONIC_RAW
233 	CLOCK_MONOTONIC_RAW,
234 #endif
235 #ifdef CLOCK_TAI
236 	CLOCK_TAI,
237 #endif
238 #ifdef CLOCK_VIRTUAL
239 	CLOCK_VIRTUAL,
240 #endif
241 #ifdef CLOCK_UPTIME
242 	CLOCK_UPTIME,
243 #endif
244 #ifdef CLOCK_PROCESS_CPUTIME_ID
245 	CLOCK_PROCESS_CPUTIME_ID,
246 #endif
247 #ifdef CLOCK_THREAD_CPUTIME_ID
248 	CLOCK_THREAD_CPUTIME_ID,
249 #endif
250 };
251 
252 static int
253 getentropy_fallback(void *buf, size_t len)
254 {
255 	uint8_t results[SHA512_DIGEST_LENGTH];
256 	int save_errno = errno, e, pgs = getpagesize(), faster = 0, repeat;
257 	static int cnt;
258 	struct timespec ts;
259 	struct timeval tv;
260 	double loadavg[3];
261 	struct rusage ru;
262 	sigset_t sigset;
263 	struct stat st;
264 	SHA512_CTX ctx;
265 	static pid_t lastpid;
266 	pid_t pid;
267 	size_t i, ii, m;
268 	char *p;
269 
270 	pid = getpid();
271 	if (lastpid == pid) {
272 		faster = 1;
273 		repeat = 2;
274 	} else {
275 		faster = 0;
276 		lastpid = pid;
277 		repeat = REPEAT;
278 	}
279 	for (i = 0; i < len; ) {
280 		int j;
281 		SHA512_Init(&ctx);
282 		for (j = 0; j < repeat; j++) {
283 			HX((e = gettimeofday(&tv, NULL)) == -1, tv);
284 			if (e != -1) {
285 				cnt += (int)tv.tv_sec;
286 				cnt += (int)tv.tv_usec;
287 			}
288 
289 			for (ii = 0; ii < sizeof(cl)/sizeof(cl[0]); ii++)
290 				HX(clock_gettime(cl[ii], &ts) == -1, ts);
291 
292 			HX((pid = getpid()) == -1, pid);
293 			HX((pid = getsid(pid)) == -1, pid);
294 			HX((pid = getppid()) == -1, pid);
295 			HX((pid = getpgid(0)) == -1, pid);
296 			HX((e = getpriority(0, 0)) == -1, e);
297 			HX((getloadavg(loadavg, 3) == -1), loadavg);
298 
299 			if (!faster) {
300 				ts.tv_sec = 0;
301 				ts.tv_nsec = 1;
302 				(void) nanosleep(&ts, NULL);
303 			}
304 
305 			HX(sigpending(&sigset) == -1, sigset);
306 			HX(sigprocmask(SIG_BLOCK, NULL, &sigset) == -1,
307 			    sigset);
308 
309 #ifdef CAN_REFERENCE_MAIN
310 			HF(main);		/* an addr in program */
311 #endif
312 			HF(getentropy);	/* an addr in this library */
313 			HF(printf);		/* an addr in libc */
314 			p = (char *)&p;
315 			HD(p);		/* an addr on stack */
316 			p = (char *)&errno;
317 			HD(p);		/* the addr of errno */
318 
319 			if (i == 0) {
320 				struct sockaddr_storage ss;
321 				struct statvfs stvfs;
322 				struct termios tios;
323 				socklen_t ssl;
324 				off_t off;
325 
326 				/*
327 				 * Prime-sized mappings encourage fragmentation;
328 				 * thus exposing some address entropy.
329 				 */
330 				struct mm {
331 					size_t	npg;
332 					void	*p;
333 				} mm[] =	 {
334 					{ 17, MAP_FAILED }, { 3, MAP_FAILED },
335 					{ 11, MAP_FAILED }, { 2, MAP_FAILED },
336 					{ 5, MAP_FAILED }, { 3, MAP_FAILED },
337 					{ 7, MAP_FAILED }, { 1, MAP_FAILED },
338 					{ 57, MAP_FAILED }, { 3, MAP_FAILED },
339 					{ 131, MAP_FAILED }, { 1, MAP_FAILED },
340 				};
341 
342 				for (m = 0; m < sizeof mm/sizeof(mm[0]); m++) {
343 					HX(mm[m].p = mmap(NULL,
344 					    mm[m].npg * pgs,
345 					    PROT_READ|PROT_WRITE,
346 					    MAP_PRIVATE|MAP_ANON, -1,
347 					    (off_t)0), mm[m].p);
348 					if (mm[m].p != MAP_FAILED) {
349 						size_t mo;
350 
351 						/* Touch some memory... */
352 						p = mm[m].p;
353 						mo = cnt %
354 						    (mm[m].npg * pgs - 1);
355 						p[mo] = 1;
356 						cnt += (int)((long)(mm[m].p)
357 						    / pgs);
358 					}
359 
360 					/* Check cnts and times... */
361 					for (ii = 0; ii < sizeof(cl)/sizeof(cl[0]);
362 					    ii++) {
363 						HX((e = clock_gettime(cl[ii],
364 						    &ts)) == -1, ts);
365 						if (e != -1)
366 							cnt += (int)ts.tv_nsec;
367 					}
368 
369 					HX((e = getrusage(RUSAGE_SELF,
370 					    &ru)) == -1, ru);
371 					if (e != -1) {
372 						cnt += (int)ru.ru_utime.tv_sec;
373 						cnt += (int)ru.ru_utime.tv_usec;
374 					}
375 				}
376 
377 				for (m = 0; m < sizeof mm/sizeof(mm[0]); m++) {
378 					if (mm[m].p != MAP_FAILED)
379 						munmap(mm[m].p, mm[m].npg * pgs);
380 					mm[m].p = MAP_FAILED;
381 				}
382 
383 				HX(stat(".", &st) == -1, st);
384 				HX(statvfs(".", &stvfs) == -1, stvfs);
385 
386 				HX(stat("/", &st) == -1, st);
387 				HX(statvfs("/", &stvfs) == -1, stvfs);
388 
389 				HX((e = fstat(0, &st)) == -1, st);
390 				if (e == -1) {
391 					if (S_ISREG(st.st_mode) ||
392 					    S_ISFIFO(st.st_mode) ||
393 					    S_ISSOCK(st.st_mode)) {
394 						HX(fstatvfs(0, &stvfs) == -1,
395 						    stvfs);
396 						HX((off = lseek(0, (off_t)0,
397 						    SEEK_CUR)) < 0, off);
398 					}
399 					if (S_ISCHR(st.st_mode)) {
400 						HX(tcgetattr(0, &tios) == -1,
401 						    tios);
402 					} else if (S_ISSOCK(st.st_mode)) {
403 						memset(&ss, 0, sizeof ss);
404 						ssl = sizeof(ss);
405 						HX(getpeername(0,
406 						    (void *)&ss, &ssl) == -1,
407 						    ss);
408 					}
409 				}
410 
411 				HX((e = getrusage(RUSAGE_CHILDREN,
412 				    &ru)) == -1, ru);
413 				if (e != -1) {
414 					cnt += (int)ru.ru_utime.tv_sec;
415 					cnt += (int)ru.ru_utime.tv_usec;
416 				}
417 			} else {
418 				/* Subsequent hashes absorb previous result */
419 				HD(results);
420 			}
421 
422 			HX((e = gettimeofday(&tv, NULL)) == -1, tv);
423 			if (e != -1) {
424 				cnt += (int)tv.tv_sec;
425 				cnt += (int)tv.tv_usec;
426 			}
427 
428 			HD(cnt);
429 		}
430 		SHA512_Final(results, &ctx);
431 		memcpy((char *)buf + i, results, min(sizeof(results), len - i));
432 		i += min(sizeof(results), len - i);
433 	}
434 	memset(results, 0, sizeof results);
435 	if (gotdata(buf, len) == 0) {
436 		errno = save_errno;
437 		return 0;		/* satisfied */
438 	}
439 	errno = EIO;
440 	return -1;
441 }
442