1 /* $OpenBSD: getentropy_osx.c,v 1.3 2014/07/12 14:48:00 deraadt 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.
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/sysctl.h>
27 #include <sys/statvfs.h>
28 #include <sys/socket.h>
29 #include <sys/mount.h>
43 #include <mach/mach_time.h>
44 #include <mach/mach_host.h>
45 #include <mach/host_info.h>
46 #include <sys/socketvar.h>
47 #include <sys/vmmeter.h>
48 #include <netinet/in.h>
49 #include <netinet/tcp.h>
50 #include <netinet/udp.h>
51 #include <netinet/ip_var.h>
52 #include <netinet/tcp_var.h>
53 #include <netinet/udp_var.h>
54 #include <CommonCrypto/CommonDigest.h>
55 #define SHA512_Update(a, b, c) (CC_SHA512_Update((a), (b), (c)))
56 #define SHA512_Init(xxx) (CC_SHA512_Init((xxx)))
57 #define SHA512_Final(xxx, yyy) (CC_SHA512_Final((xxx), (yyy)))
58 #define SHA512_CTX CC_SHA512_CTX
59 #define SHA512_DIGEST_LENGTH CC_SHA512_DIGEST_LENGTH
62 #define min(a, b) (((a) < (b)) ? (a) : (b))
72 #define HR(x, l) (SHA512_Update(&ctx, (char *)(x), (l)))
73 #define HD(x) (SHA512_Update(&ctx, (char *)&(x), sizeof (x)))
74 #define HF(x) (SHA512_Update(&ctx, (char *)&(x), sizeof (void*)))
76 int getentropy(void *buf, size_t len);
78 #ifdef CAN_REFERENCE_MAIN
79 extern int main(int, char *argv[]);
81 static int gotdata(char *buf, size_t len);
82 static int getentropy_urandom(void *buf, size_t len);
83 static int getentropy_fallback(void *buf, size_t len);
86 getentropy(void *buf, size_t len)
96 * Try to get entropy with /dev/urandom
98 * This can fail if the process is inside a chroot or if file
99 * descriptors are exhausted.
101 ret = getentropy_urandom(buf, len);
106 * Entropy collection via /dev/urandom and sysctl have failed.
108 * No other API exists for collecting entropy, and we have
109 * no failsafe way to get it on OSX that is not sensitive
110 * to resource exhaustion.
112 * We have very few options:
113 * - Even syslog_r is unsafe to call at this low level, so
114 * there is no way to alert the user or program.
115 * - Cannot call abort() because some systems have unsafe
117 * - Could raise(SIGKILL) resulting in silent program termination.
118 * - Return EIO, to hint that arc4random's stir function
119 * should raise(SIGKILL)
120 * - Do the best under the circumstances....
122 * This code path exists to bring light to the issue that OSX
123 * does not provide a failsafe API for entropy collection.
125 * We hope this demonstrates that OSX should consider
126 * providing a new failsafe API which works in a chroot or
127 * when file descriptors are exhausted.
129 #undef FAIL_INSTEAD_OF_TRYING_FALLBACK
130 #ifdef FAIL_INSTEAD_OF_TRYING_FALLBACK
133 ret = getentropy_fallback(buf, len);
142 * Basic sanity checking; wish we could do better.
145 gotdata(char *buf, size_t len)
150 for (i = 0; i < len; ++i)
158 getentropy_urandom(void *buf, size_t len)
163 int save_errno = errno;
174 fd = open("/dev/urandom", flags, 0);
181 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
184 /* Lightly verify that the device node looks sane */
185 if (fstat(fd, &st) == -1 || !S_ISCHR(st.st_mode)) {
189 for (i = 0; i < len; ) {
190 size_t wanted = len - i;
191 ssize_t ret = read(fd, (char*)buf + i, wanted);
194 if (errno == EAGAIN || errno == EINTR)
202 if (gotdata(buf, len) == 0) {
204 return 0; /* satisfied */
211 static int tcpmib[] = { CTL_NET, AF_INET, IPPROTO_TCP, TCPCTL_STATS };
212 static int udpmib[] = { CTL_NET, AF_INET, IPPROTO_UDP, UDPCTL_STATS };
213 static int ipmib[] = { CTL_NET, AF_INET, IPPROTO_IP, IPCTL_STATS };
214 static int kmib[] = { CTL_KERN, KERN_USRSTACK };
215 static int hwmib[] = { CTL_HW, HW_USERMEM };
218 getentropy_fallback(void *buf, size_t len)
220 uint8_t results[SHA512_DIGEST_LENGTH];
221 int save_errno = errno, e, pgs = getpagesize(), faster = 0, repeat;
229 static pid_t lastpid;
233 struct tcpstat tcpstat;
234 struct udpstat udpstat;
235 struct ipstat ipstat;
241 if (lastpid == pid) {
249 for (i = 0; i < len; ) {
252 for (j = 0; j < repeat; j++) {
253 HX((e = gettimeofday(&tv, NULL)) == -1, tv);
255 cnt += (int)tv.tv_sec;
256 cnt += (int)tv.tv_usec;
259 mach_time = mach_absolute_time();
263 HX(sysctl(kmib, sizeof(kmib) / sizeof(kmib[0]),
264 &addr, &ii, NULL, 0) == -1, addr);
267 HX(sysctl(hwmib, sizeof(hwmib) / sizeof(hwmib[0]),
268 &idata, &ii, NULL, 0) == -1, idata);
270 ii = sizeof(tcpstat);
271 HX(sysctl(tcpmib, sizeof(tcpmib) / sizeof(tcpmib[0]),
272 &tcpstat, &ii, NULL, 0) == -1, tcpstat);
274 ii = sizeof(udpstat);
275 HX(sysctl(udpmib, sizeof(udpmib) / sizeof(udpmib[0]),
276 &udpstat, &ii, NULL, 0) == -1, udpstat);
279 HX(sysctl(ipmib, sizeof(ipmib) / sizeof(ipmib[0]),
280 &ipstat, &ii, NULL, 0) == -1, ipstat);
282 HX((pid = getpid()) == -1, pid);
283 HX((pid = getsid(pid)) == -1, pid);
284 HX((pid = getppid()) == -1, pid);
285 HX((pid = getpgid(0)) == -1, pid);
286 HX((e = getpriority(0, 0)) == -1, e);
291 (void) nanosleep(&ts, NULL);
294 HX(sigpending(&sigset) == -1, sigset);
295 HX(sigprocmask(SIG_BLOCK, NULL, &sigset) == -1,
298 #ifdef CAN_REFERENCE_MAIN
299 HF(main); /* an addr in program */
301 HF(getentropy); /* an addr in this library */
302 HF(printf); /* an addr in libc */
304 HD(p); /* an addr on stack */
306 HD(p); /* the addr of errno */
309 struct sockaddr_storage ss;
310 struct statvfs stvfs;
317 * Prime-sized mappings encourage fragmentation;
318 * thus exposing some address entropy.
324 { 17, MAP_FAILED }, { 3, MAP_FAILED },
325 { 11, MAP_FAILED }, { 2, MAP_FAILED },
326 { 5, MAP_FAILED }, { 3, MAP_FAILED },
327 { 7, MAP_FAILED }, { 1, MAP_FAILED },
328 { 57, MAP_FAILED }, { 3, MAP_FAILED },
329 { 131, MAP_FAILED }, { 1, MAP_FAILED },
332 for (m = 0; m < sizeof mm/sizeof(mm[0]); m++) {
333 HX(mm[m].p = mmap(NULL,
335 PROT_READ|PROT_WRITE,
336 MAP_PRIVATE|MAP_ANON, -1,
338 if (mm[m].p != MAP_FAILED) {
341 /* Touch some memory... */
344 (mm[m].npg * pgs - 1);
346 cnt += (int)((long)(mm[m].p)
350 /* Check cnts and times... */
351 mach_time = mach_absolute_time();
353 cnt += (int)mach_time;
355 HX((e = getrusage(RUSAGE_SELF,
358 cnt += (int)ru.ru_utime.tv_sec;
359 cnt += (int)ru.ru_utime.tv_usec;
363 for (m = 0; m < sizeof mm/sizeof(mm[0]); m++) {
364 if (mm[m].p != MAP_FAILED)
365 munmap(mm[m].p, mm[m].npg * pgs);
366 mm[m].p = MAP_FAILED;
369 HX(stat(".", &st) == -1, st);
370 HX(statvfs(".", &stvfs) == -1, stvfs);
371 HX(statfs(".", &stfs) == -1, stfs);
373 HX(stat("/", &st) == -1, st);
374 HX(statvfs("/", &stvfs) == -1, stvfs);
375 HX(statfs("/", &stfs) == -1, stfs);
377 HX((e = fstat(0, &st)) == -1, st);
379 if (S_ISREG(st.st_mode) ||
380 S_ISFIFO(st.st_mode) ||
381 S_ISSOCK(st.st_mode)) {
382 HX(fstatvfs(0, &stvfs) == -1,
384 HX(fstatfs(0, &stfs) == -1,
386 HX((off = lseek(0, (off_t)0,
387 SEEK_CUR)) < 0, off);
389 if (S_ISCHR(st.st_mode)) {
390 HX(tcgetattr(0, &tios) == -1,
392 } else if (S_ISSOCK(st.st_mode)) {
393 memset(&ss, 0, sizeof ss);
396 (void *)&ss, &ssl) == -1,
401 HX((e = getrusage(RUSAGE_CHILDREN,
404 cnt += (int)ru.ru_utime.tv_sec;
405 cnt += (int)ru.ru_utime.tv_usec;
408 /* Subsequent hashes absorb previous result */
412 HX((e = gettimeofday(&tv, NULL)) == -1, tv);
414 cnt += (int)tv.tv_sec;
415 cnt += (int)tv.tv_usec;
421 SHA512_Final(results, &ctx);
422 memcpy((char*)buf + i, results, min(sizeof(results), len - i));
423 i += min(sizeof(results), len - i);
425 memset(results, 0, sizeof results);
426 if (gotdata(buf, len) == 0) {
428 return 0; /* satisfied */