xref: /freebsd/sys/dev/random/randomdev.c (revision 22d7dd834bc5cd189810e414701e3ad1e98102e4)
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 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/bus.h>
33 #include <sys/conf.h>
34 #include <sys/fcntl.h>
35 #include <sys/filio.h>
36 #include <sys/kernel.h>
37 #include <sys/kthread.h>
38 #include <sys/lock.h>
39 #include <sys/module.h>
40 #include <sys/malloc.h>
41 #include <sys/poll.h>
42 #include <sys/proc.h>
43 #include <sys/random.h>
44 #include <sys/sbuf.h>
45 #include <sys/selinfo.h>
46 #include <sys/sysctl.h>
47 #include <sys/systm.h>
48 #include <sys/uio.h>
49 #include <sys/unistd.h>
50 
51 #include <crypto/rijndael/rijndael-api-fst.h>
52 #include <crypto/sha2/sha256.h>
53 
54 #include <dev/random/hash.h>
55 #include <dev/random/randomdev.h>
56 #include <dev/random/random_harvestq.h>
57 
58 #define	RANDOM_UNIT	0
59 
60 /*
61  * In loadable random, the core randomdev.c / random(9) routines have static
62  * visibility and an alternative name to avoid conflicting with the function
63  * pointers of the real names in the core kernel.  random_alg_context_init
64  * installs pointers to the loadable static names into the core kernel's
65  * function pointers at SI_SUB_RANDOM:SI_ORDER_SECOND.
66  */
67 #if defined(RANDOM_LOADABLE)
68 static int (read_random_uio)(struct uio *, bool);
69 static void (read_random)(void *, u_int);
70 static bool (is_random_seeded)(void);
71 #endif
72 
73 static d_read_t randomdev_read;
74 static d_write_t randomdev_write;
75 static d_poll_t randomdev_poll;
76 static d_ioctl_t randomdev_ioctl;
77 
78 static struct cdevsw random_cdevsw = {
79 	.d_name = "random",
80 	.d_version = D_VERSION,
81 	.d_read = randomdev_read,
82 	.d_write = randomdev_write,
83 	.d_poll = randomdev_poll,
84 	.d_ioctl = randomdev_ioctl,
85 };
86 
87 /* For use with make_dev(9)/destroy_dev(9). */
88 static struct cdev *random_dev;
89 
90 #if defined(RANDOM_LOADABLE)
91 static void
92 random_alg_context_init(void *dummy __unused)
93 {
94 	_read_random_uio = (read_random_uio);
95 	_read_random = (read_random);
96 	_is_random_seeded = (is_random_seeded);
97 }
98 SYSINIT(random_device, SI_SUB_RANDOM, SI_ORDER_SECOND, random_alg_context_init,
99     NULL);
100 #endif
101 
102 static struct selinfo rsel;
103 
104 /*
105  * This is the read uio(9) interface for random(4).
106  */
107 /* ARGSUSED */
108 static int
109 randomdev_read(struct cdev *dev __unused, struct uio *uio, int flags)
110 {
111 
112 	return ((read_random_uio)(uio, (flags & O_NONBLOCK) != 0));
113 }
114 
115 /*
116  * If the random device is not seeded, blocks until it is seeded.
117  *
118  * Returns zero when the random device is seeded.
119  *
120  * If the 'interruptible' parameter is true, and the device is unseeded, this
121  * routine may be interrupted.  If interrupted, it will return either ERESTART
122  * or EINTR.
123  */
124 #define SEEDWAIT_INTERRUPTIBLE		true
125 #define SEEDWAIT_UNINTERRUPTIBLE	false
126 static int
127 randomdev_wait_until_seeded(bool interruptible)
128 {
129 	int error, spamcount, slpflags;
130 
131 	slpflags = interruptible ? PCATCH : 0;
132 
133 	error = 0;
134 	spamcount = 0;
135 	while (!p_random_alg_context->ra_seeded()) {
136 		/* keep tapping away at the pre-read until we seed/unblock. */
137 		p_random_alg_context->ra_pre_read();
138 		/* Only bother the console every 10 seconds or so */
139 		if (spamcount == 0)
140 			printf("random: %s unblock wait\n", __func__);
141 		spamcount = (spamcount + 1) % 100;
142 		error = tsleep(p_random_alg_context, slpflags, "randseed",
143 		    hz / 10);
144 		if (error == ERESTART || error == EINTR) {
145 			KASSERT(interruptible,
146 			    ("unexpected wake of non-interruptible sleep"));
147 			break;
148 		}
149 		/* Squash tsleep timeout condition */
150 		if (error == EWOULDBLOCK)
151 			error = 0;
152 		KASSERT(error == 0, ("unexpected tsleep error %d", error));
153 	}
154 	return (error);
155 }
156 
157 int
158 (read_random_uio)(struct uio *uio, bool nonblock)
159 {
160 	/* 16 MiB takes about 0.08 s CPU time on my 2017 AMD Zen CPU */
161 #define SIGCHK_PERIOD (16 * 1024 * 1024)
162 	const size_t sigchk_period = SIGCHK_PERIOD;
163 	CTASSERT(SIGCHK_PERIOD % PAGE_SIZE == 0);
164 #undef SIGCHK_PERIOD
165 
166 	uint8_t *random_buf;
167 	size_t total_read, read_len;
168 	ssize_t bufsize;
169 	int error;
170 
171 
172 	KASSERT(uio->uio_rw == UIO_READ, ("%s: bogus write", __func__));
173 	KASSERT(uio->uio_resid >= 0, ("%s: bogus negative resid", __func__));
174 
175 	p_random_alg_context->ra_pre_read();
176 	error = 0;
177 	/* (Un)Blocking logic */
178 	if (!p_random_alg_context->ra_seeded()) {
179 		if (nonblock)
180 			error = EWOULDBLOCK;
181 		else
182 			error = randomdev_wait_until_seeded(
183 			    SEEDWAIT_INTERRUPTIBLE);
184 	}
185 	if (error != 0)
186 		return (error);
187 
188 	total_read = 0;
189 
190 	/* Easy to deal with the trivial 0 byte case. */
191 	if (__predict_false(uio->uio_resid == 0))
192 		return (0);
193 
194 	/*
195 	 * If memory is plentiful, use maximally sized requests to avoid
196 	 * per-call algorithm overhead.  But fall back to a single page
197 	 * allocation if the full request isn't immediately available.
198 	 */
199 	bufsize = MIN(sigchk_period, (size_t)uio->uio_resid);
200 	random_buf = malloc(bufsize, M_ENTROPY, M_NOWAIT);
201 	if (random_buf == NULL) {
202 		bufsize = PAGE_SIZE;
203 		random_buf = malloc(bufsize, M_ENTROPY, M_WAITOK);
204 	}
205 
206 	error = 0;
207 	while (uio->uio_resid > 0 && error == 0) {
208 		read_len = MIN((size_t)uio->uio_resid, bufsize);
209 
210 		p_random_alg_context->ra_read(random_buf, read_len);
211 
212 		/*
213 		 * uiomove() may yield the CPU before each 'read_len' bytes (up
214 		 * to bufsize) are copied out.
215 		 */
216 		error = uiomove(random_buf, read_len, uio);
217 		total_read += read_len;
218 
219 		/*
220 		 * Poll for signals every few MBs to avoid very long
221 		 * uninterruptible syscalls.
222 		 */
223 		if (error == 0 && uio->uio_resid != 0 &&
224 		    total_read % sigchk_period == 0) {
225 			error = tsleep_sbt(p_random_alg_context, PCATCH,
226 			    "randrd", SBT_1NS, 0, C_HARDCLOCK);
227 			/* Squash tsleep timeout condition */
228 			if (error == EWOULDBLOCK)
229 				error = 0;
230 		}
231 	}
232 
233 	/*
234 	 * Short reads due to signal interrupt should not indicate error.
235 	 * Instead, the uio will reflect that the read was shorter than
236 	 * requested.
237 	 */
238 	if (error == ERESTART || error == EINTR)
239 		error = 0;
240 
241 	zfree(random_buf, M_ENTROPY);
242 	return (error);
243 }
244 
245 /*-
246  * Kernel API version of read_random().  This is similar to read_random_uio(),
247  * except it doesn't interface with uio(9).  It cannot assumed that random_buf
248  * is a multiple of RANDOM_BLOCKSIZE bytes.
249  *
250  * If the tunable 'kern.random.initial_seeding.bypass_before_seeding' is set
251  * non-zero, silently fail to emit random data (matching the pre-r346250
252  * behavior).  If read_random is called prior to seeding and bypassed because
253  * of this tunable, the condition is reported in the read-only sysctl
254  * 'kern.random.initial_seeding.read_random_bypassed_before_seeding'.
255  */
256 void
257 (read_random)(void *random_buf, u_int len)
258 {
259 
260 	KASSERT(random_buf != NULL, ("No suitable random buffer in %s", __func__));
261 	p_random_alg_context->ra_pre_read();
262 
263 	if (len == 0)
264 		return;
265 
266 	/* (Un)Blocking logic */
267 	if (__predict_false(!p_random_alg_context->ra_seeded())) {
268 		if (random_bypass_before_seeding) {
269 			if (!read_random_bypassed_before_seeding) {
270 				if (!random_bypass_disable_warnings)
271 					printf("read_random: WARNING: bypassing"
272 					    " request for random data because "
273 					    "the random device is not yet "
274 					    "seeded and the knob "
275 					    "'bypass_before_seeding' was "
276 					    "enabled.\n");
277 				read_random_bypassed_before_seeding = true;
278 			}
279 			/* Avoid potentially leaking stack garbage */
280 			memset(random_buf, 0, len);
281 			return;
282 		}
283 
284 		(void)randomdev_wait_until_seeded(SEEDWAIT_UNINTERRUPTIBLE);
285 	}
286 	p_random_alg_context->ra_read(random_buf, len);
287 }
288 
289 bool
290 (is_random_seeded)(void)
291 {
292 	return (p_random_alg_context->ra_seeded());
293 }
294 
295 static __inline void
296 randomdev_accumulate(uint8_t *buf, u_int count)
297 {
298 	static u_int destination = 0;
299 	static struct harvest_event event;
300 	static struct randomdev_hash hash;
301 	static uint32_t entropy_data[RANDOM_KEYSIZE_WORDS];
302 	uint32_t timestamp;
303 	int i;
304 
305 	/* Extra timing here is helpful to scrape scheduler jitter entropy */
306 	randomdev_hash_init(&hash);
307 	timestamp = (uint32_t)get_cyclecount();
308 	randomdev_hash_iterate(&hash, &timestamp, sizeof(timestamp));
309 	randomdev_hash_iterate(&hash, buf, count);
310 	timestamp = (uint32_t)get_cyclecount();
311 	randomdev_hash_iterate(&hash, &timestamp, sizeof(timestamp));
312 	randomdev_hash_finish(&hash, entropy_data);
313 	for (i = 0; i < RANDOM_KEYSIZE_WORDS; i += sizeof(event.he_entropy)/sizeof(event.he_entropy[0])) {
314 		event.he_somecounter = (uint32_t)get_cyclecount();
315 		event.he_size = sizeof(event.he_entropy);
316 		event.he_source = RANDOM_CACHED;
317 		event.he_destination = destination++; /* Harmless cheating */
318 		memcpy(event.he_entropy, entropy_data + i, sizeof(event.he_entropy));
319 		p_random_alg_context->ra_event_processor(&event);
320 	}
321 	explicit_bzero(&event, sizeof(event));
322 	explicit_bzero(entropy_data, sizeof(entropy_data));
323 }
324 
325 /* ARGSUSED */
326 static int
327 randomdev_write(struct cdev *dev __unused, struct uio *uio, int flags __unused)
328 {
329 	uint8_t *random_buf;
330 	int c, error = 0;
331 	ssize_t nbytes;
332 
333 	random_buf = malloc(PAGE_SIZE, M_ENTROPY, M_WAITOK);
334 	nbytes = uio->uio_resid;
335 	while (uio->uio_resid > 0 && error == 0) {
336 		c = MIN(uio->uio_resid, PAGE_SIZE);
337 		error = uiomove(random_buf, c, uio);
338 		if (error)
339 			break;
340 		randomdev_accumulate(random_buf, c);
341 	}
342 	if (nbytes != uio->uio_resid && (error == ERESTART || error == EINTR))
343 		/* Partial write, not error. */
344 		error = 0;
345 	free(random_buf, M_ENTROPY);
346 	return (error);
347 }
348 
349 /* ARGSUSED */
350 static int
351 randomdev_poll(struct cdev *dev __unused, int events, struct thread *td __unused)
352 {
353 
354 	if (events & (POLLIN | POLLRDNORM)) {
355 		if (p_random_alg_context->ra_seeded())
356 			events &= (POLLIN | POLLRDNORM);
357 		else
358 			selrecord(td, &rsel);
359 	}
360 	return (events);
361 }
362 
363 /* This will be called by the entropy processor when it seeds itself and becomes secure */
364 void
365 randomdev_unblock(void)
366 {
367 
368 	selwakeuppri(&rsel, PUSER);
369 	wakeup(p_random_alg_context);
370 	printf("random: unblocking device.\n");
371 #ifndef RANDOM_FENESTRASX
372 	/* Do random(9) a favour while we are about it. */
373 	(void)atomic_cmpset_int(&arc4rand_iniseed_state, ARC4_ENTR_NONE, ARC4_ENTR_HAVE);
374 #endif
375 }
376 
377 /* ARGSUSED */
378 static int
379 randomdev_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t addr __unused,
380     int flags __unused, struct thread *td __unused)
381 {
382 	int error = 0;
383 
384 	switch (cmd) {
385 		/* Really handled in upper layer */
386 	case FIOASYNC:
387 	case FIONBIO:
388 		break;
389 	default:
390 		error = ENOTTY;
391 	}
392 
393 	return (error);
394 }
395 
396 /* ARGSUSED */
397 static int
398 randomdev_modevent(module_t mod __unused, int type, void *data __unused)
399 {
400 	int error = 0;
401 
402 	switch (type) {
403 	case MOD_LOAD:
404 		printf("random: entropy device external interface\n");
405 		random_dev = make_dev_credf(MAKEDEV_ETERNAL_KLD, &random_cdevsw,
406 		    RANDOM_UNIT, NULL, UID_ROOT, GID_WHEEL, 0644, "random");
407 		make_dev_alias(random_dev, "urandom"); /* compatibility */
408 		break;
409 	case MOD_UNLOAD:
410 		error = EBUSY;
411 		break;
412 	case MOD_SHUTDOWN:
413 		break;
414 	default:
415 		error = EOPNOTSUPP;
416 		break;
417 	}
418 	return (error);
419 }
420 
421 static moduledata_t randomdev_mod = {
422 	"random_device",
423 	randomdev_modevent,
424 	0
425 };
426 
427 DECLARE_MODULE(random_device, randomdev_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST);
428 MODULE_VERSION(random_device, 1);
429 MODULE_DEPEND(random_device, crypto, 1, 1, 1);
430 MODULE_DEPEND(random_device, random_harvestq, 1, 1, 1);
431