xref: /freebsd/sys/dev/random/randomdev.c (revision 119b75925c562202145d7bac7b676b98029c6cb9)
1 /*-
2  * Copyright (c) 2000-2015 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/module.h>
41 #include <sys/malloc.h>
42 #include <sys/poll.h>
43 #include <sys/proc.h>
44 #include <sys/random.h>
45 #include <sys/sbuf.h>
46 #include <sys/selinfo.h>
47 #include <sys/sysctl.h>
48 #include <sys/systm.h>
49 #include <sys/uio.h>
50 #include <sys/unistd.h>
51 
52 #include <crypto/rijndael/rijndael-api-fst.h>
53 #include <crypto/sha2/sha2.h>
54 
55 #include <dev/random/hash.h>
56 #include <dev/random/randomdev.h>
57 #include <dev/random/random_harvestq.h>
58 
59 #include "opt_random.h"
60 
61 #if defined(RANDOM_DUMMY) && defined(RANDOM_YARROW)
62 #error "Cannot define both RANDOM_DUMMY and RANDOM_YARROW"
63 #endif
64 
65 #define	RANDOM_UNIT	0
66 
67 /* Return the largest number >= x that is a multiple of m */
68 #define CEIL_TO_MULTIPLE(x, m) ((((x) + (m) - 1)/(m))*(m))
69 
70 static d_read_t randomdev_read;
71 static d_write_t randomdev_write;
72 static d_poll_t randomdev_poll;
73 static d_ioctl_t randomdev_ioctl;
74 
75 static struct cdevsw random_cdevsw = {
76 	.d_name = "random",
77 	.d_version = D_VERSION,
78 	.d_read = randomdev_read,
79 	.d_write = randomdev_write,
80 	.d_poll = randomdev_poll,
81 	.d_ioctl = randomdev_ioctl,
82 };
83 
84 /* For use with make_dev(9)/destroy_dev(9). */
85 static struct cdev *random_dev;
86 
87 /* Set up the sysctl root node for the entropy device */
88 SYSCTL_NODE(_kern, OID_AUTO, random, CTLFLAG_RW, 0, "Cryptographically Secure Random Number Generator");
89 
90 MALLOC_DEFINE(M_ENTROPY, "entropy", "Entropy harvesting buffers and data structures");
91 
92 #if defined(RANDOM_DUMMY)
93 
94 /*-
95  * Dummy "always block" pseudo algorithm, used when there is no real
96  * random(4) driver to provide a CSPRNG.
97  */
98 
99 static u_int
100 dummy_random_zero(void)
101 {
102 
103 	return (0);
104 }
105 
106 static void
107 dummy_random(void)
108 {
109 }
110 
111 struct random_algorithm random_alg_context = {
112 	.ra_ident = "Dummy",
113 	.ra_init_alg = NULL,
114 	.ra_deinit_alg = NULL,
115 	.ra_pre_read = dummy_random,
116 	.ra_read = (random_alg_read_t *)dummy_random_zero,
117 	.ra_write = (random_alg_write_t *)dummy_random_zero,
118 	.ra_reseed = dummy_random,
119 	.ra_seeded = (random_alg_seeded_t *)dummy_random_zero,
120 	.ra_event_processor = NULL,
121 	.ra_poolcount = 0,
122 };
123 
124 #else /* !defined(RANDOM_DUMMY) */
125 
126 LIST_HEAD(sources_head, random_sources);
127 static struct sources_head source_list = LIST_HEAD_INITIALIZER(source_list);
128 static u_int read_rate;
129 
130 static void
131 random_alg_context_ra_init_alg(void *data)
132 {
133 
134 	random_alg_context.ra_init_alg(data);
135 }
136 
137 static void
138 random_alg_context_ra_deinit_alg(void *data)
139 {
140 
141 	random_alg_context.ra_deinit_alg(data);
142 }
143 
144 SYSINIT(random_device, SI_SUB_RANDOM, SI_ORDER_THIRD, random_alg_context_ra_init_alg, NULL);
145 SYSUNINIT(random_device, SI_SUB_RANDOM, SI_ORDER_THIRD, random_alg_context_ra_deinit_alg, NULL);
146 
147 #endif /* defined(RANDOM_DUMMY) */
148 
149 static struct selinfo rsel;
150 
151 /*
152  * This is the read uio(9) interface for random(4).
153  */
154 /* ARGSUSED */
155 static int
156 randomdev_read(struct cdev *dev __unused, struct uio *uio, int flags)
157 {
158 
159 	return (read_random_uio(uio, (flags & O_NONBLOCK) != 0));
160 }
161 
162 int
163 read_random_uio(struct uio *uio, bool nonblock)
164 {
165 	uint8_t *random_buf;
166 	int error, spamcount;
167 	ssize_t read_len, total_read, c;
168 
169 	random_buf = malloc(PAGE_SIZE, M_ENTROPY, M_WAITOK);
170 	random_alg_context.ra_pre_read();
171 	error = 0;
172 	spamcount = 0;
173 	/* (Un)Blocking logic */
174 	while (!random_alg_context.ra_seeded()) {
175 		if (nonblock) {
176 			error = EWOULDBLOCK;
177 			break;
178 		}
179 		/* keep tapping away at the pre-read until we seed/unblock. */
180 		random_alg_context.ra_pre_read();
181 		/* Only bother the console every 10 seconds or so */
182 		if (spamcount == 0)
183 			printf("random: %s unblock wait\n", __func__);
184 		spamcount = (spamcount + 1)%100;
185 		error = tsleep(&random_alg_context, PCATCH, "randseed", hz/10);
186 		if (error == ERESTART || error == EINTR)
187 			break;
188 	}
189 	if (error == 0) {
190 #if !defined(RANDOM_DUMMY)
191 		/* XXX: FIX!! Next line as an atomic operation? */
192 		read_rate += (uio->uio_resid + sizeof(uint32_t))/sizeof(uint32_t);
193 #endif
194 		total_read = 0;
195 		while (uio->uio_resid && !error) {
196 			read_len = uio->uio_resid;
197 			/*
198 			 * Belt-and-braces.
199 			 * Round up the read length to a crypto block size multiple,
200 			 * which is what the underlying generator is expecting.
201 			 * See the random_buf size requirements in the Yarrow/Fortuna code.
202 			 */
203 			read_len = CEIL_TO_MULTIPLE(read_len, RANDOM_BLOCKSIZE);
204 			/* Work in chunks page-sized or less */
205 			read_len = MIN(read_len, PAGE_SIZE);
206 			random_alg_context.ra_read(random_buf, read_len);
207 			c = MIN(uio->uio_resid, read_len);
208 			error = uiomove(random_buf, c, uio);
209 			total_read += c;
210 		}
211 		if (total_read != uio->uio_resid && (error == ERESTART || error == EINTR))
212 			/* Return partial read, not error. */
213 			error = 0;
214 	}
215 	free(random_buf, M_ENTROPY);
216 	return (error);
217 }
218 
219 /*-
220  * Kernel API version of read_random().
221  * This is similar to random_alg_read(),
222  * except it doesn't interface with uio(9).
223  * It cannot assumed that random_buf is a multiple of
224  * RANDOM_BLOCKSIZE bytes.
225  */
226 u_int
227 read_random(void *random_buf, u_int len)
228 {
229 	u_int read_len;
230 	uint8_t local_buf[len + RANDOM_BLOCKSIZE];
231 
232 	KASSERT(random_buf != NULL, ("No suitable random buffer in %s", __func__));
233 	random_alg_context.ra_pre_read();
234 	/* (Un)Blocking logic; if not seeded, return nothing. */
235 	if (random_alg_context.ra_seeded()) {
236 #if !defined(RANDOM_DUMMY)
237 		/* XXX: FIX!! Next line as an atomic operation? */
238 		read_rate += (len + sizeof(uint32_t))/sizeof(uint32_t);
239 #endif
240 		if (len > 0) {
241 			/*
242 			 * Belt-and-braces.
243 			 * Round up the read length to a crypto block size multiple,
244 			 * which is what the underlying generator is expecting.
245 			 */
246 			read_len = CEIL_TO_MULTIPLE(len, RANDOM_BLOCKSIZE);
247 			random_alg_context.ra_read(local_buf, read_len);
248 			memcpy(random_buf, local_buf, len);
249 		}
250 	} else
251 		len = 0;
252 	return (len);
253 }
254 
255 /* ARGSUSED */
256 static int
257 randomdev_write(struct cdev *dev __unused, struct uio *uio, int flags __unused)
258 {
259 	uint8_t *random_buf;
260 	int c, error = 0;
261 	ssize_t nbytes;
262 
263 	random_buf = malloc(PAGE_SIZE, M_ENTROPY, M_WAITOK);
264 	nbytes = uio->uio_resid;
265 	while (uio->uio_resid > 0 && error == 0) {
266 		c = MIN(uio->uio_resid, PAGE_SIZE);
267 		error = uiomove(random_buf, c, uio);
268 		if (error)
269 			break;
270 		random_alg_context.ra_write(random_buf, c);
271 		tsleep(&random_alg_context, 0, "randwr", hz/10);
272 	}
273 	if (nbytes != uio->uio_resid && (error == ERESTART || error == EINTR))
274 		/* Partial write, not error. */
275 		error = 0;
276 	free(random_buf, M_ENTROPY);
277 	return (error);
278 }
279 
280 /* ARGSUSED */
281 static int
282 randomdev_poll(struct cdev *dev __unused, int events, struct thread *td __unused)
283 {
284 
285 	if (events & (POLLIN | POLLRDNORM)) {
286 		if (random_alg_context.ra_seeded())
287 			events &= (POLLIN | POLLRDNORM);
288 		else
289 			selrecord(td, &rsel);
290 	}
291 	return (events);
292 }
293 
294 /* This will be called by the entropy processor when it seeds itself and becomes secure */
295 void
296 randomdev_unblock(void)
297 {
298 
299 	selwakeuppri(&rsel, PUSER);
300 	wakeup(&random_alg_context);
301 	printf("random: unblocking device.\n");
302 	/* Do random(9) a favour while we are about it. */
303 	(void)atomic_cmpset_int(&arc4rand_iniseed_state, ARC4_ENTR_NONE, ARC4_ENTR_HAVE);
304 }
305 
306 /* ARGSUSED */
307 static int
308 randomdev_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t addr __unused,
309     int flags __unused, struct thread *td __unused)
310 {
311 	int error = 0;
312 
313 	switch (cmd) {
314 		/* Really handled in upper layer */
315 	case FIOASYNC:
316 	case FIONBIO:
317 		break;
318 	default:
319 		error = ENOTTY;
320 	}
321 
322 	return (error);
323 }
324 
325 void
326 random_source_register(struct random_source *rsource)
327 {
328 #if defined(RANDOM_DUMMY)
329 	(void)rsource;
330 #else /* !defined(RANDOM_DUMMY) */
331 	struct random_sources *rrs;
332 
333 	KASSERT(rsource != NULL, ("invalid input to %s", __func__));
334 
335 	rrs = malloc(sizeof(*rrs), M_ENTROPY, M_WAITOK);
336 	rrs->rrs_source = rsource;
337 
338 	printf("random: registering fast source %s\n", rsource->rs_ident);
339 	LIST_INSERT_HEAD(&source_list, rrs, rrs_entries);
340 #endif /* defined(RANDOM_DUMMY) */
341 }
342 
343 void
344 random_source_deregister(struct random_source *rsource)
345 {
346 #if defined(RANDOM_DUMMY)
347 	(void)rsource;
348 #else /* !defined(RANDOM_DUMMY) */
349 	struct random_sources *rrs = NULL;
350 
351 	KASSERT(rsource != NULL, ("invalid input to %s", __func__));
352 	LIST_FOREACH(rrs, &source_list, rrs_entries)
353 		if (rrs->rrs_source == rsource) {
354 			LIST_REMOVE(rrs, rrs_entries);
355 			break;
356 		}
357 	if (rrs != NULL)
358 		free(rrs, M_ENTROPY);
359 #endif /* defined(RANDOM_DUMMY) */
360 }
361 
362 #if !defined(RANDOM_DUMMY)
363 /*
364  * Run through all fast sources reading entropy for the given
365  * number of rounds, which should be a multiple of the number
366  * of entropy accumulation pools in use; 2 for Yarrow and 32
367  * for Fortuna.
368  *
369  * BEWARE!!!
370  * This function runs inside the RNG thread! Don't do anything silly!
371  */
372 void
373 random_sources_feed(void)
374 {
375 	uint32_t entropy[HARVESTSIZE];
376 	struct random_sources *rrs;
377 	u_int i, n, local_read_rate;
378 
379 	/*
380 	 * Step over all of live entropy sources, and feed their output
381 	 * to the system-wide RNG.
382 	 */
383 	/* XXX: FIX!! Next lines as an atomic operation? */
384 	local_read_rate = read_rate;
385 	read_rate = RANDOM_ALG_READ_RATE_MINIMUM;
386 	LIST_FOREACH(rrs, &source_list, rrs_entries) {
387 		for (i = 0; i < random_alg_context.ra_poolcount*local_read_rate; i++) {
388 			n = rrs->rrs_source->rs_read(entropy, sizeof(entropy));
389 			KASSERT((n > 0 && n <= sizeof(entropy)), ("very bad return from rs_read (= %d) in %s", n, __func__));
390 			random_harvest_direct(entropy, n, (n*8)/2, rrs->rrs_source->rs_source);
391 		}
392 	}
393 	explicit_bzero(entropy, sizeof(entropy));
394 }
395 
396 static int
397 random_source_handler(SYSCTL_HANDLER_ARGS)
398 {
399 	struct random_sources *rrs;
400 	struct sbuf sbuf;
401 	int error, count;
402 
403 	sbuf_new_for_sysctl(&sbuf, NULL, 64, req);
404 	count = 0;
405 	LIST_FOREACH(rrs, &source_list, rrs_entries) {
406 		sbuf_cat(&sbuf, (count++ ? ",'" : "'"));
407 		sbuf_cat(&sbuf, rrs->rrs_source->rs_ident);
408 		sbuf_cat(&sbuf, "'");
409 	}
410 	error = sbuf_finish(&sbuf);
411 	sbuf_delete(&sbuf);
412 	return (error);
413 }
414 SYSCTL_PROC(_kern_random, OID_AUTO, random_sources, CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
415 	    NULL, 0, random_source_handler, "A",
416 	    "List of active fast entropy sources.");
417 #endif /* !defined(RANDOM_DUMMY) */
418 
419 /* ARGSUSED */
420 static int
421 randomdev_modevent(module_t mod __unused, int type, void *data __unused)
422 {
423 	int error = 0;
424 
425 	switch (type) {
426 	case MOD_LOAD:
427 		printf("random: entropy device external interface\n");
428 		random_dev = make_dev_credf(MAKEDEV_ETERNAL_KLD, &random_cdevsw,
429 		    RANDOM_UNIT, NULL, UID_ROOT, GID_WHEEL, 0644, "random");
430 		make_dev_alias(random_dev, "urandom"); /* compatibility */
431 		break;
432 	case MOD_UNLOAD:
433 		destroy_dev(random_dev);
434 		break;
435 	case MOD_SHUTDOWN:
436 		break;
437 	default:
438 		error = EOPNOTSUPP;
439 		break;
440 	}
441 	return (error);
442 }
443 
444 static moduledata_t randomdev_mod = {
445 	"random_device",
446 	randomdev_modevent,
447 	0
448 };
449 
450 DECLARE_MODULE(random_device, randomdev_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST);
451 MODULE_VERSION(random_device, 1);
452