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