1 /* $OpenBSD: getentropy_osx.c,v 1.11 2016/09/03 15:24:09 bcook 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://man.openbsd.org/getentropy.2
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>
46 #include <mach/mach_time.h>
47 #include <mach/mach_host.h>
48 #include <mach/host_info.h>
50 #include <sys/socketvar.h>
51 #include <sys/vmmeter.h>
53 #include <netinet/in.h>
54 #include <netinet/tcp.h>
56 #include <netinet/udp.h>
57 #include <netinet/ip_var.h>
58 #include <netinet/tcp_var.h>
59 #include <netinet/udp_var.h>
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
69 #define min(a, b) (((a) < (b)) ? (a) : (b))
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*)))
83 int getentropy(void *buf
, size_t len
);
85 static int gotdata(char *buf
, size_t len
);
86 static int getentropy_urandom(void *buf
, size_t len
);
87 static int getentropy_fallback(void *buf
, size_t len
);
90 getentropy(void *buf
, size_t len
)
100 * Try to get entropy with /dev/urandom
102 * This can fail if the process is inside a chroot or if file
103 * descriptors are exhausted.
105 ret
= getentropy_urandom(buf
, len
);
110 * Entropy collection via /dev/urandom and sysctl have failed.
112 * No other API exists for collecting entropy, and we have
113 * no failsafe way to get it on OSX that is not sensitive
114 * to resource exhaustion.
116 * We have very few options:
117 * - Even syslog_r is unsafe to call at this low level, so
118 * there is no way to alert the user or program.
119 * - Cannot call abort() because some systems have unsafe
121 * - Could raise(SIGKILL) resulting in silent program termination.
122 * - Return EIO, to hint that arc4random's stir function
123 * should raise(SIGKILL)
124 * - Do the best under the circumstances....
126 * This code path exists to bring light to the issue that OSX
127 * does not provide a failsafe API for entropy collection.
129 * We hope this demonstrates that OSX should consider
130 * providing a new failsafe API which works in a chroot or
131 * when file descriptors are exhausted.
133 #undef FAIL_INSTEAD_OF_TRYING_FALLBACK
134 #ifdef FAIL_INSTEAD_OF_TRYING_FALLBACK
137 ret
= getentropy_fallback(buf
, len
);
146 * Basic sanity checking; wish we could do better.
149 gotdata(char *buf
, size_t len
)
154 for (i
= 0; i
< len
; ++i
)
162 getentropy_urandom(void *buf
, size_t len
)
167 int save_errno
= errno
;
178 fd
= open("/dev/urandom", flags
, 0);
185 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
188 /* Lightly verify that the device node looks sane */
189 if (fstat(fd
, &st
) == -1 || !S_ISCHR(st
.st_mode
)) {
193 for (i
= 0; i
< len
; ) {
194 size_t wanted
= len
- i
;
195 ssize_t ret
= read(fd
, (char *)buf
+ i
, wanted
);
198 if (errno
== EAGAIN
|| errno
== EINTR
)
206 if (gotdata(buf
, len
) == 0) {
208 return (0); /* satisfied */
216 static int tcpmib
[] = { CTL_NET
, AF_INET
, IPPROTO_TCP
, TCPCTL_STATS
};
217 static int udpmib
[] = { CTL_NET
, AF_INET
, IPPROTO_UDP
, UDPCTL_STATS
};
218 static int ipmib
[] = { CTL_NET
, AF_INET
, IPPROTO_IP
, IPCTL_STATS
};
220 static int kmib
[] = { CTL_KERN
, KERN_USRSTACK
};
221 static int hwmib
[] = { CTL_HW
, HW_USERMEM
};
224 getentropy_fallback(void *buf
, size_t len
)
226 uint8_t results
[SHA512_DIGEST_LENGTH
];
227 int save_errno
= errno
, e
, pgs
= getpagesize(), faster
= 0, repeat
;
235 static pid_t lastpid
;
240 struct tcpstat tcpstat
;
241 struct udpstat udpstat
;
242 struct ipstat ipstat
;
249 if (lastpid
== pid
) {
257 for (i
= 0; i
< len
; ) {
260 for (j
= 0; j
< repeat
; j
++) {
261 HX((e
= gettimeofday(&tv
, NULL
)) == -1, tv
);
263 cnt
+= (int)tv
.tv_sec
;
264 cnt
+= (int)tv
.tv_usec
;
267 mach_time
= mach_absolute_time();
271 HX(sysctl(kmib
, sizeof(kmib
) / sizeof(kmib
[0]),
272 &addr
, &ii
, NULL
, 0) == -1, addr
);
275 HX(sysctl(hwmib
, sizeof(hwmib
) / sizeof(hwmib
[0]),
276 &idata
, &ii
, NULL
, 0) == -1, idata
);
279 ii
= sizeof(tcpstat
);
280 HX(sysctl(tcpmib
, sizeof(tcpmib
) / sizeof(tcpmib
[0]),
281 &tcpstat
, &ii
, NULL
, 0) == -1, tcpstat
);
283 ii
= sizeof(udpstat
);
284 HX(sysctl(udpmib
, sizeof(udpmib
) / sizeof(udpmib
[0]),
285 &udpstat
, &ii
, NULL
, 0) == -1, udpstat
);
288 HX(sysctl(ipmib
, sizeof(ipmib
) / sizeof(ipmib
[0]),
289 &ipstat
, &ii
, NULL
, 0) == -1, ipstat
);
292 HX((pid
= getpid()) == -1, pid
);
293 HX((pid
= getsid(pid
)) == -1, pid
);
294 HX((pid
= getppid()) == -1, pid
);
295 HX((pid
= getpgid(0)) == -1, pid
);
296 HX((e
= getpriority(0, 0)) == -1, e
);
301 (void) nanosleep(&ts
, NULL
);
304 HX(sigpending(&sigset
) == -1, sigset
);
305 HX(sigprocmask(SIG_BLOCK
, NULL
, &sigset
) == -1,
308 HF(getentropy
); /* an addr in this library */
309 HF(printf
); /* an addr in libc */
311 HD(p
); /* an addr on stack */
313 HD(p
); /* the addr of errno */
316 struct sockaddr_storage ss
;
317 struct statvfs stvfs
;
324 * Prime-sized mappings encourage fragmentation;
325 * thus exposing some address entropy.
331 { 17, MAP_FAILED
}, { 3, MAP_FAILED
},
332 { 11, MAP_FAILED
}, { 2, MAP_FAILED
},
333 { 5, MAP_FAILED
}, { 3, MAP_FAILED
},
334 { 7, MAP_FAILED
}, { 1, MAP_FAILED
},
335 { 57, MAP_FAILED
}, { 3, MAP_FAILED
},
336 { 131, MAP_FAILED
}, { 1, MAP_FAILED
},
339 for (m
= 0; m
< sizeof mm
/sizeof(mm
[0]); m
++) {
340 HX(mm
[m
].p
= mmap(NULL
,
342 PROT_READ
|PROT_WRITE
,
343 MAP_PRIVATE
|MAP_ANON
, -1,
345 if (mm
[m
].p
!= MAP_FAILED
) {
348 /* Touch some memory... */
351 (mm
[m
].npg
* pgs
- 1);
353 cnt
+= (int)((long)(mm
[m
].p
)
357 /* Check cnts and times... */
358 mach_time
= mach_absolute_time();
360 cnt
+= (int)mach_time
;
362 HX((e
= getrusage(RUSAGE_SELF
,
365 cnt
+= (int)ru
.ru_utime
.tv_sec
;
366 cnt
+= (int)ru
.ru_utime
.tv_usec
;
370 for (m
= 0; m
< sizeof mm
/sizeof(mm
[0]); m
++) {
371 if (mm
[m
].p
!= MAP_FAILED
)
372 munmap(mm
[m
].p
, mm
[m
].npg
* pgs
);
373 mm
[m
].p
= MAP_FAILED
;
376 HX(stat(".", &st
) == -1, st
);
377 HX(statvfs(".", &stvfs
) == -1, stvfs
);
378 HX(statfs(".", &stfs
) == -1, stfs
);
380 HX(stat("/", &st
) == -1, st
);
381 HX(statvfs("/", &stvfs
) == -1, stvfs
);
382 HX(statfs("/", &stfs
) == -1, stfs
);
384 HX((e
= fstat(0, &st
)) == -1, st
);
386 if (S_ISREG(st
.st_mode
) ||
387 S_ISFIFO(st
.st_mode
) ||
388 S_ISSOCK(st
.st_mode
)) {
389 HX(fstatvfs(0, &stvfs
) == -1,
391 HX(fstatfs(0, &stfs
) == -1,
393 HX((off
= lseek(0, (off_t
)0,
394 SEEK_CUR
)) < 0, off
);
396 if (S_ISCHR(st
.st_mode
)) {
397 HX(tcgetattr(0, &tios
) == -1,
399 } else if (S_ISSOCK(st
.st_mode
)) {
400 memset(&ss
, 0, sizeof ss
);
403 (void *)&ss
, &ssl
) == -1,
408 HX((e
= getrusage(RUSAGE_CHILDREN
,
411 cnt
+= (int)ru
.ru_utime
.tv_sec
;
412 cnt
+= (int)ru
.ru_utime
.tv_usec
;
415 /* Subsequent hashes absorb previous result */
419 HX((e
= gettimeofday(&tv
, NULL
)) == -1, tv
);
421 cnt
+= (int)tv
.tv_sec
;
422 cnt
+= (int)tv
.tv_usec
;
428 SHA512_Final(results
, &ctx
);
429 memcpy((char *)buf
+ i
, results
, min(sizeof(results
), len
- i
));
430 i
+= min(sizeof(results
), len
- i
);
432 explicit_bzero(&ctx
, sizeof ctx
);
433 explicit_bzero(results
, sizeof results
);
434 if (gotdata(buf
, len
) == 0) {
436 return (0); /* satisfied */