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