Merge commit 'dfc115332c94a2f62058ac7f2bce7631fbd20b3d'
[unleashed/tickless.git] / lib / libcrypto / arc4random / getentropy_solaris.c
blobf0fcdcf28b20fa87d0e94e552b9ea5dadc5e0622
1 /* $OpenBSD: getentropy_solaris.c,v 1.12 2016/08/07 03:27:21 tb 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 <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/statvfs.h>
29 #include <sys/socket.h>
30 #include <sys/mount.h>
31 #include <sys/mman.h>
32 #include <sys/stat.h>
33 #include <sys/time.h>
34 #include <stdlib.h>
35 #include <stdint.h>
36 #include <stdio.h>
37 #include <link.h>
38 #include <termios.h>
39 #include <fcntl.h>
40 #include <signal.h>
41 #include <string.h>
42 #include <errno.h>
43 #include <unistd.h>
44 #include <time.h>
45 #include <sys/sha2.h>
46 #define SHA512_Init SHA512Init
47 #define SHA512_Update SHA512Update
48 #define SHA512_Final SHA512Final
50 #include <sys/vfs.h>
51 #include <sys/statfs.h>
52 #include <sys/loadavg.h>
54 #define REPEAT 5
55 #define min(a, b) (((a) < (b)) ? (a) : (b))
57 #define HX(a, b) \
58 do { \
59 if ((a)) \
60 HD(errno); \
61 else \
62 HD(b); \
63 } while (0)
65 #define HR(x, l) (SHA512_Update(&ctx, (char *)(x), (l)))
66 #define HD(x) (SHA512_Update(&ctx, (char *)&(x), sizeof (x)))
67 #define HF(x) (SHA512_Update(&ctx, (char *)&(x), sizeof (void*)))
69 int getentropy(void *buf, size_t len);
71 static int gotdata(char *buf, size_t len);
72 static int getentropy_urandom(void *buf, size_t len, const char *path,
73 int devfscheck);
74 static int getentropy_fallback(void *buf, size_t len);
75 static int getentropy_phdr(struct dl_phdr_info *info, size_t size, void *data);
77 int
78 getentropy(void *buf, size_t len)
80 int ret = -1;
82 if (len > 256) {
83 errno = EIO;
84 return (-1);
88 * Try to get entropy with /dev/urandom
90 * Solaris provides /dev/urandom as a symbolic link to
91 * /devices/pseudo/random@0:urandom which is provided by
92 * a devfs filesystem. Best practice is to use O_NOFOLLOW,
93 * so we must try the unpublished name directly.
95 * This can fail if the process is inside a chroot which lacks
96 * the devfs mount, or if file descriptors are exhausted.
98 ret = getentropy_urandom(buf, len,
99 "/devices/pseudo/random@0:urandom", 1);
100 if (ret != -1)
101 return (ret);
104 * Unfortunately, chroot spaces on Solaris are sometimes setup
105 * with direct device node of the well-known /dev/urandom name
106 * (perhaps to avoid dragging all of devfs into the space).
108 * This can fail if the process is inside a chroot or if file
109 * descriptors are exhausted.
111 ret = getentropy_urandom(buf, len, "/dev/urandom", 0);
112 if (ret != -1)
113 return (ret);
116 * Entropy collection via /dev/urandom has failed.
118 * No other API exists for collecting entropy, and we have
119 * no failsafe way to get it on Solaris that is not sensitive
120 * to resource exhaustion.
122 * We have very few options:
123 * - Even syslog_r is unsafe to call at this low level, so
124 * there is no way to alert the user or program.
125 * - Cannot call abort() because some systems have unsafe
126 * corefiles.
127 * - Could raise(SIGKILL) resulting in silent program termination.
128 * - Return EIO, to hint that arc4random's stir function
129 * should raise(SIGKILL)
130 * - Do the best under the circumstances....
132 * This code path exists to bring light to the issue that Solaris
133 * does not provide a failsafe API for entropy collection.
135 * We hope this demonstrates that Solaris should consider
136 * providing a new failsafe API which works in a chroot or
137 * when file descriptors are exhausted.
139 #undef FAIL_INSTEAD_OF_TRYING_FALLBACK
140 #ifdef FAIL_INSTEAD_OF_TRYING_FALLBACK
141 raise(SIGKILL);
142 #endif
143 ret = getentropy_fallback(buf, len);
144 if (ret != -1)
145 return (ret);
147 errno = EIO;
148 return (ret);
152 * Basic sanity checking; wish we could do better.
154 static int
155 gotdata(char *buf, size_t len)
157 char any_set = 0;
158 size_t i;
160 for (i = 0; i < len; ++i)
161 any_set |= buf[i];
162 if (any_set == 0)
163 return (-1);
164 return (0);
167 static int
168 getentropy_urandom(void *buf, size_t len, const char *path, int devfscheck)
170 struct stat st;
171 size_t i;
172 int fd, flags;
173 int save_errno = errno;
175 start:
177 flags = O_RDONLY;
178 #ifdef O_NOFOLLOW
179 flags |= O_NOFOLLOW;
180 #endif
181 #ifdef O_CLOEXEC
182 flags |= O_CLOEXEC;
183 #endif
184 fd = open(path, flags, 0);
185 if (fd == -1) {
186 if (errno == EINTR)
187 goto start;
188 goto nodevrandom;
190 #ifndef O_CLOEXEC
191 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
192 #endif
194 /* Lightly verify that the device node looks sane */
195 if (fstat(fd, &st) == -1 || !S_ISCHR(st.st_mode) ||
196 (devfscheck && (strcmp(st.st_fstype, "devfs") != 0))) {
197 close(fd);
198 goto nodevrandom;
200 for (i = 0; i < len; ) {
201 size_t wanted = len - i;
202 ssize_t ret = read(fd, (char *)buf + i, wanted);
204 if (ret == -1) {
205 if (errno == EAGAIN || errno == EINTR)
206 continue;
207 close(fd);
208 goto nodevrandom;
210 i += ret;
212 close(fd);
213 if (gotdata(buf, len) == 0) {
214 errno = save_errno;
215 return (0); /* satisfied */
217 nodevrandom:
218 errno = EIO;
219 return (-1);
222 static const int cl[] = {
223 CLOCK_REALTIME,
224 #ifdef CLOCK_MONOTONIC
225 CLOCK_MONOTONIC,
226 #endif
227 #ifdef CLOCK_MONOTONIC_RAW
228 CLOCK_MONOTONIC_RAW,
229 #endif
230 #ifdef CLOCK_TAI
231 CLOCK_TAI,
232 #endif
233 #ifdef CLOCK_VIRTUAL
234 CLOCK_VIRTUAL,
235 #endif
236 #ifdef CLOCK_UPTIME
237 CLOCK_UPTIME,
238 #endif
239 #ifdef CLOCK_PROCESS_CPUTIME_ID
240 CLOCK_PROCESS_CPUTIME_ID,
241 #endif
242 #ifdef CLOCK_THREAD_CPUTIME_ID
243 CLOCK_THREAD_CPUTIME_ID,
244 #endif
247 static int
248 getentropy_phdr(struct dl_phdr_info *info, size_t size, void *data)
250 SHA512_CTX *ctx = data;
252 SHA512_Update(ctx, &info->dlpi_addr, sizeof (info->dlpi_addr));
253 return (0);
256 static int
257 getentropy_fallback(void *buf, size_t len)
259 uint8_t results[SHA512_DIGEST_LENGTH];
260 int save_errno = errno, e, pgs = getpagesize(), faster = 0, repeat;
261 static int cnt;
262 struct timespec ts;
263 struct timeval tv;
264 double loadavg[3];
265 struct rusage ru;
266 sigset_t sigset;
267 struct stat st;
268 SHA512_CTX ctx;
269 static pid_t lastpid;
270 pid_t pid;
271 size_t i, ii, m;
272 char *p;
274 pid = getpid();
275 if (lastpid == pid) {
276 faster = 1;
277 repeat = 2;
278 } else {
279 faster = 0;
280 lastpid = pid;
281 repeat = REPEAT;
283 for (i = 0; i < len; ) {
284 int j;
285 SHA512_Init(&ctx);
286 for (j = 0; j < repeat; j++) {
287 HX((e = gettimeofday(&tv, NULL)) == -1, tv);
288 if (e != -1) {
289 cnt += (int)tv.tv_sec;
290 cnt += (int)tv.tv_usec;
293 dl_iterate_phdr(getentropy_phdr, &ctx);
295 for (ii = 0; ii < sizeof(cl)/sizeof(cl[0]); ii++)
296 HX(clock_gettime(cl[ii], &ts) == -1, ts);
298 HX((pid = getpid()) == -1, pid);
299 HX((pid = getsid(pid)) == -1, pid);
300 HX((pid = getppid()) == -1, pid);
301 HX((pid = getpgid(0)) == -1, pid);
302 HX((e = getpriority(0, 0)) == -1, e);
303 HX((getloadavg(loadavg, 3) == -1), loadavg);
305 if (!faster) {
306 ts.tv_sec = 0;
307 ts.tv_nsec = 1;
308 (void) nanosleep(&ts, NULL);
311 HX(sigpending(&sigset) == -1, sigset);
312 HX(sigprocmask(SIG_BLOCK, NULL, &sigset) == -1,
313 sigset);
315 HF(getentropy); /* an addr in this library */
316 HF(printf); /* an addr in libc */
317 p = (char *)&p;
318 HD(p); /* an addr on stack */
319 p = (char *)&errno;
320 HD(p); /* the addr of errno */
322 if (i == 0) {
323 struct sockaddr_storage ss;
324 struct statvfs stvfs;
325 struct termios tios;
326 socklen_t ssl;
327 off_t off;
330 * Prime-sized mappings encourage fragmentation;
331 * thus exposing some address entropy.
333 struct mm {
334 size_t npg;
335 void *p;
336 } mm[] = {
337 { 17, MAP_FAILED }, { 3, MAP_FAILED },
338 { 11, MAP_FAILED }, { 2, MAP_FAILED },
339 { 5, MAP_FAILED }, { 3, MAP_FAILED },
340 { 7, MAP_FAILED }, { 1, MAP_FAILED },
341 { 57, MAP_FAILED }, { 3, MAP_FAILED },
342 { 131, MAP_FAILED }, { 1, MAP_FAILED },
345 for (m = 0; m < sizeof mm/sizeof(mm[0]); m++) {
346 HX(mm[m].p = mmap(NULL,
347 mm[m].npg * pgs,
348 PROT_READ|PROT_WRITE,
349 MAP_PRIVATE|MAP_ANON, -1,
350 (off_t)0), mm[m].p);
351 if (mm[m].p != MAP_FAILED) {
352 size_t mo;
354 /* Touch some memory... */
355 p = mm[m].p;
356 mo = cnt %
357 (mm[m].npg * pgs - 1);
358 p[mo] = 1;
359 cnt += (int)((long)(mm[m].p)
360 / pgs);
363 /* Check cnts and times... */
364 for (ii = 0; ii < sizeof(cl)/sizeof(cl[0]);
365 ii++) {
366 HX((e = clock_gettime(cl[ii],
367 &ts)) == -1, ts);
368 if (e != -1)
369 cnt += (int)ts.tv_nsec;
372 HX((e = getrusage(RUSAGE_SELF,
373 &ru)) == -1, ru);
374 if (e != -1) {
375 cnt += (int)ru.ru_utime.tv_sec;
376 cnt += (int)ru.ru_utime.tv_usec;
380 for (m = 0; m < sizeof mm/sizeof(mm[0]); m++) {
381 if (mm[m].p != MAP_FAILED)
382 munmap(mm[m].p, mm[m].npg * pgs);
383 mm[m].p = MAP_FAILED;
386 HX(stat(".", &st) == -1, st);
387 HX(statvfs(".", &stvfs) == -1, stvfs);
389 HX(stat("/", &st) == -1, st);
390 HX(statvfs("/", &stvfs) == -1, stvfs);
392 HX((e = fstat(0, &st)) == -1, st);
393 if (e == -1) {
394 if (S_ISREG(st.st_mode) ||
395 S_ISFIFO(st.st_mode) ||
396 S_ISSOCK(st.st_mode)) {
397 HX(fstatvfs(0, &stvfs) == -1,
398 stvfs);
399 HX((off = lseek(0, (off_t)0,
400 SEEK_CUR)) < 0, off);
402 if (S_ISCHR(st.st_mode)) {
403 HX(tcgetattr(0, &tios) == -1,
404 tios);
405 } else if (S_ISSOCK(st.st_mode)) {
406 memset(&ss, 0, sizeof ss);
407 ssl = sizeof(ss);
408 HX(getpeername(0,
409 (void *)&ss, &ssl) == -1,
410 ss);
414 HX((e = getrusage(RUSAGE_CHILDREN,
415 &ru)) == -1, ru);
416 if (e != -1) {
417 cnt += (int)ru.ru_utime.tv_sec;
418 cnt += (int)ru.ru_utime.tv_usec;
420 } else {
421 /* Subsequent hashes absorb previous result */
422 HD(results);
425 HX((e = gettimeofday(&tv, NULL)) == -1, tv);
426 if (e != -1) {
427 cnt += (int)tv.tv_sec;
428 cnt += (int)tv.tv_usec;
431 HD(cnt);
433 SHA512_Final(results, &ctx);
434 memcpy((char *)buf + i, results, min(sizeof(results), len - i));
435 i += min(sizeof(results), len - i);
437 explicit_bzero(&ctx, sizeof ctx);
438 explicit_bzero(results, sizeof results);
439 if (gotdata(buf, len) == 0) {
440 errno = save_errno;
441 return (0); /* satisfied */
443 errno = EIO;
444 return (-1);