xref: /freebsd/sys/dev/random/randomdev.c (revision 3d9368b2d03926ad079a2eb910f1a423df925dd5)
1 /*-
2  * Copyright (c) 2000, 2001, 2002, 2003 Mark R V Murray
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer
10  *    in this position and unchanged.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  *
26  */
27 
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30 
31 #include <sys/param.h>
32 #include <sys/systm.h>
33 #include <sys/bus.h>
34 #include <sys/conf.h>
35 #include <sys/fcntl.h>
36 #include <sys/filio.h>
37 #include <sys/kernel.h>
38 #include <sys/kthread.h>
39 #include <sys/lock.h>
40 #include <sys/malloc.h>
41 #include <sys/mutex.h>
42 #include <sys/poll.h>
43 #include <sys/proc.h>
44 #include <sys/random.h>
45 #include <sys/selinfo.h>
46 #include <sys/sysctl.h>
47 #include <sys/uio.h>
48 #include <sys/unistd.h>
49 #include <sys/vnode.h>
50 
51 #include <machine/bus.h>
52 #include <machine/cpu.h>
53 
54 #include <dev/random/randomdev.h>
55 
56 static d_close_t	random_close;
57 static d_read_t		random_read;
58 static d_write_t	random_write;
59 static d_ioctl_t	random_ioctl;
60 static d_poll_t		random_poll;
61 
62 #define RANDOM_MINOR	0
63 
64 #define RANDOM_FIFO_MAX	256	/* How many events to queue up */
65 
66 static struct cdevsw random_cdevsw = {
67 	.d_close =	random_close,
68 	.d_read =	random_read,
69 	.d_write =	random_write,
70 	.d_ioctl =	random_ioctl,
71 	.d_poll =	random_poll,
72 	.d_name =	"random",
73 };
74 
75 static void random_kthread(void *);
76 static void random_harvest_internal(u_int64_t, void *, u_int, u_int, u_int, enum esource);
77 static void random_write_internal(void *, int);
78 
79 MALLOC_DEFINE(M_ENTROPY, "entropy", "Entropy harvesting buffers");
80 
81 /* Lockable FIFO queue holding entropy buffers */
82 struct entropyfifo {
83 	struct mtx lock;
84 	int count;
85 	STAILQ_HEAD(harvestlist, harvest) head;
86 };
87 
88 /* Empty entropy buffers */
89 static struct entropyfifo emptyfifo;
90 #define EMPTYBUFFERS	1024
91 
92 /* Harvested entropy */
93 static struct entropyfifo harvestfifo[ENTROPYSOURCE];
94 
95 static struct random_systat {
96 	u_int		seeded;	/* 0 causes blocking 1 allows normal output */
97 	struct selinfo	rsel;	/* For poll(2) */
98 } random_systat;
99 
100 /* <0 to end the kthread, 0 to let it run */
101 static int random_kthread_control = 0;
102 
103 static struct proc *random_kthread_proc;
104 
105 /* For use with make_dev(9)/destroy_dev(9). */
106 static dev_t	random_dev;
107 static dev_t	urandom_dev;
108 
109 /* ARGSUSED */
110 static int
111 random_check_boolean(SYSCTL_HANDLER_ARGS)
112 {
113 	if (oidp->oid_arg1 != NULL && *(u_int *)(oidp->oid_arg1) != 0)
114 		*(u_int *)(oidp->oid_arg1) = 1;
115         return sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
116 }
117 
118 SYSCTL_NODE(_kern, OID_AUTO, random, CTLFLAG_RW,
119 	0, "Random Number Generator");
120 SYSCTL_NODE(_kern_random, OID_AUTO, sys, CTLFLAG_RW,
121 	0, "Entropy Device Parameters");
122 SYSCTL_PROC(_kern_random_sys, OID_AUTO, seeded,
123 	CTLTYPE_INT|CTLFLAG_RW, &random_systat.seeded, 1,
124 	random_check_boolean, "I", "Seeded State");
125 SYSCTL_NODE(_kern_random_sys, OID_AUTO, harvest, CTLFLAG_RW,
126 	0, "Entropy Sources");
127 SYSCTL_PROC(_kern_random_sys_harvest, OID_AUTO, ethernet,
128 	CTLTYPE_INT|CTLFLAG_RW, &harvest.ethernet, 0,
129 	random_check_boolean, "I", "Harvest NIC entropy");
130 SYSCTL_PROC(_kern_random_sys_harvest, OID_AUTO, point_to_point,
131 	CTLTYPE_INT|CTLFLAG_RW, &harvest.point_to_point, 0,
132 	random_check_boolean, "I", "Harvest serial net entropy");
133 SYSCTL_PROC(_kern_random_sys_harvest, OID_AUTO, interrupt,
134 	CTLTYPE_INT|CTLFLAG_RW, &harvest.interrupt, 0,
135 	random_check_boolean, "I", "Harvest IRQ entropy");
136 SYSCTL_PROC(_kern_random_sys_harvest, OID_AUTO, swi,
137 	CTLTYPE_INT|CTLFLAG_RW, &harvest.swi, 0,
138 	random_check_boolean, "I", "Harvest SWI entropy");
139 
140 /* ARGSUSED */
141 static int
142 random_close(dev_t dev __unused, int flags, int fmt __unused, struct thread *td)
143 {
144 	if (flags & FWRITE) {
145 		if (suser(td) == 0 && securelevel_gt(td->td_ucred, 0) == 0)
146 			random_reseed();
147 	}
148 	return 0;
149 }
150 
151 /* ARGSUSED */
152 static int
153 random_read(dev_t dev __unused, struct uio *uio, int flag)
154 {
155 	int	c, ret;
156 	int	error = 0;
157 	void	*random_buf;
158 
159 	while (!random_systat.seeded) {
160 		if (flag & IO_NDELAY)
161 			error =  EWOULDBLOCK;
162 		else
163 			error = tsleep(&random_systat, PUSER|PCATCH,
164 				"block", 0);
165 		if (error != 0)
166 			return error;
167 	}
168 	c = uio->uio_resid < PAGE_SIZE ? uio->uio_resid : PAGE_SIZE;
169 	random_buf = (void *)malloc((u_long)c, M_TEMP, M_WAITOK);
170 	while (uio->uio_resid > 0 && error == 0) {
171 		ret = read_random_real(random_buf, c);
172 		error = uiomove(random_buf, ret, uio);
173 	}
174 	free(random_buf, M_TEMP);
175 	return error;
176 }
177 
178 /* ARGSUSED */
179 static int
180 random_write(dev_t dev __unused, struct uio *uio, int flag __unused)
181 {
182 	int	c;
183 	int	error;
184 	void	*random_buf;
185 
186 	error = 0;
187 	random_buf = (void *)malloc(PAGE_SIZE, M_TEMP, M_WAITOK);
188 	while (uio->uio_resid > 0) {
189 		c = (int)(uio->uio_resid < PAGE_SIZE
190 		    ? uio->uio_resid
191 		    : PAGE_SIZE);
192 		error = uiomove(random_buf, c, uio);
193 		if (error)
194 			break;
195 		random_write_internal(random_buf, c);
196 	}
197 	free(random_buf, M_TEMP);
198 	return error;
199 }
200 
201 /* ARGSUSED */
202 static int
203 random_ioctl(dev_t dev __unused, u_long cmd, caddr_t addr __unused,
204     int flags __unused, struct thread *td __unused)
205 {
206 	switch (cmd) {
207 	/* Really handled in upper layer */
208 	case FIOASYNC:
209 	case FIONBIO:
210 		return 0;
211 	default:
212 		return ENOTTY;
213 	}
214 }
215 
216 /* ARGSUSED */
217 static int
218 random_poll(dev_t dev __unused, int events, struct thread *td)
219 {
220 	int	revents;
221 
222 	revents = 0;
223 	if (events & (POLLIN | POLLRDNORM)) {
224 		if (random_systat.seeded)
225 			revents = events & (POLLIN | POLLRDNORM);
226 		else
227 			selrecord(td, &random_systat.rsel);
228 	}
229 	return revents;
230 }
231 
232 /* ARGSUSED */
233 static int
234 random_modevent(module_t mod __unused, int type, void *data __unused)
235 {
236 	int	error, i;
237 	struct harvest *np;
238 
239 	switch(type) {
240 	case MOD_LOAD:
241 		random_init();
242 
243 		/* This can be turned off by the very paranoid
244 		 * a reseed will turn it back on.
245 		 */
246 		random_systat.seeded = 1;
247 
248 		/* Initialise the harvest fifos */
249 		STAILQ_INIT(&emptyfifo.head);
250 		emptyfifo.count = 0;
251 		mtx_init(&emptyfifo.lock, "entropy harvest buffers", NULL,
252 			MTX_SPIN);
253 		for (i = 0; i < EMPTYBUFFERS; i++) {
254 			np = malloc(sizeof(struct harvest), M_ENTROPY,
255 				M_WAITOK);
256 			STAILQ_INSERT_TAIL(&emptyfifo.head, np, next);
257 		}
258 		for (i = 0; i < ENTROPYSOURCE; i++) {
259 			STAILQ_INIT(&harvestfifo[i].head);
260 			harvestfifo[i].count = 0;
261 			mtx_init(&harvestfifo[i].lock, "entropy harvest", NULL,
262 				MTX_SPIN);
263 		}
264 
265 		if (bootverbose)
266 			printf("random: <entropy source>\n");
267 		random_dev = make_dev(&random_cdevsw, RANDOM_MINOR, UID_ROOT,
268 			GID_WHEEL, 0666, "random");
269 		urandom_dev = make_dev_alias(random_dev, "urandom");
270 
271 		/* Start the hash/reseed thread */
272 		error = kthread_create(random_kthread, NULL,
273 			&random_kthread_proc, RFHIGHPID, 0, "random");
274 		if (error != 0)
275 			return error;
276 
277 		/* Register the randomness harvesting routine */
278 		random_init_harvester(random_harvest_internal,
279 			read_random_real);
280 
281 		return 0;
282 
283 	case MOD_UNLOAD:
284 		/* Deregister the randomness harvesting routine */
285 		random_deinit_harvester();
286 
287 		/* Command the hash/reseed thread to end and
288 		 * wait for it to finish
289 		 */
290 		random_kthread_control = -1;
291 		tsleep((void *)&random_kthread_control, PUSER, "term", 0);
292 
293 		/* Destroy the harvest fifos */
294 		while (!STAILQ_EMPTY(&emptyfifo.head)) {
295 			np = STAILQ_FIRST(&emptyfifo.head);
296 			STAILQ_REMOVE_HEAD(&emptyfifo.head, next);
297 			free(np, M_ENTROPY);
298 		}
299 		mtx_destroy(&emptyfifo.lock);
300 		for (i = 0; i < ENTROPYSOURCE; i++) {
301 			while (!STAILQ_EMPTY(&harvestfifo[i].head)) {
302 				np = STAILQ_FIRST(&harvestfifo[i].head);
303 				STAILQ_REMOVE_HEAD(&harvestfifo[i].head, next);
304 				free(np, M_ENTROPY);
305 			}
306 			mtx_destroy(&harvestfifo[i].lock);
307 		}
308 
309 		random_deinit();
310 
311 		destroy_dev(random_dev);
312 		destroy_dev(urandom_dev);
313 		return 0;
314 
315 	case MOD_SHUTDOWN:
316 		return 0;
317 
318 	default:
319 		return EOPNOTSUPP;
320 	}
321 }
322 
323 DEV_MODULE(random, random_modevent, NULL);
324 
325 /* ARGSUSED */
326 static void
327 random_kthread(void *arg __unused)
328 {
329 	struct harvest	*event = NULL;
330 	int		found, active;
331 	enum esource	source;
332 
333 	/* Process until told to stop */
334 	for (; random_kthread_control == 0;) {
335 
336 		active = 0;
337 
338 		/* Cycle through all the entropy sources */
339 		for (source = 0; source < ENTROPYSOURCE; source++) {
340 
341 			found = 0;
342 
343 			/* Lock up queue draining */
344 			mtx_lock_spin(&harvestfifo[source].lock);
345 
346 			if (!STAILQ_EMPTY(&harvestfifo[source].head)) {
347 
348 				/* Get a harvested entropy event */
349 				harvestfifo[source].count--;
350 				event = STAILQ_FIRST(&harvestfifo[source].head);
351 				STAILQ_REMOVE_HEAD(&harvestfifo[source].head,
352 					next);
353 
354 				active = found = 1;
355 
356 			}
357 
358 			/* Unlock the queue */
359 			mtx_unlock_spin(&harvestfifo[source].lock);
360 
361 			/* Deal with the event and dispose of it */
362 			if (found) {
363 
364 				random_process_event(event);
365 
366 				/* Lock the empty event buffer fifo */
367 				mtx_lock_spin(&emptyfifo.lock);
368 
369 				STAILQ_INSERT_TAIL(&emptyfifo.head, event, next);
370 
371 				mtx_unlock_spin(&emptyfifo.lock);
372 
373 			}
374 
375 		}
376 
377 		/* Found nothing, so don't belabour the issue */
378 		if (!active)
379 			tsleep(&harvestfifo, PUSER, "-", hz/10);
380 
381 	}
382 
383 	random_set_wakeup_exit(&random_kthread_control);
384 	/* NOTREACHED */
385 }
386 
387 /* Entropy harvesting routine. This is supposed to be fast; do
388  * not do anything slow in here!
389  */
390 static void
391 random_harvest_internal(u_int64_t somecounter, void *entropy, u_int count,
392 	u_int bits, u_int frac, enum esource origin)
393 {
394 	struct harvest	*event;
395 
396 	/* Lock the particular fifo */
397 	mtx_lock_spin(&harvestfifo[origin].lock);
398 
399 	/* Don't make the harvest queues too big - help to prevent
400 	 * low-grade entropy swamping
401 	 */
402 	if (harvestfifo[origin].count < RANDOM_FIFO_MAX) {
403 
404 		/* Lock the empty event buffer fifo */
405 		mtx_lock_spin(&emptyfifo.lock);
406 
407 		if (!STAILQ_EMPTY(&emptyfifo.head)) {
408 			event = STAILQ_FIRST(&emptyfifo.head);
409 			STAILQ_REMOVE_HEAD(&emptyfifo.head, next);
410 		}
411 		else
412 			event = NULL;
413 
414 		mtx_unlock_spin(&emptyfifo.lock);
415 
416 		/* If we didn't obtain a buffer, tough */
417 		if (event) {
418 
419 			/* Add the harvested data to the fifo */
420 			harvestfifo[origin].count++;
421 			event->somecounter = somecounter;
422 			event->size = count;
423 			event->bits = bits;
424 			event->frac = frac;
425 			event->source = origin;
426 
427 			/* XXXX Come back and make this dynamic! */
428 			count = count > HARVESTSIZE ? HARVESTSIZE : count;
429 			memcpy(event->entropy, entropy, count);
430 
431 			STAILQ_INSERT_TAIL(&harvestfifo[origin].head, event, next);
432 		}
433 
434 	}
435 
436 	mtx_unlock_spin(&harvestfifo[origin].lock);
437 
438 }
439 
440 static void
441 random_write_internal(void *buf, int count)
442 {
443 	int	i;
444 	u_int	chunk;
445 
446 	/* Break the input up into HARVESTSIZE chunks.
447 	 * The writer has too much control here, so "estimate" the
448 	 * the entropy as zero.
449 	 */
450 	for (i = 0; i < count; i += HARVESTSIZE) {
451 		chunk = HARVESTSIZE;
452 		if (i + chunk >= count)
453 			chunk = (u_int)(count - i);
454 		random_harvest_internal(get_cyclecount(), (char *)buf + i,
455 			chunk, 0, 0, RANDOM_WRITE);
456 	}
457 }
458 
459 void
460 random_unblock(void)
461 {
462 	if (!random_systat.seeded) {
463 		random_systat.seeded = 1;
464 		selwakeuppri(&random_systat.rsel, PUSER);
465 		wakeup(&random_systat);
466 	}
467 }
468