1 /*- 2 * Copyright (c) 2017 Oliver Pinter 3 * Copyright (c) 2000-2015 Mark R V Murray 4 * All rights reserved. 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, this list of conditions and the following disclaimer 11 * in this position and unchanged. 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 * 16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 19 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 * 27 */ 28 29 #include <sys/cdefs.h> 30 __FBSDID("$FreeBSD$"); 31 32 #include <sys/param.h> 33 #include <sys/systm.h> 34 #include <sys/bus.h> 35 #include <sys/conf.h> 36 #include <sys/fcntl.h> 37 #include <sys/filio.h> 38 #include <sys/kernel.h> 39 #include <sys/kthread.h> 40 #include <sys/lock.h> 41 #include <sys/module.h> 42 #include <sys/malloc.h> 43 #include <sys/poll.h> 44 #include <sys/proc.h> 45 #include <sys/random.h> 46 #include <sys/sbuf.h> 47 #include <sys/selinfo.h> 48 #include <sys/sysctl.h> 49 #include <sys/systm.h> 50 #include <sys/uio.h> 51 #include <sys/unistd.h> 52 53 #include <crypto/rijndael/rijndael-api-fst.h> 54 #include <crypto/sha2/sha256.h> 55 56 #include <dev/random/hash.h> 57 #include <dev/random/randomdev.h> 58 #include <dev/random/random_harvestq.h> 59 60 #define RANDOM_UNIT 0 61 62 #if defined(RANDOM_LOADABLE) 63 #define READ_RANDOM_UIO _read_random_uio 64 #define READ_RANDOM _read_random 65 #define IS_RANDOM_SEEDED _is_random_seeded 66 static int READ_RANDOM_UIO(struct uio *, bool); 67 static void READ_RANDOM(void *, u_int); 68 static bool IS_RANDOM_SEEDED(void); 69 #else 70 #define READ_RANDOM_UIO read_random_uio 71 #define READ_RANDOM read_random 72 #define IS_RANDOM_SEEDED is_random_seeded 73 #endif 74 75 static d_read_t randomdev_read; 76 static d_write_t randomdev_write; 77 static d_poll_t randomdev_poll; 78 static d_ioctl_t randomdev_ioctl; 79 80 static struct cdevsw random_cdevsw = { 81 .d_name = "random", 82 .d_version = D_VERSION, 83 .d_read = randomdev_read, 84 .d_write = randomdev_write, 85 .d_poll = randomdev_poll, 86 .d_ioctl = randomdev_ioctl, 87 }; 88 89 /* For use with make_dev(9)/destroy_dev(9). */ 90 static struct cdev *random_dev; 91 92 static void 93 random_alg_context_ra_init_alg(void *data) 94 { 95 96 p_random_alg_context = &random_alg_context; 97 p_random_alg_context->ra_init_alg(data); 98 #if defined(RANDOM_LOADABLE) 99 random_infra_init(READ_RANDOM_UIO, READ_RANDOM, IS_RANDOM_SEEDED); 100 #endif 101 } 102 103 static void 104 random_alg_context_ra_deinit_alg(void *data) 105 { 106 107 #if defined(RANDOM_LOADABLE) 108 random_infra_uninit(); 109 #endif 110 p_random_alg_context->ra_deinit_alg(data); 111 p_random_alg_context = NULL; 112 } 113 114 SYSINIT(random_device, SI_SUB_RANDOM, SI_ORDER_THIRD, random_alg_context_ra_init_alg, NULL); 115 SYSUNINIT(random_device, SI_SUB_RANDOM, SI_ORDER_THIRD, random_alg_context_ra_deinit_alg, NULL); 116 117 static struct selinfo rsel; 118 119 /* 120 * This is the read uio(9) interface for random(4). 121 */ 122 /* ARGSUSED */ 123 static int 124 randomdev_read(struct cdev *dev __unused, struct uio *uio, int flags) 125 { 126 127 return (READ_RANDOM_UIO(uio, (flags & O_NONBLOCK) != 0)); 128 } 129 130 /* 131 * If the random device is not seeded, blocks until it is seeded. 132 * 133 * Returns zero when the random device is seeded. 134 * 135 * If the 'interruptible' parameter is true, and the device is unseeded, this 136 * routine may be interrupted. If interrupted, it will return either ERESTART 137 * or EINTR. 138 */ 139 #define SEEDWAIT_INTERRUPTIBLE true 140 #define SEEDWAIT_UNINTERRUPTIBLE false 141 static int 142 randomdev_wait_until_seeded(bool interruptible) 143 { 144 int error, spamcount, slpflags; 145 146 slpflags = interruptible ? PCATCH : 0; 147 148 error = 0; 149 spamcount = 0; 150 while (!p_random_alg_context->ra_seeded()) { 151 /* keep tapping away at the pre-read until we seed/unblock. */ 152 p_random_alg_context->ra_pre_read(); 153 /* Only bother the console every 10 seconds or so */ 154 if (spamcount == 0) 155 printf("random: %s unblock wait\n", __func__); 156 spamcount = (spamcount + 1) % 100; 157 error = tsleep(&random_alg_context, slpflags, "randseed", 158 hz / 10); 159 if (error == ERESTART || error == EINTR) { 160 KASSERT(interruptible, 161 ("unexpected wake of non-interruptible sleep")); 162 break; 163 } 164 /* Squash tsleep timeout condition */ 165 if (error == EWOULDBLOCK) 166 error = 0; 167 KASSERT(error == 0, ("unexpected tsleep error %d", error)); 168 } 169 return (error); 170 } 171 172 int 173 READ_RANDOM_UIO(struct uio *uio, bool nonblock) 174 { 175 uint8_t *random_buf; 176 int error; 177 ssize_t read_len, total_read, c; 178 /* 16 MiB takes about 0.08 s CPU time on my 2017 AMD Zen CPU */ 179 #define SIGCHK_PERIOD (16 * 1024 * 1024) 180 const size_t sigchk_period = SIGCHK_PERIOD; 181 182 CTASSERT(SIGCHK_PERIOD % PAGE_SIZE == 0); 183 #undef SIGCHK_PERIOD 184 185 random_buf = malloc(PAGE_SIZE, M_ENTROPY, M_WAITOK); 186 p_random_alg_context->ra_pre_read(); 187 error = 0; 188 /* (Un)Blocking logic */ 189 if (!p_random_alg_context->ra_seeded()) { 190 if (nonblock) 191 error = EWOULDBLOCK; 192 else 193 error = randomdev_wait_until_seeded( 194 SEEDWAIT_INTERRUPTIBLE); 195 } 196 if (error == 0) { 197 read_rate_increment((uio->uio_resid + sizeof(uint32_t))/sizeof(uint32_t)); 198 total_read = 0; 199 while (uio->uio_resid && !error) { 200 read_len = uio->uio_resid; 201 /* 202 * Belt-and-braces. 203 * Round up the read length to a crypto block size multiple, 204 * which is what the underlying generator is expecting. 205 * See the random_buf size requirements in the Fortuna code. 206 */ 207 read_len = roundup(read_len, RANDOM_BLOCKSIZE); 208 /* Work in chunks page-sized or less */ 209 read_len = MIN(read_len, PAGE_SIZE); 210 p_random_alg_context->ra_read(random_buf, read_len); 211 c = MIN(uio->uio_resid, read_len); 212 /* 213 * uiomove() may yield the CPU before each 'c' bytes 214 * (up to PAGE_SIZE) are copied out. 215 */ 216 error = uiomove(random_buf, c, uio); 217 total_read += c; 218 /* 219 * Poll for signals every few MBs to avoid very long 220 * uninterruptible syscalls. 221 */ 222 if (error == 0 && uio->uio_resid != 0 && 223 total_read % sigchk_period == 0) { 224 error = tsleep_sbt(&random_alg_context, PCATCH, 225 "randrd", SBT_1NS, 0, C_HARDCLOCK); 226 /* Squash tsleep timeout condition */ 227 if (error == EWOULDBLOCK) 228 error = 0; 229 } 230 } 231 if (error == ERESTART || error == EINTR) 232 error = 0; 233 } 234 free(random_buf, M_ENTROPY); 235 return (error); 236 } 237 238 /*- 239 * Kernel API version of read_random(). 240 * This is similar to random_alg_read(), 241 * except it doesn't interface with uio(9). 242 * It cannot assumed that random_buf is a multiple of 243 * RANDOM_BLOCKSIZE bytes. 244 */ 245 void 246 READ_RANDOM(void *random_buf, u_int len) 247 { 248 u_int read_directly_len; 249 250 KASSERT(random_buf != NULL, ("No suitable random buffer in %s", __func__)); 251 p_random_alg_context->ra_pre_read(); 252 /* (Un)Blocking logic */ 253 if (!p_random_alg_context->ra_seeded()) 254 (void)randomdev_wait_until_seeded(SEEDWAIT_UNINTERRUPTIBLE); 255 read_rate_increment(roundup2(len, sizeof(uint32_t))); 256 if (len == 0) 257 return; 258 /* 259 * The underlying generator expects multiples of 260 * RANDOM_BLOCKSIZE. 261 */ 262 read_directly_len = rounddown(len, RANDOM_BLOCKSIZE); 263 if (read_directly_len > 0) 264 p_random_alg_context->ra_read(random_buf, read_directly_len); 265 if (read_directly_len < len) { 266 uint8_t remainder_buf[RANDOM_BLOCKSIZE]; 267 268 p_random_alg_context->ra_read(remainder_buf, 269 sizeof(remainder_buf)); 270 memcpy((char *)random_buf + read_directly_len, remainder_buf, 271 len - read_directly_len); 272 273 explicit_bzero(remainder_buf, sizeof(remainder_buf)); 274 } 275 } 276 277 bool 278 IS_RANDOM_SEEDED(void) 279 { 280 return (p_random_alg_context->ra_seeded()); 281 } 282 283 static __inline void 284 randomdev_accumulate(uint8_t *buf, u_int count) 285 { 286 static u_int destination = 0; 287 static struct harvest_event event; 288 static struct randomdev_hash hash; 289 static uint32_t entropy_data[RANDOM_KEYSIZE_WORDS]; 290 uint32_t timestamp; 291 int i; 292 293 /* Extra timing here is helpful to scrape scheduler jitter entropy */ 294 randomdev_hash_init(&hash); 295 timestamp = (uint32_t)get_cyclecount(); 296 randomdev_hash_iterate(&hash, ×tamp, sizeof(timestamp)); 297 randomdev_hash_iterate(&hash, buf, count); 298 timestamp = (uint32_t)get_cyclecount(); 299 randomdev_hash_iterate(&hash, ×tamp, sizeof(timestamp)); 300 randomdev_hash_finish(&hash, entropy_data); 301 explicit_bzero(&hash, sizeof(hash)); 302 for (i = 0; i < RANDOM_KEYSIZE_WORDS; i += sizeof(event.he_entropy)/sizeof(event.he_entropy[0])) { 303 event.he_somecounter = (uint32_t)get_cyclecount(); 304 event.he_size = sizeof(event.he_entropy); 305 event.he_source = RANDOM_CACHED; 306 event.he_destination = destination++; /* Harmless cheating */ 307 memcpy(event.he_entropy, entropy_data + i, sizeof(event.he_entropy)); 308 p_random_alg_context->ra_event_processor(&event); 309 } 310 explicit_bzero(entropy_data, sizeof(entropy_data)); 311 } 312 313 /* ARGSUSED */ 314 static int 315 randomdev_write(struct cdev *dev __unused, struct uio *uio, int flags __unused) 316 { 317 uint8_t *random_buf; 318 int c, error = 0; 319 ssize_t nbytes; 320 321 random_buf = malloc(PAGE_SIZE, M_ENTROPY, M_WAITOK); 322 nbytes = uio->uio_resid; 323 while (uio->uio_resid > 0 && error == 0) { 324 c = MIN(uio->uio_resid, PAGE_SIZE); 325 error = uiomove(random_buf, c, uio); 326 if (error) 327 break; 328 randomdev_accumulate(random_buf, c); 329 tsleep(&random_alg_context, 0, "randwr", hz/10); 330 } 331 if (nbytes != uio->uio_resid && (error == ERESTART || error == EINTR)) 332 /* Partial write, not error. */ 333 error = 0; 334 free(random_buf, M_ENTROPY); 335 return (error); 336 } 337 338 /* ARGSUSED */ 339 static int 340 randomdev_poll(struct cdev *dev __unused, int events, struct thread *td __unused) 341 { 342 343 if (events & (POLLIN | POLLRDNORM)) { 344 if (p_random_alg_context->ra_seeded()) 345 events &= (POLLIN | POLLRDNORM); 346 else 347 selrecord(td, &rsel); 348 } 349 return (events); 350 } 351 352 /* This will be called by the entropy processor when it seeds itself and becomes secure */ 353 void 354 randomdev_unblock(void) 355 { 356 357 selwakeuppri(&rsel, PUSER); 358 wakeup(&random_alg_context); 359 printf("random: unblocking device.\n"); 360 /* Do random(9) a favour while we are about it. */ 361 (void)atomic_cmpset_int(&arc4rand_iniseed_state, ARC4_ENTR_NONE, ARC4_ENTR_HAVE); 362 } 363 364 /* ARGSUSED */ 365 static int 366 randomdev_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t addr __unused, 367 int flags __unused, struct thread *td __unused) 368 { 369 int error = 0; 370 371 switch (cmd) { 372 /* Really handled in upper layer */ 373 case FIOASYNC: 374 case FIONBIO: 375 break; 376 default: 377 error = ENOTTY; 378 } 379 380 return (error); 381 } 382 383 void 384 random_source_register(struct random_source *rsource) 385 { 386 struct random_sources *rrs; 387 388 KASSERT(rsource != NULL, ("invalid input to %s", __func__)); 389 390 rrs = malloc(sizeof(*rrs), M_ENTROPY, M_WAITOK); 391 rrs->rrs_source = rsource; 392 393 random_harvest_register_source(rsource->rs_source); 394 395 printf("random: registering fast source %s\n", rsource->rs_ident); 396 LIST_INSERT_HEAD(&source_list, rrs, rrs_entries); 397 } 398 399 void 400 random_source_deregister(struct random_source *rsource) 401 { 402 struct random_sources *rrs = NULL; 403 404 KASSERT(rsource != NULL, ("invalid input to %s", __func__)); 405 406 random_harvest_deregister_source(rsource->rs_source); 407 408 LIST_FOREACH(rrs, &source_list, rrs_entries) 409 if (rrs->rrs_source == rsource) { 410 LIST_REMOVE(rrs, rrs_entries); 411 break; 412 } 413 if (rrs != NULL) 414 free(rrs, M_ENTROPY); 415 } 416 417 static int 418 random_source_handler(SYSCTL_HANDLER_ARGS) 419 { 420 struct random_sources *rrs; 421 struct sbuf sbuf; 422 int error, count; 423 424 sbuf_new_for_sysctl(&sbuf, NULL, 64, req); 425 count = 0; 426 LIST_FOREACH(rrs, &source_list, rrs_entries) { 427 sbuf_cat(&sbuf, (count++ ? ",'" : "'")); 428 sbuf_cat(&sbuf, rrs->rrs_source->rs_ident); 429 sbuf_cat(&sbuf, "'"); 430 } 431 error = sbuf_finish(&sbuf); 432 sbuf_delete(&sbuf); 433 return (error); 434 } 435 SYSCTL_PROC(_kern_random, OID_AUTO, random_sources, CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, 436 NULL, 0, random_source_handler, "A", 437 "List of active fast entropy sources."); 438 439 /* ARGSUSED */ 440 static int 441 randomdev_modevent(module_t mod __unused, int type, void *data __unused) 442 { 443 int error = 0; 444 445 switch (type) { 446 case MOD_LOAD: 447 printf("random: entropy device external interface\n"); 448 random_dev = make_dev_credf(MAKEDEV_ETERNAL_KLD, &random_cdevsw, 449 RANDOM_UNIT, NULL, UID_ROOT, GID_WHEEL, 0644, "random"); 450 make_dev_alias(random_dev, "urandom"); /* compatibility */ 451 break; 452 case MOD_UNLOAD: 453 destroy_dev(random_dev); 454 break; 455 case MOD_SHUTDOWN: 456 break; 457 default: 458 error = EOPNOTSUPP; 459 break; 460 } 461 return (error); 462 } 463 464 static moduledata_t randomdev_mod = { 465 "random_device", 466 randomdev_modevent, 467 0 468 }; 469 470 DECLARE_MODULE(random_device, randomdev_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST); 471 MODULE_VERSION(random_device, 1); 472 MODULE_DEPEND(random_device, crypto, 1, 1, 1); 473 MODULE_DEPEND(random_device, random_harvestq, 1, 1, 1); 474