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