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