]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/random/random_adaptors.c
When the new random adaptor code was brought it in r273872, a call to
[FreeBSD/FreeBSD.git] / sys / dev / random / random_adaptors.c
1 /*-
2  * Copyright (c) 2013 Mark R V Murray
3  * Copyright (c) 2013 Arthur Mesh <arthurmesh@gmail.com>
4  * Copyright (c) 2013 David E. O'Brien <obrien@NUXI.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer
12  *    in this position and unchanged.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 #include <sys/param.h>
30 __FBSDID("$FreeBSD$");
31
32 #include "opt_random.h"
33
34 #include <sys/systm.h>
35 #include <sys/conf.h>
36 #include <sys/fcntl.h>
37 #include <sys/kernel.h>
38 #include <sys/kthread.h>
39 #include <sys/libkern.h>
40 #include <sys/lock.h>
41 #include <sys/malloc.h>
42 #include <sys/module.h>
43 #include <sys/mutex.h>
44 #include <sys/poll.h>
45 #include <sys/queue.h>
46 #include <sys/random.h>
47 #include <sys/sbuf.h>
48 #include <sys/selinfo.h>
49 #include <sys/sx.h>
50 #include <sys/sysctl.h>
51 #include <sys/uio.h>
52 #include <sys/unistd.h>
53
54 #include <dev/random/randomdev.h>
55 #include <dev/random/random_adaptors.h>
56 #include <dev/random/live_entropy_sources.h>
57
58 /* The random_adaptors_lock protects random_adaptors_list and friends and random_adaptor.
59  * We need a sleepable lock for uiomove/block/poll/sbuf/sysctl.
60  */
61 static struct sx random_adaptors_lock;
62 LIST_HEAD(adaptors_head, random_adaptors);
63 static struct adaptors_head random_adaptors_list = LIST_HEAD_INITIALIZER(random_adaptors_list);
64 static struct random_adaptor *random_adaptor = NULL; /* Currently active adaptor */
65 /* End of data items requiring random_adaptors_lock protection */
66
67 /* The random_readrate_mtx mutex protects the read-rate estimator.
68  */
69 static struct mtx random_read_rate_mtx;
70 static int random_adaptor_read_rate_cache;
71 /* End of data items requiring random_readrate_mtx mutex protection */
72
73 static struct selinfo rsel;
74
75 /* Utility routine to change active adaptor when the random_adaptors_list
76  * gets modified.
77  *
78  * Walk a list of registered random(4) adaptors and pick either a requested
79  * one or the highest priority one, whichever comes first. Panic on failure
80  * as the fallback must always be the "dummy" adaptor.
81  */
82 static void
83 random_adaptor_choose(void)
84 {
85         char                     rngs[128], *token, *cp;
86         struct random_adaptors  *rra, *rrai;
87         struct random_adaptor   *random_adaptor_previous;
88         int                      primax;
89
90         /* We are going to be messing with random_adaptor.
91          * Exclusive lock is mandatory.
92          */
93         sx_assert(&random_adaptors_lock, SA_XLOCKED);
94
95         random_adaptor_previous = random_adaptor;
96
97         random_adaptor = NULL;
98         if (TUNABLE_STR_FETCH("kern.random.active_adaptor", rngs, sizeof(rngs))) {
99                 cp = rngs;
100
101                 /* XXX: FIX!! (DES):
102                  * - fetch tunable once, at boot
103                  * - make sysctl r/w
104                  * - when fetching tunable or processing a sysctl
105                  *   write, parse into list of strings so we don't
106                  *   have to do it here again and again
107                  * - sysctl read should return a reconstructed string
108                  */
109                 while ((token = strsep(&cp, ",")) != NULL) {
110                         LIST_FOREACH(rra, &random_adaptors_list, rra_entries)
111                                 if (strcmp(rra->rra_name, token) == 0) {
112                                         random_adaptor = rra->rra_ra;
113                                         break;
114                                 }
115                         if (random_adaptor != NULL) {
116                                 printf("random: selecting requested adaptor <%s>\n",
117                                     random_adaptor->ra_ident);
118                                 break;
119                         }
120                         else
121                                 printf("random: requested adaptor <%s> not available\n",
122                                     token);
123                 }
124         }
125
126         primax = 0;
127         if (random_adaptor == NULL) {
128                 /*
129                  * Fall back to the highest priority item on the available
130                  * RNG list.
131                  */
132                 LIST_FOREACH(rrai, &random_adaptors_list, rra_entries) {
133                         if (rrai->rra_ra->ra_priority >= primax) {
134                                 random_adaptor = rrai->rra_ra;
135                                 primax = rrai->rra_ra->ra_priority;
136                         }
137                 }
138                 if (random_adaptor != NULL)
139                         printf("random: selecting highest priority adaptor <%s>\n",
140                             random_adaptor->ra_ident);
141         }
142
143         KASSERT(random_adaptor != NULL, ("adaptor not found"));
144
145         /* If we are changing adaptors, deinit the old and init the new. */
146         if (random_adaptor != random_adaptor_previous) {
147 #ifdef RANDOM_DEBUG
148                 printf("random: %s - changing from %s to %s\n", __func__,
149                     (random_adaptor_previous == NULL ? "NULL" : random_adaptor_previous->ra_ident),
150                     random_adaptor->ra_ident);
151 #endif
152                 if (random_adaptor_previous != NULL) {
153                         randomdev_deinit_reader();
154                         (random_adaptor_previous->ra_deinit)();
155                 }
156                 (random_adaptor->ra_init)();
157         }
158
159         randomdev_init_reader(random_adaptor->ra_read);
160 }
161
162
163 /* XXX: FIX!! Make sure we are not inserting a duplicate */
164 void
165 random_adaptor_register(const char *name, struct random_adaptor *ra)
166 {
167         struct random_adaptors *rra;
168
169         KASSERT(name != NULL && ra != NULL, ("invalid input to %s", __func__));
170
171         rra = malloc(sizeof(*rra), M_ENTROPY, M_WAITOK);
172         rra->rra_name = name;
173         rra->rra_ra = ra;
174
175         sx_xlock(&random_adaptors_lock);
176         LIST_INSERT_HEAD(&random_adaptors_list, rra, rra_entries);
177         random_adaptor_choose();
178         KASSERT(random_adaptor != NULL, ("No active random adaptor in %s", __func__));
179         sx_xunlock(&random_adaptors_lock);
180 }
181
182 void
183 random_adaptor_deregister(const char *name)
184 {
185         struct random_adaptors *rra;
186
187         KASSERT(name != NULL, ("invalid input to %s", __func__));
188
189         sx_xlock(&random_adaptors_lock);
190         KASSERT(random_adaptor != NULL, ("No active random adaptor in %s", __func__));
191         LIST_FOREACH(rra, &random_adaptors_list, rra_entries)
192                 if (strcmp(rra->rra_name, name) == 0) {
193                         LIST_REMOVE(rra, rra_entries);
194                         break;
195                 }
196         random_adaptor_choose();
197         sx_xunlock(&random_adaptors_lock);
198
199         free(rra, M_ENTROPY);
200 }
201
202 /* ARGSUSED */
203 int
204 random_adaptor_read(struct cdev *dev __unused, struct uio *uio, int flags)
205 {
206         void *random_buf;
207         int c, error;
208         ssize_t nbytes;
209
210 #ifdef RANDOM_DEBUG_VERBOSE
211         printf("random: %s %ld\n", __func__, uio->uio_resid);
212 #endif
213
214         random_buf = malloc(PAGE_SIZE, M_ENTROPY, M_WAITOK);
215
216         sx_slock(&random_adaptors_lock);
217
218         KASSERT(random_adaptor != NULL, ("No active random adaptor in %s", __func__));
219
220         /* Let the entropy source do any pre-read setup. */
221         (random_adaptor->ra_read)(NULL, 0);
222
223         /* (Un)Blocking logic */
224         error = 0;
225         while (!random_adaptor->ra_seeded() && error == 0) {
226                 if (flags & O_NONBLOCK) {
227                         error = EWOULDBLOCK;
228                         break;
229                 }
230
231                 /* Sleep instead of going into a spin-frenzy */
232                 error = sx_sleep(&random_adaptor, &random_adaptors_lock,
233                     PUSER | PCATCH, "randrd", hz/10);
234                 KASSERT(random_adaptor != NULL, ("No active random adaptor in %s",
235                     __func__));
236
237                 /* keep tapping away at the pre-read until we seed/unblock. */
238                 (random_adaptor->ra_read)(NULL, 0);
239         }
240
241         mtx_lock(&random_read_rate_mtx);
242
243         /* The read-rate stuff is a rough indication of the instantaneous read rate,
244          * used to increase the use of 'live' entropy sources when lots of reads are done.
245          */
246         nbytes = (uio->uio_resid + 32 - 1)/32; /* Round up to units of 32 */
247         random_adaptor_read_rate_cache += nbytes*32;
248         random_adaptor_read_rate_cache = MIN(random_adaptor_read_rate_cache, 32);
249
250         mtx_unlock(&random_read_rate_mtx);
251
252         if (error == 0) {
253                 nbytes = uio->uio_resid;
254
255                 /* The actual read */
256                 while (uio->uio_resid && !error) {
257                         c = MIN(uio->uio_resid, PAGE_SIZE);
258                         (random_adaptor->ra_read)(random_buf, c);
259                         error = uiomove(random_buf, c, uio);
260                 }
261
262                 /* Let the entropy source do any post-read cleanup. */
263                 (random_adaptor->ra_read)(NULL, 1);
264
265                 if (nbytes != uio->uio_resid && (error == ERESTART ||
266                     error == EINTR) )
267                         error = 0;      /* Return partial read, not error. */
268
269         }
270         sx_sunlock(&random_adaptors_lock);
271
272         free(random_buf, M_ENTROPY);
273
274         return (error);
275 }
276
277 int
278 random_adaptor_read_rate(void)
279 {
280         int ret;
281
282         mtx_lock(&random_read_rate_mtx);
283
284         ret = random_adaptor_read_rate_cache;
285         random_adaptor_read_rate_cache = 1;
286
287         mtx_unlock(&random_read_rate_mtx);
288
289         return (ret);
290 }
291
292 /* ARGSUSED */
293 int
294 random_adaptor_write(struct cdev *dev __unused, struct uio *uio, int flags __unused)
295 {
296         int c, error = 0;
297         void *random_buf;
298         ssize_t nbytes;
299
300 #ifdef RANDOM_DEBUG
301         printf("random: %s %zd\n", __func__, uio->uio_resid);
302 #endif
303
304         random_buf = malloc(PAGE_SIZE, M_ENTROPY, M_WAITOK);
305
306         sx_slock(&random_adaptors_lock);
307
308         KASSERT(random_adaptor != NULL, ("No active random adaptor in %s", __func__));
309
310         nbytes = uio->uio_resid;
311         while (uio->uio_resid > 0 && error == 0) {
312                 c = MIN(uio->uio_resid, PAGE_SIZE);
313                 error = uiomove(random_buf, c, uio);
314                 if (error)
315                         break;
316                 (random_adaptor->ra_write)(random_buf, c);
317
318                 /* Introduce an annoying delay to stop swamping */
319                 error = sx_sleep(&random_adaptor, &random_adaptors_lock,
320                     PUSER | PCATCH, "randwr", hz/10);
321                 KASSERT(random_adaptor != NULL, ("No active random adaptor in %s",
322                     __func__));
323         }
324
325         sx_sunlock(&random_adaptors_lock);
326
327         if (nbytes != uio->uio_resid && (error == ERESTART ||
328             error == EINTR) )
329                 error = 0;      /* Partial write, not error. */
330
331         free(random_buf, M_ENTROPY);
332
333         return (error);
334 }
335
336 /* ARGSUSED */
337 int
338 random_adaptor_poll(struct cdev *dev __unused, int events, struct thread *td __unused)
339 {
340
341 #ifdef RANDOM_DEBUG
342         printf("random: %s\n", __func__);
343 #endif
344
345         sx_slock(&random_adaptors_lock);
346
347         KASSERT(random_adaptor != NULL, ("No active random adaptor in %s", __func__));
348
349         if (events & (POLLIN | POLLRDNORM)) {
350                 if (random_adaptor->ra_seeded())
351                         events &= (POLLIN | POLLRDNORM);
352                 else
353                         selrecord(td, &rsel);
354         }
355
356         sx_sunlock(&random_adaptors_lock);
357
358         return (events);
359 }
360
361 /* This will be called by the entropy processor when it seeds itself and becomes secure */
362 void
363 random_adaptor_unblock(void)
364 {
365
366         selwakeuppri(&rsel, PUSER);
367         wakeup(&random_adaptor);
368         printf("random: unblocking device.\n");
369
370         /* Do arc4random(9) a favour while we are about it. */
371         (void)atomic_cmpset_int(&arc4rand_iniseed_state, ARC4_ENTR_NONE, ARC4_ENTR_HAVE);
372 }
373
374 static int
375 random_sysctl_adaptors_handler(SYSCTL_HANDLER_ARGS)
376 {
377         struct random_adaptors *rra;
378         struct sbuf sbuf;
379         int error, count;
380
381         sx_slock(&random_adaptors_lock);
382         sbuf_new_for_sysctl(&sbuf, NULL, 64, req);
383         count = 0;
384         LIST_FOREACH(rra, &random_adaptors_list, rra_entries)
385                 sbuf_printf(&sbuf, "%s%s(%d)",
386                     (count++ ? "," : ""), rra->rra_name, rra->rra_ra->ra_priority);
387
388         error = sbuf_finish(&sbuf);
389         sbuf_delete(&sbuf);
390         sx_sunlock(&random_adaptors_lock);
391
392         return (error);
393 }
394
395 static int
396 random_sysctl_active_adaptor_handler(SYSCTL_HANDLER_ARGS)
397 {
398         struct random_adaptors *rra;
399         struct sbuf sbuf;
400         int error;
401
402         sx_slock(&random_adaptors_lock);
403         KASSERT(random_adaptor != NULL, ("No active random adaptor in %s", __func__));
404
405         sbuf_new_for_sysctl(&sbuf, NULL, 16, req);
406         LIST_FOREACH(rra, &random_adaptors_list, rra_entries)
407                 if (rra->rra_ra == random_adaptor) {
408                         sbuf_cat(&sbuf, rra->rra_name);
409                         break;
410                 }
411         error = sbuf_finish(&sbuf);
412         sbuf_delete(&sbuf);
413         sx_sunlock(&random_adaptors_lock);
414
415         return (error);
416 }
417
418 void
419 random_adaptors_init(void)
420 {
421
422 #ifdef RANDOM_DEBUG
423         printf("random: %s\n", __func__);
424 #endif
425
426         SYSCTL_PROC(_kern_random, OID_AUTO, adaptors,
427             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
428             NULL, 0, random_sysctl_adaptors_handler, "A",
429             "Random Number Generator adaptors");
430
431         SYSCTL_PROC(_kern_random, OID_AUTO, active_adaptor,
432             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
433             NULL, 0, random_sysctl_active_adaptor_handler, "A",
434             "Active Random Number Generator Adaptor");
435
436         sx_init(&random_adaptors_lock, "random_adaptors");
437
438         mtx_init(&random_read_rate_mtx, "read rate mutex", NULL, MTX_DEF);
439
440         /* The dummy adaptor is not a module by itself, but part of the
441          * randomdev module.
442          */
443         random_adaptor_register("dummy", &randomdev_dummy);
444
445         live_entropy_sources_init();
446 }
447
448 void
449 random_adaptors_deinit(void)
450 {
451
452 #ifdef RANDOM_DEBUG
453         printf("random: %s\n", __func__);
454 #endif
455
456         live_entropy_sources_deinit();
457
458         /* Don't do this! Panic will surely follow! */
459         /* random_adaptor_deregister("dummy"); */
460
461         mtx_destroy(&random_read_rate_mtx);
462
463         sx_destroy(&random_adaptors_lock);
464 }
465
466 /*
467  * Reseed the active adaptor shortly before starting init(8).
468  */
469 /* ARGSUSED */
470 static void
471 random_adaptors_seed(void *unused __unused)
472 {
473  
474         sx_slock(&random_adaptors_lock);
475         KASSERT(random_adaptor != NULL, ("No active random adaptor in %s", __func__));
476
477         random_adaptor->ra_reseed();
478         sx_sunlock(&random_adaptors_lock);
479
480         arc4rand(NULL, 0, 1);
481 }
482 SYSINIT(random_seed, SI_SUB_KTHREAD_INIT, SI_ORDER_FIRST,
483     random_adaptors_seed, NULL);