8914 loader: gcc 4.4.4 fails to allocate register for do_cpuid()
[unleashed.git] / lib / libcrypto / arc4random / getentropy_osx.c
blob2a5f83f3bb76940c23d6072b355932ecf819cd97
1 /* $OpenBSD: getentropy_osx.c,v 1.11 2016/09/03 15:24:09 bcook Exp $ */
3 /*
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>
33 #include <sys/mman.h>
34 #include <sys/stat.h>
35 #include <sys/time.h>
36 #include <stdlib.h>
37 #include <stdint.h>
38 #include <stdio.h>
39 #include <termios.h>
40 #include <fcntl.h>
41 #include <signal.h>
42 #include <string.h>
43 #include <errno.h>
44 #include <unistd.h>
45 #include <time.h>
46 #include <mach/mach_time.h>
47 #include <mach/mach_host.h>
48 #include <mach/host_info.h>
49 #if TARGET_OS_OSX
50 #include <sys/socketvar.h>
51 #include <sys/vmmeter.h>
52 #endif
53 #include <netinet/in.h>
54 #include <netinet/tcp.h>
55 #if TARGET_OS_OSX
56 #include <netinet/udp.h>
57 #include <netinet/ip_var.h>
58 #include <netinet/tcp_var.h>
59 #include <netinet/udp_var.h>
60 #endif
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
68 #define REPEAT 5
69 #define min(a, b) (((a) < (b)) ? (a) : (b))
71 #define HX(a, b) \
72 do { \
73 if ((a)) \
74 HD(errno); \
75 else \
76 HD(b); \
77 } while (0)
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);
89 int
90 getentropy(void *buf, size_t len)
92 int ret = -1;
94 if (len > 256) {
95 errno = EIO;
96 return (-1);
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);
106 if (ret != -1)
107 return (ret);
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
120 * corefiles.
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
135 raise(SIGKILL);
136 #endif
137 ret = getentropy_fallback(buf, len);
138 if (ret != -1)
139 return (ret);
141 errno = EIO;
142 return (ret);
146 * Basic sanity checking; wish we could do better.
148 static int
149 gotdata(char *buf, size_t len)
151 char any_set = 0;
152 size_t i;
154 for (i = 0; i < len; ++i)
155 any_set |= buf[i];
156 if (any_set == 0)
157 return (-1);
158 return (0);
161 static int
162 getentropy_urandom(void *buf, size_t len)
164 struct stat st;
165 size_t i;
166 int fd, flags;
167 int save_errno = errno;
169 start:
171 flags = O_RDONLY;
172 #ifdef O_NOFOLLOW
173 flags |= O_NOFOLLOW;
174 #endif
175 #ifdef O_CLOEXEC
176 flags |= O_CLOEXEC;
177 #endif
178 fd = open("/dev/urandom", flags, 0);
179 if (fd == -1) {
180 if (errno == EINTR)
181 goto start;
182 goto nodevrandom;
184 #ifndef O_CLOEXEC
185 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
186 #endif
188 /* Lightly verify that the device node looks sane */
189 if (fstat(fd, &st) == -1 || !S_ISCHR(st.st_mode)) {
190 close(fd);
191 goto nodevrandom;
193 for (i = 0; i < len; ) {
194 size_t wanted = len - i;
195 ssize_t ret = read(fd, (char *)buf + i, wanted);
197 if (ret == -1) {
198 if (errno == EAGAIN || errno == EINTR)
199 continue;
200 close(fd);
201 goto nodevrandom;
203 i += ret;
205 close(fd);
206 if (gotdata(buf, len) == 0) {
207 errno = save_errno;
208 return (0); /* satisfied */
210 nodevrandom:
211 errno = EIO;
212 return (-1);
215 #if TARGET_OS_OSX
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 };
219 #endif
220 static int kmib[] = { CTL_KERN, KERN_USRSTACK };
221 static int hwmib[] = { CTL_HW, HW_USERMEM };
223 static int
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;
228 static int cnt;
229 struct timespec ts;
230 struct timeval tv;
231 struct rusage ru;
232 sigset_t sigset;
233 struct stat st;
234 SHA512_CTX ctx;
235 static pid_t lastpid;
236 pid_t pid;
237 size_t i, ii, m;
238 char *p;
239 #if TARGET_OS_OSX
240 struct tcpstat tcpstat;
241 struct udpstat udpstat;
242 struct ipstat ipstat;
243 #endif
244 u_int64_t mach_time;
245 unsigned int idata;
246 void *addr;
248 pid = getpid();
249 if (lastpid == pid) {
250 faster = 1;
251 repeat = 2;
252 } else {
253 faster = 0;
254 lastpid = pid;
255 repeat = REPEAT;
257 for (i = 0; i < len; ) {
258 int j;
259 SHA512_Init(&ctx);
260 for (j = 0; j < repeat; j++) {
261 HX((e = gettimeofday(&tv, NULL)) == -1, tv);
262 if (e != -1) {
263 cnt += (int)tv.tv_sec;
264 cnt += (int)tv.tv_usec;
267 mach_time = mach_absolute_time();
268 HD(mach_time);
270 ii = sizeof(addr);
271 HX(sysctl(kmib, sizeof(kmib) / sizeof(kmib[0]),
272 &addr, &ii, NULL, 0) == -1, addr);
274 ii = sizeof(idata);
275 HX(sysctl(hwmib, sizeof(hwmib) / sizeof(hwmib[0]),
276 &idata, &ii, NULL, 0) == -1, idata);
278 #if TARGET_OS_OSX
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);
287 ii = sizeof(ipstat);
288 HX(sysctl(ipmib, sizeof(ipmib) / sizeof(ipmib[0]),
289 &ipstat, &ii, NULL, 0) == -1, ipstat);
290 #endif
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);
298 if (!faster) {
299 ts.tv_sec = 0;
300 ts.tv_nsec = 1;
301 (void) nanosleep(&ts, NULL);
304 HX(sigpending(&sigset) == -1, sigset);
305 HX(sigprocmask(SIG_BLOCK, NULL, &sigset) == -1,
306 sigset);
308 HF(getentropy); /* an addr in this library */
309 HF(printf); /* an addr in libc */
310 p = (char *)&p;
311 HD(p); /* an addr on stack */
312 p = (char *)&errno;
313 HD(p); /* the addr of errno */
315 if (i == 0) {
316 struct sockaddr_storage ss;
317 struct statvfs stvfs;
318 struct termios tios;
319 struct statfs stfs;
320 socklen_t ssl;
321 off_t off;
324 * Prime-sized mappings encourage fragmentation;
325 * thus exposing some address entropy.
327 struct mm {
328 size_t npg;
329 void *p;
330 } mm[] = {
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,
341 mm[m].npg * pgs,
342 PROT_READ|PROT_WRITE,
343 MAP_PRIVATE|MAP_ANON, -1,
344 (off_t)0), mm[m].p);
345 if (mm[m].p != MAP_FAILED) {
346 size_t mo;
348 /* Touch some memory... */
349 p = mm[m].p;
350 mo = cnt %
351 (mm[m].npg * pgs - 1);
352 p[mo] = 1;
353 cnt += (int)((long)(mm[m].p)
354 / pgs);
357 /* Check cnts and times... */
358 mach_time = mach_absolute_time();
359 HD(mach_time);
360 cnt += (int)mach_time;
362 HX((e = getrusage(RUSAGE_SELF,
363 &ru)) == -1, ru);
364 if (e != -1) {
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);
385 if (e == -1) {
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,
390 stvfs);
391 HX(fstatfs(0, &stfs) == -1,
392 stfs);
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,
398 tios);
399 } else if (S_ISSOCK(st.st_mode)) {
400 memset(&ss, 0, sizeof ss);
401 ssl = sizeof(ss);
402 HX(getpeername(0,
403 (void *)&ss, &ssl) == -1,
404 ss);
408 HX((e = getrusage(RUSAGE_CHILDREN,
409 &ru)) == -1, ru);
410 if (e != -1) {
411 cnt += (int)ru.ru_utime.tv_sec;
412 cnt += (int)ru.ru_utime.tv_usec;
414 } else {
415 /* Subsequent hashes absorb previous result */
416 HD(results);
419 HX((e = gettimeofday(&tv, NULL)) == -1, tv);
420 if (e != -1) {
421 cnt += (int)tv.tv_sec;
422 cnt += (int)tv.tv_usec;
425 HD(cnt);
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) {
435 errno = save_errno;
436 return (0); /* satisfied */
438 errno = EIO;
439 return (-1);