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