]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/random/randomdev.c
Upgrade Unbound to 1.7.1.
[FreeBSD/FreeBSD.git] / sys / dev / random / randomdev.c
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         /* 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;
136
137         CTASSERT(SIGCHK_PERIOD % PAGE_SIZE == 0);
138 #undef SIGCHK_PERIOD
139
140         random_buf = malloc(PAGE_SIZE, M_ENTROPY, M_WAITOK);
141         p_random_alg_context->ra_pre_read();
142         error = 0;
143         spamcount = 0;
144         /* (Un)Blocking logic */
145         while (!p_random_alg_context->ra_seeded()) {
146                 if (nonblock) {
147                         error = EWOULDBLOCK;
148                         break;
149                 }
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 */
153                 if (spamcount == 0)
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)
158                         break;
159         }
160         if (error == 0) {
161                 read_rate_increment((uio->uio_resid + sizeof(uint32_t))/sizeof(uint32_t));
162                 total_read = 0;
163                 while (uio->uio_resid && !error) {
164                         read_len = uio->uio_resid;
165                         /*
166                          * Belt-and-braces.
167                          * Round up the read length to a crypto block size multiple,
168                          * which is what the underlying generator is expecting.
169                          * See the random_buf size requirements in the Yarrow/Fortuna code.
170                          */
171                         read_len = roundup(read_len, RANDOM_BLOCKSIZE);
172                         /* Work in chunks page-sized or less */
173                         read_len = MIN(read_len, PAGE_SIZE);
174                         p_random_alg_context->ra_read(random_buf, read_len);
175                         c = MIN(uio->uio_resid, read_len);
176                         /*
177                          * uiomove() may yield the CPU before each 'c' bytes
178                          * (up to PAGE_SIZE) are copied out.
179                          */
180                         error = uiomove(random_buf, c, uio);
181                         total_read += c;
182                         /*
183                          * Poll for signals every few MBs to avoid very long
184                          * uninterruptible syscalls.
185                          */
186                         if (error == 0 && uio->uio_resid != 0 &&
187                             total_read % sigchk_period == 0)
188                                 error = tsleep_sbt(&random_alg_context, PCATCH,
189                                     "randrd", SBT_1NS, 0, C_HARDCLOCK);
190                 }
191                 if (error == ERESTART || error == EINTR)
192                         error = 0;
193         }
194         free(random_buf, M_ENTROPY);
195         return (error);
196 }
197
198 /*-
199  * Kernel API version of read_random().
200  * This is similar to random_alg_read(),
201  * except it doesn't interface with uio(9).
202  * It cannot assumed that random_buf is a multiple of
203  * RANDOM_BLOCKSIZE bytes.
204  */
205 u_int
206 READ_RANDOM(void *random_buf, u_int len)
207 {
208         u_int read_len;
209         uint8_t local_buf[len + RANDOM_BLOCKSIZE];
210
211         KASSERT(random_buf != NULL, ("No suitable random buffer in %s", __func__));
212         p_random_alg_context->ra_pre_read();
213         /* (Un)Blocking logic; if not seeded, return nothing. */
214         if (p_random_alg_context->ra_seeded()) {
215                 read_rate_increment((len + sizeof(uint32_t))/sizeof(uint32_t));
216                 if (len > 0) {
217                         /*
218                          * Belt-and-braces.
219                          * Round up the read length to a crypto block size multiple,
220                          * which is what the underlying generator is expecting.
221                          */
222                         read_len = roundup(len, RANDOM_BLOCKSIZE);
223                         p_random_alg_context->ra_read(local_buf, read_len);
224                         memcpy(random_buf, local_buf, len);
225                 }
226         } else
227                 len = 0;
228         return (len);
229 }
230
231 static __inline void
232 randomdev_accumulate(uint8_t *buf, u_int count)
233 {
234         static u_int destination = 0;
235         static struct harvest_event event;
236         static struct randomdev_hash hash;
237         static uint32_t entropy_data[RANDOM_KEYSIZE_WORDS];
238         uint32_t timestamp;
239         int i;
240
241         /* Extra timing here is helpful to scrape scheduler jitter entropy */
242         randomdev_hash_init(&hash);
243         timestamp = (uint32_t)get_cyclecount();
244         randomdev_hash_iterate(&hash, &timestamp, sizeof(timestamp));
245         randomdev_hash_iterate(&hash, buf, count);
246         timestamp = (uint32_t)get_cyclecount();
247         randomdev_hash_iterate(&hash, &timestamp, sizeof(timestamp));
248         randomdev_hash_finish(&hash, entropy_data);
249         explicit_bzero(&hash, sizeof(hash));
250         for (i = 0; i < RANDOM_KEYSIZE_WORDS; i += sizeof(event.he_entropy)/sizeof(event.he_entropy[0])) {
251                 event.he_somecounter = (uint32_t)get_cyclecount();
252                 event.he_size = sizeof(event.he_entropy);
253                 event.he_bits = event.he_size/8;
254                 event.he_source = RANDOM_CACHED;
255                 event.he_destination = destination++; /* Harmless cheating */
256                 memcpy(event.he_entropy, entropy_data + i, sizeof(event.he_entropy));
257                 p_random_alg_context->ra_event_processor(&event);
258         }
259         explicit_bzero(entropy_data, sizeof(entropy_data));
260 }
261
262 /* ARGSUSED */
263 static int
264 randomdev_write(struct cdev *dev __unused, struct uio *uio, int flags __unused)
265 {
266         uint8_t *random_buf;
267         int c, error = 0;
268         ssize_t nbytes;
269
270         random_buf = malloc(PAGE_SIZE, M_ENTROPY, M_WAITOK);
271         nbytes = uio->uio_resid;
272         while (uio->uio_resid > 0 && error == 0) {
273                 c = MIN(uio->uio_resid, PAGE_SIZE);
274                 error = uiomove(random_buf, c, uio);
275                 if (error)
276                         break;
277                 randomdev_accumulate(random_buf, c);
278                 tsleep(&random_alg_context, 0, "randwr", hz/10);
279         }
280         if (nbytes != uio->uio_resid && (error == ERESTART || error == EINTR))
281                 /* Partial write, not error. */
282                 error = 0;
283         free(random_buf, M_ENTROPY);
284         return (error);
285 }
286
287 /* ARGSUSED */
288 static int
289 randomdev_poll(struct cdev *dev __unused, int events, struct thread *td __unused)
290 {
291
292         if (events & (POLLIN | POLLRDNORM)) {
293                 if (p_random_alg_context->ra_seeded())
294                         events &= (POLLIN | POLLRDNORM);
295                 else
296                         selrecord(td, &rsel);
297         }
298         return (events);
299 }
300
301 /* This will be called by the entropy processor when it seeds itself and becomes secure */
302 void
303 randomdev_unblock(void)
304 {
305
306         selwakeuppri(&rsel, PUSER);
307         wakeup(&random_alg_context);
308         printf("random: unblocking device.\n");
309         /* Do random(9) a favour while we are about it. */
310         (void)atomic_cmpset_int(&arc4rand_iniseed_state, ARC4_ENTR_NONE, ARC4_ENTR_HAVE);
311 }
312
313 /* ARGSUSED */
314 static int
315 randomdev_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t addr __unused,
316     int flags __unused, struct thread *td __unused)
317 {
318         int error = 0;
319
320         switch (cmd) {
321                 /* Really handled in upper layer */
322         case FIOASYNC:
323         case FIONBIO:
324                 break;
325         default:
326                 error = ENOTTY;
327         }
328
329         return (error);
330 }
331
332 void
333 random_source_register(struct random_source *rsource)
334 {
335         struct random_sources *rrs;
336
337         KASSERT(rsource != NULL, ("invalid input to %s", __func__));
338
339         rrs = malloc(sizeof(*rrs), M_ENTROPY, M_WAITOK);
340         rrs->rrs_source = rsource;
341
342         random_harvest_register_source(rsource->rs_source);
343
344         printf("random: registering fast source %s\n", rsource->rs_ident);
345         LIST_INSERT_HEAD(&source_list, rrs, rrs_entries);
346 }
347
348 void
349 random_source_deregister(struct random_source *rsource)
350 {
351         struct random_sources *rrs = NULL;
352
353         KASSERT(rsource != NULL, ("invalid input to %s", __func__));
354
355         random_harvest_deregister_source(rsource->rs_source);
356
357         LIST_FOREACH(rrs, &source_list, rrs_entries)
358                 if (rrs->rrs_source == rsource) {
359                         LIST_REMOVE(rrs, rrs_entries);
360                         break;
361                 }
362         if (rrs != NULL)
363                 free(rrs, M_ENTROPY);
364 }
365
366 static int
367 random_source_handler(SYSCTL_HANDLER_ARGS)
368 {
369         struct random_sources *rrs;
370         struct sbuf sbuf;
371         int error, count;
372
373         sbuf_new_for_sysctl(&sbuf, NULL, 64, req);
374         count = 0;
375         LIST_FOREACH(rrs, &source_list, rrs_entries) {
376                 sbuf_cat(&sbuf, (count++ ? ",'" : "'"));
377                 sbuf_cat(&sbuf, rrs->rrs_source->rs_ident);
378                 sbuf_cat(&sbuf, "'");
379         }
380         error = sbuf_finish(&sbuf);
381         sbuf_delete(&sbuf);
382         return (error);
383 }
384 SYSCTL_PROC(_kern_random, OID_AUTO, random_sources, CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
385             NULL, 0, random_source_handler, "A",
386             "List of active fast entropy sources.");
387
388 /* ARGSUSED */
389 static int
390 randomdev_modevent(module_t mod __unused, int type, void *data __unused)
391 {
392         int error = 0;
393
394         switch (type) {
395         case MOD_LOAD:
396                 printf("random: entropy device external interface\n");
397                 random_dev = make_dev_credf(MAKEDEV_ETERNAL_KLD, &random_cdevsw,
398                     RANDOM_UNIT, NULL, UID_ROOT, GID_WHEEL, 0644, "random");
399                 make_dev_alias(random_dev, "urandom"); /* compatibility */
400                 break;
401         case MOD_UNLOAD:
402                 destroy_dev(random_dev);
403                 break;
404         case MOD_SHUTDOWN:
405                 break;
406         default:
407                 error = EOPNOTSUPP;
408                 break;
409         }
410         return (error);
411 }
412
413 static moduledata_t randomdev_mod = {
414         "random_device",
415         randomdev_modevent,
416         0
417 };
418
419 DECLARE_MODULE(random_device, randomdev_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST);
420 MODULE_VERSION(random_device, 1);
421 MODULE_DEPEND(random_device, crypto, 1, 1, 1);
422 MODULE_DEPEND(random_device, random_harvestq, 1, 1, 1);