]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/random/random_adaptors.c
Update LLDB snapshot to upstream r225923 (git 2b588ecd)
[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                         (random_adaptor_previous->ra_deinit)();
154                 (random_adaptor->ra_init)();
155         }
156 }
157
158
159 /* XXX: FIX!! Make sure we are not inserting a duplicate */
160 void
161 random_adaptor_register(const char *name, struct random_adaptor *ra)
162 {
163         struct random_adaptors *rra;
164
165         KASSERT(name != NULL && ra != NULL, ("invalid input to %s", __func__));
166
167         rra = malloc(sizeof(*rra), M_ENTROPY, M_WAITOK);
168         rra->rra_name = name;
169         rra->rra_ra = ra;
170
171         sx_xlock(&random_adaptors_lock);
172         LIST_INSERT_HEAD(&random_adaptors_list, rra, rra_entries);
173         random_adaptor_choose();
174         KASSERT(random_adaptor != NULL, ("No active random adaptor in %s", __func__));
175         sx_xunlock(&random_adaptors_lock);
176 }
177
178 void
179 random_adaptor_deregister(const char *name)
180 {
181         struct random_adaptors *rra;
182
183         KASSERT(name != NULL, ("invalid input to %s", __func__));
184
185         sx_xlock(&random_adaptors_lock);
186         KASSERT(random_adaptor != NULL, ("No active random adaptor in %s", __func__));
187         LIST_FOREACH(rra, &random_adaptors_list, rra_entries)
188                 if (strcmp(rra->rra_name, name) == 0) {
189                         LIST_REMOVE(rra, rra_entries);
190                         break;
191                 }
192         random_adaptor_choose();
193         sx_xunlock(&random_adaptors_lock);
194
195         free(rra, M_ENTROPY);
196 }
197
198 /* ARGSUSED */
199 int
200 random_adaptor_read(struct cdev *dev __unused, struct uio *uio, int flags)
201 {
202         void *random_buf;
203         int c, error;
204         ssize_t nbytes;
205
206 #ifdef RANDOM_DEBUG_VERBOSE
207         printf("random: %s %ld\n", __func__, uio->uio_resid);
208 #endif
209
210         random_buf = malloc(PAGE_SIZE, M_ENTROPY, M_WAITOK);
211
212         sx_slock(&random_adaptors_lock);
213
214         KASSERT(random_adaptor != NULL, ("No active random adaptor in %s", __func__));
215
216         /* Let the entropy source do any pre-read setup. */
217         (random_adaptor->ra_read)(NULL, 0);
218
219         /* (Un)Blocking logic */
220         error = 0;
221         while (!random_adaptor->ra_seeded() && error == 0) {
222                 if (flags & O_NONBLOCK) {
223                         error = EWOULDBLOCK;
224                         break;
225                 }
226
227                 /* Sleep instead of going into a spin-frenzy */
228                 error = sx_sleep(&random_adaptor, &random_adaptors_lock,
229                     PUSER | PCATCH, "randrd", hz/10);
230                 KASSERT(random_adaptor != NULL, ("No active random adaptor in %s",
231                     __func__));
232
233                 /* keep tapping away at the pre-read until we seed/unblock. */
234                 (random_adaptor->ra_read)(NULL, 0);
235         }
236
237         mtx_lock(&random_read_rate_mtx);
238
239         /* The read-rate stuff is a rough indication of the instantaneous read rate,
240          * used to increase the use of 'live' entropy sources when lots of reads are done.
241          */
242         nbytes = (uio->uio_resid + 32 - 1)/32; /* Round up to units of 32 */
243         random_adaptor_read_rate_cache += nbytes*32;
244         random_adaptor_read_rate_cache = MIN(random_adaptor_read_rate_cache, 32);
245
246         mtx_unlock(&random_read_rate_mtx);
247
248         if (error == 0) {
249                 nbytes = uio->uio_resid;
250
251                 /* The actual read */
252                 while (uio->uio_resid && !error) {
253                         c = MIN(uio->uio_resid, PAGE_SIZE);
254                         (random_adaptor->ra_read)(random_buf, c);
255                         error = uiomove(random_buf, c, uio);
256                 }
257
258                 /* Let the entropy source do any post-read cleanup. */
259                 (random_adaptor->ra_read)(NULL, 1);
260
261                 if (nbytes != uio->uio_resid && (error == ERESTART ||
262                     error == EINTR) )
263                         error = 0;      /* Return partial read, not error. */
264
265         }
266         sx_sunlock(&random_adaptors_lock);
267
268         free(random_buf, M_ENTROPY);
269
270         return (error);
271 }
272
273 int
274 random_adaptor_read_rate(void)
275 {
276         int ret;
277
278         mtx_lock(&random_read_rate_mtx);
279
280         ret = random_adaptor_read_rate_cache;
281         random_adaptor_read_rate_cache = 1;
282
283         mtx_unlock(&random_read_rate_mtx);
284
285         return (ret);
286 }
287
288 /* ARGSUSED */
289 int
290 random_adaptor_write(struct cdev *dev __unused, struct uio *uio, int flags __unused)
291 {
292         int c, error = 0;
293         void *random_buf;
294         ssize_t nbytes;
295
296 #ifdef RANDOM_DEBUG
297         printf("random: %s %zd\n", __func__, uio->uio_resid);
298 #endif
299
300         random_buf = malloc(PAGE_SIZE, M_ENTROPY, M_WAITOK);
301
302         sx_slock(&random_adaptors_lock);
303
304         KASSERT(random_adaptor != NULL, ("No active random adaptor in %s", __func__));
305
306         nbytes = uio->uio_resid;
307         while (uio->uio_resid > 0 && error == 0) {
308                 c = MIN(uio->uio_resid, PAGE_SIZE);
309                 error = uiomove(random_buf, c, uio);
310                 if (error)
311                         break;
312                 (random_adaptor->ra_write)(random_buf, c);
313
314                 /* Introduce an annoying delay to stop swamping */
315                 error = sx_sleep(&random_adaptor, &random_adaptors_lock,
316                     PUSER | PCATCH, "randwr", hz/10);
317                 KASSERT(random_adaptor != NULL, ("No active random adaptor in %s",
318                     __func__));
319         }
320
321         sx_sunlock(&random_adaptors_lock);
322
323         if (nbytes != uio->uio_resid && (error == ERESTART ||
324             error == EINTR) )
325                 error = 0;      /* Partial write, not error. */
326
327         free(random_buf, M_ENTROPY);
328
329         return (error);
330 }
331
332 /* ARGSUSED */
333 int
334 random_adaptor_poll(struct cdev *dev __unused, int events, struct thread *td __unused)
335 {
336
337 #ifdef RANDOM_DEBUG
338         printf("random: %s\n", __func__);
339 #endif
340
341         sx_slock(&random_adaptors_lock);
342
343         KASSERT(random_adaptor != NULL, ("No active random adaptor in %s", __func__));
344
345         if (events & (POLLIN | POLLRDNORM)) {
346                 if (random_adaptor->ra_seeded())
347                         events &= (POLLIN | POLLRDNORM);
348                 else
349                         selrecord(td, &rsel);
350         }
351
352         sx_sunlock(&random_adaptors_lock);
353
354         return (events);
355 }
356
357 /* This will be called by the entropy processor when it seeds itself and becomes secure */
358 void
359 random_adaptor_unblock(void)
360 {
361
362         selwakeuppri(&rsel, PUSER);
363         wakeup(&random_adaptor);
364         printf("random: unblocking device.\n");
365
366         /* Do arc4random(9) a favour while we are about it. */
367         (void)atomic_cmpset_int(&arc4rand_iniseed_state, ARC4_ENTR_NONE, ARC4_ENTR_HAVE);
368 }
369
370 static int
371 random_sysctl_adaptors_handler(SYSCTL_HANDLER_ARGS)
372 {
373         struct random_adaptors *rra;
374         struct sbuf sbuf;
375         int error, count;
376
377         sx_slock(&random_adaptors_lock);
378         sbuf_new_for_sysctl(&sbuf, NULL, 64, req);
379         count = 0;
380         LIST_FOREACH(rra, &random_adaptors_list, rra_entries)
381                 sbuf_printf(&sbuf, "%s%s(%d)",
382                     (count++ ? "," : ""), rra->rra_name, rra->rra_ra->ra_priority);
383
384         error = sbuf_finish(&sbuf);
385         sbuf_delete(&sbuf);
386         sx_sunlock(&random_adaptors_lock);
387
388         return (error);
389 }
390
391 static int
392 random_sysctl_active_adaptor_handler(SYSCTL_HANDLER_ARGS)
393 {
394         struct random_adaptors *rra;
395         struct sbuf sbuf;
396         int error;
397
398         sx_slock(&random_adaptors_lock);
399         KASSERT(random_adaptor != NULL, ("No active random adaptor in %s", __func__));
400
401         sbuf_new_for_sysctl(&sbuf, NULL, 16, req);
402         LIST_FOREACH(rra, &random_adaptors_list, rra_entries)
403                 if (rra->rra_ra == random_adaptor) {
404                         sbuf_cat(&sbuf, rra->rra_name);
405                         break;
406                 }
407         error = sbuf_finish(&sbuf);
408         sbuf_delete(&sbuf);
409         sx_sunlock(&random_adaptors_lock);
410
411         return (error);
412 }
413
414 void
415 random_adaptors_init(void)
416 {
417
418 #ifdef RANDOM_DEBUG
419         printf("random: %s\n", __func__);
420 #endif
421
422         SYSCTL_PROC(_kern_random, OID_AUTO, adaptors,
423             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
424             NULL, 0, random_sysctl_adaptors_handler, "A",
425             "Random Number Generator adaptors");
426
427         SYSCTL_PROC(_kern_random, OID_AUTO, active_adaptor,
428             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
429             NULL, 0, random_sysctl_active_adaptor_handler, "A",
430             "Active Random Number Generator Adaptor");
431
432         sx_init(&random_adaptors_lock, "random_adaptors");
433
434         mtx_init(&random_read_rate_mtx, "read rate mutex", NULL, MTX_DEF);
435
436         /* The dummy adaptor is not a module by itself, but part of the
437          * randomdev module.
438          */
439         random_adaptor_register("dummy", &randomdev_dummy);
440
441         live_entropy_sources_init();
442 }
443
444 void
445 random_adaptors_deinit(void)
446 {
447
448 #ifdef RANDOM_DEBUG
449         printf("random: %s\n", __func__);
450 #endif
451
452         live_entropy_sources_deinit();
453
454         /* Don't do this! Panic will surely follow! */
455         /* random_adaptor_deregister("dummy"); */
456
457         mtx_destroy(&random_read_rate_mtx);
458
459         sx_destroy(&random_adaptors_lock);
460 }
461
462 /*
463  * Reseed the active adaptor shortly before starting init(8).
464  */
465 /* ARGSUSED */
466 static void
467 random_adaptors_seed(void *unused __unused)
468 {
469  
470         sx_slock(&random_adaptors_lock);
471         KASSERT(random_adaptor != NULL, ("No active random adaptor in %s", __func__));
472
473         random_adaptor->ra_reseed();
474         sx_sunlock(&random_adaptors_lock);
475
476         arc4rand(NULL, 0, 1);
477 }
478 SYSINIT(random_seed, SI_SUB_KTHREAD_INIT, SI_ORDER_FIRST,
479     random_adaptors_seed, NULL);