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