lua-arc4random

Cryptographically secure PRNG for Lua
Log | Files | Refs | README

getentropy_osx.c (10801B)


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