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