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