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