getentropy_osx.c revision 356345
12786Ssos/*	$OpenBSD: getentropy_osx.c,v 1.12 2018/11/20 08:04:28 deraadt Exp $	*/
22786Ssos
32786Ssos/*
42786Ssos * Copyright (c) 2014 Theo de Raadt <deraadt@openbsd.org>
52786Ssos * Copyright (c) 2014 Bob Beck <beck@obtuse.com>
632822Syokota *
76857Sse * Permission to use, copy, modify, and distribute this software for any
824578Ssos * purpose with or without fee is hereby granted, provided that the above
924578Ssos * copyright notice and this permission notice appear in all copies.
102786Ssos *
112786Ssos * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
126857Sse * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
136857Sse * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
146857Sse * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
152786Ssos * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
166857Sse * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
176857Sse * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
186857Sse *
197420Ssos * Emulation of getentropy(2) as documented at:
202786Ssos * http://man.openbsd.org/getentropy.2
216857Sse */
222786Ssos
232786Ssos#include <TargetConditionals.h>
242786Ssos#include <sys/types.h>
252786Ssos#include <sys/param.h>
262786Ssos#include <sys/ioctl.h>
272786Ssos#include <sys/resource.h>
282786Ssos#include <sys/syscall.h>
292786Ssos#include <sys/sysctl.h>
302786Ssos#include <sys/statvfs.h>
316857Sse#include <sys/socket.h>
326857Sse#include <sys/mount.h>
332786Ssos#include <sys/mman.h>
342786Ssos#include <sys/stat.h>
352786Ssos#include <sys/time.h>
362786Ssos#include <stdlib.h>
372786Ssos#include <stdint.h>
382786Ssos#include <stdio.h>
392786Ssos#include <termios.h>
402786Ssos#include <fcntl.h>
412786Ssos#include <signal.h>
422786Ssos#include <string.h>
432786Ssos#include <errno.h>
442786Ssos#include <unistd.h>
452786Ssos#include <time.h>
4624578Ssos#include <mach/mach_time.h>
472786Ssos#include <mach/mach_host.h>
486857Sse#include <mach/host_info.h>
492786Ssos#if TARGET_OS_OSX
502786Ssos#include <sys/socketvar.h>
512786Ssos#include <sys/vmmeter.h>
522786Ssos#endif
532786Ssos#include <netinet/in.h>
542786Ssos#include <netinet/tcp.h>
5524578Ssos#if TARGET_OS_OSX
562786Ssos#include <netinet/udp.h>
572786Ssos#include <netinet/ip_var.h>
5838140Syokota#include <netinet/tcp_var.h>
592786Ssos#include <netinet/udp_var.h>
6043334Syokota#endif
612786Ssos#include <CommonCrypto/CommonDigest.h>
6232822Syokota#define SHA512_Update(a, b, c)	(CC_SHA512_Update((a), (b), (c)))
632786Ssos#define SHA512_Init(xxx) (CC_SHA512_Init((xxx)))
642786Ssos#define SHA512_Final(xxx, yyy) (CC_SHA512_Final((xxx), (yyy)))
652786Ssos#define SHA512_CTX CC_SHA512_CTX
662786Ssos#define SHA512_DIGEST_LENGTH CC_SHA512_DIGEST_LENGTH
672786Ssos
682786Ssos#define REPEAT 5
692786Ssos#define min(a, b) (((a) < (b)) ? (a) : (b))
702786Ssos
712786Ssos#define HX(a, b) \
722786Ssos	do { \
732786Ssos		if ((a)) \
7443334Syokota			HD(errno); \
7543334Syokota		else \
762786Ssos			HD(b); \
772786Ssos	} while (0)
782786Ssos
7943334Syokota#define HR(x, l) (SHA512_Update(&ctx, (char *)(x), (l)))
802786Ssos#define HD(x)	 (SHA512_Update(&ctx, (char *)&(x), sizeof (x)))
815994Ssos#define HF(x)    (SHA512_Update(&ctx, (char *)&(x), sizeof (void*)))
8243334Syokota
832786Ssosint	getentropy(void *buf, size_t len);
842786Ssos
852786Ssosstatic int getentropy_urandom(void *buf, size_t len);
862786Ssosstatic int getentropy_fallback(void *buf, size_t len);
872786Ssos
886045Ssosint
8943334Syokotagetentropy(void *buf, size_t len)
902786Ssos{
9124578Ssos	int ret = -1;
922786Ssos
932786Ssos	if (len > 256) {
9418194Ssos		errno = EIO;
952786Ssos		return (-1);
962786Ssos	}
9743334Syokota
982786Ssos	/*
992786Ssos	 * Try to get entropy with /dev/urandom
1002786Ssos	 *
1012786Ssos	 * This can fail if the process is inside a chroot or if file
1022786Ssos	 * descriptors are exhausted.
1032786Ssos	 */
1042786Ssos	ret = getentropy_urandom(buf, len);
1052786Ssos	if (ret != -1)
1062786Ssos		return (ret);
1072786Ssos
1086851Ssos	/*
10943334Syokota	 * Entropy collection via /dev/urandom and sysctl have failed.
11043334Syokota	 *
11143334Syokota	 * No other API exists for collecting entropy, and we have
11243334Syokota	 * no failsafe way to get it on OSX that is not sensitive
11343334Syokota	 * 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
144static int
145getentropy_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
152start:
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 */
191nodevrandom:
192	errno = EIO;
193	return (-1);
194}
195
196#if TARGET_OS_OSX
197static int tcpmib[] = { CTL_NET, AF_INET, IPPROTO_TCP, TCPCTL_STATS };
198static int udpmib[] = { CTL_NET, AF_INET, IPPROTO_UDP, UDPCTL_STATS };
199static int ipmib[] = { CTL_NET, AF_INET, IPPROTO_IP, IPCTL_STATS };
200#endif
201static int kmib[] = { CTL_KERN, KERN_USRSTACK };
202static int hwmib[] = { CTL_HW, HW_USERMEM };
203
204static int
205getentropy_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, min(sizeof(results), len - i));
411		i += min(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