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