xref: /freebsd/sys/dev/random/randomdev.c (revision 1b6c76a2fe091c74f08427e6c870851025a9cf67)
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/module.h>
40 #include <sys/mutex.h>
41 #include <sys/poll.h>
42 #include <sys/queue.h>
43 #include <sys/random.h>
44 #include <sys/selinfo.h>
45 #include <sys/sysctl.h>
46 #include <sys/uio.h>
47 #include <sys/unistd.h>
48 #include <sys/vnode.h>
49 
50 #include <machine/bus.h>
51 #include <machine/cpu.h>
52 #include <machine/resource.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 	/* open */	random_open,
68 	/* close */	random_close,
69 	/* read */	random_read,
70 	/* write */	random_write,
71 	/* ioctl */	random_ioctl,
72 	/* poll */	random_poll,
73 	/* mmap */	nommap,
74 	/* strategy */	nostrategy,
75 	/* name */	"random",
76 	/* maj */	CDEV_MAJOR,
77 	/* dump */	nodump,
78 	/* psize */	nopsize,
79 	/* flags */	0,
80 };
81 
82 static void random_kthread(void *);
83 static void random_harvest_internal(u_int64_t, void *, u_int, u_int, u_int, enum esource);
84 static void random_write_internal(void *, u_int);
85 
86 /* Ring buffer holding harvested entropy */
87 static struct harvestring {
88 	volatile u_int	head;
89 	volatile u_int	tail;
90 	struct harvest	data[HARVEST_RING_SIZE];
91 } harvestring;
92 
93 static struct random_systat {
94 	u_int		seeded;	/* 0 causes blocking 1 allows normal output */
95 	u_int		burst;	/* number of events to do before sleeping */
96 	struct selinfo	rsel;	/* For poll(2) */
97 } random_systat;
98 
99 /* <0 to end the kthread, 0 to let it run */
100 static int random_kthread_control = 0;
101 
102 static struct proc *random_kthread_proc;
103 
104 /* For use with make_dev(9)/destroy_dev(9). */
105 static dev_t	random_dev;
106 static dev_t	urandom_dev;
107 
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 
140 static int
141 random_open(dev_t dev, int flags, int fmt, struct proc *p)
142 {
143 	if ((flags & FWRITE) && (securelevel > 0 || suser(p)))
144 		return EPERM;
145 	else
146 		return 0;
147 }
148 
149 static int
150 random_close(dev_t dev, int flags, int fmt, struct proc *p)
151 {
152 	if ((flags & FWRITE) && !(securelevel > 0 || suser(p)))
153 		random_reseed();
154 	return 0;
155 }
156 
157 static int
158 random_read(dev_t dev, struct uio *uio, int flag)
159 {
160 	u_int	c, ret;
161 	int	error = 0;
162 	void	*random_buf;
163 
164 	while (!random_systat.seeded) {
165 		if (flag & IO_NDELAY)
166 			error =  EWOULDBLOCK;
167 		else
168 			error = tsleep(&random_systat, PUSER|PCATCH,
169 				"block", 0);
170 		if (error != 0)
171 			return error;
172 	}
173 	c = min(uio->uio_resid, PAGE_SIZE);
174 	random_buf = (void *)malloc(c, M_TEMP, M_WAITOK);
175 	while (uio->uio_resid > 0 && error == 0) {
176 		ret = read_random_real(random_buf, c);
177 		error = uiomove(random_buf, ret, uio);
178 	}
179 	free(random_buf, M_TEMP);
180 	return error;
181 }
182 
183 static int
184 random_write(dev_t dev, struct uio *uio, int flag)
185 {
186 	u_int	c;
187 	int	error;
188 	void	*random_buf;
189 
190 	error = 0;
191 	random_buf = (void *)malloc(PAGE_SIZE, M_TEMP, M_WAITOK);
192 	while (uio->uio_resid > 0) {
193 		c = min(uio->uio_resid, PAGE_SIZE);
194 		error = uiomove(random_buf, c, uio);
195 		if (error)
196 			break;
197 		random_write_internal(random_buf, c);
198 	}
199 	free(random_buf, M_TEMP);
200 	return error;
201 }
202 
203 static int
204 random_ioctl(dev_t dev, u_long cmd, caddr_t addr, int flags, struct proc *p)
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 static int
217 random_poll(dev_t dev, int events, struct proc *p)
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(p, &random_systat.rsel);
227 	}
228 	return revents;
229 }
230 
231 static int
232 random_modevent(module_t mod, int type, void *data)
233 {
234 	int	error;
235 
236 	switch(type) {
237 	case MOD_LOAD:
238 		random_init();
239 
240 		/* This can be turned off by the very paranoid
241 		 * a reseed will turn it back on.
242 		 */
243 		random_systat.seeded = 1;
244 
245 		/* Number of envents to process off the harvest
246 		 * queue before giving it a break and sleeping
247 		 */
248 		random_systat.burst = 20;
249 
250 		/* Initialise the harvest ringbuffer */
251 		harvestring.head = 0;
252 		harvestring.tail = 0;
253 
254 		if (bootverbose)
255 			printf("random: <entropy source>\n");
256 		random_dev = make_dev(&random_cdevsw, RANDOM_MINOR, UID_ROOT,
257 			GID_WHEEL, 0666, "random");
258 		urandom_dev = make_dev_alias(random_dev, "urandom");
259 
260 		/* Start the hash/reseed thread */
261 		error = kthread_create(random_kthread, NULL,
262 			&random_kthread_proc, RFHIGHPID, "random");
263 		if (error != 0)
264 			return error;
265 
266 		/* Register the randomness harvesting routine */
267 		random_init_harvester(random_harvest_internal,
268 			read_random_real);
269 
270 		return 0;
271 
272 	case MOD_UNLOAD:
273 		/* Deregister the randomness harvesting routine */
274 		random_deinit_harvester();
275 
276 		/* Command the hash/reseed thread to end and
277 		 * wait for it to finish
278 		 */
279 		random_kthread_control = -1;
280 		tsleep((void *)&random_kthread_control, PUSER, "term", 0);
281 
282 		random_deinit();
283 
284 		destroy_dev(random_dev);
285 		destroy_dev(urandom_dev);
286 		return 0;
287 
288 	case MOD_SHUTDOWN:
289 		return 0;
290 
291 	default:
292 		return EOPNOTSUPP;
293 	}
294 }
295 
296 DEV_MODULE(random, random_modevent, NULL);
297 
298 static void
299 random_kthread(void *arg /* NOTUSED */)
300 {
301 	struct harvest	*event;
302 	int		newtail, burst;
303 
304 	/* Drain the harvest queue (in 'burst' size chunks,
305 	 * if 'burst' > 0. If 'burst' == 0, then completely
306 	 * drain the queue.
307 	 */
308 	for (burst = 0; ; burst++) {
309 
310 		if ((harvestring.tail == harvestring.head) ||
311 			(random_systat.burst && burst == random_systat.burst)) {
312 				tsleep(&harvestring, PUSER, "sleep", hz/10);
313 				burst = 0;
314 
315 		}
316 		else {
317 
318 			/* Suck a harvested entropy event out of the queue and
319 			 * hand it to the event processor
320 			 */
321 
322 			newtail = (harvestring.tail + 1) & HARVEST_RING_MASK;
323 			event = &harvestring.data[harvestring.tail];
324 
325 			/* Bump the ring counter. This action is assumed
326 			 * to be atomic.
327 			 */
328 			harvestring.tail = newtail;
329 
330 			random_process_event(event);
331 
332 		}
333 
334 		/* Is the thread scheduled for a shutdown? */
335 		if (random_kthread_control != 0) {
336 #ifdef DEBUG
337 			mtx_lock(&Giant);
338 			printf("Random kthread setting terminate\n");
339 			mtx_unlock(&Giant);
340 #endif
341 			random_set_wakeup_exit(&random_kthread_control);
342 			/* NOTREACHED */
343 			break;
344 		}
345 
346 	}
347 
348 }
349 
350 /* Entropy harvesting routine. This is supposed to be fast; do
351  * not do anything slow in here!
352  */
353 static void
354 random_harvest_internal(u_int64_t somecounter, void *entropy, u_int count,
355 	u_int bits, u_int frac, enum esource origin)
356 {
357 	struct harvest	*harvest;
358 	int		newhead;
359 
360 	newhead = (harvestring.head + 1) & HARVEST_RING_MASK;
361 
362 	if (newhead != harvestring.tail) {
363 
364 		/* Add the harvested data to the ring buffer */
365 
366 		harvest = &harvestring.data[harvestring.head];
367 
368 		/* Stuff the harvested data into the ring */
369 		harvest->somecounter = somecounter;
370 		count = count > HARVESTSIZE ? HARVESTSIZE : count;
371 		memcpy(harvest->entropy, entropy, count);
372 		harvest->size = count;
373 		harvest->bits = bits;
374 		harvest->frac = frac;
375 		harvest->source = origin < ENTROPYSOURCE ? origin : 0;
376 
377 		/* Bump the ring counter. This action is assumed
378 		 * to be atomic.
379 		 */
380 		harvestring.head = newhead;
381 
382 	}
383 
384 }
385 
386 static void
387 random_write_internal(void *buf, u_int count)
388 {
389 	u_int	i;
390 
391 	/* Break the input up into HARVESTSIZE chunks.
392 	 * The writer has too much control here, so "estimate" the
393 	 * the entropy as zero.
394 	 */
395 	for (i = 0; i < count; i += HARVESTSIZE) {
396 		random_harvest_internal(get_cyclecount(), (char *)buf + i,
397 			HARVESTSIZE, 0, 0, RANDOM_WRITE);
398 	}
399 
400 	/* Maybe the loop iterated at least once */
401 	if (i > count)
402 		i -= HARVESTSIZE;
403 
404 	/* Get the last bytes even if the input length is not
405 	 * a multiple of HARVESTSIZE.
406 	 */
407 	count %= HARVESTSIZE;
408 	if (count) {
409 		random_harvest_internal(get_cyclecount(), (char *)buf + i,
410 			count, 0, 0, RANDOM_WRITE);
411 	}
412 }
413 
414 void
415 random_unblock(void)
416 {
417 	if (!random_systat.seeded) {
418 		random_systat.seeded = 1;
419 		selwakeup(&random_systat.rsel);
420 		wakeup(&random_systat);
421 	}
422 }
423