1 /* $OpenBSD: getentropy_osx.c,v 1.8 2014/07/21 20:19:47 guenther Exp $ */
4 * Copyright (c) 2014 Theo de Raadt <deraadt@openbsd.org>
5 * Copyright (c) 2014 Bob Beck <beck@obtuse.com>
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.
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.
19 * Emulation of getentropy(2) as documented at:
20 * http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man2/getentropy.2
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>
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
64 #define min(a, b) (((a) < (b)) ? (a) : (b))
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*)))
78 int getentropy(void *buf, size_t len);
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);
85 getentropy(void *buf, size_t len)
95 * Try to get entropy with /dev/urandom
97 * This can fail if the process is inside a chroot or if file
98 * descriptors are exhausted.
100 ret = getentropy_urandom(buf, len);
105 * Entropy collection via /dev/urandom and sysctl have failed.
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.
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
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....
121 * This code path exists to bring light to the issue that OSX
122 * does not provide a failsafe API for entropy collection.
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.
128 #undef FAIL_INSTEAD_OF_TRYING_FALLBACK
129 #ifdef FAIL_INSTEAD_OF_TRYING_FALLBACK
132 ret = getentropy_fallback(buf, len);
141 * Basic sanity checking; wish we could do better.
144 gotdata(char *buf, size_t len)
149 for (i = 0; i < len; ++i)
157 getentropy_urandom(void *buf, size_t len)
162 int save_errno = errno;
173 fd = open("/dev/urandom", flags, 0);
180 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
183 /* Lightly verify that the device node looks sane */
184 if (fstat(fd, &st) == -1 || !S_ISCHR(st.st_mode)) {
188 for (i = 0; i < len; ) {
189 size_t wanted = len - i;
190 ssize_t ret = read(fd, (char *)buf + i, wanted);
193 if (errno == EAGAIN || errno == EINTR)
201 if (gotdata(buf, len) == 0) {
203 return (0); /* satisfied */
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 };
217 getentropy_fallback(void *buf, size_t len)
219 uint8_t results[SHA512_DIGEST_LENGTH];
220 int save_errno = errno, e, pgs = getpagesize(), faster = 0, repeat;
228 static pid_t lastpid;
232 struct tcpstat tcpstat;
233 struct udpstat udpstat;
234 struct ipstat ipstat;
240 if (lastpid == pid) {
248 for (i = 0; i < len; ) {
251 for (j = 0; j < repeat; j++) {
252 HX((e = gettimeofday(&tv, NULL)) == -1, tv);
254 cnt += (int)tv.tv_sec;
255 cnt += (int)tv.tv_usec;
258 mach_time = mach_absolute_time();
262 HX(sysctl(kmib, sizeof(kmib) / sizeof(kmib[0]),
263 &addr, &ii, NULL, 0) == -1, addr);
266 HX(sysctl(hwmib, sizeof(hwmib) / sizeof(hwmib[0]),
267 &idata, &ii, NULL, 0) == -1, idata);
269 ii = sizeof(tcpstat);
270 HX(sysctl(tcpmib, sizeof(tcpmib) / sizeof(tcpmib[0]),
271 &tcpstat, &ii, NULL, 0) == -1, tcpstat);
273 ii = sizeof(udpstat);
274 HX(sysctl(udpmib, sizeof(udpmib) / sizeof(udpmib[0]),
275 &udpstat, &ii, NULL, 0) == -1, udpstat);
278 HX(sysctl(ipmib, sizeof(ipmib) / sizeof(ipmib[0]),
279 &ipstat, &ii, NULL, 0) == -1, ipstat);
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);
290 (void) nanosleep(&ts, NULL);
293 HX(sigpending(&sigset) == -1, sigset);
294 HX(sigprocmask(SIG_BLOCK, NULL, &sigset) == -1,
297 HF(getentropy); /* an addr in this library */
298 HF(printf); /* an addr in libc */
300 HD(p); /* an addr on stack */
302 HD(p); /* the addr of errno */
305 struct sockaddr_storage ss;
306 struct statvfs stvfs;
313 * Prime-sized mappings encourage fragmentation;
314 * thus exposing some address entropy.
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 },
328 for (m = 0; m < sizeof mm/sizeof(mm[0]); m++) {
329 HX(mm[m].p = mmap(NULL,
331 PROT_READ|PROT_WRITE,
332 MAP_PRIVATE|MAP_ANON, -1,
334 if (mm[m].p != MAP_FAILED) {
337 /* Touch some memory... */
340 (mm[m].npg * pgs - 1);
342 cnt += (int)((long)(mm[m].p)
346 /* Check cnts and times... */
347 mach_time = mach_absolute_time();
349 cnt += (int)mach_time;
351 HX((e = getrusage(RUSAGE_SELF,
354 cnt += (int)ru.ru_utime.tv_sec;
355 cnt += (int)ru.ru_utime.tv_usec;
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;
365 HX(stat(".", &st) == -1, st);
366 HX(statvfs(".", &stvfs) == -1, stvfs);
367 HX(statfs(".", &stfs) == -1, stfs);
369 HX(stat("/", &st) == -1, st);
370 HX(statvfs("/", &stvfs) == -1, stvfs);
371 HX(statfs("/", &stfs) == -1, stfs);
373 HX((e = fstat(0, &st)) == -1, st);
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,
380 HX(fstatfs(0, &stfs) == -1,
382 HX((off = lseek(0, (off_t)0,
383 SEEK_CUR)) < 0, off);
385 if (S_ISCHR(st.st_mode)) {
386 HX(tcgetattr(0, &tios) == -1,
388 } else if (S_ISSOCK(st.st_mode)) {
389 memset(&ss, 0, sizeof ss);
392 (void *)&ss, &ssl) == -1,
397 HX((e = getrusage(RUSAGE_CHILDREN,
400 cnt += (int)ru.ru_utime.tv_sec;
401 cnt += (int)ru.ru_utime.tv_usec;
404 /* Subsequent hashes absorb previous result */
408 HX((e = gettimeofday(&tv, NULL)) == -1, tv);
410 cnt += (int)tv.tv_sec;
411 cnt += (int)tv.tv_usec;
417 SHA512_Final(results, &ctx);
418 memcpy((char *)buf + i, results, min(sizeof(results), len - i));
419 i += min(sizeof(results), len - i);
421 explicit_bzero(&ctx, sizeof ctx);
422 explicit_bzero(results, sizeof results);
423 if (gotdata(buf, len) == 0) {
425 return (0); /* satisfied */