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