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@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 * Emulation of getentropy(2) as documented at: 20 * http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man2/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 #include <openssl/sha.h> 51 52 #include <linux/types.h> 53 #include <linux/random.h> 54 #ifdef HAVE_GETAUXVAL 55 #include <sys/auxv.h> 56 #endif 57 #include <sys/vfs.h> 58 59 #define REPEAT 5 60 #define min(a, b) (((a) < (b)) ? (a) : (b)) 61 62 #define HX(a, b) \ 63 do { \ 64 if ((a)) \ 65 HD(errno); \ 66 else \ 67 HD(b); \ 68 } while (0) 69 70 #define HR(x, l) (SHA512_Update(&ctx, (char *)(x), (l))) 71 #define HD(x) (SHA512_Update(&ctx, (char *)&(x), sizeof (x))) 72 #define HF(x) (SHA512_Update(&ctx, (char *)&(x), sizeof (void*))) 73 74 int getentropy(void *buf, size_t len); 75 76 static int gotdata(char *buf, size_t len); 77 #ifdef SYS_getrandom 78 static int getentropy_getrandom(void *buf, size_t len); 79 #endif 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 static int getentropy_fallback(void *buf, size_t len); 85 static int getentropy_phdr(struct dl_phdr_info *info, size_t size, void *data); 86 87 int 88 getentropy(void *buf, size_t len) 89 { 90 int ret = -1; 91 92 if (len > 256) { 93 errno = EIO; 94 return (-1); 95 } 96 97 #ifdef SYS_getrandom 98 /* 99 * Try descriptor-less getrandom() 100 */ 101 ret = getentropy_getrandom(buf, len); 102 if (ret != -1) 103 return (ret); 104 if (errno != ENOSYS) 105 return (-1); 106 #endif 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 ret = getentropy_fallback(buf, len); 170 if (ret != -1) 171 return (ret); 172 173 errno = EIO; 174 return (ret); 175 } 176 177 /* 178 * Basic sanity checking; wish we could do better. 179 */ 180 static int 181 gotdata(char *buf, size_t len) 182 { 183 char any_set = 0; 184 size_t i; 185 186 for (i = 0; i < len; ++i) 187 any_set |= buf[i]; 188 if (any_set == 0) 189 return (-1); 190 return (0); 191 } 192 193 #ifdef SYS_getrandom 194 static int 195 getentropy_getrandom(void *buf, size_t len) 196 { 197 int pre_errno = errno; 198 int ret; 199 if (len > 256) 200 return (-1); 201 do { 202 ret = syscall(SYS_getrandom, buf, len, 0); 203 } while (ret == -1 && errno == EINTR); 204 205 if (ret != len) 206 return (-1); 207 errno = pre_errno; 208 return (0); 209 } 210 #endif 211 212 static int 213 getentropy_urandom(void *buf, size_t len) 214 { 215 struct stat st; 216 size_t i; 217 int fd, cnt, flags; 218 int save_errno = errno; 219 220 start: 221 222 flags = O_RDONLY; 223 #ifdef O_NOFOLLOW 224 flags |= O_NOFOLLOW; 225 #endif 226 #ifdef O_CLOEXEC 227 flags |= O_CLOEXEC; 228 #endif 229 fd = open("/dev/urandom", flags, 0); 230 if (fd == -1) { 231 if (errno == EINTR) 232 goto start; 233 goto nodevrandom; 234 } 235 #ifndef O_CLOEXEC 236 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC); 237 #endif 238 239 /* Lightly verify that the device node looks sane */ 240 if (fstat(fd, &st) == -1 || !S_ISCHR(st.st_mode)) { 241 close(fd); 242 goto nodevrandom; 243 } 244 if (ioctl(fd, RNDGETENTCNT, &cnt) == -1) { 245 close(fd); 246 goto nodevrandom; 247 } 248 for (i = 0; i < len; ) { 249 size_t wanted = len - i; 250 ssize_t ret = read(fd, (char *)buf + i, wanted); 251 252 if (ret == -1) { 253 if (errno == EAGAIN || errno == EINTR) 254 continue; 255 close(fd); 256 goto nodevrandom; 257 } 258 i += ret; 259 } 260 close(fd); 261 if (gotdata(buf, len) == 0) { 262 errno = save_errno; 263 return (0); /* satisfied */ 264 } 265 nodevrandom: 266 errno = EIO; 267 return (-1); 268 } 269 270 #ifdef SYS__sysctl 271 static int 272 getentropy_sysctl(void *buf, size_t len) 273 { 274 static int mib[] = { CTL_KERN, KERN_RANDOM, RANDOM_UUID }; 275 size_t i; 276 int save_errno = errno; 277 278 for (i = 0; i < len; ) { 279 size_t chunk = min(len - i, 16); 280 281 /* SYS__sysctl because some systems already removed sysctl() */ 282 struct __sysctl_args args = { 283 .name = mib, 284 .nlen = 3, 285 .oldval = (char *)buf + i, 286 .oldlenp = &chunk, 287 }; 288 if (syscall(SYS__sysctl, &args) != 0) 289 goto sysctlfailed; 290 i += chunk; 291 } 292 if (gotdata(buf, len) == 0) { 293 errno = save_errno; 294 return (0); /* satisfied */ 295 } 296 sysctlfailed: 297 errno = EIO; 298 return (-1); 299 } 300 #endif /* SYS__sysctl */ 301 302 static const int cl[] = { 303 CLOCK_REALTIME, 304 #ifdef CLOCK_MONOTONIC 305 CLOCK_MONOTONIC, 306 #endif 307 #ifdef CLOCK_MONOTONIC_RAW 308 CLOCK_MONOTONIC_RAW, 309 #endif 310 #ifdef CLOCK_TAI 311 CLOCK_TAI, 312 #endif 313 #ifdef CLOCK_VIRTUAL 314 CLOCK_VIRTUAL, 315 #endif 316 #ifdef CLOCK_UPTIME 317 CLOCK_UPTIME, 318 #endif 319 #ifdef CLOCK_PROCESS_CPUTIME_ID 320 CLOCK_PROCESS_CPUTIME_ID, 321 #endif 322 #ifdef CLOCK_THREAD_CPUTIME_ID 323 CLOCK_THREAD_CPUTIME_ID, 324 #endif 325 }; 326 327 static int 328 getentropy_phdr(struct dl_phdr_info *info, size_t size, void *data) 329 { 330 SHA512_CTX *ctx = data; 331 332 SHA512_Update(ctx, &info->dlpi_addr, sizeof (info->dlpi_addr)); 333 return (0); 334 } 335 336 static int 337 getentropy_fallback(void *buf, size_t len) 338 { 339 uint8_t results[SHA512_DIGEST_LENGTH]; 340 int save_errno = errno, e, pgs = getpagesize(), faster = 0, repeat; 341 static int cnt; 342 struct timespec ts; 343 struct timeval tv; 344 struct rusage ru; 345 sigset_t sigset; 346 struct stat st; 347 SHA512_CTX ctx; 348 static pid_t lastpid; 349 pid_t pid; 350 size_t i, ii, m; 351 char *p; 352 353 pid = getpid(); 354 if (lastpid == pid) { 355 faster = 1; 356 repeat = 2; 357 } else { 358 faster = 0; 359 lastpid = pid; 360 repeat = REPEAT; 361 } 362 for (i = 0; i < len; ) { 363 int j; 364 SHA512_Init(&ctx); 365 for (j = 0; j < repeat; j++) { 366 HX((e = gettimeofday(&tv, NULL)) == -1, tv); 367 if (e != -1) { 368 cnt += (int)tv.tv_sec; 369 cnt += (int)tv.tv_usec; 370 } 371 372 dl_iterate_phdr(getentropy_phdr, &ctx); 373 374 for (ii = 0; ii < sizeof(cl)/sizeof(cl[0]); ii++) 375 HX(clock_gettime(cl[ii], &ts) == -1, ts); 376 377 HX((pid = getpid()) == -1, pid); 378 HX((pid = getsid(pid)) == -1, pid); 379 HX((pid = getppid()) == -1, pid); 380 HX((pid = getpgid(0)) == -1, pid); 381 HX((e = getpriority(0, 0)) == -1, e); 382 383 if (!faster) { 384 ts.tv_sec = 0; 385 ts.tv_nsec = 1; 386 (void) nanosleep(&ts, NULL); 387 } 388 389 HX(sigpending(&sigset) == -1, sigset); 390 HX(sigprocmask(SIG_BLOCK, NULL, &sigset) == -1, 391 sigset); 392 393 HF(getentropy); /* an addr in this library */ 394 HF(printf); /* an addr in libc */ 395 p = (char *)&p; 396 HD(p); /* an addr on stack */ 397 p = (char *)&errno; 398 HD(p); /* the addr of errno */ 399 400 if (i == 0) { 401 struct sockaddr_storage ss; 402 struct statvfs stvfs; 403 struct termios tios; 404 struct statfs stfs; 405 socklen_t ssl; 406 off_t off; 407 408 /* 409 * Prime-sized mappings encourage fragmentation; 410 * thus exposing some address entropy. 411 */ 412 struct mm { 413 size_t npg; 414 void *p; 415 } mm[] = { 416 { 17, MAP_FAILED }, { 3, MAP_FAILED }, 417 { 11, MAP_FAILED }, { 2, MAP_FAILED }, 418 { 5, MAP_FAILED }, { 3, MAP_FAILED }, 419 { 7, MAP_FAILED }, { 1, MAP_FAILED }, 420 { 57, MAP_FAILED }, { 3, MAP_FAILED }, 421 { 131, MAP_FAILED }, { 1, MAP_FAILED }, 422 }; 423 424 for (m = 0; m < sizeof mm/sizeof(mm[0]); m++) { 425 HX(mm[m].p = mmap(NULL, 426 mm[m].npg * pgs, 427 PROT_READ|PROT_WRITE, 428 MAP_PRIVATE|MAP_ANON, -1, 429 (off_t)0), mm[m].p); 430 if (mm[m].p != MAP_FAILED) { 431 size_t mo; 432 433 /* Touch some memory... */ 434 p = mm[m].p; 435 mo = cnt % 436 (mm[m].npg * pgs - 1); 437 p[mo] = 1; 438 cnt += (int)((long)(mm[m].p) 439 / pgs); 440 } 441 442 /* Check cnts and times... */ 443 for (ii = 0; ii < sizeof(cl)/sizeof(cl[0]); 444 ii++) { 445 HX((e = clock_gettime(cl[ii], 446 &ts)) == -1, ts); 447 if (e != -1) 448 cnt += (int)ts.tv_nsec; 449 } 450 451 HX((e = getrusage(RUSAGE_SELF, 452 &ru)) == -1, ru); 453 if (e != -1) { 454 cnt += (int)ru.ru_utime.tv_sec; 455 cnt += (int)ru.ru_utime.tv_usec; 456 } 457 } 458 459 for (m = 0; m < sizeof mm/sizeof(mm[0]); m++) { 460 if (mm[m].p != MAP_FAILED) 461 munmap(mm[m].p, mm[m].npg * pgs); 462 mm[m].p = MAP_FAILED; 463 } 464 465 HX(stat(".", &st) == -1, st); 466 HX(statvfs(".", &stvfs) == -1, stvfs); 467 HX(statfs(".", &stfs) == -1, stfs); 468 469 HX(stat("/", &st) == -1, st); 470 HX(statvfs("/", &stvfs) == -1, stvfs); 471 HX(statfs("/", &stfs) == -1, stfs); 472 473 HX((e = fstat(0, &st)) == -1, st); 474 if (e == -1) { 475 if (S_ISREG(st.st_mode) || 476 S_ISFIFO(st.st_mode) || 477 S_ISSOCK(st.st_mode)) { 478 HX(fstatvfs(0, &stvfs) == -1, 479 stvfs); 480 HX(fstatfs(0, &stfs) == -1, 481 stfs); 482 HX((off = lseek(0, (off_t)0, 483 SEEK_CUR)) < 0, off); 484 } 485 if (S_ISCHR(st.st_mode)) { 486 HX(tcgetattr(0, &tios) == -1, 487 tios); 488 } else if (S_ISSOCK(st.st_mode)) { 489 memset(&ss, 0, sizeof ss); 490 ssl = sizeof(ss); 491 HX(getpeername(0, 492 (void *)&ss, &ssl) == -1, 493 ss); 494 } 495 } 496 497 HX((e = getrusage(RUSAGE_CHILDREN, 498 &ru)) == -1, ru); 499 if (e != -1) { 500 cnt += (int)ru.ru_utime.tv_sec; 501 cnt += (int)ru.ru_utime.tv_usec; 502 } 503 } else { 504 /* Subsequent hashes absorb previous result */ 505 HD(results); 506 } 507 508 HX((e = gettimeofday(&tv, NULL)) == -1, tv); 509 if (e != -1) { 510 cnt += (int)tv.tv_sec; 511 cnt += (int)tv.tv_usec; 512 } 513 514 HD(cnt); 515 } 516 #ifdef HAVE_GETAUXVAL 517 #ifdef AT_RANDOM 518 /* Not as random as you think but we take what we are given */ 519 p = (char *) getauxval(AT_RANDOM); 520 if (p) 521 HR(p, 16); 522 #endif 523 #ifdef AT_SYSINFO_EHDR 524 p = (char *) getauxval(AT_SYSINFO_EHDR); 525 if (p) 526 HR(p, pgs); 527 #endif 528 #ifdef AT_BASE 529 p = (char *) getauxval(AT_BASE); 530 if (p) 531 HD(p); 532 #endif 533 #endif 534 535 SHA512_Final(results, &ctx); 536 memcpy((char *)buf + i, results, min(sizeof(results), len - i)); 537 i += min(sizeof(results), len - i); 538 } 539 explicit_bzero(&ctx, sizeof ctx); 540 explicit_bzero(results, sizeof results); 541 if (gotdata(buf, len) == 0) { 542 errno = save_errno; 543 return (0); /* satisfied */ 544 } 545 errno = EIO; 546 return (-1); 547 } 548