1 /*- 2 * Copyright (c) 2017 Oliver Pinter 3 * Copyright (c) 2017 W. Dean Freeman 4 * Copyright (c) 2000-2015 Mark R V Murray 5 * Copyright (c) 2013 Arthur Mesh 6 * Copyright (c) 2004 Robert N. M. Watson 7 * All rights reserved. 8 * 9 * Redistribution and use in source and binary forms, with or without 10 * modification, are permitted provided that the following conditions 11 * are met: 12 * 1. Redistributions of source code must retain the above copyright 13 * notice, this list of conditions and the following disclaimer 14 * in this position and unchanged. 15 * 2. Redistributions in binary form must reproduce the above copyright 16 * notice, this list of conditions and the following disclaimer in the 17 * documentation and/or other materials provided with the distribution. 18 * 19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 20 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 21 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 23 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 24 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 28 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 * 30 */ 31 32 #include <sys/cdefs.h> 33 __FBSDID("$FreeBSD$"); 34 35 #include <sys/param.h> 36 #include <sys/systm.h> 37 #include <sys/conf.h> 38 #include <sys/eventhandler.h> 39 #include <sys/hash.h> 40 #include <sys/kernel.h> 41 #include <sys/kthread.h> 42 #include <sys/linker.h> 43 #include <sys/lock.h> 44 #include <sys/malloc.h> 45 #include <sys/module.h> 46 #include <sys/mutex.h> 47 #include <sys/random.h> 48 #include <sys/sbuf.h> 49 #include <sys/sysctl.h> 50 #include <sys/unistd.h> 51 52 #if defined(RANDOM_LOADABLE) 53 #include <sys/lock.h> 54 #include <sys/sx.h> 55 #endif 56 57 #include <machine/atomic.h> 58 #include <machine/cpu.h> 59 60 #include <crypto/rijndael/rijndael-api-fst.h> 61 #include <crypto/sha2/sha256.h> 62 63 #include <dev/random/hash.h> 64 #include <dev/random/randomdev.h> 65 #include <dev/random/random_harvestq.h> 66 67 #if defined(RANDOM_ENABLE_ETHER) 68 #define _RANDOM_HARVEST_ETHER_OFF 0 69 #else 70 #define _RANDOM_HARVEST_ETHER_OFF (1u << RANDOM_NET_ETHER) 71 #endif 72 #if defined(RANDOM_ENABLE_UMA) 73 #define _RANDOM_HARVEST_UMA_OFF 0 74 #else 75 #define _RANDOM_HARVEST_UMA_OFF (1u << RANDOM_UMA) 76 #endif 77 78 static void random_kthread(void); 79 static void random_sources_feed(void); 80 81 static u_int read_rate; 82 83 /* List for the dynamic sysctls */ 84 static struct sysctl_ctx_list random_clist; 85 86 /* 87 * How many events to queue up. We create this many items in 88 * an 'empty' queue, then transfer them to the 'harvest' queue with 89 * supplied junk. When used, they are transferred back to the 90 * 'empty' queue. 91 */ 92 #define RANDOM_RING_MAX 1024 93 #define RANDOM_ACCUM_MAX 8 94 95 /* 1 to let the kernel thread run, 0 to terminate, -1 to mark completion */ 96 volatile int random_kthread_control; 97 98 99 /* Allow the sysadmin to select the broad category of 100 * entropy types to harvest. 101 */ 102 __read_frequently u_int hc_source_mask; 103 104 /* 105 * Put all the harvest queue context stuff in one place. 106 * this make is a bit easier to lock and protect. 107 */ 108 static struct harvest_context { 109 /* The harvest mutex protects all of harvest_context and 110 * the related data. 111 */ 112 struct mtx hc_mtx; 113 /* Round-robin destination cache. */ 114 u_int hc_destination[ENTROPYSOURCE]; 115 /* The context of the kernel thread processing harvested entropy */ 116 struct proc *hc_kthread_proc; 117 /* 118 * Lockless ring buffer holding entropy events 119 * If ring.in == ring.out, 120 * the buffer is empty. 121 * If ring.in != ring.out, 122 * the buffer contains harvested entropy. 123 * If (ring.in + 1) == ring.out (mod RANDOM_RING_MAX), 124 * the buffer is full. 125 * 126 * NOTE: ring.in points to the last added element, 127 * and ring.out points to the last consumed element. 128 * 129 * The ring.in variable needs locking as there are multiple 130 * sources to the ring. Only the sources may change ring.in, 131 * but the consumer may examine it. 132 * 133 * The ring.out variable does not need locking as there is 134 * only one consumer. Only the consumer may change ring.out, 135 * but the sources may examine it. 136 */ 137 struct entropy_ring { 138 struct harvest_event ring[RANDOM_RING_MAX]; 139 volatile u_int in; 140 volatile u_int out; 141 } hc_entropy_ring; 142 struct fast_entropy_accumulator { 143 volatile u_int pos; 144 uint32_t buf[RANDOM_ACCUM_MAX]; 145 } hc_entropy_fast_accumulator; 146 } harvest_context; 147 148 static struct kproc_desc random_proc_kp = { 149 "rand_harvestq", 150 random_kthread, 151 &harvest_context.hc_kthread_proc, 152 }; 153 154 /* Pass the given event straight through to Fortuna/Whatever. */ 155 static __inline void 156 random_harvestq_fast_process_event(struct harvest_event *event) 157 { 158 #if defined(RANDOM_LOADABLE) 159 RANDOM_CONFIG_S_LOCK(); 160 if (p_random_alg_context) 161 #endif 162 p_random_alg_context->ra_event_processor(event); 163 #if defined(RANDOM_LOADABLE) 164 RANDOM_CONFIG_S_UNLOCK(); 165 #endif 166 } 167 168 static void 169 random_kthread(void) 170 { 171 u_int maxloop, ring_out, i; 172 173 /* 174 * Locking is not needed as this is the only place we modify ring.out, and 175 * we only examine ring.in without changing it. Both of these are volatile, 176 * and this is a unique thread. 177 */ 178 for (random_kthread_control = 1; random_kthread_control;) { 179 /* Deal with events, if any. Restrict the number we do in one go. */ 180 maxloop = RANDOM_RING_MAX; 181 while (harvest_context.hc_entropy_ring.out != harvest_context.hc_entropy_ring.in) { 182 ring_out = (harvest_context.hc_entropy_ring.out + 1)%RANDOM_RING_MAX; 183 random_harvestq_fast_process_event(harvest_context.hc_entropy_ring.ring + ring_out); 184 harvest_context.hc_entropy_ring.out = ring_out; 185 if (!--maxloop) 186 break; 187 } 188 random_sources_feed(); 189 /* XXX: FIX!! Increase the high-performance data rate? Need some measurements first. */ 190 for (i = 0; i < RANDOM_ACCUM_MAX; i++) { 191 if (harvest_context.hc_entropy_fast_accumulator.buf[i]) { 192 random_harvest_direct(harvest_context.hc_entropy_fast_accumulator.buf + i, sizeof(harvest_context.hc_entropy_fast_accumulator.buf[0]), RANDOM_UMA); 193 harvest_context.hc_entropy_fast_accumulator.buf[i] = 0; 194 } 195 } 196 /* XXX: FIX!! This is a *great* place to pass hardware/live entropy to random(9) */ 197 tsleep_sbt(&harvest_context.hc_kthread_proc, 0, "-", SBT_1S/10, 0, C_PREL(1)); 198 } 199 random_kthread_control = -1; 200 wakeup(&harvest_context.hc_kthread_proc); 201 kproc_exit(0); 202 /* NOTREACHED */ 203 } 204 /* This happens well after SI_SUB_RANDOM */ 205 SYSINIT(random_device_h_proc, SI_SUB_KICK_SCHEDULER, SI_ORDER_ANY, kproc_start, 206 &random_proc_kp); 207 208 /* 209 * Run through all fast sources reading entropy for the given 210 * number of rounds, which should be a multiple of the number 211 * of entropy accumulation pools in use; it is 32 for Fortuna. 212 */ 213 static void 214 random_sources_feed(void) 215 { 216 uint32_t entropy[HARVESTSIZE]; 217 struct random_sources *rrs; 218 u_int i, n, local_read_rate; 219 220 /* 221 * Step over all of live entropy sources, and feed their output 222 * to the system-wide RNG. 223 */ 224 #if defined(RANDOM_LOADABLE) 225 RANDOM_CONFIG_S_LOCK(); 226 if (p_random_alg_context) { 227 /* It's an indenting error. Yeah, Yeah. */ 228 #endif 229 local_read_rate = atomic_readandclear_32(&read_rate); 230 /* Perform at least one read per round */ 231 local_read_rate = MAX(local_read_rate, 1); 232 /* But not exceeding RANDOM_KEYSIZE_WORDS */ 233 local_read_rate = MIN(local_read_rate, RANDOM_KEYSIZE_WORDS); 234 LIST_FOREACH(rrs, &source_list, rrs_entries) { 235 for (i = 0; i < p_random_alg_context->ra_poolcount*local_read_rate; i++) { 236 n = rrs->rrs_source->rs_read(entropy, sizeof(entropy)); 237 KASSERT((n <= sizeof(entropy)), ("%s: rs_read returned too much data (%u > %zu)", __func__, n, sizeof(entropy))); 238 /* It would appear that in some circumstances (e.g. virtualisation), 239 * the underlying hardware entropy source might not always return 240 * random numbers. Accept this but make a noise. If too much happens, 241 * can that source be trusted? 242 */ 243 if (n == 0) { 244 printf("%s: rs_read for hardware device '%s' returned no entropy.\n", __func__, rrs->rrs_source->rs_ident); 245 continue; 246 } 247 random_harvest_direct(entropy, n, rrs->rrs_source->rs_source); 248 } 249 } 250 explicit_bzero(entropy, sizeof(entropy)); 251 #if defined(RANDOM_LOADABLE) 252 } 253 RANDOM_CONFIG_S_UNLOCK(); 254 #endif 255 } 256 257 void 258 read_rate_increment(u_int chunk) 259 { 260 261 atomic_add_32(&read_rate, chunk); 262 } 263 264 /* ARGSUSED */ 265 static int 266 random_check_uint_harvestmask(SYSCTL_HANDLER_ARGS) 267 { 268 static const u_int user_immutable_mask = 269 (((1 << ENTROPYSOURCE) - 1) & (-1UL << RANDOM_PURE_START)) | 270 _RANDOM_HARVEST_ETHER_OFF | _RANDOM_HARVEST_UMA_OFF; 271 272 int error; 273 u_int value, orig_value; 274 275 orig_value = value = hc_source_mask; 276 error = sysctl_handle_int(oidp, &value, 0, req); 277 if (error != 0 || req->newptr == NULL) 278 return (error); 279 280 if (flsl(value) > ENTROPYSOURCE) 281 return (EINVAL); 282 283 /* 284 * Disallow userspace modification of pure entropy sources. 285 */ 286 hc_source_mask = (value & ~user_immutable_mask) | 287 (orig_value & user_immutable_mask); 288 return (0); 289 } 290 291 /* ARGSUSED */ 292 static int 293 random_print_harvestmask(SYSCTL_HANDLER_ARGS) 294 { 295 struct sbuf sbuf; 296 int error, i; 297 298 error = sysctl_wire_old_buffer(req, 0); 299 if (error == 0) { 300 sbuf_new_for_sysctl(&sbuf, NULL, 128, req); 301 for (i = ENTROPYSOURCE - 1; i >= 0; i--) 302 sbuf_cat(&sbuf, (hc_source_mask & (1 << i)) ? "1" : "0"); 303 error = sbuf_finish(&sbuf); 304 sbuf_delete(&sbuf); 305 } 306 return (error); 307 } 308 309 static const char *random_source_descr[ENTROPYSOURCE] = { 310 [RANDOM_CACHED] = "CACHED", 311 [RANDOM_ATTACH] = "ATTACH", 312 [RANDOM_KEYBOARD] = "KEYBOARD", 313 [RANDOM_MOUSE] = "MOUSE", 314 [RANDOM_NET_TUN] = "NET_TUN", 315 [RANDOM_NET_ETHER] = "NET_ETHER", 316 [RANDOM_NET_NG] = "NET_NG", 317 [RANDOM_INTERRUPT] = "INTERRUPT", 318 [RANDOM_SWI] = "SWI", 319 [RANDOM_FS_ATIME] = "FS_ATIME", 320 [RANDOM_UMA] = "UMA", /* ENVIRONMENTAL_END */ 321 [RANDOM_PURE_OCTEON] = "PURE_OCTEON", /* PURE_START */ 322 [RANDOM_PURE_SAFE] = "PURE_SAFE", 323 [RANDOM_PURE_GLXSB] = "PURE_GLXSB", 324 [RANDOM_PURE_UBSEC] = "PURE_UBSEC", 325 [RANDOM_PURE_HIFN] = "PURE_HIFN", 326 [RANDOM_PURE_RDRAND] = "PURE_RDRAND", 327 [RANDOM_PURE_NEHEMIAH] = "PURE_NEHEMIAH", 328 [RANDOM_PURE_RNDTEST] = "PURE_RNDTEST", 329 [RANDOM_PURE_VIRTIO] = "PURE_VIRTIO", 330 [RANDOM_PURE_BROADCOM] = "PURE_BROADCOM", 331 [RANDOM_PURE_CCP] = "PURE_CCP", 332 [RANDOM_PURE_DARN] = "PURE_DARN", 333 [RANDOM_PURE_TPM] = "PURE_TPM", 334 /* "ENTROPYSOURCE" */ 335 }; 336 337 /* ARGSUSED */ 338 static int 339 random_print_harvestmask_symbolic(SYSCTL_HANDLER_ARGS) 340 { 341 struct sbuf sbuf; 342 int error, i; 343 bool first; 344 345 first = true; 346 error = sysctl_wire_old_buffer(req, 0); 347 if (error == 0) { 348 sbuf_new_for_sysctl(&sbuf, NULL, 128, req); 349 for (i = ENTROPYSOURCE - 1; i >= 0; i--) { 350 if (i >= RANDOM_PURE_START && 351 (hc_source_mask & (1 << i)) == 0) 352 continue; 353 if (!first) 354 sbuf_cat(&sbuf, ","); 355 sbuf_cat(&sbuf, !(hc_source_mask & (1 << i)) ? "[" : ""); 356 sbuf_cat(&sbuf, random_source_descr[i]); 357 sbuf_cat(&sbuf, !(hc_source_mask & (1 << i)) ? "]" : ""); 358 first = false; 359 } 360 error = sbuf_finish(&sbuf); 361 sbuf_delete(&sbuf); 362 } 363 return (error); 364 } 365 366 /* ARGSUSED */ 367 static void 368 random_harvestq_init(void *unused __unused) 369 { 370 static const u_int almost_everything_mask = 371 (((1 << (RANDOM_ENVIRONMENTAL_END + 1)) - 1) & 372 ~_RANDOM_HARVEST_ETHER_OFF & ~_RANDOM_HARVEST_UMA_OFF); 373 374 struct sysctl_oid *random_sys_o; 375 376 random_sys_o = SYSCTL_ADD_NODE(&random_clist, 377 SYSCTL_STATIC_CHILDREN(_kern_random), 378 OID_AUTO, "harvest", CTLFLAG_RW, 0, 379 "Entropy Device Parameters"); 380 hc_source_mask = almost_everything_mask; 381 SYSCTL_ADD_PROC(&random_clist, 382 SYSCTL_CHILDREN(random_sys_o), 383 OID_AUTO, "mask", CTLTYPE_UINT | CTLFLAG_RW, 384 NULL, 0, random_check_uint_harvestmask, "IU", 385 "Entropy harvesting mask"); 386 SYSCTL_ADD_PROC(&random_clist, 387 SYSCTL_CHILDREN(random_sys_o), 388 OID_AUTO, "mask_bin", CTLTYPE_STRING | CTLFLAG_RD, 389 NULL, 0, random_print_harvestmask, "A", "Entropy harvesting mask (printable)"); 390 SYSCTL_ADD_PROC(&random_clist, 391 SYSCTL_CHILDREN(random_sys_o), 392 OID_AUTO, "mask_symbolic", CTLTYPE_STRING | CTLFLAG_RD, 393 NULL, 0, random_print_harvestmask_symbolic, "A", "Entropy harvesting mask (symbolic)"); 394 RANDOM_HARVEST_INIT_LOCK(); 395 harvest_context.hc_entropy_ring.in = harvest_context.hc_entropy_ring.out = 0; 396 } 397 SYSINIT(random_device_h_init, SI_SUB_RANDOM, SI_ORDER_SECOND, random_harvestq_init, NULL); 398 399 /* 400 * This is used to prime the RNG by grabbing any early random stuff 401 * known to the kernel, and inserting it directly into the hashing 402 * module, currently Fortuna. 403 */ 404 /* ARGSUSED */ 405 static void 406 random_harvestq_prime(void *unused __unused) 407 { 408 struct harvest_event event; 409 size_t count, size, i; 410 uint8_t *keyfile, *data; 411 412 /* 413 * Get entropy that may have been preloaded by loader(8) 414 * and use it to pre-charge the entropy harvest queue. 415 */ 416 keyfile = preload_search_by_type(RANDOM_CACHED_BOOT_ENTROPY_MODULE); 417 #ifndef NO_BACKWARD_COMPATIBILITY 418 if (keyfile == NULL) 419 keyfile = preload_search_by_type(RANDOM_LEGACY_BOOT_ENTROPY_MODULE); 420 #endif 421 if (keyfile != NULL) { 422 data = preload_fetch_addr(keyfile); 423 size = preload_fetch_size(keyfile); 424 /* Trim the size. If the admin has a file with a funny size, we lose some. Tough. */ 425 size -= (size % sizeof(event.he_entropy)); 426 if (data != NULL && size != 0) { 427 for (i = 0; i < size; i += sizeof(event.he_entropy)) { 428 count = sizeof(event.he_entropy); 429 event.he_somecounter = (uint32_t)get_cyclecount(); 430 event.he_size = count; 431 event.he_source = RANDOM_CACHED; 432 event.he_destination = 433 harvest_context.hc_destination[RANDOM_CACHED]++; 434 memcpy(event.he_entropy, data + i, sizeof(event.he_entropy)); 435 random_harvestq_fast_process_event(&event); 436 explicit_bzero(&event, sizeof(event)); 437 } 438 explicit_bzero(data, size); 439 if (bootverbose) 440 printf("random: read %zu bytes from preloaded cache\n", size); 441 } else 442 if (bootverbose) 443 printf("random: no preloaded entropy cache\n"); 444 } 445 } 446 SYSINIT(random_device_prime, SI_SUB_RANDOM, SI_ORDER_FOURTH, random_harvestq_prime, NULL); 447 448 /* ARGSUSED */ 449 static void 450 random_harvestq_deinit(void *unused __unused) 451 { 452 453 /* Command the hash/reseed thread to end and wait for it to finish */ 454 random_kthread_control = 0; 455 while (random_kthread_control >= 0) 456 tsleep(&harvest_context.hc_kthread_proc, 0, "harvqterm", hz/5); 457 sysctl_ctx_free(&random_clist); 458 } 459 SYSUNINIT(random_device_h_init, SI_SUB_RANDOM, SI_ORDER_SECOND, random_harvestq_deinit, NULL); 460 461 /*- 462 * Entropy harvesting queue routine. 463 * 464 * This is supposed to be fast; do not do anything slow in here! 465 * It is also illegal (and morally reprehensible) to insert any 466 * high-rate data here. "High-rate" is defined as a data source 467 * that will usually cause lots of failures of the "Lockless read" 468 * check a few lines below. This includes the "always-on" sources 469 * like the Intel "rdrand" or the VIA Nehamiah "xstore" sources. 470 */ 471 /* XXXRW: get_cyclecount() is cheap on most modern hardware, where cycle 472 * counters are built in, but on older hardware it will do a real time clock 473 * read which can be quite expensive. 474 */ 475 void 476 random_harvest_queue_(const void *entropy, u_int size, enum random_entropy_source origin) 477 { 478 struct harvest_event *event; 479 u_int ring_in; 480 481 KASSERT(origin >= RANDOM_START && origin < ENTROPYSOURCE, ("%s: origin %d invalid\n", __func__, origin)); 482 RANDOM_HARVEST_LOCK(); 483 ring_in = (harvest_context.hc_entropy_ring.in + 1)%RANDOM_RING_MAX; 484 if (ring_in != harvest_context.hc_entropy_ring.out) { 485 /* The ring is not full */ 486 event = harvest_context.hc_entropy_ring.ring + ring_in; 487 event->he_somecounter = (uint32_t)get_cyclecount(); 488 event->he_source = origin; 489 event->he_destination = harvest_context.hc_destination[origin]++; 490 if (size <= sizeof(event->he_entropy)) { 491 event->he_size = size; 492 memcpy(event->he_entropy, entropy, size); 493 } 494 else { 495 /* Big event, so squash it */ 496 event->he_size = sizeof(event->he_entropy[0]); 497 event->he_entropy[0] = jenkins_hash(entropy, size, (uint32_t)(uintptr_t)event); 498 } 499 harvest_context.hc_entropy_ring.in = ring_in; 500 } 501 RANDOM_HARVEST_UNLOCK(); 502 } 503 504 /*- 505 * Entropy harvesting fast routine. 506 * 507 * This is supposed to be very fast; do not do anything slow in here! 508 * This is the right place for high-rate harvested data. 509 */ 510 void 511 random_harvest_fast_(const void *entropy, u_int size) 512 { 513 u_int pos; 514 515 pos = harvest_context.hc_entropy_fast_accumulator.pos; 516 harvest_context.hc_entropy_fast_accumulator.buf[pos] ^= jenkins_hash(entropy, size, (uint32_t)get_cyclecount()); 517 harvest_context.hc_entropy_fast_accumulator.pos = (pos + 1)%RANDOM_ACCUM_MAX; 518 } 519 520 /*- 521 * Entropy harvesting direct routine. 522 * 523 * This is not supposed to be fast, but will only be used during 524 * (e.g.) booting when initial entropy is being gathered. 525 */ 526 void 527 random_harvest_direct_(const void *entropy, u_int size, enum random_entropy_source origin) 528 { 529 struct harvest_event event; 530 531 KASSERT(origin >= RANDOM_START && origin < ENTROPYSOURCE, ("%s: origin %d invalid\n", __func__, origin)); 532 size = MIN(size, sizeof(event.he_entropy)); 533 event.he_somecounter = (uint32_t)get_cyclecount(); 534 event.he_size = size; 535 event.he_source = origin; 536 event.he_destination = harvest_context.hc_destination[origin]++; 537 memcpy(event.he_entropy, entropy, size); 538 random_harvestq_fast_process_event(&event); 539 explicit_bzero(&event, sizeof(event)); 540 } 541 542 void 543 random_harvest_register_source(enum random_entropy_source source) 544 { 545 546 hc_source_mask |= (1 << source); 547 } 548 549 void 550 random_harvest_deregister_source(enum random_entropy_source source) 551 { 552 553 hc_source_mask &= ~(1 << source); 554 } 555 556 MODULE_VERSION(random_harvestq, 1); 557