| 1 | /* |
| 2 | * Non-physical true random number generator based on timing jitter. |
| 3 | * |
| 4 | * Copyright Stephan Mueller <[email protected]>, 2014 - 2026 |
| 5 | * |
| 6 | * Redistribution and use in source and binary forms, with or without |
| 7 | * modification, are permitted provided that the following conditions |
| 8 | * are met: |
| 9 | * 1. Redistributions of source code must retain the above copyright |
| 10 | * notice, and the entire permission notice in its entirety, |
| 11 | * including the disclaimer of warranties. |
| 12 | * 2. Redistributions in binary form must reproduce the above copyright |
| 13 | * notice, this list of conditions and the following disclaimer in the |
| 14 | * documentation and/or other materials provided with the distribution. |
| 15 | * 3. The name of the author may not be used to endorse or promote |
| 16 | * products derived from this software without specific prior |
| 17 | * written permission. |
| 18 | * |
| 19 | * ALTERNATIVELY, this product may be distributed under the terms of |
| 20 | * the GNU General Public License, in which case the provisions of the GPL are |
| 21 | * required INSTEAD OF the above restrictions. (This clause is |
| 22 | * necessary due to a potential bad interaction between the GPL and |
| 23 | * the restrictions contained in a BSD-style copyright.) |
| 24 | * |
| 25 | * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED |
| 26 | * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES |
| 27 | * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF |
| 28 | * WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE |
| 29 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR |
| 30 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT |
| 31 | * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR |
| 32 | * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF |
| 33 | * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
| 34 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE |
| 35 | * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH |
| 36 | * DAMAGE. |
| 37 | */ |
| 38 | |
| 39 | #include <unistd.h> |
| 40 | #include <stdio.h> |
| 41 | #include <stdarg.h> |
| 42 | #include <sys/types.h> |
| 43 | #include <asm/types.h> |
| 44 | #include <errno.h> |
| 45 | #include <limits.h> |
| 46 | #include <string.h> |
| 47 | #include <stdlib.h> |
| 48 | #include <sys/ioctl.h> |
| 49 | #include <sys/utsname.h> |
| 50 | #define _GNU_SOURCE |
| 51 | #include <getopt.h> |
| 52 | #include <sys/stat.h> |
| 53 | #include <fcntl.h> |
| 54 | #include <linux/random.h> |
| 55 | #include <linux/version.h> |
| 56 | #include <signal.h> |
| 57 | |
| 58 | #include "jitterentropy.h" |
| 59 | |
| 60 | #define MAJVERSION 1 /* API / ABI incompatible changes, functional changes that |
| 61 | * require consumer to be updated (as long as this number |
| 62 | * is zero, the API is not considered stable and can |
| 63 | * change without a bump of the major version) */ |
| 64 | #define MINVERSION 3 /* API compatible, ABI may change, functional |
| 65 | * enhancements only, consumer can be left unchanged if |
| 66 | * enhancements are not considered */ |
| 67 | #define PATCHLEVEL 2 /* API / ABI compatible, no functional changes, no |
| 68 | * enhancements, bug fixes only */ |
| 69 | |
| 70 | static int Verbosity = 0; |
| 71 | static int force_sp80090b = 0; |
| 72 | static int status = 0; |
| 73 | |
| 74 | /* |
| 75 | * When set, the daemon will exit on any error it encounters. The goal is that |
| 76 | * a wrapping monitor will pick up the errors and handle it as it sees fit, such |
| 77 | * as creating audit logs and possibly restart the daemon. |
| 78 | * |
| 79 | * The following errors are returned: |
| 80 | * |
| 81 | * * EOPNOTSUPP - the Jitter RNG triggered a fatal health test error |
| 82 | * * Errors reported by IOCTLs of RNDADDENTROPY and RNDRESEEDCRNG to /dev/random |
| 83 | * * Errors triggered by system calls including select(2), open(2), truncate(2), |
| 84 | * write(2), fork(2), as well as errors from library functions including |
| 85 | * lockf(3). |
| 86 | */ |
| 87 | static int exit_on_error = 0; |
| 88 | |
| 89 | struct kernel_rng { |
| 90 | int fd; |
| 91 | struct rand_data *ec; |
| 92 | struct rand_pool_info *rpi; |
| 93 | const char *dev; |
| 94 | }; |
| 95 | |
| 96 | static struct kernel_rng Random = { |
| 97 | /*.fd = */ -1, |
| 98 | /*.ec = */ NULL, |
| 99 | /*.rpi = */ NULL, |
| 100 | /*.dev = */ "/dev/random" |
| 101 | }; |
| 102 | |
| 103 | /* |
| 104 | * handler for /dev/urandom not needed as used IOCTL alters input_pool |
| 105 | static struct kernel_rng Urandom = { |
| 106 | .fd = 0, |
| 107 | .ec = NULL, |
| 108 | .rpi = NULL, |
| 109 | .dev = "/dev/urandom" |
| 110 | }; |
| 111 | */ |
| 112 | |
| 113 | static int Pidfile_fd = -1; |
| 114 | /* "/var/run/jitterentropy-rngd.pid" */ |
| 115 | static char *Pidfile = NULL; |
| 116 | |
| 117 | static int Entropy_avail_fd = -1; |
| 118 | static int Entropy_thresh_fd = -1; |
| 119 | static unsigned int jent_flags = 0; |
| 120 | static unsigned int jent_osr = 1; |
| 121 | |
| 122 | #define ENTROPYBYTES 32 |
| 123 | #define OVERSAMPLINGFACTOR 2 |
| 124 | /* |
| 125 | * After (force reseed wakeups), the installed alarm handler will unconditionally |
| 126 | * trigger a reseed irrespective of the seed level in two phases. This ensures |
| 127 | * that new seed is added after every (force reseed wakeups) * (alarm period). |
| 128 | * PHASE1: 120(force reseed wakeups) * 5(alarm period) == 600s |
| 129 | * PHASE2: 12(force reseed wakeups) * 50(alarm period) == 600s |
| 130 | */ |
| 131 | #define FORCE_RESEED_WAKEUPS_PHASE1 120 |
| 132 | #define ALARM_PERIOD_PHASE1 5 |
| 133 | #define FORCE_RESEED_WAKEUPS_PHASE2 12 |
| 134 | #define ALARM_PERIOD_PHASE2 50 |
| 135 | #define ENTROPYAVAIL "/proc/sys/kernel/random/entropy_avail" |
| 136 | #define ENTROPYTHRESH "/proc/sys/kernel/random/write_wakeup_threshold" |
| 137 | #define LRNG_FILE "/proc/lrng_type" |
| 138 | |
| 139 | static void install_alarm(unsigned int secs); |
| 140 | static void dealloc(void); |
| 141 | static int alloc(void); |
| 142 | static void dealloc_rng(struct kernel_rng *rng); |
| 143 | |
| 144 | static unsigned long kern_maj = ULONG_MAX, kern_minor, kern_patchlevel; |
| 145 | |
| 146 | static void jentrng_versionstring(char *buf, size_t buflen) |
| 147 | { |
| 148 | snprintf(buf, buflen, "jitterentropy-rngd %d.%d.%d", |
| 149 | MAJVERSION, MINVERSION, PATCHLEVEL); |
| 150 | } |
| 151 | |
| 152 | /* Is the LRNG present instead of the legacy /dev/random? */ |
| 153 | static int lrng_present(void) |
| 154 | { |
| 155 | struct stat buf; |
| 156 | static int lrng_present = -1; |
| 157 | |
| 158 | if (lrng_present < 0) { |
| 159 | int ret = stat(LRNG_FILE, &buf); |
| 160 | |
| 161 | if (ret == -1 && errno == ENOENT) |
| 162 | lrng_present = 0; |
| 163 | else |
| 164 | lrng_present = 1; |
| 165 | } |
| 166 | |
| 167 | return lrng_present; |
| 168 | } |
| 169 | |
| 170 | static int get_kernver(void) |
| 171 | { |
| 172 | struct utsname kernel; |
| 173 | char *saveptr = NULL; |
| 174 | char *res = NULL; |
| 175 | |
| 176 | if (kern_maj != ULONG_MAX) |
| 177 | return 0; |
| 178 | |
| 179 | if (uname(&kernel)) |
| 180 | return -errno; |
| 181 | |
| 182 | /* 5.11.2 */ |
| 183 | res = strtok_r(kernel.release, ".", &saveptr); |
| 184 | if (!res) { |
| 185 | printf("Could not parse kernel version"); |
| 186 | return -EFAULT; |
| 187 | } |
| 188 | kern_maj = strtoul(res, NULL, 10); |
| 189 | |
| 190 | res = strtok_r(NULL, ".", &saveptr); |
| 191 | if (!res) { |
| 192 | printf("Could not parse kernel version"); |
| 193 | return -EFAULT; |
| 194 | } |
| 195 | kern_minor = strtoul(res, NULL, 10); |
| 196 | |
| 197 | res = strtok_r(NULL, ".", &saveptr); |
| 198 | if (!res) { |
| 199 | printf("Could not parse kernel version"); |
| 200 | return -EFAULT; |
| 201 | } |
| 202 | kern_patchlevel = strtoul(res, NULL, 10); |
| 203 | |
| 204 | return 0; |
| 205 | } |
| 206 | |
| 207 | /* return true if kernel is greater or equal to given values, otherwise false */ |
| 208 | static int kernver_ge(unsigned int maj, unsigned int minor, |
| 209 | unsigned int patchlevel) |
| 210 | { |
| 211 | if (get_kernver()) |
| 212 | return 0; |
| 213 | |
| 214 | if (maj < kern_maj) |
| 215 | return 1; |
| 216 | if (maj == kern_maj) { |
| 217 | if (minor < kern_minor) |
| 218 | return 1; |
| 219 | if (minor == kern_minor) { |
| 220 | if (patchlevel <= kern_patchlevel) |
| 221 | return 1; |
| 222 | } |
| 223 | } |
| 224 | return 0; |
| 225 | } |
| 226 | |
| 227 | static void usage(void) |
| 228 | { |
| 229 | unsigned int ver = jent_version(); |
| 230 | char version[30]; |
| 231 | |
| 232 | memset(version, 0, 30); |
| 233 | jentrng_versionstring(version, sizeof(version)); |
| 234 | |
| 235 | fprintf(stderr, "\njitterentropy rngd feeding entropy to input_pool of Linux RNG\n"); |
| 236 | fprintf(stderr, "Version %s\n\n", version); |
| 237 | fprintf(stderr, "Reported numeric version number of jent library %u\n\n", ver); |
| 238 | fprintf(stderr, "Usage:\n"); |
| 239 | fprintf(stderr, "\t-h --help\tThis help information\n"); |
| 240 | fprintf(stderr, "\t --version\tPrint version\n"); |
| 241 | fprintf(stderr, "\t-v --verbose\tVerbose logging, multiple options increase verbosity\n"); |
| 242 | fprintf(stderr, "\t\t\tVerbose logging implies running in foreground\n"); |
| 243 | fprintf(stderr, "\t-p --pid\tWrite daemon PID to file\n"); |
| 244 | fprintf(stderr, "\t-s --sp800-90b\tForce SP800-90B compliance\n"); |
| 245 | fprintf(stderr, "\t-f --flags\tInteger with flags used to allocate Jitter RNG\n"); |
| 246 | fprintf(stderr, "\t-o --osr\tInteger with OSR used to allocate Jitter RNG\n"); |
| 247 | fprintf(stderr, "\t --status\tStatus information of the Jitter RNG - invoke with\n"); |
| 248 | fprintf(stderr, "\t \tsame flags as used for runtime\n"); |
| 249 | fprintf(stderr, "\t --exit-on-error\tCause the daemon to exit on errors\n"); |
| 250 | fprintf(stderr, "\nLRNG presence %sdetected\n", |
| 251 | lrng_present() ? "" : "not "); |
| 252 | exit(1); |
| 253 | } |
| 254 | |
| 255 | static void parse_opts(int argc, char *argv[]) |
| 256 | { |
| 257 | int c = 0; |
| 258 | char version[30]; |
| 259 | |
| 260 | while (1) { |
| 261 | int opt_index = 0; |
| 262 | static struct option opts[] = { |
| 263 | {"verbose", 0, 0, 0}, |
| 264 | {"pid", 1, 0, 0}, |
| 265 | {"help", 0, 0, 0}, |
| 266 | {"version", 0, 0, 0}, |
| 267 | {"sp800-90b", 0, 0, 0}, |
| 268 | {"flags", 1, 0, 0}, |
| 269 | {"osr", 1, 0, 0}, |
| 270 | {"status", 0, 0, 0}, |
| 271 | {"exit-on-error", 0, 0, 0}, |
| 272 | {0, 0, 0, 0} |
| 273 | }; |
| 274 | c = getopt_long(argc, argv, "svp:hf:o:", opts, &opt_index); |
| 275 | if (-1 == c) |
| 276 | break; |
| 277 | switch (c) { |
| 278 | case 0: |
| 279 | switch (opt_index) { |
| 280 | |
| 281 | /* verbose */ |
| 282 | case 0: |
| 283 | Verbosity++; |
| 284 | break; |
| 285 | |
| 286 | /* pid */ |
| 287 | case 1: |
| 288 | Pidfile = optarg; |
| 289 | break; |
| 290 | |
| 291 | /* help */ |
| 292 | case 2: |
| 293 | usage(); |
| 294 | break; |
| 295 | |
| 296 | /* version */ |
| 297 | case 3: |
| 298 | jentrng_versionstring(version, sizeof(version)); |
| 299 | fprintf(stderr, "Version %s\n", version); |
| 300 | fprintf(stderr, "Version Jitterentropy Core %u\n", jent_version()); |
| 301 | exit(0); |
| 302 | break; |
| 303 | |
| 304 | /* sp800-90b */ |
| 305 | case 4: |
| 306 | force_sp80090b = 1; |
| 307 | break; |
| 308 | |
| 309 | /* flags */ |
| 310 | case 5: |
| 311 | { |
| 312 | unsigned long val = strtoul(optarg, NULL, 10); |
| 313 | |
| 314 | if (val > UINT_MAX) |
| 315 | usage(); |
| 316 | jent_flags = (unsigned int)val; |
| 317 | |
| 318 | break; |
| 319 | } |
| 320 | |
| 321 | /* osr */ |
| 322 | case 6: |
| 323 | { |
| 324 | unsigned long val = strtoul(optarg, NULL, 10); |
| 325 | |
| 326 | if (val > UINT_MAX) |
| 327 | usage(); |
| 328 | jent_osr = (unsigned int)val; |
| 329 | |
| 330 | break; |
| 331 | } |
| 332 | |
| 333 | /* status */ |
| 334 | case 7: |
| 335 | status = 1; |
| 336 | break; |
| 337 | |
| 338 | /* exit-on-error */ |
| 339 | case 8: |
| 340 | exit_on_error = 1; |
| 341 | break; |
| 342 | |
| 343 | default: |
| 344 | usage(); |
| 345 | } |
| 346 | break; |
| 347 | case 'v': |
| 348 | Verbosity++; |
| 349 | break; |
| 350 | case 'p': |
| 351 | Pidfile = optarg; |
| 352 | break; |
| 353 | case 'h': |
| 354 | usage(); |
| 355 | break; |
| 356 | case 's': |
| 357 | force_sp80090b = 1; |
| 358 | break; |
| 359 | case 'f': |
| 360 | { |
| 361 | unsigned long val = strtoul(optarg, NULL, 10); |
| 362 | |
| 363 | if (val > UINT_MAX) |
| 364 | usage(); |
| 365 | jent_flags = (unsigned int)val; |
| 366 | |
| 367 | break; |
| 368 | } |
| 369 | case 'o': |
| 370 | { |
| 371 | unsigned long val = strtoul(optarg, NULL, 10); |
| 372 | |
| 373 | if (val > UINT_MAX) |
| 374 | usage(); |
| 375 | jent_osr = (unsigned int)val; |
| 376 | |
| 377 | break; |
| 378 | } |
| 379 | default: |
| 380 | usage(); |
| 381 | } |
| 382 | } |
| 383 | } |
| 384 | |
| 385 | #define LOG_DEBUG 3 |
| 386 | #define LOG_VERBOSE 2 |
| 387 | #define LOG_WARN 1 |
| 388 | #define LOG_ERR 0 |
| 389 | static void dolog(int severity, const char *fmt, ...) |
| 390 | { |
| 391 | va_list args; |
| 392 | char msg[1024]; |
| 393 | char sev[10]; |
| 394 | |
| 395 | if (severity <= Verbosity) { |
| 396 | va_start(args, fmt); |
| 397 | vsnprintf(msg, sizeof(msg), fmt, args); |
| 398 | va_end(args); |
| 399 | |
| 400 | switch (severity) { |
| 401 | case LOG_DEBUG: |
| 402 | snprintf(sev, sizeof(sev), "Debug"); |
| 403 | break; |
| 404 | case LOG_VERBOSE: |
| 405 | snprintf(sev, sizeof(sev), "Verbose"); |
| 406 | break; |
| 407 | case LOG_WARN: |
| 408 | snprintf(sev, sizeof(sev), "Warning"); |
| 409 | break; |
| 410 | case LOG_ERR: |
| 411 | snprintf(sev, sizeof(sev), "Error"); |
| 412 | break; |
| 413 | default: |
| 414 | snprintf(sev, sizeof(sev), "Unknown"); |
| 415 | } |
| 416 | printf("jitterentropy-rngd - %s: %s\n", sev, msg); |
| 417 | } |
| 418 | |
| 419 | if (LOG_ERR == severity) { |
| 420 | dealloc(); |
| 421 | exit(1); |
| 422 | } |
| 423 | } |
| 424 | |
| 425 | static inline void memset_secure(void *s, int c, size_t n) |
| 426 | { |
| 427 | memset(s, c, n); |
| 428 | __asm__ __volatile__("" : : "r" (s) : "memory"); |
| 429 | } |
| 430 | |
| 431 | /******************************************************************* |
| 432 | * entropy handler functions |
| 433 | *******************************************************************/ |
| 434 | |
| 435 | static ssize_t write_random(struct kernel_rng *rng, char *buf, size_t len, |
| 436 | size_t entropy_bytes, int force_reseed) |
| 437 | { |
| 438 | ssize_t written = 0; |
| 439 | int ret; |
| 440 | |
| 441 | if (len > SSIZE_MAX) |
| 442 | return -EOVERFLOW; |
| 443 | |
| 444 | /* value is in bits */ |
| 445 | rng->rpi->entropy_count = (entropy_bytes * 8); |
| 446 | rng->rpi->buf_size = len; |
| 447 | memcpy(rng->rpi->buf, buf, len); |
| 448 | |
| 449 | ret = ioctl(rng->fd, RNDADDENTROPY, rng->rpi); |
| 450 | if (0 > ret) { |
| 451 | int errsv = errno; |
| 452 | |
| 453 | dolog(LOG_WARN, "Error injecting entropy: %s", strerror(errsv)); |
| 454 | return -errsv; |
| 455 | } else { |
| 456 | dolog(LOG_DEBUG, "Injected %u bytes with an entropy count of %u bytes of entropy", |
| 457 | len, entropy_bytes); |
| 458 | written = len; |
| 459 | } |
| 460 | |
| 461 | rng->rpi->entropy_count = 0; |
| 462 | rng->rpi->buf_size = 0; |
| 463 | memset(rng->rpi->buf, 0, len); |
| 464 | |
| 465 | #if LINUX_VERSION_CODE >= KERNEL_VERSION(4,17,0) |
| 466 | /* |
| 467 | * The LRNG does not require this IOCTL as the reseed is automatically |
| 468 | * triggered. |
| 469 | */ |
| 470 | if (force_reseed && kernver_ge(4, 17, 0) && !lrng_present()) { |
| 471 | if (ioctl(rng->fd, RNDRESEEDCRNG) < 0) { |
| 472 | written = -errno; |
| 473 | if (errno == EINVAL) |
| 474 | goto out; |
| 475 | dolog(LOG_WARN, |
| 476 | "Error triggering a reseed of the kernel DRNG: %s", |
| 477 | strerror(errno)); |
| 478 | } else { |
| 479 | dolog(LOG_DEBUG, "Reseeding of kernel DRNG triggered"); |
| 480 | } |
| 481 | } |
| 482 | #endif |
| 483 | |
| 484 | out: |
| 485 | return written; |
| 486 | } |
| 487 | |
| 488 | static ssize_t read_jent(struct kernel_rng *rng, char *buf, size_t buflen) |
| 489 | { |
| 490 | ssize_t ret; |
| 491 | |
| 492 | /* |
| 493 | *jent_read_entropy_safe implies a changing H_submitter which is not |
| 494 | * allowed in SP800-90B. |
| 495 | */ |
| 496 | if (force_sp80090b) |
| 497 | ret = jent_read_entropy(rng->ec, buf, buflen); |
| 498 | else |
| 499 | ret = jent_read_entropy_safe(&rng->ec, buf, buflen); |
| 500 | |
| 501 | if (ret >= 0) |
| 502 | return ret; |
| 503 | |
| 504 | dolog(LOG_WARN, "Cannot read entropy"); |
| 505 | |
| 506 | return -EOPNOTSUPP; |
| 507 | } |
| 508 | |
| 509 | static ssize_t gather_entropy(struct kernel_rng *rng) |
| 510 | { |
| 511 | sigset_t blocking_set, previous_set; |
| 512 | #define ENTBLOCKSIZE (ENTROPYBYTES * OVERSAMPLINGFACTOR) |
| 513 | /* |
| 514 | * Maximum numbers of blocks is determined by numbers of reseed IOCTLs: if |
| 515 | * the reseed IOCTL is used, we call ceil(256 / 80) numbers of IOCTLs. As |
| 516 | * each IOCTL may drain the entropy pool by 256 bits, we need to ensure that |
| 517 | * after the numbers of IOCTLs, we finally inject more blocks than the numbers |
| 518 | * of IOCTLs into the input_pool. Otherwise the entropy estimator will never |
| 519 | * rise and we encounter an endless loop. |
| 520 | */ |
| 521 | #define ENTBLOCKS (4 + 2 + 1) |
| 522 | char buf[(ENTBLOCKSIZE * ENTBLOCKS)]; |
| 523 | ssize_t buflen = ENTBLOCKSIZE; |
| 524 | ssize_t ret = 0; |
| 525 | |
| 526 | sigemptyset(&previous_set); |
| 527 | sigemptyset(&blocking_set); |
| 528 | sigaddset(&blocking_set, SIGALRM); |
| 529 | |
| 530 | sigprocmask(SIG_BLOCK, &blocking_set, &previous_set); |
| 531 | |
| 532 | if (lrng_present()) { |
| 533 | /* |
| 534 | * The LRNG operates fully 90B compliant, no special handling |
| 535 | * is necessary. |
| 536 | */ |
| 537 | ret = read_jent(rng, buf, buflen); |
| 538 | if (ret < 0) |
| 539 | goto out; |
| 540 | |
| 541 | dolog(LOG_DEBUG, "LRNG: Inject %u bits of data with %u bits of entropy into Blake2S state", |
| 542 | buflen << 3, ret << 3); |
| 543 | |
| 544 | /* |
| 545 | * Write the entropy, LRNG seeds automatically - the Jitter RNG |
| 546 | * provides full entropy so, we tell the Linux RNG the amount of |
| 547 | * entropy. |
| 548 | */ |
| 549 | ret = write_random(rng, buf, buflen, ret, 0); |
| 550 | } else { |
| 551 | if (!kernver_ge(5, 18, 0)) { |
| 552 | static int reported = 0; |
| 553 | |
| 554 | if (!reported) { |
| 555 | dolog(LOG_WARN, "Kernel older than 5.18 detected - DRT.1 status unclear"); |
| 556 | reported = 1; |
| 557 | } |
| 558 | } |
| 559 | |
| 560 | /* |
| 561 | * AIS 20/31 DRT.1, no special handling is necessary. |
| 562 | */ |
| 563 | ret = read_jent(rng, buf, buflen); |
| 564 | if (ret < 0) |
| 565 | goto out; |
| 566 | |
| 567 | dolog(LOG_DEBUG, "Linux kernel >= 5.18: Inject %u bits of data with %u bits of entropy into Blake2S state", |
| 568 | buflen << 3, ret << 3); |
| 569 | |
| 570 | /* |
| 571 | * Write the entropy and trigger reseed - the Jitter RNG provides |
| 572 | * full entropy so, we tell the Linux RNG the amount of entropy. |
| 573 | */ |
| 574 | ret = write_random(rng, buf, buflen, ret, 1); |
| 575 | } |
| 576 | |
| 577 | if (ret >= 0 && buflen != ret) { |
| 578 | dolog(LOG_WARN, "Injected %lu bytes into %s, expected %d", |
| 579 | ret, rng->dev, buflen); |
| 580 | ret = 0; |
| 581 | } |
| 582 | |
| 583 | out: |
| 584 | memset_secure(buf, 0, buflen); |
| 585 | |
| 586 | if (exit_on_error && ret < 0) { |
| 587 | /* We now exit as requested by caller */ |
| 588 | dealloc(); |
| 589 | exit(-ret); |
| 590 | } |
| 591 | |
| 592 | sigprocmask(SIG_SETMASK, &previous_set, NULL); |
| 593 | |
| 594 | return ret; |
| 595 | } |
| 596 | |
| 597 | static int read_entropy_value(int fd) |
| 598 | { |
| 599 | ssize_t data = 0; |
| 600 | char buf[5]; |
| 601 | int entropy = 0; |
| 602 | |
| 603 | data = read(fd, buf, sizeof(buf)); |
| 604 | lseek(fd, 0, SEEK_SET); |
| 605 | |
| 606 | if (0 > data) { |
| 607 | dolog(LOG_WARN, "Error reading data from entropy fd: %s", |
| 608 | strerror(errno)); |
| 609 | return 0; |
| 610 | } |
| 611 | if (0 == data) { |
| 612 | dolog(LOG_WARN, "Could not read data from entropy fd"); |
| 613 | return 0; |
| 614 | } |
| 615 | |
| 616 | entropy = atoi(buf); |
| 617 | if (0 > entropy || 4096 < entropy) { |
| 618 | dolog(LOG_WARN, "Entropy read from entropy fd (%d) is outsize of range", entropy); |
| 619 | return 0; |
| 620 | } |
| 621 | |
| 622 | return entropy; |
| 623 | } |
| 624 | |
| 625 | /******************************************************************* |
| 626 | * Signal handling functions |
| 627 | *******************************************************************/ |
| 628 | |
| 629 | /* |
| 630 | * Wakeup and check entropy_avail -- this covers the drain of entropy |
| 631 | * from the nonblocking_pool via get_random_bytes |
| 632 | */ |
| 633 | static void sig_entropy_avail(int sig) |
| 634 | { |
| 635 | int entropy = 0, thresh = 0; |
| 636 | ssize_t written = 0; |
| 637 | static unsigned int force_reseed = FORCE_RESEED_WAKEUPS_PHASE1; |
| 638 | static unsigned int alarm_period = ALARM_PERIOD_PHASE1; |
| 639 | |
| 640 | (void)sig; |
| 641 | |
| 642 | dolog(LOG_VERBOSE, "Wakeup call for alarm on %s", ENTROPYAVAIL); |
| 643 | |
| 644 | if (--force_reseed == 0) { |
| 645 | force_reseed = FORCE_RESEED_WAKEUPS_PHASE2; |
| 646 | alarm_period = ALARM_PERIOD_PHASE2; |
| 647 | dolog(LOG_DEBUG, "Force reseed", entropy); |
| 648 | do { |
| 649 | if (written < 0) { |
| 650 | dolog(LOG_DEBUG, "Re-initializing rngd\n"); |
| 651 | dealloc(); |
| 652 | if (alloc() < 0) |
| 653 | goto out; |
| 654 | } |
| 655 | written = gather_entropy(&Random); |
| 656 | } while (written < 0); |
| 657 | dolog(LOG_VERBOSE, "%zd bytes written to /dev/random", written); |
| 658 | goto out; |
| 659 | } |
| 660 | |
| 661 | entropy = read_entropy_value(Entropy_avail_fd); |
| 662 | thresh = read_entropy_value(Entropy_thresh_fd); |
| 663 | |
| 664 | if (0 == entropy || 0 == thresh) |
| 665 | goto out; |
| 666 | if (entropy >= thresh) { |
| 667 | dolog(LOG_DEBUG, "Sufficient entropy %d available", entropy); |
| 668 | goto out; |
| 669 | } |
| 670 | dolog(LOG_DEBUG, "Insufficient entropy %d available (threshold %d)", |
| 671 | entropy, thresh); |
| 672 | do { |
| 673 | if (written < 0) { |
| 674 | dolog(LOG_DEBUG, "Re-initializing rngd\n"); |
| 675 | dealloc(); |
| 676 | if (alloc() < 0) |
| 677 | goto out; |
| 678 | } |
| 679 | written = gather_entropy(&Random); |
| 680 | } while (written < 0); |
| 681 | dolog(LOG_VERBOSE, "%zd bytes written to /dev/random", written); |
| 682 | out: |
| 683 | install_alarm(alarm_period); |
| 684 | return; |
| 685 | } |
| 686 | |
| 687 | /* terminate the daemon cleanly */ |
| 688 | static void sig_term(int sig) |
| 689 | { |
| 690 | (void)sig; |
| 691 | dolog(LOG_DEBUG, "Shutting down cleanly\n"); |
| 692 | |
| 693 | /* Prevent the kernel from interfering with the shutdown */ |
| 694 | signal(SIGALRM, SIG_IGN); |
| 695 | |
| 696 | /* If we got another termination signal, just get killed */ |
| 697 | signal(SIGHUP, SIG_DFL); |
| 698 | signal(SIGINT, SIG_DFL); |
| 699 | signal(SIGQUIT, SIG_DFL); |
| 700 | signal(SIGTERM, SIG_DFL); |
| 701 | |
| 702 | dealloc(); |
| 703 | exit(0); |
| 704 | } |
| 705 | |
| 706 | /* |
| 707 | * Wakeup on insufficient entropy on /dev/random |
| 708 | */ |
| 709 | static void select_fd(void) |
| 710 | { |
| 711 | fd_set fds; |
| 712 | int ret = 0; |
| 713 | ssize_t written = 0; |
| 714 | |
| 715 | while (1) { |
| 716 | FD_ZERO(&fds); |
| 717 | dolog(LOG_DEBUG, "Polling /dev/random"); |
| 718 | FD_SET(Random.fd, &fds); |
| 719 | /* only /dev/random implements polling */ |
| 720 | ret = select((Random.fd + 1), NULL, &fds, NULL, NULL); |
| 721 | |
| 722 | if (-1 == ret && EINTR != errno) { |
| 723 | if (exit_on_error) { |
| 724 | int errsv = errno; |
| 725 | |
| 726 | dealloc(); |
| 727 | exit(errsv); |
| 728 | } |
| 729 | dolog(LOG_ERR, "Select returned with error %s", strerror(errno)); |
| 730 | } |
| 731 | if (0 <= ret) { |
| 732 | dolog(LOG_VERBOSE, "Wakeup call for select on /dev/random"); |
| 733 | do { |
| 734 | if (written < 0) { |
| 735 | dolog(LOG_DEBUG, |
| 736 | "Re-initializing rngd\n"); |
| 737 | dealloc(); |
| 738 | if (alloc() < 0) |
| 739 | continue; |
| 740 | } |
| 741 | written = gather_entropy(&Random); |
| 742 | } while (written < 0); |
| 743 | dolog(LOG_VERBOSE, "%zd bytes written to /dev/random", |
| 744 | written); |
| 745 | } |
| 746 | } |
| 747 | } |
| 748 | |
| 749 | static void install_alarm(unsigned int secs) |
| 750 | { |
| 751 | if (lrng_present()) |
| 752 | return; |
| 753 | dolog(LOG_DEBUG, "Install alarm signal handler"); |
| 754 | signal(SIGALRM, sig_entropy_avail); |
| 755 | alarm(secs); |
| 756 | } |
| 757 | |
| 758 | static void install_term(void) |
| 759 | { |
| 760 | dolog(LOG_DEBUG, "Install termination signal handler"); |
| 761 | signal(SIGHUP, sig_term); |
| 762 | signal(SIGINT, sig_term); |
| 763 | signal(SIGQUIT, sig_term); |
| 764 | signal(SIGTERM, sig_term); |
| 765 | } |
| 766 | |
| 767 | /******************************************************************* |
| 768 | * allocation functions |
| 769 | *******************************************************************/ |
| 770 | |
| 771 | static void dealloc_rng(struct kernel_rng *rng) |
| 772 | { |
| 773 | if (NULL != rng->ec) { |
| 774 | jent_entropy_collector_free(rng->ec); |
| 775 | rng->ec = NULL; |
| 776 | } |
| 777 | if (NULL != rng->rpi) { |
| 778 | memset(rng->rpi, 0,(sizeof(struct rand_pool_info) + |
| 779 | (ENTROPYBYTES * OVERSAMPLINGFACTOR * |
| 780 | sizeof(char)))); |
| 781 | free(rng->rpi); |
| 782 | rng->rpi = NULL; |
| 783 | } |
| 784 | if (-1 != rng->fd) { |
| 785 | close(rng->fd); |
| 786 | rng->fd = -1; |
| 787 | } |
| 788 | } |
| 789 | |
| 790 | static void dealloc(void) |
| 791 | { |
| 792 | dealloc_rng(&Random); |
| 793 | if (-1 != Entropy_avail_fd) { |
| 794 | close(Entropy_avail_fd); |
| 795 | Entropy_avail_fd = -1; |
| 796 | } |
| 797 | if (-1 != Entropy_thresh_fd) { |
| 798 | close(Entropy_thresh_fd); |
| 799 | Entropy_thresh_fd = -1; |
| 800 | } |
| 801 | if (-1 != Pidfile_fd) { |
| 802 | close(Pidfile_fd); |
| 803 | Pidfile_fd = -1; |
| 804 | if (NULL != Pidfile) |
| 805 | unlink(Pidfile); |
| 806 | } |
| 807 | } |
| 808 | |
| 809 | static int alloc_rng(struct kernel_rng *rng) |
| 810 | { |
| 811 | rng->ec = jent_entropy_collector_alloc(jent_osr, jent_flags); |
| 812 | if (!rng->ec) { |
| 813 | dolog(LOG_ERR, "Allocation of entropy collector failed"); |
| 814 | return -EAGAIN; |
| 815 | } |
| 816 | |
| 817 | if (status) { |
| 818 | char buf[2500]; |
| 819 | int ret = jent_status(rng->ec, buf, sizeof(buf)); |
| 820 | |
| 821 | if (ret) |
| 822 | return ret; |
| 823 | |
| 824 | fprintf(stderr, "%s\n", buf); |
| 825 | return -EAGAIN; |
| 826 | } |
| 827 | |
| 828 | rng->rpi = malloc((sizeof(struct rand_pool_info) + |
| 829 | (ENTROPYBYTES * OVERSAMPLINGFACTOR * sizeof(char)))); |
| 830 | if (!rng->rpi) { |
| 831 | dolog(LOG_ERR, "Cannot allocate memory for random bytes"); |
| 832 | dealloc_rng(rng); |
| 833 | return -ENOMEM; |
| 834 | } |
| 835 | |
| 836 | rng->fd = open(rng->dev, O_WRONLY); |
| 837 | if (-1 == rng->fd) { |
| 838 | int errsv = errno; |
| 839 | |
| 840 | dolog(LOG_ERR, "Open of %s failed: %s", rng->dev, strerror(errno)); |
| 841 | dealloc_rng(rng); |
| 842 | return -errsv; |
| 843 | } |
| 844 | |
| 845 | return 0; |
| 846 | } |
| 847 | |
| 848 | static int alloc(void) |
| 849 | { |
| 850 | int ret = 0; |
| 851 | ssize_t written = 0; |
| 852 | |
| 853 | ret = jent_entropy_init_ex(jent_osr, jent_flags); |
| 854 | if (ret) { |
| 855 | dolog(LOG_ERR, "The initialization of CPU Jitter RNG failed with error code %d\n", ret); |
| 856 | return ret; |
| 857 | } |
| 858 | |
| 859 | ret = alloc_rng(&Random); |
| 860 | if (ret) |
| 861 | return ret; |
| 862 | |
| 863 | Entropy_avail_fd = open(ENTROPYAVAIL, O_RDONLY); |
| 864 | if (-1 == Entropy_avail_fd) { |
| 865 | int errsv = errno; |
| 866 | |
| 867 | dolog(LOG_ERR, "Open of %s failed: %s", ENTROPYAVAIL, strerror(errno)); |
| 868 | dealloc(); |
| 869 | return -errsv; |
| 870 | } |
| 871 | |
| 872 | Entropy_thresh_fd = open(ENTROPYTHRESH, O_RDONLY); |
| 873 | if (-1 == Entropy_thresh_fd) { |
| 874 | int errsv = errno; |
| 875 | |
| 876 | dolog(LOG_ERR, "Open of %s failed: %s", ENTROPYTHRESH, strerror(errno)); |
| 877 | dealloc(); |
| 878 | return -errsv; |
| 879 | } |
| 880 | |
| 881 | written = gather_entropy(&Random); |
| 882 | if (written >= 0) { |
| 883 | dolog(LOG_VERBOSE, "%zd bytes to /dev/random", written); |
| 884 | } else { |
| 885 | dolog(LOG_ERR, "Cannot write to /dev/random, failure: %zd", |
| 886 | written); |
| 887 | /* We consider this as no error at this point */ |
| 888 | } |
| 889 | |
| 890 | return 0; |
| 891 | } |
| 892 | |
| 893 | static void create_pid_file(const char *pid_file) |
| 894 | { |
| 895 | char pid_str[12]; /* max. integer length + '\n' + null */ |
| 896 | |
| 897 | /* Ensure only one copy */ |
| 898 | Pidfile_fd = open(pid_file, O_RDWR|O_CREAT|O_EXCL, S_IRUSR|S_IWUSR); |
| 899 | if (Pidfile_fd == -1) |
| 900 | dolog(LOG_ERR, "Cannot open pid file\n"); |
| 901 | |
| 902 | if (lockf(Pidfile_fd, F_TLOCK, 0) == -1) { |
| 903 | if (errno == EAGAIN || errno == EACCES) { |
| 904 | int errsv = errno; |
| 905 | |
| 906 | dolog(LOG_ERR, "PID file already locked\n"); |
| 907 | exit(errsv); |
| 908 | } else |
| 909 | dolog(LOG_ERR, "Cannot lock pid file\n"); |
| 910 | } |
| 911 | |
| 912 | if (ftruncate(Pidfile_fd, 0) == -1) { |
| 913 | int errsv = errno; |
| 914 | |
| 915 | dolog(LOG_ERR, "Cannot truncate pid file\n"); |
| 916 | exit(errsv); |
| 917 | } |
| 918 | |
| 919 | /* write our pid to the pid file */ |
| 920 | snprintf(pid_str, sizeof(pid_str), "%d\n", getpid()); |
| 921 | if (write(Pidfile_fd, pid_str, strlen(pid_str)) != |
| 922 | (ssize_t)strlen(pid_str)) { |
| 923 | dolog(LOG_ERR, "Cannot write to pid file\n"); |
| 924 | exit(1); |
| 925 | } |
| 926 | } |
| 927 | |
| 928 | static void daemonize(void) |
| 929 | { |
| 930 | pid_t pid; |
| 931 | |
| 932 | /* already a daemon */ |
| 933 | if (1 == getppid()) |
| 934 | return; |
| 935 | |
| 936 | pid = fork(); |
| 937 | if (pid < 0) |
| 938 | dolog(LOG_ERR, "Cannot fork to daemonize\n"); |
| 939 | |
| 940 | /* the parent process exits -- nothing has been allocated, nothing |
| 941 | * needs to be freed */ |
| 942 | if (0 < pid) |
| 943 | exit(0); |
| 944 | |
| 945 | /* we are the child now */ |
| 946 | |
| 947 | /* new SID for the child process */ |
| 948 | if (setsid() < 0) |
| 949 | dolog(LOG_ERR, "Cannot obtain new SID for child\n"); |
| 950 | |
| 951 | /* Change the current working directory. This prevents the current |
| 952 | * directory from being locked; hence not being able to remove it. */ |
| 953 | if ((chdir("/")) < 0) |
| 954 | dolog(LOG_ERR, "Cannot change directory\n"); |
| 955 | |
| 956 | if (Pidfile && strlen(Pidfile)) |
| 957 | create_pid_file(Pidfile); |
| 958 | |
| 959 | /* Redirect standard files to /dev/null */ |
| 960 | #pragma GCC diagnostic push |
| 961 | #pragma GCC diagnostic ignored "-Wunused-result" |
| 962 | freopen( "/dev/null", "r", stdin); |
| 963 | freopen( "/dev/null", "w", stdout); |
| 964 | freopen( "/dev/null", "w", stderr); |
| 965 | #pragma GCC diagnostic pop |
| 966 | } |
| 967 | |
| 968 | |
| 969 | int main(int argc, char *argv[]) |
| 970 | { |
| 971 | int ret; |
| 972 | |
| 973 | parse_opts(argc, argv); |
| 974 | |
| 975 | if (geteuid()) |
| 976 | dolog(LOG_ERR, "Program must start as root!"); |
| 977 | |
| 978 | ret = alloc(); |
| 979 | if (ret) |
| 980 | goto out; |
| 981 | |
| 982 | if (0 == Verbosity) |
| 983 | daemonize(); |
| 984 | install_term(); |
| 985 | install_alarm(ALARM_PERIOD_PHASE1); |
| 986 | select_fd(); |
| 987 | /* NOTREACHED */ |
| 988 | |
| 989 | out: |
| 990 | dealloc(); |
| 991 | return -ret; |
| 992 | } |