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