xref: /freebsd/sys/dev/random/randomdev.c (revision ca987d4641cdcd7f27e153db17c5bf064934faf5)
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 static int READ_RANDOM_UIO(struct uio *, bool);
66 static u_int READ_RANDOM(void *, u_int);
67 #else
68 #define READ_RANDOM_UIO	read_random_uio
69 #define READ_RANDOM	read_random
70 #endif
71 
72 static d_read_t randomdev_read;
73 static d_write_t randomdev_write;
74 static d_poll_t randomdev_poll;
75 static d_ioctl_t randomdev_ioctl;
76 
77 static struct cdevsw random_cdevsw = {
78 	.d_name = "random",
79 	.d_version = D_VERSION,
80 	.d_read = randomdev_read,
81 	.d_write = randomdev_write,
82 	.d_poll = randomdev_poll,
83 	.d_ioctl = randomdev_ioctl,
84 };
85 
86 /* For use with make_dev(9)/destroy_dev(9). */
87 static struct cdev *random_dev;
88 
89 static void
90 random_alg_context_ra_init_alg(void *data)
91 {
92 
93 	p_random_alg_context = &random_alg_context;
94 	p_random_alg_context->ra_init_alg(data);
95 #if defined(RANDOM_LOADABLE)
96 	random_infra_init(READ_RANDOM_UIO, READ_RANDOM);
97 #endif
98 }
99 
100 static void
101 random_alg_context_ra_deinit_alg(void *data)
102 {
103 
104 #if defined(RANDOM_LOADABLE)
105 	random_infra_uninit();
106 #endif
107 	p_random_alg_context->ra_deinit_alg(data);
108 	p_random_alg_context = NULL;
109 }
110 
111 SYSINIT(random_device, SI_SUB_RANDOM, SI_ORDER_THIRD, random_alg_context_ra_init_alg, NULL);
112 SYSUNINIT(random_device, SI_SUB_RANDOM, SI_ORDER_THIRD, random_alg_context_ra_deinit_alg, NULL);
113 
114 static struct selinfo rsel;
115 
116 /*
117  * This is the read uio(9) interface for random(4).
118  */
119 /* ARGSUSED */
120 static int
121 randomdev_read(struct cdev *dev __unused, struct uio *uio, int flags)
122 {
123 
124 	return (READ_RANDOM_UIO(uio, (flags & O_NONBLOCK) != 0));
125 }
126 
127 int
128 READ_RANDOM_UIO(struct uio *uio, bool nonblock)
129 {
130 	uint8_t *random_buf;
131 	int error, spamcount;
132 	ssize_t read_len, total_read, c;
133 
134 	random_buf = malloc(PAGE_SIZE, M_ENTROPY, M_WAITOK);
135 	p_random_alg_context->ra_pre_read();
136 	error = 0;
137 	spamcount = 0;
138 	/* (Un)Blocking logic */
139 	while (!p_random_alg_context->ra_seeded()) {
140 		if (nonblock) {
141 			error = EWOULDBLOCK;
142 			break;
143 		}
144 		/* keep tapping away at the pre-read until we seed/unblock. */
145 		p_random_alg_context->ra_pre_read();
146 		/* Only bother the console every 10 seconds or so */
147 		if (spamcount == 0)
148 			printf("random: %s unblock wait\n", __func__);
149 		spamcount = (spamcount + 1)%100;
150 		error = tsleep(&random_alg_context, PCATCH, "randseed", hz/10);
151 		if (error == ERESTART || error == EINTR)
152 			break;
153 	}
154 	if (error == 0) {
155 		read_rate_increment((uio->uio_resid + sizeof(uint32_t))/sizeof(uint32_t));
156 		total_read = 0;
157 		while (uio->uio_resid && !error) {
158 			read_len = uio->uio_resid;
159 			/*
160 			 * Belt-and-braces.
161 			 * Round up the read length to a crypto block size multiple,
162 			 * which is what the underlying generator is expecting.
163 			 * See the random_buf size requirements in the Yarrow/Fortuna code.
164 			 */
165 			read_len = roundup(read_len, RANDOM_BLOCKSIZE);
166 			/* Work in chunks page-sized or less */
167 			read_len = MIN(read_len, PAGE_SIZE);
168 			p_random_alg_context->ra_read(random_buf, read_len);
169 			c = MIN(uio->uio_resid, read_len);
170 			error = uiomove(random_buf, c, uio);
171 			total_read += c;
172 		}
173 		if (total_read != uio->uio_resid && (error == ERESTART || error == EINTR))
174 			/* Return partial read, not error. */
175 			error = 0;
176 	}
177 	free(random_buf, M_ENTROPY);
178 	return (error);
179 }
180 
181 /*-
182  * Kernel API version of read_random().
183  * This is similar to random_alg_read(),
184  * except it doesn't interface with uio(9).
185  * It cannot assumed that random_buf is a multiple of
186  * RANDOM_BLOCKSIZE bytes.
187  */
188 u_int
189 READ_RANDOM(void *random_buf, u_int len)
190 {
191 	u_int read_len;
192 	uint8_t local_buf[len + RANDOM_BLOCKSIZE];
193 
194 	KASSERT(random_buf != NULL, ("No suitable random buffer in %s", __func__));
195 	p_random_alg_context->ra_pre_read();
196 	/* (Un)Blocking logic; if not seeded, return nothing. */
197 	if (p_random_alg_context->ra_seeded()) {
198 		read_rate_increment((len + sizeof(uint32_t))/sizeof(uint32_t));
199 		if (len > 0) {
200 			/*
201 			 * Belt-and-braces.
202 			 * Round up the read length to a crypto block size multiple,
203 			 * which is what the underlying generator is expecting.
204 			 */
205 			read_len = roundup(len, RANDOM_BLOCKSIZE);
206 			p_random_alg_context->ra_read(local_buf, read_len);
207 			memcpy(random_buf, local_buf, len);
208 		}
209 	} else
210 		len = 0;
211 	return (len);
212 }
213 
214 static __inline void
215 randomdev_accumulate(uint8_t *buf, u_int count)
216 {
217 	static u_int destination = 0;
218 	static struct harvest_event event;
219 	static struct randomdev_hash hash;
220 	static uint32_t entropy_data[RANDOM_KEYSIZE_WORDS];
221 	uint32_t timestamp;
222 	int i;
223 
224 	/* Extra timing here is helpful to scrape scheduler jitter entropy */
225 	randomdev_hash_init(&hash);
226 	timestamp = (uint32_t)get_cyclecount();
227 	randomdev_hash_iterate(&hash, &timestamp, sizeof(timestamp));
228 	randomdev_hash_iterate(&hash, buf, count);
229 	timestamp = (uint32_t)get_cyclecount();
230 	randomdev_hash_iterate(&hash, &timestamp, sizeof(timestamp));
231 	randomdev_hash_finish(&hash, entropy_data);
232 	explicit_bzero(&hash, sizeof(hash));
233 	for (i = 0; i < RANDOM_KEYSIZE_WORDS; i += sizeof(event.he_entropy)/sizeof(event.he_entropy[0])) {
234 		event.he_somecounter = (uint32_t)get_cyclecount();
235 		event.he_size = sizeof(event.he_entropy);
236 		event.he_bits = event.he_size/8;
237 		event.he_source = RANDOM_CACHED;
238 		event.he_destination = destination++; /* Harmless cheating */
239 		memcpy(event.he_entropy, entropy_data + i, sizeof(event.he_entropy));
240 		p_random_alg_context->ra_event_processor(&event);
241 	}
242 	explicit_bzero(entropy_data, sizeof(entropy_data));
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 		randomdev_accumulate(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 (p_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 	struct random_sources *rrs;
319 
320 	KASSERT(rsource != NULL, ("invalid input to %s", __func__));
321 
322 	rrs = malloc(sizeof(*rrs), M_ENTROPY, M_WAITOK);
323 	rrs->rrs_source = rsource;
324 
325 	random_harvest_register_source(rsource->rs_source);
326 
327 	printf("random: registering fast source %s\n", rsource->rs_ident);
328 	LIST_INSERT_HEAD(&source_list, rrs, rrs_entries);
329 }
330 
331 void
332 random_source_deregister(struct random_source *rsource)
333 {
334 	struct random_sources *rrs = NULL;
335 
336 	KASSERT(rsource != NULL, ("invalid input to %s", __func__));
337 
338 	random_harvest_deregister_source(rsource->rs_source);
339 
340 	LIST_FOREACH(rrs, &source_list, rrs_entries)
341 		if (rrs->rrs_source == rsource) {
342 			LIST_REMOVE(rrs, rrs_entries);
343 			break;
344 		}
345 	if (rrs != NULL)
346 		free(rrs, M_ENTROPY);
347 }
348 
349 static int
350 random_source_handler(SYSCTL_HANDLER_ARGS)
351 {
352 	struct random_sources *rrs;
353 	struct sbuf sbuf;
354 	int error, count;
355 
356 	sbuf_new_for_sysctl(&sbuf, NULL, 64, req);
357 	count = 0;
358 	LIST_FOREACH(rrs, &source_list, rrs_entries) {
359 		sbuf_cat(&sbuf, (count++ ? ",'" : "'"));
360 		sbuf_cat(&sbuf, rrs->rrs_source->rs_ident);
361 		sbuf_cat(&sbuf, "'");
362 	}
363 	error = sbuf_finish(&sbuf);
364 	sbuf_delete(&sbuf);
365 	return (error);
366 }
367 SYSCTL_PROC(_kern_random, OID_AUTO, random_sources, CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
368 	    NULL, 0, random_source_handler, "A",
369 	    "List of active fast entropy sources.");
370 
371 /* ARGSUSED */
372 static int
373 randomdev_modevent(module_t mod __unused, int type, void *data __unused)
374 {
375 	int error = 0;
376 
377 	switch (type) {
378 	case MOD_LOAD:
379 		printf("random: entropy device external interface\n");
380 		random_dev = make_dev_credf(MAKEDEV_ETERNAL_KLD, &random_cdevsw,
381 		    RANDOM_UNIT, NULL, UID_ROOT, GID_WHEEL, 0644, "random");
382 		make_dev_alias(random_dev, "urandom"); /* compatibility */
383 		break;
384 	case MOD_UNLOAD:
385 		destroy_dev(random_dev);
386 		break;
387 	case MOD_SHUTDOWN:
388 		break;
389 	default:
390 		error = EOPNOTSUPP;
391 		break;
392 	}
393 	return (error);
394 }
395 
396 static moduledata_t randomdev_mod = {
397 	"random_device",
398 	randomdev_modevent,
399 	0
400 };
401 
402 DECLARE_MODULE(random_device, randomdev_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST);
403 MODULE_VERSION(random_device, 1);
404 MODULE_DEPEND(random_device, crypto, 1, 1, 1);
405 MODULE_DEPEND(random_device, random_harvestq, 1, 1, 1);
406