2 * Copyright (c) 2017 Oliver Pinter
3 * Copyright (c) 2000-2015 Mark R V Murray
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
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.
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.
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
32 #include <sys/param.h>
33 #include <sys/systm.h>
36 #include <sys/fcntl.h>
37 #include <sys/filio.h>
38 #include <sys/kernel.h>
39 #include <sys/kthread.h>
41 #include <sys/module.h>
42 #include <sys/malloc.h>
45 #include <sys/random.h>
47 #include <sys/selinfo.h>
48 #include <sys/sysctl.h>
49 #include <sys/systm.h>
51 #include <sys/unistd.h>
53 #include <crypto/rijndael/rijndael-api-fst.h>
54 #include <crypto/sha2/sha256.h>
56 #include <dev/random/hash.h>
57 #include <dev/random/randomdev.h>
58 #include <dev/random/random_harvestq.h>
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);
68 #define READ_RANDOM_UIO read_random_uio
69 #define READ_RANDOM read_random
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;
77 static struct cdevsw random_cdevsw = {
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,
86 /* For use with make_dev(9)/destroy_dev(9). */
87 static struct cdev *random_dev;
90 random_alg_context_ra_init_alg(void *data)
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);
101 random_alg_context_ra_deinit_alg(void *data)
104 #if defined(RANDOM_LOADABLE)
105 random_infra_uninit();
107 p_random_alg_context->ra_deinit_alg(data);
108 p_random_alg_context = NULL;
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);
114 static struct selinfo rsel;
117 * This is the read uio(9) interface for random(4).
121 randomdev_read(struct cdev *dev __unused, struct uio *uio, int flags)
124 return (READ_RANDOM_UIO(uio, (flags & O_NONBLOCK) != 0));
128 READ_RANDOM_UIO(struct uio *uio, bool nonblock)
131 int error, spamcount;
132 ssize_t read_len, total_read, c;
133 /* 16 MiB takes about 0.08 s CPU time on my 2017 AMD Zen CPU */
134 #define SIGCHK_PERIOD (16 * 1024 * 1024)
135 const size_t sigchk_period = SIGCHK_PERIOD;
137 CTASSERT(SIGCHK_PERIOD % PAGE_SIZE == 0);
140 random_buf = malloc(PAGE_SIZE, M_ENTROPY, M_WAITOK);
141 p_random_alg_context->ra_pre_read();
144 /* (Un)Blocking logic */
145 while (!p_random_alg_context->ra_seeded()) {
150 /* keep tapping away at the pre-read until we seed/unblock. */
151 p_random_alg_context->ra_pre_read();
152 /* Only bother the console every 10 seconds or so */
154 printf("random: %s unblock wait\n", __func__);
155 spamcount = (spamcount + 1)%100;
156 error = tsleep(&random_alg_context, PCATCH, "randseed", hz/10);
157 if (error == ERESTART || error == EINTR)
159 /* Squash tsleep timeout condition */
160 if (error == EWOULDBLOCK)
162 KASSERT(error == 0, ("unexpected tsleep error %d", error));
165 read_rate_increment((uio->uio_resid + sizeof(uint32_t))/sizeof(uint32_t));
167 while (uio->uio_resid && !error) {
168 read_len = uio->uio_resid;
171 * Round up the read length to a crypto block size multiple,
172 * which is what the underlying generator is expecting.
173 * See the random_buf size requirements in the Fortuna code.
175 read_len = roundup(read_len, RANDOM_BLOCKSIZE);
176 /* Work in chunks page-sized or less */
177 read_len = MIN(read_len, PAGE_SIZE);
178 p_random_alg_context->ra_read(random_buf, read_len);
179 c = MIN(uio->uio_resid, read_len);
181 * uiomove() may yield the CPU before each 'c' bytes
182 * (up to PAGE_SIZE) are copied out.
184 error = uiomove(random_buf, c, uio);
187 * Poll for signals every few MBs to avoid very long
188 * uninterruptible syscalls.
190 if (error == 0 && uio->uio_resid != 0 &&
191 total_read % sigchk_period == 0) {
192 error = tsleep_sbt(&random_alg_context, PCATCH,
193 "randrd", SBT_1NS, 0, C_HARDCLOCK);
194 /* Squash tsleep timeout condition */
195 if (error == EWOULDBLOCK)
199 if (error == ERESTART || error == EINTR)
202 free(random_buf, M_ENTROPY);
207 * Kernel API version of read_random().
208 * This is similar to random_alg_read(),
209 * except it doesn't interface with uio(9).
210 * It cannot assumed that random_buf is a multiple of
211 * RANDOM_BLOCKSIZE bytes.
214 READ_RANDOM(void *random_buf, u_int len)
217 uint8_t local_buf[len + RANDOM_BLOCKSIZE];
219 KASSERT(random_buf != NULL, ("No suitable random buffer in %s", __func__));
220 p_random_alg_context->ra_pre_read();
221 /* (Un)Blocking logic; if not seeded, return nothing. */
222 if (p_random_alg_context->ra_seeded()) {
223 read_rate_increment((len + sizeof(uint32_t))/sizeof(uint32_t));
227 * Round up the read length to a crypto block size multiple,
228 * which is what the underlying generator is expecting.
230 read_len = roundup(len, RANDOM_BLOCKSIZE);
231 p_random_alg_context->ra_read(local_buf, read_len);
232 memcpy(random_buf, local_buf, len);
240 randomdev_accumulate(uint8_t *buf, u_int count)
242 static u_int destination = 0;
243 static struct harvest_event event;
244 static struct randomdev_hash hash;
245 static uint32_t entropy_data[RANDOM_KEYSIZE_WORDS];
249 /* Extra timing here is helpful to scrape scheduler jitter entropy */
250 randomdev_hash_init(&hash);
251 timestamp = (uint32_t)get_cyclecount();
252 randomdev_hash_iterate(&hash, ×tamp, sizeof(timestamp));
253 randomdev_hash_iterate(&hash, buf, count);
254 timestamp = (uint32_t)get_cyclecount();
255 randomdev_hash_iterate(&hash, ×tamp, sizeof(timestamp));
256 randomdev_hash_finish(&hash, entropy_data);
257 explicit_bzero(&hash, sizeof(hash));
258 for (i = 0; i < RANDOM_KEYSIZE_WORDS; i += sizeof(event.he_entropy)/sizeof(event.he_entropy[0])) {
259 event.he_somecounter = (uint32_t)get_cyclecount();
260 event.he_size = sizeof(event.he_entropy);
261 event.he_source = RANDOM_CACHED;
262 event.he_destination = destination++; /* Harmless cheating */
263 memcpy(event.he_entropy, entropy_data + i, sizeof(event.he_entropy));
264 p_random_alg_context->ra_event_processor(&event);
266 explicit_bzero(entropy_data, sizeof(entropy_data));
271 randomdev_write(struct cdev *dev __unused, struct uio *uio, int flags __unused)
277 random_buf = malloc(PAGE_SIZE, M_ENTROPY, M_WAITOK);
278 nbytes = uio->uio_resid;
279 while (uio->uio_resid > 0 && error == 0) {
280 c = MIN(uio->uio_resid, PAGE_SIZE);
281 error = uiomove(random_buf, c, uio);
284 randomdev_accumulate(random_buf, c);
285 tsleep(&random_alg_context, 0, "randwr", hz/10);
287 if (nbytes != uio->uio_resid && (error == ERESTART || error == EINTR))
288 /* Partial write, not error. */
290 free(random_buf, M_ENTROPY);
296 randomdev_poll(struct cdev *dev __unused, int events, struct thread *td __unused)
299 if (events & (POLLIN | POLLRDNORM)) {
300 if (p_random_alg_context->ra_seeded())
301 events &= (POLLIN | POLLRDNORM);
303 selrecord(td, &rsel);
308 /* This will be called by the entropy processor when it seeds itself and becomes secure */
310 randomdev_unblock(void)
313 selwakeuppri(&rsel, PUSER);
314 wakeup(&random_alg_context);
315 printf("random: unblocking device.\n");
316 /* Do random(9) a favour while we are about it. */
317 (void)atomic_cmpset_int(&arc4rand_iniseed_state, ARC4_ENTR_NONE, ARC4_ENTR_HAVE);
322 randomdev_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t addr __unused,
323 int flags __unused, struct thread *td __unused)
328 /* Really handled in upper layer */
340 random_source_register(struct random_source *rsource)
342 struct random_sources *rrs;
344 KASSERT(rsource != NULL, ("invalid input to %s", __func__));
346 rrs = malloc(sizeof(*rrs), M_ENTROPY, M_WAITOK);
347 rrs->rrs_source = rsource;
349 random_harvest_register_source(rsource->rs_source);
351 printf("random: registering fast source %s\n", rsource->rs_ident);
352 LIST_INSERT_HEAD(&source_list, rrs, rrs_entries);
356 random_source_deregister(struct random_source *rsource)
358 struct random_sources *rrs = NULL;
360 KASSERT(rsource != NULL, ("invalid input to %s", __func__));
362 random_harvest_deregister_source(rsource->rs_source);
364 LIST_FOREACH(rrs, &source_list, rrs_entries)
365 if (rrs->rrs_source == rsource) {
366 LIST_REMOVE(rrs, rrs_entries);
370 free(rrs, M_ENTROPY);
374 random_source_handler(SYSCTL_HANDLER_ARGS)
376 struct random_sources *rrs;
380 sbuf_new_for_sysctl(&sbuf, NULL, 64, req);
382 LIST_FOREACH(rrs, &source_list, rrs_entries) {
383 sbuf_cat(&sbuf, (count++ ? ",'" : "'"));
384 sbuf_cat(&sbuf, rrs->rrs_source->rs_ident);
385 sbuf_cat(&sbuf, "'");
387 error = sbuf_finish(&sbuf);
391 SYSCTL_PROC(_kern_random, OID_AUTO, random_sources, CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
392 NULL, 0, random_source_handler, "A",
393 "List of active fast entropy sources.");
397 randomdev_modevent(module_t mod __unused, int type, void *data __unused)
403 printf("random: entropy device external interface\n");
404 random_dev = make_dev_credf(MAKEDEV_ETERNAL_KLD, &random_cdevsw,
405 RANDOM_UNIT, NULL, UID_ROOT, GID_WHEEL, 0644, "random");
406 make_dev_alias(random_dev, "urandom"); /* compatibility */
409 destroy_dev(random_dev);
420 static moduledata_t randomdev_mod = {
426 DECLARE_MODULE(random_device, randomdev_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST);
427 MODULE_VERSION(random_device, 1);
428 MODULE_DEPEND(random_device, crypto, 1, 1, 1);
429 MODULE_DEPEND(random_device, random_harvestq, 1, 1, 1);