xref: /freebsd/sys/dev/random/randomdev.c (revision 9034852c84a13f0e3b5527e1c886ca94b2863b2b)
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 #define	RANDOM_UNIT	0
60 
61 #if defined(RANDOM_LOADABLE)
62 #define READ_RANDOM_UIO	_read_random_uio
63 #define READ_RANDOM	_read_random
64 static int READ_RANDOM_UIO(struct uio *, bool);
65 static u_int READ_RANDOM(void *, u_int);
66 #else
67 #define READ_RANDOM_UIO	read_random_uio
68 #define READ_RANDOM	read_random
69 #endif
70 
71 /* Return the largest number >= x that is a multiple of m */
72 #define CEIL_TO_MULTIPLE(x, m) ((((x) + (m) - 1)/(m))*(m))
73 
74 static d_read_t randomdev_read;
75 static d_write_t randomdev_write;
76 static d_poll_t randomdev_poll;
77 static d_ioctl_t randomdev_ioctl;
78 
79 static struct cdevsw random_cdevsw = {
80 	.d_name = "random",
81 	.d_version = D_VERSION,
82 	.d_read = randomdev_read,
83 	.d_write = randomdev_write,
84 	.d_poll = randomdev_poll,
85 	.d_ioctl = randomdev_ioctl,
86 };
87 
88 /* For use with make_dev(9)/destroy_dev(9). */
89 static struct cdev *random_dev;
90 
91 static void
92 random_alg_context_ra_init_alg(void *data)
93 {
94 
95 	p_random_alg_context = &random_alg_context;
96 	p_random_alg_context->ra_init_alg(data);
97 #if defined(RANDOM_LOADABLE)
98 	random_infra_init(READ_RANDOM_UIO, READ_RANDOM);
99 #endif
100 }
101 
102 static void
103 random_alg_context_ra_deinit_alg(void *data)
104 {
105 
106 #if defined(RANDOM_LOADABLE)
107 	random_infra_uninit();
108 #endif
109 	p_random_alg_context->ra_deinit_alg(data);
110 	p_random_alg_context = NULL;
111 }
112 
113 SYSINIT(random_device, SI_SUB_RANDOM, SI_ORDER_THIRD, random_alg_context_ra_init_alg, NULL);
114 SYSUNINIT(random_device, SI_SUB_RANDOM, SI_ORDER_THIRD, random_alg_context_ra_deinit_alg, NULL);
115 
116 static struct selinfo rsel;
117 
118 /*
119  * This is the read uio(9) interface for random(4).
120  */
121 /* ARGSUSED */
122 static int
123 randomdev_read(struct cdev *dev __unused, struct uio *uio, int flags)
124 {
125 
126 	return (READ_RANDOM_UIO(uio, (flags & O_NONBLOCK) != 0));
127 }
128 
129 int
130 READ_RANDOM_UIO(struct uio *uio, bool nonblock)
131 {
132 	uint8_t *random_buf;
133 	int error, spamcount;
134 	ssize_t read_len, total_read, c;
135 
136 	random_buf = malloc(PAGE_SIZE, M_ENTROPY, M_WAITOK);
137 	p_random_alg_context->ra_pre_read();
138 	error = 0;
139 	spamcount = 0;
140 	/* (Un)Blocking logic */
141 	while (!p_random_alg_context->ra_seeded()) {
142 		if (nonblock) {
143 			error = EWOULDBLOCK;
144 			break;
145 		}
146 		/* keep tapping away at the pre-read until we seed/unblock. */
147 		p_random_alg_context->ra_pre_read();
148 		/* Only bother the console every 10 seconds or so */
149 		if (spamcount == 0)
150 			printf("random: %s unblock wait\n", __func__);
151 		spamcount = (spamcount + 1)%100;
152 		error = tsleep(&random_alg_context, PCATCH, "randseed", hz/10);
153 		if (error == ERESTART || error == EINTR)
154 			break;
155 	}
156 	if (error == 0) {
157 		read_rate_increment((uio->uio_resid + sizeof(uint32_t))/sizeof(uint32_t));
158 		total_read = 0;
159 		while (uio->uio_resid && !error) {
160 			read_len = uio->uio_resid;
161 			/*
162 			 * Belt-and-braces.
163 			 * Round up the read length to a crypto block size multiple,
164 			 * which is what the underlying generator is expecting.
165 			 * See the random_buf size requirements in the Yarrow/Fortuna code.
166 			 */
167 			read_len = CEIL_TO_MULTIPLE(read_len, RANDOM_BLOCKSIZE);
168 			/* Work in chunks page-sized or less */
169 			read_len = MIN(read_len, PAGE_SIZE);
170 			p_random_alg_context->ra_read(random_buf, read_len);
171 			c = MIN(uio->uio_resid, read_len);
172 			error = uiomove(random_buf, c, uio);
173 			total_read += c;
174 		}
175 		if (total_read != uio->uio_resid && (error == ERESTART || error == EINTR))
176 			/* Return partial read, not error. */
177 			error = 0;
178 	}
179 	free(random_buf, M_ENTROPY);
180 	return (error);
181 }
182 
183 /*-
184  * Kernel API version of read_random().
185  * This is similar to random_alg_read(),
186  * except it doesn't interface with uio(9).
187  * It cannot assumed that random_buf is a multiple of
188  * RANDOM_BLOCKSIZE bytes.
189  */
190 u_int
191 READ_RANDOM(void *random_buf, u_int len)
192 {
193 	u_int read_len;
194 	uint8_t local_buf[len + RANDOM_BLOCKSIZE];
195 
196 	KASSERT(random_buf != NULL, ("No suitable random buffer in %s", __func__));
197 	p_random_alg_context->ra_pre_read();
198 	/* (Un)Blocking logic; if not seeded, return nothing. */
199 	if (p_random_alg_context->ra_seeded()) {
200 		read_rate_increment((len + sizeof(uint32_t))/sizeof(uint32_t));
201 		if (len > 0) {
202 			/*
203 			 * Belt-and-braces.
204 			 * Round up the read length to a crypto block size multiple,
205 			 * which is what the underlying generator is expecting.
206 			 */
207 			read_len = CEIL_TO_MULTIPLE(len, RANDOM_BLOCKSIZE);
208 			p_random_alg_context->ra_read(local_buf, read_len);
209 			memcpy(random_buf, local_buf, len);
210 		}
211 	} else
212 		len = 0;
213 	return (len);
214 }
215 
216 static __inline void
217 randomdev_accumulate(uint8_t *buf, u_int count)
218 {
219 	static u_int destination = 0;
220 	static struct harvest_event event;
221 	static struct randomdev_hash hash;
222 	static uint32_t entropy_data[RANDOM_KEYSIZE_WORDS];
223 	uint32_t timestamp;
224 	int i;
225 
226 	/* Extra timing here is helpful to scrape scheduler jitter entropy */
227 	randomdev_hash_init(&hash);
228 	timestamp = (uint32_t)get_cyclecount();
229 	randomdev_hash_iterate(&hash, &timestamp, sizeof(timestamp));
230 	randomdev_hash_iterate(&hash, buf, count);
231 	timestamp = (uint32_t)get_cyclecount();
232 	randomdev_hash_iterate(&hash, &timestamp, sizeof(timestamp));
233 	randomdev_hash_finish(&hash, entropy_data);
234 	explicit_bzero(&hash, sizeof(hash));
235 	for (i = 0; i < RANDOM_KEYSIZE_WORDS; i += sizeof(event.he_entropy)/sizeof(event.he_entropy[0])) {
236 		event.he_somecounter = (uint32_t)get_cyclecount();
237 		event.he_size = sizeof(event.he_entropy);
238 		event.he_bits = event.he_size/8;
239 		event.he_source = RANDOM_CACHED;
240 		event.he_destination = destination++; /* Harmless cheating */
241 		memcpy(event.he_entropy, entropy_data + i, sizeof(event.he_entropy));
242 		p_random_alg_context->ra_event_processor(&event);
243 	}
244 	explicit_bzero(entropy_data, sizeof(entropy_data));
245 }
246 
247 /* ARGSUSED */
248 static int
249 randomdev_write(struct cdev *dev __unused, struct uio *uio, int flags __unused)
250 {
251 	uint8_t *random_buf;
252 	int c, error = 0;
253 	ssize_t nbytes;
254 
255 	random_buf = malloc(PAGE_SIZE, M_ENTROPY, M_WAITOK);
256 	nbytes = uio->uio_resid;
257 	while (uio->uio_resid > 0 && error == 0) {
258 		c = MIN(uio->uio_resid, PAGE_SIZE);
259 		error = uiomove(random_buf, c, uio);
260 		if (error)
261 			break;
262 		randomdev_accumulate(random_buf, c);
263 		tsleep(&random_alg_context, 0, "randwr", hz/10);
264 	}
265 	if (nbytes != uio->uio_resid && (error == ERESTART || error == EINTR))
266 		/* Partial write, not error. */
267 		error = 0;
268 	free(random_buf, M_ENTROPY);
269 	return (error);
270 }
271 
272 /* ARGSUSED */
273 static int
274 randomdev_poll(struct cdev *dev __unused, int events, struct thread *td __unused)
275 {
276 
277 	if (events & (POLLIN | POLLRDNORM)) {
278 		if (p_random_alg_context->ra_seeded())
279 			events &= (POLLIN | POLLRDNORM);
280 		else
281 			selrecord(td, &rsel);
282 	}
283 	return (events);
284 }
285 
286 /* This will be called by the entropy processor when it seeds itself and becomes secure */
287 void
288 randomdev_unblock(void)
289 {
290 
291 	selwakeuppri(&rsel, PUSER);
292 	wakeup(&random_alg_context);
293 	printf("random: unblocking device.\n");
294 	/* Do random(9) a favour while we are about it. */
295 	(void)atomic_cmpset_int(&arc4rand_iniseed_state, ARC4_ENTR_NONE, ARC4_ENTR_HAVE);
296 }
297 
298 /* ARGSUSED */
299 static int
300 randomdev_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t addr __unused,
301     int flags __unused, struct thread *td __unused)
302 {
303 	int error = 0;
304 
305 	switch (cmd) {
306 		/* Really handled in upper layer */
307 	case FIOASYNC:
308 	case FIONBIO:
309 		break;
310 	default:
311 		error = ENOTTY;
312 	}
313 
314 	return (error);
315 }
316 
317 void
318 random_source_register(struct random_source *rsource)
319 {
320 	struct random_sources *rrs;
321 
322 	KASSERT(rsource != NULL, ("invalid input to %s", __func__));
323 
324 	rrs = malloc(sizeof(*rrs), M_ENTROPY, M_WAITOK);
325 	rrs->rrs_source = rsource;
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 	LIST_FOREACH(rrs, &source_list, rrs_entries)
338 		if (rrs->rrs_source == rsource) {
339 			LIST_REMOVE(rrs, rrs_entries);
340 			break;
341 		}
342 	if (rrs != NULL)
343 		free(rrs, M_ENTROPY);
344 }
345 
346 static int
347 random_source_handler(SYSCTL_HANDLER_ARGS)
348 {
349 	struct random_sources *rrs;
350 	struct sbuf sbuf;
351 	int error, count;
352 
353 	sbuf_new_for_sysctl(&sbuf, NULL, 64, req);
354 	count = 0;
355 	LIST_FOREACH(rrs, &source_list, rrs_entries) {
356 		sbuf_cat(&sbuf, (count++ ? ",'" : "'"));
357 		sbuf_cat(&sbuf, rrs->rrs_source->rs_ident);
358 		sbuf_cat(&sbuf, "'");
359 	}
360 	error = sbuf_finish(&sbuf);
361 	sbuf_delete(&sbuf);
362 	return (error);
363 }
364 SYSCTL_PROC(_kern_random, OID_AUTO, random_sources, CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
365 	    NULL, 0, random_source_handler, "A",
366 	    "List of active fast entropy sources.");
367 
368 /* ARGSUSED */
369 static int
370 randomdev_modevent(module_t mod __unused, int type, void *data __unused)
371 {
372 	int error = 0;
373 
374 	switch (type) {
375 	case MOD_LOAD:
376 		printf("random: entropy device external interface\n");
377 		random_dev = make_dev_credf(MAKEDEV_ETERNAL_KLD, &random_cdevsw,
378 		    RANDOM_UNIT, NULL, UID_ROOT, GID_WHEEL, 0644, "random");
379 		make_dev_alias(random_dev, "urandom"); /* compatibility */
380 		break;
381 	case MOD_UNLOAD:
382 		destroy_dev(random_dev);
383 		break;
384 	case MOD_SHUTDOWN:
385 		break;
386 	default:
387 		error = EOPNOTSUPP;
388 		break;
389 	}
390 	return (error);
391 }
392 
393 static moduledata_t randomdev_mod = {
394 	"random_device",
395 	randomdev_modevent,
396 	0
397 };
398 
399 DECLARE_MODULE(random_device, randomdev_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST);
400 MODULE_VERSION(random_device, 1);
401 MODULE_DEPEND(random_device, crypto, 1, 1, 1);
402 MODULE_DEPEND(random_device, random_harvestq, 1, 1, 1);
403