1/*-
2 * Copyright (c) 2000-2015 Mark R V Murray
3 * Copyright (c) 2013 Arthur Mesh
4 * Copyright (c) 2004 Robert N. M. Watson
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer
12 *    in this position and unchanged.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 */
29
30#include <sys/cdefs.h>
31__FBSDID("$FreeBSD: stable/11/sys/dev/random/random_harvestq.c 346725 2019-04-26 01:58:36Z mw $");
32
33#include <sys/param.h>
34#include <sys/systm.h>
35#include <sys/conf.h>
36#include <sys/eventhandler.h>
37#include <sys/hash.h>
38#include <sys/kernel.h>
39#include <sys/kthread.h>
40#include <sys/linker.h>
41#include <sys/lock.h>
42#include <sys/malloc.h>
43#include <sys/module.h>
44#include <sys/mutex.h>
45#include <sys/random.h>
46#include <sys/sbuf.h>
47#include <sys/sysctl.h>
48#include <sys/unistd.h>
49
50#if defined(RANDOM_LOADABLE)
51#include <sys/lock.h>
52#include <sys/sx.h>
53#endif
54
55#include <machine/atomic.h>
56#include <machine/cpu.h>
57
58#include <crypto/rijndael/rijndael-api-fst.h>
59#include <crypto/sha2/sha256.h>
60
61#include <dev/random/hash.h>
62#include <dev/random/randomdev.h>
63#include <dev/random/random_harvestq.h>
64
65static void random_kthread(void);
66static void random_sources_feed(void);
67
68static u_int read_rate;
69
70/* List for the dynamic sysctls */
71static struct sysctl_ctx_list random_clist;
72
73/*
74 * How many events to queue up. We create this many items in
75 * an 'empty' queue, then transfer them to the 'harvest' queue with
76 * supplied junk. When used, they are transferred back to the
77 * 'empty' queue.
78 */
79#define	RANDOM_RING_MAX		1024
80#define	RANDOM_ACCUM_MAX	8
81
82/* 1 to let the kernel thread run, 0 to terminate, -1 to mark completion */
83volatile int random_kthread_control;
84
85/*
86 * Put all the harvest queue context stuff in one place.
87 * this make is a bit easier to lock and protect.
88 */
89static struct harvest_context {
90	/* The harvest mutex protects all of harvest_context and
91	 * the related data.
92	 */
93	struct mtx hc_mtx;
94	/* Round-robin destination cache. */
95	u_int hc_destination[ENTROPYSOURCE];
96	/* The context of the kernel thread processing harvested entropy */
97	struct proc *hc_kthread_proc;
98	/* Allow the sysadmin to select the broad category of
99	 * entropy types to harvest.
100	 */
101	u_int hc_source_mask;
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
133static 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. */
140static __inline void
141random_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
153static void
154random_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 */
190SYSINIT(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 */
199static void
200random_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	/* Perform at least one read per round */
217	local_read_rate = MAX(local_read_rate, 1);
218	/* But not exceeding RANDOM_KEYSIZE_WORDS */
219	local_read_rate = MIN(local_read_rate, RANDOM_KEYSIZE_WORDS);
220	LIST_FOREACH(rrs, &source_list, rrs_entries) {
221		for (i = 0; i < p_random_alg_context->ra_poolcount*local_read_rate; i++) {
222			n = rrs->rrs_source->rs_read(entropy, sizeof(entropy));
223			KASSERT((n <= sizeof(entropy)), ("%s: rs_read returned too much data (%u > %zu)", __func__, n, sizeof(entropy)));
224			/* It would appear that in some circumstances (e.g. virtualisation),
225			 * the underlying hardware entropy source might not always return
226			 * random numbers. Accept this but make a noise. If too much happens,
227			 * can that source be trusted?
228			 */
229			if (n == 0) {
230				printf("%s: rs_read for hardware device '%s' returned no entropy.\n", __func__, rrs->rrs_source->rs_ident);
231				continue;
232			}
233			random_harvest_direct(entropy, n, (n*8)/2, rrs->rrs_source->rs_source);
234		}
235	}
236	explicit_bzero(entropy, sizeof(entropy));
237#if defined(RANDOM_LOADABLE)
238	}
239	RANDOM_CONFIG_S_UNLOCK();
240#endif
241}
242
243void
244read_rate_increment(u_int chunk)
245{
246
247	atomic_add_32(&read_rate, chunk);
248}
249
250/* ARGSUSED */
251RANDOM_CHECK_UINT(harvestmask, 0, RANDOM_HARVEST_EVERYTHING_MASK);
252
253/* ARGSUSED */
254static int
255random_print_harvestmask(SYSCTL_HANDLER_ARGS)
256{
257	struct sbuf sbuf;
258	int error, i;
259
260	error = sysctl_wire_old_buffer(req, 0);
261	if (error == 0) {
262		sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
263		for (i = RANDOM_ENVIRONMENTAL_END; i >= 0; i--)
264			sbuf_cat(&sbuf, (harvest_context.hc_source_mask & (1 << i)) ? "1" : "0");
265		error = sbuf_finish(&sbuf);
266		sbuf_delete(&sbuf);
267	}
268	return (error);
269}
270
271static const char *(random_source_descr[]) = {
272	"CACHED",
273	"ATTACH",
274	"KEYBOARD",
275	"MOUSE",
276	"NET_TUN",
277	"NET_ETHER",
278	"NET_NG",
279	"INTERRUPT",
280	"SWI",
281	"FS_ATIME",
282	"UMA", /* ENVIRONMENTAL_END */
283	"PURE_OCTEON",
284	"PURE_SAFE",
285	"PURE_GLXSB",
286	"PURE_UBSEC",
287	"PURE_HIFN",
288	"PURE_RDRAND",
289	"PURE_NEHEMIAH",
290	"PURE_RNDTEST",
291	[RANDOM_PURE_TPM] = "PURE_TPM",
292	/* "ENTROPYSOURCE" */
293};
294
295/* ARGSUSED */
296static int
297random_print_harvestmask_symbolic(SYSCTL_HANDLER_ARGS)
298{
299	struct sbuf sbuf;
300	int error, i;
301
302	error = sysctl_wire_old_buffer(req, 0);
303	if (error == 0) {
304		sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
305		for (i = RANDOM_ENVIRONMENTAL_END; i >= 0; i--) {
306			sbuf_cat(&sbuf, (i == RANDOM_ENVIRONMENTAL_END) ? "" : ",");
307			sbuf_cat(&sbuf, !(harvest_context.hc_source_mask & (1 << i)) ? "[" : "");
308			sbuf_cat(&sbuf, random_source_descr[i]);
309			sbuf_cat(&sbuf, !(harvest_context.hc_source_mask & (1 << i)) ? "]" : "");
310		}
311		error = sbuf_finish(&sbuf);
312		sbuf_delete(&sbuf);
313	}
314	return (error);
315}
316
317/* ARGSUSED */
318static void
319random_harvestq_init(void *unused __unused)
320{
321	struct sysctl_oid *random_sys_o;
322
323	random_sys_o = SYSCTL_ADD_NODE(&random_clist,
324	    SYSCTL_STATIC_CHILDREN(_kern_random),
325	    OID_AUTO, "harvest", CTLFLAG_RW, 0,
326	    "Entropy Device Parameters");
327	harvest_context.hc_source_mask = RANDOM_HARVEST_EVERYTHING_MASK;
328	SYSCTL_ADD_PROC(&random_clist,
329	    SYSCTL_CHILDREN(random_sys_o),
330	    OID_AUTO, "mask", CTLTYPE_UINT | CTLFLAG_RW,
331	    &harvest_context.hc_source_mask, 0,
332	    random_check_uint_harvestmask, "IU",
333	    "Entropy harvesting mask");
334	SYSCTL_ADD_PROC(&random_clist,
335	    SYSCTL_CHILDREN(random_sys_o),
336	    OID_AUTO, "mask_bin", CTLTYPE_STRING | CTLFLAG_RD,
337	    NULL, 0, random_print_harvestmask, "A", "Entropy harvesting mask (printable)");
338	SYSCTL_ADD_PROC(&random_clist,
339	    SYSCTL_CHILDREN(random_sys_o),
340	    OID_AUTO, "mask_symbolic", CTLTYPE_STRING | CTLFLAG_RD,
341	    NULL, 0, random_print_harvestmask_symbolic, "A", "Entropy harvesting mask (symbolic)");
342	RANDOM_HARVEST_INIT_LOCK();
343	harvest_context.hc_entropy_ring.in = harvest_context.hc_entropy_ring.out = 0;
344}
345SYSINIT(random_device_h_init, SI_SUB_RANDOM, SI_ORDER_SECOND, random_harvestq_init, NULL);
346
347/*
348 * This is used to prime the RNG by grabbing any early random stuff
349 * known to the kernel, and inserting it directly into the hashing
350 * module, e.g. Fortuna or Yarrow.
351 */
352/* ARGSUSED */
353static void
354random_harvestq_prime(void *unused __unused)
355{
356	struct harvest_event event;
357	size_t count, size, i;
358	uint8_t *keyfile, *data;
359
360	/*
361	 * Get entropy that may have been preloaded by loader(8)
362	 * and use it to pre-charge the entropy harvest queue.
363	 */
364	keyfile = preload_search_by_type(RANDOM_HARVESTQ_BOOT_ENTROPY_FILE);
365	if (keyfile != NULL) {
366		data = preload_fetch_addr(keyfile);
367		size = preload_fetch_size(keyfile);
368		/* Trim the size. If the admin has a file with a funny size, we lose some. Tough. */
369		size -= (size % sizeof(event.he_entropy));
370		if (data != NULL && size != 0) {
371			for (i = 0; i < size; i += sizeof(event.he_entropy)) {
372				count = sizeof(event.he_entropy);
373				event.he_somecounter = (uint32_t)get_cyclecount();
374				event.he_size = count;
375				event.he_bits = count/4; /* Underestimate the size for Yarrow */
376				event.he_source = RANDOM_CACHED;
377				event.he_destination = harvest_context.hc_destination[0]++;
378				memcpy(event.he_entropy, data + i, sizeof(event.he_entropy));
379				random_harvestq_fast_process_event(&event);
380				explicit_bzero(&event, sizeof(event));
381			}
382			explicit_bzero(data, size);
383			if (bootverbose)
384				printf("random: read %zu bytes from preloaded cache\n", size);
385		} else
386			if (bootverbose)
387				printf("random: no preloaded entropy cache\n");
388	}
389}
390SYSINIT(random_device_prime, SI_SUB_RANDOM, SI_ORDER_FOURTH, random_harvestq_prime, NULL);
391
392/* ARGSUSED */
393static void
394random_harvestq_deinit(void *unused __unused)
395{
396
397	/* Command the hash/reseed thread to end and wait for it to finish */
398	random_kthread_control = 0;
399	while (random_kthread_control >= 0)
400		tsleep(&harvest_context.hc_kthread_proc, 0, "harvqterm", hz/5);
401	sysctl_ctx_free(&random_clist);
402}
403SYSUNINIT(random_device_h_init, SI_SUB_RANDOM, SI_ORDER_SECOND, random_harvestq_deinit, NULL);
404
405/*-
406 * Entropy harvesting queue routine.
407 *
408 * This is supposed to be fast; do not do anything slow in here!
409 * It is also illegal (and morally reprehensible) to insert any
410 * high-rate data here. "High-rate" is defined as a data source
411 * that will usually cause lots of failures of the "Lockless read"
412 * check a few lines below. This includes the "always-on" sources
413 * like the Intel "rdrand" or the VIA Nehamiah "xstore" sources.
414 */
415/* XXXRW: get_cyclecount() is cheap on most modern hardware, where cycle
416 * counters are built in, but on older hardware it will do a real time clock
417 * read which can be quite expensive.
418 */
419void
420random_harvest_queue(const void *entropy, u_int size, u_int bits, enum random_entropy_source origin)
421{
422	struct harvest_event *event;
423	u_int ring_in;
424
425	KASSERT(origin >= RANDOM_START && origin < ENTROPYSOURCE, ("%s: origin %d invalid\n", __func__, origin));
426	if (!(harvest_context.hc_source_mask & (1 << origin)))
427		return;
428	RANDOM_HARVEST_LOCK();
429	ring_in = (harvest_context.hc_entropy_ring.in + 1)%RANDOM_RING_MAX;
430	if (ring_in != harvest_context.hc_entropy_ring.out) {
431		/* The ring is not full */
432		event = harvest_context.hc_entropy_ring.ring + ring_in;
433		event->he_somecounter = (uint32_t)get_cyclecount();
434		event->he_source = origin;
435		event->he_destination = harvest_context.hc_destination[origin]++;
436		event->he_bits = bits;
437		if (size <= sizeof(event->he_entropy)) {
438			event->he_size = size;
439			memcpy(event->he_entropy, entropy, size);
440		}
441		else {
442			/* Big event, so squash it */
443			event->he_size = sizeof(event->he_entropy[0]);
444			event->he_entropy[0] = jenkins_hash(entropy, size, (uint32_t)(uintptr_t)event);
445		}
446		harvest_context.hc_entropy_ring.in = ring_in;
447	}
448	RANDOM_HARVEST_UNLOCK();
449}
450
451/*-
452 * Entropy harvesting fast routine.
453 *
454 * This is supposed to be very fast; do not do anything slow in here!
455 * This is the right place for high-rate harvested data.
456 */
457void
458random_harvest_fast(const void *entropy, u_int size, u_int bits, enum random_entropy_source origin)
459{
460	u_int pos;
461
462	KASSERT(origin >= RANDOM_START && origin < ENTROPYSOURCE, ("%s: origin %d invalid\n", __func__, origin));
463	/* XXX: FIX!! The above KASSERT is BS. Right now we ignore most structure and just accumulate the supplied data */
464	if (!(harvest_context.hc_source_mask & (1 << origin)))
465		return;
466	pos = harvest_context.hc_entropy_fast_accumulator.pos;
467	harvest_context.hc_entropy_fast_accumulator.buf[pos] ^= jenkins_hash(entropy, size, (uint32_t)get_cyclecount());
468	harvest_context.hc_entropy_fast_accumulator.pos = (pos + 1)%RANDOM_ACCUM_MAX;
469}
470
471/*-
472 * Entropy harvesting direct routine.
473 *
474 * This is not supposed to be fast, but will only be used during
475 * (e.g.) booting when initial entropy is being gathered.
476 */
477void
478random_harvest_direct(const void *entropy, u_int size, u_int bits, enum random_entropy_source origin)
479{
480	struct harvest_event event;
481
482	KASSERT(origin >= RANDOM_START && origin < ENTROPYSOURCE, ("%s: origin %d invalid\n", __func__, origin));
483	if (!(harvest_context.hc_source_mask & (1 << origin)))
484		return;
485	size = MIN(size, sizeof(event.he_entropy));
486	event.he_somecounter = (uint32_t)get_cyclecount();
487	event.he_size = size;
488	event.he_bits = bits;
489	event.he_source = origin;
490	event.he_destination = harvest_context.hc_destination[origin]++;
491	memcpy(event.he_entropy, entropy, size);
492	random_harvestq_fast_process_event(&event);
493	explicit_bzero(&event, sizeof(event));
494}
495
496MODULE_VERSION(random_harvestq, 1);
497