xref: /freebsd/sys/dev/random/randomdev.c (revision 7660b554bc59a07be0431c17e0e33815818baa69)
1 /*-
2  * Copyright (c) 2000 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_open_t		random_open;
57 static d_close_t	random_close;
58 static d_read_t		random_read;
59 static d_write_t	random_write;
60 static d_ioctl_t	random_ioctl;
61 static d_poll_t		random_poll;
62 
63 #define CDEV_MAJOR	2
64 #define RANDOM_MINOR	3
65 
66 static struct cdevsw random_cdevsw = {
67 	.d_open =	random_open,
68 	.d_close =	random_close,
69 	.d_read =	random_read,
70 	.d_write =	random_write,
71 	.d_ioctl =	random_ioctl,
72 	.d_poll =	random_poll,
73 	.d_name =	"random",
74 	.d_maj =	CDEV_MAJOR,
75 };
76 
77 static void random_kthread(void *);
78 static void random_harvest_internal(u_int64_t, void *, u_int, u_int, u_int, enum esource);
79 static void random_write_internal(void *, int);
80 
81 /* Ring buffer holding harvested entropy */
82 static struct harvestring {
83 	volatile u_int	head;
84 	volatile u_int	tail;
85 	struct harvest	data[HARVEST_RING_SIZE];
86 } harvestring;
87 
88 static struct random_systat {
89 	u_int		seeded;	/* 0 causes blocking 1 allows normal output */
90 	u_int		burst;	/* number of events to do before sleeping */
91 	struct selinfo	rsel;	/* For poll(2) */
92 } random_systat;
93 
94 /* <0 to end the kthread, 0 to let it run */
95 static int random_kthread_control = 0;
96 
97 static struct proc *random_kthread_proc;
98 
99 /* For use with make_dev(9)/destroy_dev(9). */
100 static dev_t	random_dev;
101 static dev_t	urandom_dev;
102 
103 /* ARGSUSED */
104 static int
105 random_check_boolean(SYSCTL_HANDLER_ARGS)
106 {
107 	if (oidp->oid_arg1 != NULL && *(u_int *)(oidp->oid_arg1) != 0)
108 		*(u_int *)(oidp->oid_arg1) = 1;
109         return sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
110 }
111 
112 RANDOM_CHECK_UINT(burst, 0, 20);
113 
114 SYSCTL_NODE(_kern, OID_AUTO, random, CTLFLAG_RW,
115 	0, "Random Number Generator");
116 SYSCTL_NODE(_kern_random, OID_AUTO, sys, CTLFLAG_RW,
117 	0, "Entropy Device Parameters");
118 SYSCTL_PROC(_kern_random_sys, OID_AUTO, seeded,
119 	CTLTYPE_INT|CTLFLAG_RW, &random_systat.seeded, 1,
120 	random_check_boolean, "I", "Seeded State");
121 SYSCTL_PROC(_kern_random_sys, OID_AUTO, burst,
122 	CTLTYPE_INT|CTLFLAG_RW, &random_systat.burst, 20,
123 	random_check_uint_burst, "I", "Harvest Burst Size");
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_open(dev_t dev __unused, int flags, int fmt __unused, struct thread *td)
142 {
143 	int error;
144 
145 	if (flags & FWRITE) {
146 		error = suser(td);
147 		if (error)
148 			return (error);
149 		error = securelevel_gt(td->td_ucred, 0);
150 		if (error)
151 			return (error);
152 	}
153 	return 0;
154 }
155 
156 /* ARGSUSED */
157 static int
158 random_close(dev_t dev __unused, int flags, int fmt __unused, struct thread *td)
159 {
160 	if (flags & FWRITE) {
161 		if (!(suser(td) ||
162 		    securelevel_gt(td->td_ucred, 0)))
163 			random_reseed();
164 	}
165 	return 0;
166 }
167 
168 /* ARGSUSED */
169 static int
170 random_read(dev_t dev __unused, struct uio *uio, int flag)
171 {
172 	int	c, ret;
173 	int	error = 0;
174 	void	*random_buf;
175 
176 	while (!random_systat.seeded) {
177 		if (flag & IO_NDELAY)
178 			error =  EWOULDBLOCK;
179 		else
180 			error = tsleep(&random_systat, PUSER|PCATCH,
181 				"block", 0);
182 		if (error != 0)
183 			return error;
184 	}
185 	c = uio->uio_resid < PAGE_SIZE ? uio->uio_resid : PAGE_SIZE;
186 	random_buf = (void *)malloc((u_long)c, M_TEMP, M_WAITOK);
187 	while (uio->uio_resid > 0 && error == 0) {
188 		ret = read_random_real(random_buf, c);
189 		error = uiomove(random_buf, ret, uio);
190 	}
191 	free(random_buf, M_TEMP);
192 	return error;
193 }
194 
195 /* ARGSUSED */
196 static int
197 random_write(dev_t dev __unused, struct uio *uio, int flag __unused)
198 {
199 	int	c;
200 	int	error;
201 	void	*random_buf;
202 
203 	error = 0;
204 	random_buf = (void *)malloc(PAGE_SIZE, M_TEMP, M_WAITOK);
205 	while (uio->uio_resid > 0) {
206 		c = (int)(uio->uio_resid < PAGE_SIZE
207 		    ? uio->uio_resid
208 		    : PAGE_SIZE);
209 		error = uiomove(random_buf, c, uio);
210 		if (error)
211 			break;
212 		random_write_internal(random_buf, c);
213 	}
214 	free(random_buf, M_TEMP);
215 	return error;
216 }
217 
218 /* ARGSUSED */
219 static int
220 random_ioctl(dev_t dev __unused, u_long cmd, caddr_t addr __unused,
221     int flags __unused, struct thread *td __unused)
222 {
223 	switch (cmd) {
224 	/* Really handled in upper layer */
225 	case FIOASYNC:
226 	case FIONBIO:
227 		return 0;
228 	default:
229 		return ENOTTY;
230 	}
231 }
232 
233 /* ARGSUSED */
234 static int
235 random_poll(dev_t dev __unused, int events, struct thread *td)
236 {
237 	int	revents;
238 
239 	revents = 0;
240 	if (events & (POLLIN | POLLRDNORM)) {
241 		if (random_systat.seeded)
242 			revents = events & (POLLIN | POLLRDNORM);
243 		else
244 			selrecord(td, &random_systat.rsel);
245 	}
246 	return revents;
247 }
248 
249 /* ARGSUSED */
250 static int
251 random_modevent(module_t mod __unused, int type, void *data __unused)
252 {
253 	int	error;
254 
255 	switch(type) {
256 	case MOD_LOAD:
257 		random_init();
258 
259 		/* This can be turned off by the very paranoid
260 		 * a reseed will turn it back on.
261 		 */
262 		random_systat.seeded = 1;
263 
264 		/* Number of envents to process off the harvest
265 		 * queue before giving it a break and sleeping
266 		 */
267 		random_systat.burst = 20;
268 
269 		/* Initialise the harvest ringbuffer */
270 		harvestring.head = 0;
271 		harvestring.tail = 0;
272 
273 		if (bootverbose)
274 			printf("random: <entropy source>\n");
275 		random_dev = make_dev(&random_cdevsw, RANDOM_MINOR, UID_ROOT,
276 			GID_WHEEL, 0666, "random");
277 		urandom_dev = make_dev_alias(random_dev, "urandom");
278 
279 		/* Start the hash/reseed thread */
280 		error = kthread_create(random_kthread, NULL,
281 			&random_kthread_proc, RFHIGHPID, 0, "random");
282 		if (error != 0)
283 			return error;
284 
285 		/* Register the randomness harvesting routine */
286 		random_init_harvester(random_harvest_internal,
287 			read_random_real);
288 
289 		return 0;
290 
291 	case MOD_UNLOAD:
292 		/* Deregister the randomness harvesting routine */
293 		random_deinit_harvester();
294 
295 		/* Command the hash/reseed thread to end and
296 		 * wait for it to finish
297 		 */
298 		random_kthread_control = -1;
299 		tsleep((void *)&random_kthread_control, PUSER, "term", 0);
300 
301 		random_deinit();
302 
303 		destroy_dev(random_dev);
304 		destroy_dev(urandom_dev);
305 		return 0;
306 
307 	case MOD_SHUTDOWN:
308 		return 0;
309 
310 	default:
311 		return EOPNOTSUPP;
312 	}
313 }
314 
315 DEV_MODULE(random, random_modevent, NULL);
316 
317 /* ARGSUSED */
318 static void
319 random_kthread(void *arg __unused)
320 {
321 	struct harvest	*event;
322 	u_int		newtail, burst;
323 
324 	/* Drain the harvest queue (in 'burst' size chunks,
325 	 * if 'burst' > 0. If 'burst' == 0, then completely
326 	 * drain the queue.
327 	 */
328 	for (burst = 0; ; burst++) {
329 
330 		if ((harvestring.tail == harvestring.head) ||
331 			(random_systat.burst && burst == random_systat.burst)) {
332 				tsleep(&harvestring, PUSER, "-", hz/10);
333 				burst = 0;
334 
335 		}
336 		else {
337 
338 			/* Suck a harvested entropy event out of the queue and
339 			 * hand it to the event processor
340 			 */
341 
342 			newtail = (harvestring.tail + 1) & HARVEST_RING_MASK;
343 			event = &harvestring.data[harvestring.tail];
344 
345 			/* Bump the ring counter. This action is assumed
346 			 * to be atomic.
347 			 */
348 			harvestring.tail = newtail;
349 
350 			random_process_event(event);
351 
352 		}
353 
354 		/* Is the thread scheduled for a shutdown? */
355 		if (random_kthread_control != 0) {
356 #ifdef DEBUG
357 			printf("Random kthread setting terminate\n");
358 #endif
359 			random_set_wakeup_exit(&random_kthread_control);
360 			/* NOTREACHED */
361 			break;
362 		}
363 
364 	}
365 
366 }
367 
368 /* Entropy harvesting routine. This is supposed to be fast; do
369  * not do anything slow in here!
370  */
371 static void
372 random_harvest_internal(u_int64_t somecounter, void *entropy, u_int count,
373 	u_int bits, u_int frac, enum esource origin)
374 {
375 	struct harvest	*pharvest;
376 	u_int		newhead;
377 
378 	newhead = (harvestring.head + 1) & HARVEST_RING_MASK;
379 
380 	if (newhead != harvestring.tail) {
381 
382 		/* Add the harvested data to the ring buffer */
383 
384 		pharvest = &harvestring.data[harvestring.head];
385 
386 		/* Stuff the harvested data into the ring */
387 		pharvest->somecounter = somecounter;
388 		count = count > HARVESTSIZE ? HARVESTSIZE : count;
389 		memcpy(pharvest->entropy, entropy, count);
390 		pharvest->size = count;
391 		pharvest->bits = bits;
392 		pharvest->frac = frac;
393 		pharvest->source =
394 		    origin < ENTROPYSOURCE ? origin : RANDOM_START;
395 
396 		/* Bump the ring counter. This action is assumed
397 		 * to be atomic.
398 		 */
399 		harvestring.head = newhead;
400 
401 	}
402 
403 }
404 
405 static void
406 random_write_internal(void *buf, int count)
407 {
408 	int	i;
409 
410 	/* Break the input up into HARVESTSIZE chunks.
411 	 * The writer has too much control here, so "estimate" the
412 	 * the entropy as zero.
413 	 */
414 	for (i = 0; i < count; i += HARVESTSIZE) {
415 		random_harvest_internal(get_cyclecount(), (char *)buf + i,
416 			HARVESTSIZE, 0, 0, RANDOM_WRITE);
417 	}
418 
419 	/* Maybe the loop iterated at least once */
420 	if (i > count)
421 		i -= HARVESTSIZE;
422 
423 	/* Get the last bytes even if the input length is not
424 	 * a multiple of HARVESTSIZE.
425 	 */
426 	count %= HARVESTSIZE;
427 	if (count) {
428 		random_harvest_internal(get_cyclecount(), (char *)buf + i,
429 			(u_int)count, 0, 0, RANDOM_WRITE);
430 	}
431 }
432 
433 void
434 random_unblock(void)
435 {
436 	if (!random_systat.seeded) {
437 		random_systat.seeded = 1;
438 		selwakeup(&random_systat.rsel);
439 		wakeup(&random_systat);
440 	}
441 }
442