xref: /freebsd/sys/dev/random/randomdev.c (revision 148a8da8)
1 /*-
2  * Copyright (c) 2017 Oliver Pinter
3  * Copyright (c) 2000-2015 Mark R V Murray
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer
11  *    in this position and unchanged.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  *
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/bus.h>
35 #include <sys/conf.h>
36 #include <sys/fcntl.h>
37 #include <sys/filio.h>
38 #include <sys/kernel.h>
39 #include <sys/kthread.h>
40 #include <sys/lock.h>
41 #include <sys/module.h>
42 #include <sys/malloc.h>
43 #include <sys/poll.h>
44 #include <sys/proc.h>
45 #include <sys/random.h>
46 #include <sys/sbuf.h>
47 #include <sys/selinfo.h>
48 #include <sys/sysctl.h>
49 #include <sys/systm.h>
50 #include <sys/uio.h>
51 #include <sys/unistd.h>
52 
53 #include <crypto/rijndael/rijndael-api-fst.h>
54 #include <crypto/sha2/sha256.h>
55 
56 #include <dev/random/hash.h>
57 #include <dev/random/randomdev.h>
58 #include <dev/random/random_harvestq.h>
59 
60 #define	RANDOM_UNIT	0
61 
62 #if defined(RANDOM_LOADABLE)
63 #define READ_RANDOM_UIO	_read_random_uio
64 #define READ_RANDOM	_read_random
65 #define IS_RANDOM_SEEDED	_is_random_seeded
66 static int READ_RANDOM_UIO(struct uio *, bool);
67 static void READ_RANDOM(void *, u_int);
68 static bool IS_RANDOM_SEEDED(void);
69 #else
70 #define READ_RANDOM_UIO	read_random_uio
71 #define READ_RANDOM	read_random
72 #define IS_RANDOM_SEEDED	is_random_seeded
73 #endif
74 
75 static d_read_t randomdev_read;
76 static d_write_t randomdev_write;
77 static d_poll_t randomdev_poll;
78 static d_ioctl_t randomdev_ioctl;
79 
80 static struct cdevsw random_cdevsw = {
81 	.d_name = "random",
82 	.d_version = D_VERSION,
83 	.d_read = randomdev_read,
84 	.d_write = randomdev_write,
85 	.d_poll = randomdev_poll,
86 	.d_ioctl = randomdev_ioctl,
87 };
88 
89 /* For use with make_dev(9)/destroy_dev(9). */
90 static struct cdev *random_dev;
91 
92 static void
93 random_alg_context_ra_init_alg(void *data)
94 {
95 
96 	p_random_alg_context = &random_alg_context;
97 	p_random_alg_context->ra_init_alg(data);
98 #if defined(RANDOM_LOADABLE)
99 	random_infra_init(READ_RANDOM_UIO, READ_RANDOM, IS_RANDOM_SEEDED);
100 #endif
101 }
102 
103 static void
104 random_alg_context_ra_deinit_alg(void *data)
105 {
106 
107 #if defined(RANDOM_LOADABLE)
108 	random_infra_uninit();
109 #endif
110 	p_random_alg_context->ra_deinit_alg(data);
111 	p_random_alg_context = NULL;
112 }
113 
114 SYSINIT(random_device, SI_SUB_RANDOM, SI_ORDER_THIRD, random_alg_context_ra_init_alg, NULL);
115 SYSUNINIT(random_device, SI_SUB_RANDOM, SI_ORDER_THIRD, random_alg_context_ra_deinit_alg, NULL);
116 
117 static struct selinfo rsel;
118 
119 /*
120  * This is the read uio(9) interface for random(4).
121  */
122 /* ARGSUSED */
123 static int
124 randomdev_read(struct cdev *dev __unused, struct uio *uio, int flags)
125 {
126 
127 	return (READ_RANDOM_UIO(uio, (flags & O_NONBLOCK) != 0));
128 }
129 
130 /*
131  * If the random device is not seeded, blocks until it is seeded.
132  *
133  * Returns zero when the random device is seeded.
134  *
135  * If the 'interruptible' parameter is true, and the device is unseeded, this
136  * routine may be interrupted.  If interrupted, it will return either ERESTART
137  * or EINTR.
138  */
139 #define SEEDWAIT_INTERRUPTIBLE		true
140 #define SEEDWAIT_UNINTERRUPTIBLE	false
141 static int
142 randomdev_wait_until_seeded(bool interruptible)
143 {
144 	int error, spamcount, slpflags;
145 
146 	slpflags = interruptible ? PCATCH : 0;
147 
148 	error = 0;
149 	spamcount = 0;
150 	while (!p_random_alg_context->ra_seeded()) {
151 		/* keep tapping away at the pre-read until we seed/unblock. */
152 		p_random_alg_context->ra_pre_read();
153 		/* Only bother the console every 10 seconds or so */
154 		if (spamcount == 0)
155 			printf("random: %s unblock wait\n", __func__);
156 		spamcount = (spamcount + 1) % 100;
157 		error = tsleep(&random_alg_context, slpflags, "randseed",
158 		    hz / 10);
159 		if (error == ERESTART || error == EINTR) {
160 			KASSERT(interruptible,
161 			    ("unexpected wake of non-interruptible sleep"));
162 			break;
163 		}
164 		/* Squash tsleep timeout condition */
165 		if (error == EWOULDBLOCK)
166 			error = 0;
167 		KASSERT(error == 0, ("unexpected tsleep error %d", error));
168 	}
169 	return (error);
170 }
171 
172 int
173 READ_RANDOM_UIO(struct uio *uio, bool nonblock)
174 {
175 	uint8_t *random_buf;
176 	int error;
177 	ssize_t read_len, total_read, c;
178 	/* 16 MiB takes about 0.08 s CPU time on my 2017 AMD Zen CPU */
179 #define SIGCHK_PERIOD (16 * 1024 * 1024)
180 	const size_t sigchk_period = SIGCHK_PERIOD;
181 
182 	CTASSERT(SIGCHK_PERIOD % PAGE_SIZE == 0);
183 #undef SIGCHK_PERIOD
184 
185 	random_buf = malloc(PAGE_SIZE, M_ENTROPY, M_WAITOK);
186 	p_random_alg_context->ra_pre_read();
187 	error = 0;
188 	/* (Un)Blocking logic */
189 	if (!p_random_alg_context->ra_seeded()) {
190 		if (nonblock)
191 			error = EWOULDBLOCK;
192 		else
193 			error = randomdev_wait_until_seeded(
194 			    SEEDWAIT_INTERRUPTIBLE);
195 	}
196 	if (error == 0) {
197 		read_rate_increment((uio->uio_resid + sizeof(uint32_t))/sizeof(uint32_t));
198 		total_read = 0;
199 		while (uio->uio_resid && !error) {
200 			read_len = uio->uio_resid;
201 			/*
202 			 * Belt-and-braces.
203 			 * Round up the read length to a crypto block size multiple,
204 			 * which is what the underlying generator is expecting.
205 			 * See the random_buf size requirements in the Fortuna code.
206 			 */
207 			read_len = roundup(read_len, RANDOM_BLOCKSIZE);
208 			/* Work in chunks page-sized or less */
209 			read_len = MIN(read_len, PAGE_SIZE);
210 			p_random_alg_context->ra_read(random_buf, read_len);
211 			c = MIN(uio->uio_resid, read_len);
212 			/*
213 			 * uiomove() may yield the CPU before each 'c' bytes
214 			 * (up to PAGE_SIZE) are copied out.
215 			 */
216 			error = uiomove(random_buf, c, uio);
217 			total_read += c;
218 			/*
219 			 * Poll for signals every few MBs to avoid very long
220 			 * uninterruptible syscalls.
221 			 */
222 			if (error == 0 && uio->uio_resid != 0 &&
223 			    total_read % sigchk_period == 0) {
224 				error = tsleep_sbt(&random_alg_context, PCATCH,
225 				    "randrd", SBT_1NS, 0, C_HARDCLOCK);
226 				/* Squash tsleep timeout condition */
227 				if (error == EWOULDBLOCK)
228 					error = 0;
229 			}
230 		}
231 		if (error == ERESTART || error == EINTR)
232 			error = 0;
233 	}
234 	free(random_buf, M_ENTROPY);
235 	return (error);
236 }
237 
238 /*-
239  * Kernel API version of read_random().  This is similar to read_random_uio(),
240  * except it doesn't interface with uio(9).  It cannot assumed that random_buf
241  * is a multiple of RANDOM_BLOCKSIZE bytes.
242  *
243  * If the tunable 'kern.random.initial_seeding.bypass_before_seeding' is set
244  * non-zero, silently fail to emit random data (matching the pre-r346250
245  * behavior).  If read_random is called prior to seeding and bypassed because
246  * of this tunable, the condition is reported in the read-only sysctl
247  * 'kern.random.initial_seeding.read_random_bypassed_before_seeding'.
248  */
249 void
250 READ_RANDOM(void *random_buf, u_int len)
251 {
252 	u_int read_directly_len;
253 
254 	KASSERT(random_buf != NULL, ("No suitable random buffer in %s", __func__));
255 	p_random_alg_context->ra_pre_read();
256 
257 	if (len == 0)
258 		return;
259 
260 	/* (Un)Blocking logic */
261 	if (__predict_false(!p_random_alg_context->ra_seeded())) {
262 		if (random_bypass_before_seeding) {
263 			if (!read_random_bypassed_before_seeding) {
264 				if (!random_bypass_disable_warnings)
265 					printf("read_random: WARNING: bypassing"
266 					    " request for random data because "
267 					    "the random device is not yet "
268 					    "seeded and the knob "
269 					    "'bypass_before_seeding' was "
270 					    "enabled.\n");
271 				read_random_bypassed_before_seeding = true;
272 			}
273 			/* Avoid potentially leaking stack garbage */
274 			memset(random_buf, 0, len);
275 			return;
276 		}
277 
278 		(void)randomdev_wait_until_seeded(SEEDWAIT_UNINTERRUPTIBLE);
279 	}
280 	read_rate_increment(roundup2(len, sizeof(uint32_t)));
281 	/*
282 	 * The underlying generator expects multiples of
283 	 * RANDOM_BLOCKSIZE.
284 	 */
285 	read_directly_len = rounddown(len, RANDOM_BLOCKSIZE);
286 	if (read_directly_len > 0)
287 		p_random_alg_context->ra_read(random_buf, read_directly_len);
288 	if (read_directly_len < len) {
289 		uint8_t remainder_buf[RANDOM_BLOCKSIZE];
290 
291 		p_random_alg_context->ra_read(remainder_buf,
292 		    sizeof(remainder_buf));
293 		memcpy((char *)random_buf + read_directly_len, remainder_buf,
294 		    len - read_directly_len);
295 
296 		explicit_bzero(remainder_buf, sizeof(remainder_buf));
297 	}
298 }
299 
300 bool
301 IS_RANDOM_SEEDED(void)
302 {
303 	return (p_random_alg_context->ra_seeded());
304 }
305 
306 static __inline void
307 randomdev_accumulate(uint8_t *buf, u_int count)
308 {
309 	static u_int destination = 0;
310 	static struct harvest_event event;
311 	static struct randomdev_hash hash;
312 	static uint32_t entropy_data[RANDOM_KEYSIZE_WORDS];
313 	uint32_t timestamp;
314 	int i;
315 
316 	/* Extra timing here is helpful to scrape scheduler jitter entropy */
317 	randomdev_hash_init(&hash);
318 	timestamp = (uint32_t)get_cyclecount();
319 	randomdev_hash_iterate(&hash, &timestamp, sizeof(timestamp));
320 	randomdev_hash_iterate(&hash, buf, count);
321 	timestamp = (uint32_t)get_cyclecount();
322 	randomdev_hash_iterate(&hash, &timestamp, sizeof(timestamp));
323 	randomdev_hash_finish(&hash, entropy_data);
324 	explicit_bzero(&hash, sizeof(hash));
325 	for (i = 0; i < RANDOM_KEYSIZE_WORDS; i += sizeof(event.he_entropy)/sizeof(event.he_entropy[0])) {
326 		event.he_somecounter = (uint32_t)get_cyclecount();
327 		event.he_size = sizeof(event.he_entropy);
328 		event.he_source = RANDOM_CACHED;
329 		event.he_destination = destination++; /* Harmless cheating */
330 		memcpy(event.he_entropy, entropy_data + i, sizeof(event.he_entropy));
331 		p_random_alg_context->ra_event_processor(&event);
332 	}
333 	explicit_bzero(entropy_data, sizeof(entropy_data));
334 }
335 
336 /* ARGSUSED */
337 static int
338 randomdev_write(struct cdev *dev __unused, struct uio *uio, int flags __unused)
339 {
340 	uint8_t *random_buf;
341 	int c, error = 0;
342 	ssize_t nbytes;
343 
344 	random_buf = malloc(PAGE_SIZE, M_ENTROPY, M_WAITOK);
345 	nbytes = uio->uio_resid;
346 	while (uio->uio_resid > 0 && error == 0) {
347 		c = MIN(uio->uio_resid, PAGE_SIZE);
348 		error = uiomove(random_buf, c, uio);
349 		if (error)
350 			break;
351 		randomdev_accumulate(random_buf, c);
352 		tsleep(&random_alg_context, 0, "randwr", hz/10);
353 	}
354 	if (nbytes != uio->uio_resid && (error == ERESTART || error == EINTR))
355 		/* Partial write, not error. */
356 		error = 0;
357 	free(random_buf, M_ENTROPY);
358 	return (error);
359 }
360 
361 /* ARGSUSED */
362 static int
363 randomdev_poll(struct cdev *dev __unused, int events, struct thread *td __unused)
364 {
365 
366 	if (events & (POLLIN | POLLRDNORM)) {
367 		if (p_random_alg_context->ra_seeded())
368 			events &= (POLLIN | POLLRDNORM);
369 		else
370 			selrecord(td, &rsel);
371 	}
372 	return (events);
373 }
374 
375 /* This will be called by the entropy processor when it seeds itself and becomes secure */
376 void
377 randomdev_unblock(void)
378 {
379 
380 	selwakeuppri(&rsel, PUSER);
381 	wakeup(&random_alg_context);
382 	printf("random: unblocking device.\n");
383 	/* Do random(9) a favour while we are about it. */
384 	(void)atomic_cmpset_int(&arc4rand_iniseed_state, ARC4_ENTR_NONE, ARC4_ENTR_HAVE);
385 }
386 
387 /* ARGSUSED */
388 static int
389 randomdev_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t addr __unused,
390     int flags __unused, struct thread *td __unused)
391 {
392 	int error = 0;
393 
394 	switch (cmd) {
395 		/* Really handled in upper layer */
396 	case FIOASYNC:
397 	case FIONBIO:
398 		break;
399 	default:
400 		error = ENOTTY;
401 	}
402 
403 	return (error);
404 }
405 
406 void
407 random_source_register(struct random_source *rsource)
408 {
409 	struct random_sources *rrs;
410 
411 	KASSERT(rsource != NULL, ("invalid input to %s", __func__));
412 
413 	rrs = malloc(sizeof(*rrs), M_ENTROPY, M_WAITOK);
414 	rrs->rrs_source = rsource;
415 
416 	random_harvest_register_source(rsource->rs_source);
417 
418 	printf("random: registering fast source %s\n", rsource->rs_ident);
419 	LIST_INSERT_HEAD(&source_list, rrs, rrs_entries);
420 }
421 
422 void
423 random_source_deregister(struct random_source *rsource)
424 {
425 	struct random_sources *rrs = NULL;
426 
427 	KASSERT(rsource != NULL, ("invalid input to %s", __func__));
428 
429 	random_harvest_deregister_source(rsource->rs_source);
430 
431 	LIST_FOREACH(rrs, &source_list, rrs_entries)
432 		if (rrs->rrs_source == rsource) {
433 			LIST_REMOVE(rrs, rrs_entries);
434 			break;
435 		}
436 	if (rrs != NULL)
437 		free(rrs, M_ENTROPY);
438 }
439 
440 static int
441 random_source_handler(SYSCTL_HANDLER_ARGS)
442 {
443 	struct random_sources *rrs;
444 	struct sbuf sbuf;
445 	int error, count;
446 
447 	sbuf_new_for_sysctl(&sbuf, NULL, 64, req);
448 	count = 0;
449 	LIST_FOREACH(rrs, &source_list, rrs_entries) {
450 		sbuf_cat(&sbuf, (count++ ? ",'" : "'"));
451 		sbuf_cat(&sbuf, rrs->rrs_source->rs_ident);
452 		sbuf_cat(&sbuf, "'");
453 	}
454 	error = sbuf_finish(&sbuf);
455 	sbuf_delete(&sbuf);
456 	return (error);
457 }
458 SYSCTL_PROC(_kern_random, OID_AUTO, random_sources, CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
459 	    NULL, 0, random_source_handler, "A",
460 	    "List of active fast entropy sources.");
461 
462 /* ARGSUSED */
463 static int
464 randomdev_modevent(module_t mod __unused, int type, void *data __unused)
465 {
466 	int error = 0;
467 
468 	switch (type) {
469 	case MOD_LOAD:
470 		printf("random: entropy device external interface\n");
471 		random_dev = make_dev_credf(MAKEDEV_ETERNAL_KLD, &random_cdevsw,
472 		    RANDOM_UNIT, NULL, UID_ROOT, GID_WHEEL, 0644, "random");
473 		make_dev_alias(random_dev, "urandom"); /* compatibility */
474 		break;
475 	case MOD_UNLOAD:
476 		destroy_dev(random_dev);
477 		break;
478 	case MOD_SHUTDOWN:
479 		break;
480 	default:
481 		error = EOPNOTSUPP;
482 		break;
483 	}
484 	return (error);
485 }
486 
487 static moduledata_t randomdev_mod = {
488 	"random_device",
489 	randomdev_modevent,
490 	0
491 };
492 
493 DECLARE_MODULE(random_device, randomdev_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST);
494 MODULE_VERSION(random_device, 1);
495 MODULE_DEPEND(random_device, crypto, 1, 1, 1);
496 MODULE_DEPEND(random_device, random_harvestq, 1, 1, 1);
497