]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - compat/getentropy_linux.c
import unbound 1.5.0
[FreeBSD/FreeBSD.git] / compat / getentropy_linux.c
1 /*      $OpenBSD: getentropy_linux.c,v 1.20 2014/07/12 15:43:49 beck Exp $      */
2
3 /*
4  * Copyright (c) 2014 Theo de Raadt <deraadt@openbsd.org>
5  * Copyright (c) 2014 Bob Beck <beck@obtuse.com>
6  *
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.
10  *
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.
18  */
19 #include "config.h"
20
21 /*
22 #define _POSIX_C_SOURCE 199309L
23 #define _GNU_SOURCE     1
24 */
25 #include <sys/types.h>
26 #include <sys/param.h>
27 #include <sys/ioctl.h>
28 #include <sys/resource.h>
29 #include <sys/syscall.h>
30 #ifdef HAVE_SYS_SYSCTL_H
31 #include <sys/sysctl.h>
32 #endif
33 #include <sys/statvfs.h>
34 #include <sys/socket.h>
35 #include <sys/mount.h>
36 #include <sys/mman.h>
37 #include <sys/stat.h>
38 #include <sys/time.h>
39 #include <stdlib.h>
40 #include <stdint.h>
41 #include <stdio.h>
42 #include <termios.h>
43 #include <fcntl.h>
44 #include <signal.h>
45 #include <string.h>
46 #include <errno.h>
47 #include <unistd.h>
48 #include <time.h>
49 #include <openssl/sha.h>
50
51 #include <linux/random.h>
52 #include <linux/sysctl.h>
53 #ifdef HAVE_GETAUXVAL
54 #include <sys/auxv.h>
55 #endif
56 #include <sys/vfs.h>
57
58 #define REPEAT 5
59 #define min(a, b) (((a) < (b)) ? (a) : (b))
60
61 #define HX(a, b) \
62         do { \
63                 if ((a)) \
64                         HD(errno); \
65                 else \
66                         HD(b); \
67         } while (0)
68
69 #define HR(x, l) (SHA512_Update(&ctx, (char *)(x), (l)))
70 #define HD(x)    (SHA512_Update(&ctx, (char *)&(x), sizeof (x)))
71 #define HF(x)    (SHA512_Update(&ctx, (char *)&(x), sizeof (void*)))
72
73 int     getentropy(void *buf, size_t len);
74
75 #ifdef CAN_REFERENCE_MAIN
76 extern int main(int, char *argv[]);
77 #endif
78 static int gotdata(char *buf, size_t len);
79 static int getentropy_urandom(void *buf, size_t len);
80 #ifdef CTL_MAXNAME
81 static int getentropy_sysctl(void *buf, size_t len);
82 #endif
83 static int getentropy_fallback(void *buf, size_t len);
84
85 int
86 getentropy(void *buf, size_t len)
87 {
88         int ret = -1;
89
90         if (len > 256) {
91                 errno = EIO;
92                 return -1;
93         }
94
95         /*
96          * Try to get entropy with /dev/urandom
97          *
98          * This can fail if the process is inside a chroot or if file
99          * descriptors are exhausted.
100          */
101         ret = getentropy_urandom(buf, len);
102         if (ret != -1)
103                 return (ret);
104
105 #ifdef CTL_MAXNAME
106         /*
107          * Try to use sysctl CTL_KERN, KERN_RANDOM, RANDOM_UUID.
108          * sysctl is a failsafe API, so it guarantees a result.  This
109          * should work inside a chroot, or when file descriptors are
110          * exhuasted.
111          *
112          * However this can fail if the Linux kernel removes support
113          * for sysctl.  Starting in 2007, there have been efforts to
114          * deprecate the sysctl API/ABI, and push callers towards use
115          * of the chroot-unavailable fd-using /proc mechanism --
116          * essentially the same problems as /dev/urandom.
117          *
118          * Numerous setbacks have been encountered in their deprecation
119          * schedule, so as of June 2014 the kernel ABI still exists on
120          * most Linux architectures. The sysctl() stub in libc is missing
121          * on some systems.  There are also reports that some kernels
122          * spew messages to the console.
123          */
124         ret = getentropy_sysctl(buf, len);
125         if (ret != -1)
126                 return (ret);
127 #endif /* CTL_MAXNAME */
128
129         /*
130          * Entropy collection via /dev/urandom and sysctl have failed.
131          *
132          * No other API exists for collecting entropy.  See the large
133          * comment block above.
134          *
135          * We have very few options:
136          *     - Even syslog_r is unsafe to call at this low level, so
137          *       there is no way to alert the user or program.
138          *     - Cannot call abort() because some systems have unsafe
139          *       corefiles.
140          *     - Could raise(SIGKILL) resulting in silent program termination.
141          *     - Return EIO, to hint that arc4random's stir function
142          *       should raise(SIGKILL)
143          *     - Do the best under the circumstances....
144          *
145          * This code path exists to bring light to the issue that Linux
146          * does not provide a failsafe API for entropy collection.
147          *
148          * We hope this demonstrates that Linux should either retain their
149          * sysctl ABI, or consider providing a new failsafe API which
150          * works in a chroot or when file descriptors are exhausted.
151          */
152 #undef FAIL_INSTEAD_OF_TRYING_FALLBACK
153 #ifdef FAIL_INSTEAD_OF_TRYING_FALLBACK
154         raise(SIGKILL);
155 #endif
156         ret = getentropy_fallback(buf, len);
157         if (ret != -1)
158                 return (ret);
159
160         errno = EIO;
161         return (ret);
162 }
163
164 /*
165  * Basic sanity checking; wish we could do better.
166  */
167 static int
168 gotdata(char *buf, size_t len)
169 {
170         char    any_set = 0;
171         size_t  i;
172
173         for (i = 0; i < len; ++i)
174                 any_set |= buf[i];
175         if (any_set == 0)
176                 return -1;
177         return 0;
178 }
179
180 static int
181 getentropy_urandom(void *buf, size_t len)
182 {
183         struct stat st;
184         size_t i;
185         int fd, cnt, flags;
186         int save_errno = errno;
187
188 start:
189
190         flags = O_RDONLY;
191 #ifdef O_NOFOLLOW
192         flags |= O_NOFOLLOW;
193 #endif
194 #ifdef O_CLOEXEC
195         flags |= O_CLOEXEC;
196 #endif
197         fd = open("/dev/urandom", flags, 0);
198         if (fd == -1) {
199                 if (errno == EINTR)
200                         goto start;
201                 goto nodevrandom;
202         }
203 #ifndef O_CLOEXEC
204         fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
205 #endif
206
207         /* Lightly verify that the device node looks sane */
208         if (fstat(fd, &st) == -1 || !S_ISCHR(st.st_mode)) {
209                 close(fd);
210                 goto nodevrandom;
211         }
212         if (ioctl(fd, RNDGETENTCNT, &cnt) == -1) {
213                 close(fd);
214                 goto nodevrandom;
215         }
216         for (i = 0; i < len; ) {
217                 size_t wanted = len - i;
218                 ssize_t ret = read(fd, (char*)buf + i, wanted);
219
220                 if (ret == -1) {
221                         if (errno == EAGAIN || errno == EINTR)
222                                 continue;
223                         close(fd);
224                         goto nodevrandom;
225                 }
226                 i += ret;
227         }
228         close(fd);
229         if (gotdata(buf, len) == 0) {
230                 errno = save_errno;
231                 return 0;               /* satisfied */
232         }
233 nodevrandom:
234         errno = EIO;
235         return -1;
236 }
237
238 #ifdef CTL_MAXNAME
239 static int
240 getentropy_sysctl(void *buf, size_t len)
241 {
242         static int mib[] = { CTL_KERN, KERN_RANDOM, RANDOM_UUID };
243         size_t i;
244         int save_errno = errno;
245
246         for (i = 0; i < len; ) {
247                 size_t chunk = min(len - i, 16);
248
249                 /* SYS__sysctl because some systems already removed sysctl() */
250                 struct __sysctl_args args = {
251                         .name = mib,
252                         .nlen = 3,
253                         .oldval = buf + i,
254                         .oldlenp = &chunk,
255                 };
256                 if (syscall(SYS__sysctl, &args) != 0)
257                         goto sysctlfailed;
258                 i += chunk;
259         }
260         if (gotdata(buf, len) == 0) {
261                 errno = save_errno;
262                 return (0);                     /* satisfied */
263         }
264 sysctlfailed:
265         errno = EIO;
266         return -1;
267 }
268 #endif /* CTL_MAXNAME */
269
270 static int cl[] = {
271         CLOCK_REALTIME,
272 #ifdef CLOCK_MONOTONIC
273         CLOCK_MONOTONIC,
274 #endif
275 #ifdef CLOCK_MONOTONIC_RAW
276         CLOCK_MONOTONIC_RAW,
277 #endif
278 #ifdef CLOCK_TAI
279         CLOCK_TAI,
280 #endif
281 #ifdef CLOCK_VIRTUAL
282         CLOCK_VIRTUAL,
283 #endif
284 #ifdef CLOCK_UPTIME
285         CLOCK_UPTIME,
286 #endif
287 #ifdef CLOCK_PROCESS_CPUTIME_ID
288         CLOCK_PROCESS_CPUTIME_ID,
289 #endif
290 #ifdef CLOCK_THREAD_CPUTIME_ID
291         CLOCK_THREAD_CPUTIME_ID,
292 #endif
293 };
294
295 static int
296 getentropy_fallback(void *buf, size_t len)
297 {
298         uint8_t results[SHA512_DIGEST_LENGTH];
299         int save_errno = errno, e, pgs = getpagesize(), faster = 0, repeat;
300         static int cnt;
301         struct timespec ts;
302         struct timeval tv;
303         struct rusage ru;
304         sigset_t sigset;
305         struct stat st;
306         SHA512_CTX ctx;
307         static pid_t lastpid;
308         pid_t pid;
309         size_t i, ii, m;
310         char *p;
311
312         pid = getpid();
313         if (lastpid == pid) {
314                 faster = 1;
315                 repeat = 2;
316         } else {
317                 faster = 0;
318                 lastpid = pid;
319                 repeat = REPEAT;
320         }
321         for (i = 0; i < len; ) {
322                 int j;
323                 SHA512_Init(&ctx);
324                 for (j = 0; j < repeat; j++) {
325                         HX((e = gettimeofday(&tv, NULL)) == -1, tv);
326                         if (e != -1) {
327                                 cnt += (int)tv.tv_sec;
328                                 cnt += (int)tv.tv_usec;
329                         }
330
331                         for (ii = 0; ii < sizeof(cl)/sizeof(cl[0]); ii++)
332                                 HX(clock_gettime(cl[ii], &ts) == -1, ts);
333
334                         HX((pid = getpid()) == -1, pid);
335                         HX((pid = getsid(pid)) == -1, pid);
336                         HX((pid = getppid()) == -1, pid);
337                         HX((pid = getpgid(0)) == -1, pid);
338                         HX((e = getpriority(0, 0)) == -1, e);
339
340                         if (!faster) {
341                                 ts.tv_sec = 0;
342                                 ts.tv_nsec = 1;
343                                 (void) nanosleep(&ts, NULL);
344                         }
345
346                         HX(sigpending(&sigset) == -1, sigset);
347                         HX(sigprocmask(SIG_BLOCK, NULL, &sigset) == -1,
348                             sigset);
349
350 #ifdef CAN_REFERENCE_MAIN
351                         HF(main);               /* an addr in program */
352 #endif
353                         HF(getentropy); /* an addr in this library */
354                         HF(printf);             /* an addr in libc */
355                         p = (char *)&p;
356                         HD(p);          /* an addr on stack */
357                         p = (char *)&errno;
358                         HD(p);          /* the addr of errno */
359
360                         if (i == 0) {
361                                 struct sockaddr_storage ss;
362                                 struct statvfs stvfs;
363                                 struct termios tios;
364                                 struct statfs stfs;
365                                 socklen_t ssl;
366                                 off_t off;
367
368                                 /*
369                                  * Prime-sized mappings encourage fragmentation;
370                                  * thus exposing some address entropy.
371                                  */
372                                 struct mm {
373                                         size_t  npg;
374                                         void    *p;
375                                 } mm[] =         {
376                                         { 17, MAP_FAILED }, { 3, MAP_FAILED },
377                                         { 11, MAP_FAILED }, { 2, MAP_FAILED },
378                                         { 5, MAP_FAILED }, { 3, MAP_FAILED },
379                                         { 7, MAP_FAILED }, { 1, MAP_FAILED },
380                                         { 57, MAP_FAILED }, { 3, MAP_FAILED },
381                                         { 131, MAP_FAILED }, { 1, MAP_FAILED },
382                                 };
383
384                                 for (m = 0; m < sizeof mm/sizeof(mm[0]); m++) {
385                                         HX(mm[m].p = mmap(NULL,
386                                             mm[m].npg * pgs,
387                                             PROT_READ|PROT_WRITE,
388                                             MAP_PRIVATE|MAP_ANON, -1,
389                                             (off_t)0), mm[m].p);
390                                         if (mm[m].p != MAP_FAILED) {
391                                                 size_t mo;
392
393                                                 /* Touch some memory... */
394                                                 p = mm[m].p;
395                                                 mo = cnt %
396                                                     (mm[m].npg * pgs - 1);
397                                                 p[mo] = 1;
398                                                 cnt += (int)((long)(mm[m].p)
399                                                     / pgs);
400                                         }
401
402                                         /* Check cnts and times... */
403                                         for (ii = 0; ii < sizeof(cl)/sizeof(cl[0]);
404                                             ii++) {
405                                                 HX((e = clock_gettime(cl[ii],
406                                                     &ts)) == -1, ts);
407                                                 if (e != -1)
408                                                         cnt += (int)ts.tv_nsec;
409                                         }
410
411                                         HX((e = getrusage(RUSAGE_SELF,
412                                             &ru)) == -1, ru);
413                                         if (e != -1) {
414                                                 cnt += (int)ru.ru_utime.tv_sec;
415                                                 cnt += (int)ru.ru_utime.tv_usec;
416                                         }
417                                 }
418
419                                 for (m = 0; m < sizeof mm/sizeof(mm[0]); m++) {
420                                         if (mm[m].p != MAP_FAILED)
421                                                 munmap(mm[m].p, mm[m].npg * pgs);
422                                         mm[m].p = MAP_FAILED;
423                                 }
424
425                                 HX(stat(".", &st) == -1, st);
426                                 HX(statvfs(".", &stvfs) == -1, stvfs);
427                                 HX(statfs(".", &stfs) == -1, stfs);
428
429                                 HX(stat("/", &st) == -1, st);
430                                 HX(statvfs("/", &stvfs) == -1, stvfs);
431                                 HX(statfs("/", &stfs) == -1, stfs);
432
433                                 HX((e = fstat(0, &st)) == -1, st);
434                                 if (e == -1) {
435                                         if (S_ISREG(st.st_mode) ||
436                                             S_ISFIFO(st.st_mode) ||
437                                             S_ISSOCK(st.st_mode)) {
438                                                 HX(fstatvfs(0, &stvfs) == -1,
439                                                     stvfs);
440                                                 HX(fstatfs(0, &stfs) == -1,
441                                                     stfs);
442                                                 HX((off = lseek(0, (off_t)0,
443                                                     SEEK_CUR)) < 0, off);
444                                         }
445                                         if (S_ISCHR(st.st_mode)) {
446                                                 HX(tcgetattr(0, &tios) == -1,
447                                                     tios);
448                                         } else if (S_ISSOCK(st.st_mode)) {
449                                                 memset(&ss, 0, sizeof ss);
450                                                 ssl = sizeof(ss);
451                                                 HX(getpeername(0,
452                                                     (void *)&ss, &ssl) == -1,
453                                                     ss);
454                                         }
455                                 }
456
457                                 HX((e = getrusage(RUSAGE_CHILDREN,
458                                     &ru)) == -1, ru);
459                                 if (e != -1) {
460                                         cnt += (int)ru.ru_utime.tv_sec;
461                                         cnt += (int)ru.ru_utime.tv_usec;
462                                 }
463                         } else {
464                                 /* Subsequent hashes absorb previous result */
465                                 HD(results);
466                         }
467
468                         HX((e = gettimeofday(&tv, NULL)) == -1, tv);
469                         if (e != -1) {
470                                 cnt += (int)tv.tv_sec;
471                                 cnt += (int)tv.tv_usec;
472                         }
473
474                         HD(cnt);
475                 }
476 #ifdef AT_RANDOM
477                 /* Not as random as you think but we take what we are given */
478                 p = (char *) getauxval(AT_RANDOM);
479                 if (p)
480                         HR(p, 16);
481 #endif
482 #ifdef AT_SYSINFO_EHDR
483                 p = (char *) getauxval(AT_SYSINFO_EHDR);
484                 if (p)
485                         HR(p, pgs);
486 #endif
487 #ifdef AT_BASE
488                 p = (char *) getauxval(AT_BASE);
489                 if (p)
490                         HD(p);
491 #endif
492
493                 SHA512_Final(results, &ctx);
494                 memcpy((char*)buf + i, results, min(sizeof(results), len - i));
495                 i += min(sizeof(results), len - i);
496         }
497         memset(results, 0, sizeof results);
498         if (gotdata(buf, len) == 0) {
499                 errno = save_errno;
500                 return 0;               /* satisfied */
501         }
502         errno = EIO;
503         return -1;
504 }