xref: /freebsd-14.2/sys/dev/random/randomdev.c (revision e27b3bf5)
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 
108 /* ARGSUSED */
109 static int
110 random_check_boolean(SYSCTL_HANDLER_ARGS)
111 {
112 	if (oidp->oid_arg1 != NULL && *(u_int *)(oidp->oid_arg1) != 0)
113 		*(u_int *)(oidp->oid_arg1) = 1;
114         return sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
115 }
116 
117 SYSCTL_NODE(_kern, OID_AUTO, random, CTLFLAG_RW,
118 	0, "Random Number Generator");
119 SYSCTL_NODE(_kern_random, OID_AUTO, sys, CTLFLAG_RW,
120 	0, "Entropy Device Parameters");
121 SYSCTL_PROC(_kern_random_sys, OID_AUTO, seeded,
122 	CTLTYPE_INT|CTLFLAG_RW, &random_systat.seeded, 1,
123 	random_check_boolean, "I", "Seeded State");
124 SYSCTL_NODE(_kern_random_sys, OID_AUTO, harvest, CTLFLAG_RW,
125 	0, "Entropy Sources");
126 SYSCTL_PROC(_kern_random_sys_harvest, OID_AUTO, ethernet,
127 	CTLTYPE_INT|CTLFLAG_RW, &harvest.ethernet, 0,
128 	random_check_boolean, "I", "Harvest NIC entropy");
129 SYSCTL_PROC(_kern_random_sys_harvest, OID_AUTO, point_to_point,
130 	CTLTYPE_INT|CTLFLAG_RW, &harvest.point_to_point, 0,
131 	random_check_boolean, "I", "Harvest serial net entropy");
132 SYSCTL_PROC(_kern_random_sys_harvest, OID_AUTO, interrupt,
133 	CTLTYPE_INT|CTLFLAG_RW, &harvest.interrupt, 0,
134 	random_check_boolean, "I", "Harvest IRQ entropy");
135 SYSCTL_PROC(_kern_random_sys_harvest, OID_AUTO, swi,
136 	CTLTYPE_INT|CTLFLAG_RW, &harvest.swi, 0,
137 	random_check_boolean, "I", "Harvest SWI entropy");
138 
139 /* ARGSUSED */
140 static int
141 random_close(dev_t dev __unused, int flags, int fmt __unused, struct thread *td)
142 {
143 	if (flags & FWRITE) {
144 		if (suser(td) == 0 && securelevel_gt(td->td_ucred, 0) == 0)
145 			random_reseed();
146 	}
147 	return 0;
148 }
149 
150 /* ARGSUSED */
151 static int
152 random_read(dev_t dev __unused, struct uio *uio, int flag)
153 {
154 	int	c, ret;
155 	int	error = 0;
156 	void	*random_buf;
157 
158 	while (!random_systat.seeded) {
159 		if (flag & IO_NDELAY)
160 			error =  EWOULDBLOCK;
161 		else
162 			error = tsleep(&random_systat, PUSER|PCATCH,
163 				"block", 0);
164 		if (error != 0)
165 			return error;
166 	}
167 	c = uio->uio_resid < PAGE_SIZE ? uio->uio_resid : PAGE_SIZE;
168 	random_buf = (void *)malloc((u_long)c, M_TEMP, M_WAITOK);
169 	while (uio->uio_resid > 0 && error == 0) {
170 		ret = read_random_real(random_buf, c);
171 		error = uiomove(random_buf, ret, uio);
172 	}
173 	free(random_buf, M_TEMP);
174 	return error;
175 }
176 
177 /* ARGSUSED */
178 static int
179 random_write(dev_t dev __unused, struct uio *uio, int flag __unused)
180 {
181 	int	c;
182 	int	error;
183 	void	*random_buf;
184 
185 	error = 0;
186 	random_buf = (void *)malloc(PAGE_SIZE, M_TEMP, M_WAITOK);
187 	while (uio->uio_resid > 0) {
188 		c = (int)(uio->uio_resid < PAGE_SIZE
189 		    ? uio->uio_resid
190 		    : PAGE_SIZE);
191 		error = uiomove(random_buf, c, uio);
192 		if (error)
193 			break;
194 		random_write_internal(random_buf, c);
195 	}
196 	free(random_buf, M_TEMP);
197 	return error;
198 }
199 
200 /* ARGSUSED */
201 static int
202 random_ioctl(dev_t dev __unused, u_long cmd, caddr_t addr __unused,
203     int flags __unused, struct thread *td __unused)
204 {
205 	switch (cmd) {
206 	/* Really handled in upper layer */
207 	case FIOASYNC:
208 	case FIONBIO:
209 		return 0;
210 	default:
211 		return ENOTTY;
212 	}
213 }
214 
215 /* ARGSUSED */
216 static int
217 random_poll(dev_t dev __unused, int events, struct thread *td)
218 {
219 	int	revents;
220 
221 	revents = 0;
222 	if (events & (POLLIN | POLLRDNORM)) {
223 		if (random_systat.seeded)
224 			revents = events & (POLLIN | POLLRDNORM);
225 		else
226 			selrecord(td, &random_systat.rsel);
227 	}
228 	return revents;
229 }
230 
231 /* ARGSUSED */
232 static int
233 random_modevent(module_t mod __unused, int type, void *data __unused)
234 {
235 	int	error, i;
236 	struct harvest *np;
237 
238 	switch(type) {
239 	case MOD_LOAD:
240 		random_init();
241 
242 		/* This can be turned off by the very paranoid
243 		 * a reseed will turn it back on.
244 		 */
245 		random_systat.seeded = 1;
246 
247 		/* Initialise the harvest fifos */
248 		STAILQ_INIT(&emptyfifo.head);
249 		emptyfifo.count = 0;
250 		mtx_init(&emptyfifo.lock, "entropy harvest buffers", NULL,
251 			MTX_SPIN);
252 		for (i = 0; i < EMPTYBUFFERS; i++) {
253 			np = malloc(sizeof(struct harvest), M_ENTROPY,
254 				M_WAITOK);
255 			STAILQ_INSERT_TAIL(&emptyfifo.head, np, next);
256 		}
257 		for (i = 0; i < ENTROPYSOURCE; i++) {
258 			STAILQ_INIT(&harvestfifo[i].head);
259 			harvestfifo[i].count = 0;
260 			mtx_init(&harvestfifo[i].lock, "entropy harvest", NULL,
261 				MTX_SPIN);
262 		}
263 
264 		if (bootverbose)
265 			printf("random: <entropy source>\n");
266 		random_dev = make_dev(&random_cdevsw, RANDOM_MINOR, UID_ROOT,
267 			GID_WHEEL, 0666, "random");
268 		make_dev_alias(random_dev, "urandom");
269 
270 		/* Start the hash/reseed thread */
271 		error = kthread_create(random_kthread, NULL,
272 			&random_kthread_proc, RFHIGHPID, 0, "random");
273 		if (error != 0)
274 			return error;
275 
276 		/* Register the randomness harvesting routine */
277 		random_init_harvester(random_harvest_internal,
278 			read_random_real);
279 
280 		return 0;
281 
282 	case MOD_UNLOAD:
283 		/* Deregister the randomness harvesting routine */
284 		random_deinit_harvester();
285 
286 		/* Command the hash/reseed thread to end and
287 		 * wait for it to finish
288 		 */
289 		random_kthread_control = -1;
290 		tsleep((void *)&random_kthread_control, PUSER, "term", 0);
291 
292 		/* Destroy the harvest fifos */
293 		while (!STAILQ_EMPTY(&emptyfifo.head)) {
294 			np = STAILQ_FIRST(&emptyfifo.head);
295 			STAILQ_REMOVE_HEAD(&emptyfifo.head, next);
296 			free(np, M_ENTROPY);
297 		}
298 		mtx_destroy(&emptyfifo.lock);
299 		for (i = 0; i < ENTROPYSOURCE; i++) {
300 			while (!STAILQ_EMPTY(&harvestfifo[i].head)) {
301 				np = STAILQ_FIRST(&harvestfifo[i].head);
302 				STAILQ_REMOVE_HEAD(&harvestfifo[i].head, next);
303 				free(np, M_ENTROPY);
304 			}
305 			mtx_destroy(&harvestfifo[i].lock);
306 		}
307 
308 		random_deinit();
309 
310 		destroy_dev(random_dev);
311 		return 0;
312 
313 	case MOD_SHUTDOWN:
314 		return 0;
315 
316 	default:
317 		return EOPNOTSUPP;
318 	}
319 }
320 
321 DEV_MODULE(random, random_modevent, NULL);
322 
323 /* ARGSUSED */
324 static void
325 random_kthread(void *arg __unused)
326 {
327 	struct harvest	*event = NULL;
328 	int		found, active;
329 	enum esource	source;
330 
331 	/* Process until told to stop */
332 	for (; random_kthread_control == 0;) {
333 
334 		active = 0;
335 
336 		/* Cycle through all the entropy sources */
337 		for (source = 0; source < ENTROPYSOURCE; source++) {
338 
339 			found = 0;
340 
341 			/* Lock up queue draining */
342 			mtx_lock_spin(&harvestfifo[source].lock);
343 
344 			if (!STAILQ_EMPTY(&harvestfifo[source].head)) {
345 
346 				/* Get a harvested entropy event */
347 				harvestfifo[source].count--;
348 				event = STAILQ_FIRST(&harvestfifo[source].head);
349 				STAILQ_REMOVE_HEAD(&harvestfifo[source].head,
350 					next);
351 
352 				active = found = 1;
353 
354 			}
355 
356 			/* Unlock the queue */
357 			mtx_unlock_spin(&harvestfifo[source].lock);
358 
359 			/* Deal with the event and dispose of it */
360 			if (found) {
361 
362 				random_process_event(event);
363 
364 				/* Lock the empty event buffer fifo */
365 				mtx_lock_spin(&emptyfifo.lock);
366 
367 				STAILQ_INSERT_TAIL(&emptyfifo.head, event, next);
368 
369 				mtx_unlock_spin(&emptyfifo.lock);
370 
371 			}
372 
373 		}
374 
375 		/* Found nothing, so don't belabour the issue */
376 		if (!active)
377 			tsleep(&harvestfifo, PUSER, "-", hz/10);
378 
379 	}
380 
381 	random_set_wakeup_exit(&random_kthread_control);
382 	/* NOTREACHED */
383 }
384 
385 /* Entropy harvesting routine. This is supposed to be fast; do
386  * not do anything slow in here!
387  */
388 static void
389 random_harvest_internal(u_int64_t somecounter, void *entropy, u_int count,
390 	u_int bits, u_int frac, enum esource origin)
391 {
392 	struct harvest	*event;
393 
394 	/* Lock the particular fifo */
395 	mtx_lock_spin(&harvestfifo[origin].lock);
396 
397 	/* Don't make the harvest queues too big - help to prevent
398 	 * low-grade entropy swamping
399 	 */
400 	if (harvestfifo[origin].count < RANDOM_FIFO_MAX) {
401 
402 		/* Lock the empty event buffer fifo */
403 		mtx_lock_spin(&emptyfifo.lock);
404 
405 		if (!STAILQ_EMPTY(&emptyfifo.head)) {
406 			event = STAILQ_FIRST(&emptyfifo.head);
407 			STAILQ_REMOVE_HEAD(&emptyfifo.head, next);
408 		}
409 		else
410 			event = NULL;
411 
412 		mtx_unlock_spin(&emptyfifo.lock);
413 
414 		/* If we didn't obtain a buffer, tough */
415 		if (event) {
416 
417 			/* Add the harvested data to the fifo */
418 			harvestfifo[origin].count++;
419 			event->somecounter = somecounter;
420 			event->size = count;
421 			event->bits = bits;
422 			event->frac = frac;
423 			event->source = origin;
424 
425 			/* XXXX Come back and make this dynamic! */
426 			count = count > HARVESTSIZE ? HARVESTSIZE : count;
427 			memcpy(event->entropy, entropy, count);
428 
429 			STAILQ_INSERT_TAIL(&harvestfifo[origin].head, event, next);
430 		}
431 
432 	}
433 
434 	mtx_unlock_spin(&harvestfifo[origin].lock);
435 
436 }
437 
438 static void
439 random_write_internal(void *buf, int count)
440 {
441 	int	i;
442 	u_int	chunk;
443 
444 	/* Break the input up into HARVESTSIZE chunks.
445 	 * The writer has too much control here, so "estimate" the
446 	 * the entropy as zero.
447 	 */
448 	for (i = 0; i < count; i += HARVESTSIZE) {
449 		chunk = HARVESTSIZE;
450 		if (i + chunk >= count)
451 			chunk = (u_int)(count - i);
452 		random_harvest_internal(get_cyclecount(), (char *)buf + i,
453 			chunk, 0, 0, RANDOM_WRITE);
454 	}
455 }
456 
457 void
458 random_unblock(void)
459 {
460 	if (!random_systat.seeded) {
461 		random_systat.seeded = 1;
462 		selwakeuppri(&random_systat.rsel, PUSER);
463 		wakeup(&random_systat);
464 	}
465 }
466