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