1 /* $OpenBSD: getentropy_osx.c,v 1.11.8.1 2018/12/15 15:10:12 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 getentropy_urandom(void *buf
, size_t len
);
86 static int getentropy_fallback(void *buf
, size_t len
);
89 getentropy(void *buf
, size_t len
)
99 * Try to get entropy with /dev/urandom
101 * This can fail if the process is inside a chroot or if file
102 * descriptors are exhausted.
104 ret
= getentropy_urandom(buf
, len
);
109 * Entropy collection via /dev/urandom and sysctl have failed.
111 * No other API exists for collecting entropy, and we have
112 * no failsafe way to get it on OSX that is not sensitive
113 * to resource exhaustion.
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
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....
125 * This code path exists to bring light to the issue that OSX
126 * does not provide a failsafe API for entropy collection.
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.
132 #undef FAIL_INSTEAD_OF_TRYING_FALLBACK
133 #ifdef FAIL_INSTEAD_OF_TRYING_FALLBACK
136 ret
= getentropy_fallback(buf
, len
);
145 getentropy_urandom(void *buf
, size_t len
)
150 int save_errno
= errno
;
161 fd
= open("/dev/urandom", flags
, 0);
168 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
171 /* Lightly verify that the device node looks sane */
172 if (fstat(fd
, &st
) == -1 || !S_ISCHR(st
.st_mode
)) {
176 for (i
= 0; i
< len
; ) {
177 size_t wanted
= len
- i
;
178 ssize_t ret
= read(fd
, (char *)buf
+ i
, wanted
);
181 if (errno
== EAGAIN
|| errno
== EINTR
)
190 return (0); /* satisfied */
197 static int tcpmib
[] = { CTL_NET
, AF_INET
, IPPROTO_TCP
, TCPCTL_STATS
};
198 static int udpmib
[] = { CTL_NET
, AF_INET
, IPPROTO_UDP
, UDPCTL_STATS
};
199 static int ipmib
[] = { CTL_NET
, AF_INET
, IPPROTO_IP
, IPCTL_STATS
};
201 static int kmib
[] = { CTL_KERN
, KERN_USRSTACK
};
202 static int hwmib
[] = { CTL_HW
, HW_USERMEM
};
205 getentropy_fallback(void *buf
, size_t len
)
207 uint8_t results
[SHA512_DIGEST_LENGTH
];
208 int save_errno
= errno
, e
, pgs
= getpagesize(), faster
= 0, repeat
;
216 static pid_t lastpid
;
221 struct tcpstat tcpstat
;
222 struct udpstat udpstat
;
223 struct ipstat ipstat
;
230 if (lastpid
== pid
) {
238 for (i
= 0; i
< len
; ) {
241 for (j
= 0; j
< repeat
; j
++) {
242 HX((e
= gettimeofday(&tv
, NULL
)) == -1, tv
);
244 cnt
+= (int)tv
.tv_sec
;
245 cnt
+= (int)tv
.tv_usec
;
248 mach_time
= mach_absolute_time();
252 HX(sysctl(kmib
, sizeof(kmib
) / sizeof(kmib
[0]),
253 &addr
, &ii
, NULL
, 0) == -1, addr
);
256 HX(sysctl(hwmib
, sizeof(hwmib
) / sizeof(hwmib
[0]),
257 &idata
, &ii
, NULL
, 0) == -1, idata
);
260 ii
= sizeof(tcpstat
);
261 HX(sysctl(tcpmib
, sizeof(tcpmib
) / sizeof(tcpmib
[0]),
262 &tcpstat
, &ii
, NULL
, 0) == -1, tcpstat
);
264 ii
= sizeof(udpstat
);
265 HX(sysctl(udpmib
, sizeof(udpmib
) / sizeof(udpmib
[0]),
266 &udpstat
, &ii
, NULL
, 0) == -1, udpstat
);
269 HX(sysctl(ipmib
, sizeof(ipmib
) / sizeof(ipmib
[0]),
270 &ipstat
, &ii
, NULL
, 0) == -1, ipstat
);
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
);
282 (void) nanosleep(&ts
, NULL
);
285 HX(sigpending(&sigset
) == -1, sigset
);
286 HX(sigprocmask(SIG_BLOCK
, NULL
, &sigset
) == -1,
289 HF(getentropy
); /* an addr in this library */
290 HF(printf
); /* an addr in libc */
292 HD(p
); /* an addr on stack */
294 HD(p
); /* the addr of errno */
297 struct sockaddr_storage ss
;
298 struct statvfs stvfs
;
305 * Prime-sized mappings encourage fragmentation;
306 * thus exposing some address entropy.
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
},
320 for (m
= 0; m
< sizeof mm
/sizeof(mm
[0]); m
++) {
321 HX(mm
[m
].p
= mmap(NULL
,
323 PROT_READ
|PROT_WRITE
,
324 MAP_PRIVATE
|MAP_ANON
, -1,
326 if (mm
[m
].p
!= MAP_FAILED
) {
329 /* Touch some memory... */
332 (mm
[m
].npg
* pgs
- 1);
334 cnt
+= (int)((long)(mm
[m
].p
)
338 /* Check cnts and times... */
339 mach_time
= mach_absolute_time();
341 cnt
+= (int)mach_time
;
343 HX((e
= getrusage(RUSAGE_SELF
,
346 cnt
+= (int)ru
.ru_utime
.tv_sec
;
347 cnt
+= (int)ru
.ru_utime
.tv_usec
;
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
;
357 HX(stat(".", &st
) == -1, st
);
358 HX(statvfs(".", &stvfs
) == -1, stvfs
);
359 HX(statfs(".", &stfs
) == -1, stfs
);
361 HX(stat("/", &st
) == -1, st
);
362 HX(statvfs("/", &stvfs
) == -1, stvfs
);
363 HX(statfs("/", &stfs
) == -1, stfs
);
365 HX((e
= fstat(0, &st
)) == -1, st
);
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,
372 HX(fstatfs(0, &stfs
) == -1,
374 HX((off
= lseek(0, (off_t
)0,
375 SEEK_CUR
)) < 0, off
);
377 if (S_ISCHR(st
.st_mode
)) {
378 HX(tcgetattr(0, &tios
) == -1,
380 } else if (S_ISSOCK(st
.st_mode
)) {
381 memset(&ss
, 0, sizeof ss
);
384 (void *)&ss
, &ssl
) == -1,
389 HX((e
= getrusage(RUSAGE_CHILDREN
,
392 cnt
+= (int)ru
.ru_utime
.tv_sec
;
393 cnt
+= (int)ru
.ru_utime
.tv_usec
;
396 /* Subsequent hashes absorb previous result */
400 HX((e
= gettimeofday(&tv
, NULL
)) == -1, tv
);
402 cnt
+= (int)tv
.tv_sec
;
403 cnt
+= (int)tv
.tv_usec
;
409 SHA512_Final(results
, &ctx
);
410 memcpy((char *)buf
+ i
, results
, min(sizeof(results
), len
- i
));
411 i
+= min(sizeof(results
), len
- i
);
413 explicit_bzero(&ctx
, sizeof ctx
);
414 explicit_bzero(results
, sizeof results
);
416 return (0); /* satisfied */