subr_cprng.c revision 1.24 1 /* $NetBSD: subr_cprng.c,v 1.24 2014/08/10 16:44:36 tls Exp $ */
2
3 /*-
4 * Copyright (c) 2011-2013 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Thor Lancelot Simon and Taylor R. Campbell.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32 #include <sys/cdefs.h>
33 __KERNEL_RCSID(0, "$NetBSD: subr_cprng.c,v 1.24 2014/08/10 16:44:36 tls Exp $");
34
35 #include <sys/param.h>
36 #include <sys/types.h>
37 #include <sys/condvar.h>
38 #include <sys/cprng.h>
39 #include <sys/errno.h>
40 #include <sys/event.h> /* XXX struct knote */
41 #include <sys/fcntl.h> /* XXX FNONBLOCK */
42 #include <sys/kernel.h>
43 #include <sys/kmem.h>
44 #include <sys/lwp.h>
45 #include <sys/once.h>
46 #include <sys/percpu.h>
47 #include <sys/poll.h> /* XXX POLLIN/POLLOUT/&c. */
48 #include <sys/select.h>
49 #include <sys/systm.h>
50 #include <sys/sysctl.h>
51 #include <sys/rnd.h>
52 #include <sys/rndsink.h>
53 #if DEBUG
54 #include <sys/rngtest.h>
55 #endif
56
57 #include <crypto/nist_ctr_drbg/nist_ctr_drbg.h>
58
59 #if defined(__HAVE_CPU_COUNTER)
60 #include <machine/cpu_counter.h>
61 #endif
62
63 static int sysctl_kern_urnd(SYSCTLFN_PROTO);
64 static int sysctl_kern_arnd(SYSCTLFN_PROTO);
65
66 static void cprng_strong_generate(struct cprng_strong *, void *, size_t);
67 static void cprng_strong_reseed(struct cprng_strong *);
68 static void cprng_strong_reseed_from(struct cprng_strong *, const void *,
69 size_t, bool);
70 #if DEBUG
71 static void cprng_strong_rngtest(struct cprng_strong *);
72 #endif
73
74 static rndsink_callback_t cprng_strong_rndsink_callback;
75
76 void
77 cprng_init(void)
78 {
79 static struct sysctllog *random_sysctllog;
80
81 nist_ctr_initialize();
82
83 sysctl_createv(&random_sysctllog, 0, NULL, NULL,
84 CTLFLAG_PERMANENT,
85 CTLTYPE_INT, "urandom",
86 SYSCTL_DESCR("Random integer value"),
87 sysctl_kern_urnd, 0, NULL, 0,
88 CTL_KERN, KERN_URND, CTL_EOL);
89 sysctl_createv(&random_sysctllog, 0, NULL, NULL,
90 CTLFLAG_PERMANENT,
91 CTLTYPE_INT, "arandom",
92 SYSCTL_DESCR("n bytes of random data"),
93 sysctl_kern_arnd, 0, NULL, 0,
94 CTL_KERN, KERN_ARND, CTL_EOL);
95 }
96
97 static inline uint32_t
98 cprng_counter(void)
99 {
100 struct timeval tv;
101
102 #if defined(__HAVE_CPU_COUNTER)
103 if (cpu_hascounter())
104 return cpu_counter32();
105 #endif
106 if (__predict_false(cold)) {
107 static int ctr;
108 /* microtime unsafe if clock not running yet */
109 return ctr++;
110 }
111 getmicrotime(&tv);
112 return (tv.tv_sec * 1000000 + tv.tv_usec);
113 }
114
115 struct cprng_strong {
116 char cs_name[16];
117 int cs_flags;
118 kmutex_t cs_lock;
119 percpu_t *cs_percpu;
120 kcondvar_t cs_cv;
121 struct selinfo cs_selq;
122 struct rndsink *cs_rndsink;
123 bool cs_ready;
124 NIST_CTR_DRBG cs_drbg;
125
126 /* XXX Kludge for /dev/random `information-theoretic' properties. */
127 unsigned int cs_remaining;
128 };
129
130 struct cprng_strong *
131 cprng_strong_create(const char *name, int ipl, int flags)
132 {
133 const uint32_t cc = cprng_counter();
134 struct cprng_strong *const cprng = kmem_alloc(sizeof(*cprng),
135 KM_SLEEP);
136
137 /*
138 * rndsink_request takes a spin lock at IPL_VM, so we can be no
139 * higher than that.
140 */
141 KASSERT(ipl != IPL_SCHED && ipl != IPL_HIGH);
142
143 /* Initialize the easy fields. */
144 (void)strlcpy(cprng->cs_name, name, sizeof(cprng->cs_name));
145 cprng->cs_flags = flags;
146 mutex_init(&cprng->cs_lock, MUTEX_DEFAULT, ipl);
147 cv_init(&cprng->cs_cv, cprng->cs_name);
148 selinit(&cprng->cs_selq);
149 cprng->cs_rndsink = rndsink_create(NIST_BLOCK_KEYLEN_BYTES,
150 &cprng_strong_rndsink_callback, cprng);
151
152 /* Get some initial entropy. Record whether it is full entropy. */
153 uint8_t seed[NIST_BLOCK_KEYLEN_BYTES];
154 cprng->cs_ready = rndsink_request(cprng->cs_rndsink, seed,
155 sizeof(seed));
156 if (nist_ctr_drbg_instantiate(&cprng->cs_drbg, seed, sizeof(seed),
157 &cc, sizeof(cc), cprng->cs_name, sizeof(cprng->cs_name)))
158 /* XXX Fix nist_ctr_drbg API so this can't happen. */
159 panic("cprng %s: NIST CTR_DRBG instantiation failed",
160 cprng->cs_name);
161 explicit_memset(seed, 0, sizeof(seed));
162
163 if (ISSET(flags, CPRNG_HARD))
164 cprng->cs_remaining = NIST_BLOCK_KEYLEN_BYTES;
165 else
166 cprng->cs_remaining = 0;
167
168 if (!cprng->cs_ready && !ISSET(flags, CPRNG_INIT_ANY))
169 printf("cprng %s: creating with partial entropy\n",
170 cprng->cs_name);
171
172 return cprng;
173 }
174
175 void
176 cprng_strong_destroy(struct cprng_strong *cprng)
177 {
178
179 /*
180 * Destroy the rndsink first to prevent calls to the callback.
181 */
182 rndsink_destroy(cprng->cs_rndsink);
183
184 KASSERT(!cv_has_waiters(&cprng->cs_cv));
185 #if 0
186 KASSERT(!select_has_waiters(&cprng->cs_selq)) /* XXX ? */
187 #endif
188
189 nist_ctr_drbg_destroy(&cprng->cs_drbg);
190 seldestroy(&cprng->cs_selq);
191 cv_destroy(&cprng->cs_cv);
192 mutex_destroy(&cprng->cs_lock);
193
194 explicit_memset(cprng, 0, sizeof(*cprng)); /* paranoia */
195 kmem_free(cprng, sizeof(*cprng));
196 }
197
198 /*
199 * Generate some data from cprng. Block or return zero bytes,
200 * depending on flags & FNONBLOCK, if cprng was created without
201 * CPRNG_REKEY_ANY.
202 */
203 size_t
204 cprng_strong(struct cprng_strong *cprng, void *buffer, size_t bytes, int flags)
205 {
206 size_t result;
207
208 /* Caller must loop for more than CPRNG_MAX_LEN bytes. */
209 bytes = MIN(bytes, CPRNG_MAX_LEN);
210
211 mutex_enter(&cprng->cs_lock);
212
213 if (ISSET(cprng->cs_flags, CPRNG_REKEY_ANY)) {
214 if (!cprng->cs_ready)
215 cprng_strong_reseed(cprng);
216 } else {
217 while (!cprng->cs_ready) {
218 if (ISSET(flags, FNONBLOCK) ||
219 !ISSET(cprng->cs_flags, CPRNG_USE_CV) ||
220 cv_wait_sig(&cprng->cs_cv, &cprng->cs_lock)) {
221 result = 0;
222 goto out;
223 }
224 }
225 }
226
227 /*
228 * Debit the entropy if requested.
229 *
230 * XXX Kludge for /dev/random `information-theoretic' properties.
231 */
232 if (__predict_false(ISSET(cprng->cs_flags, CPRNG_HARD))) {
233 KASSERT(0 < cprng->cs_remaining);
234 KASSERT(cprng->cs_remaining <= NIST_BLOCK_KEYLEN_BYTES);
235 if (bytes < cprng->cs_remaining) {
236 cprng->cs_remaining -= bytes;
237 } else {
238 bytes = cprng->cs_remaining;
239 cprng->cs_remaining = NIST_BLOCK_KEYLEN_BYTES;
240 cprng->cs_ready = false;
241 rndsink_schedule(cprng->cs_rndsink);
242 }
243 KASSERT(bytes <= NIST_BLOCK_KEYLEN_BYTES);
244 KASSERT(0 < cprng->cs_remaining);
245 KASSERT(cprng->cs_remaining <= NIST_BLOCK_KEYLEN_BYTES);
246 }
247
248 cprng_strong_generate(cprng, buffer, bytes);
249 result = bytes;
250
251 out: mutex_exit(&cprng->cs_lock);
252 return result;
253 }
254
255 static void filt_cprng_detach(struct knote *);
256 static int filt_cprng_event(struct knote *, long);
257
258 static const struct filterops cprng_filtops =
259 { 1, NULL, filt_cprng_detach, filt_cprng_event };
260
261 int
262 cprng_strong_kqfilter(struct cprng_strong *cprng, struct knote *kn)
263 {
264
265 switch (kn->kn_filter) {
266 case EVFILT_READ:
267 kn->kn_fop = &cprng_filtops;
268 kn->kn_hook = cprng;
269 mutex_enter(&cprng->cs_lock);
270 SLIST_INSERT_HEAD(&cprng->cs_selq.sel_klist, kn, kn_selnext);
271 mutex_exit(&cprng->cs_lock);
272 return 0;
273
274 case EVFILT_WRITE:
275 default:
276 return EINVAL;
277 }
278 }
279
280 static void
281 filt_cprng_detach(struct knote *kn)
282 {
283 struct cprng_strong *const cprng = kn->kn_hook;
284
285 mutex_enter(&cprng->cs_lock);
286 SLIST_REMOVE(&cprng->cs_selq.sel_klist, kn, knote, kn_selnext);
287 mutex_exit(&cprng->cs_lock);
288 }
289
290 static int
291 filt_cprng_event(struct knote *kn, long hint)
292 {
293 struct cprng_strong *const cprng = kn->kn_hook;
294 int ret;
295
296 if (hint == NOTE_SUBMIT)
297 KASSERT(mutex_owned(&cprng->cs_lock));
298 else
299 mutex_enter(&cprng->cs_lock);
300 if (cprng->cs_ready) {
301 kn->kn_data = CPRNG_MAX_LEN; /* XXX Too large? */
302 ret = 1;
303 } else {
304 ret = 0;
305 }
306 if (hint == NOTE_SUBMIT)
307 KASSERT(mutex_owned(&cprng->cs_lock));
308 else
309 mutex_exit(&cprng->cs_lock);
310
311 return ret;
312 }
313
314 int
315 cprng_strong_poll(struct cprng_strong *cprng, int events)
316 {
317 int revents;
318
319 if (!ISSET(events, (POLLIN | POLLRDNORM)))
320 return 0;
321
322 mutex_enter(&cprng->cs_lock);
323 if (cprng->cs_ready) {
324 revents = (events & (POLLIN | POLLRDNORM));
325 } else {
326 selrecord(curlwp, &cprng->cs_selq);
327 revents = 0;
328 }
329 mutex_exit(&cprng->cs_lock);
330
331 return revents;
332 }
333
334 /*
335 * XXX Move nist_ctr_drbg_reseed_advised_p and
336 * nist_ctr_drbg_reseed_needed_p into the nist_ctr_drbg API and make
337 * the NIST_CTR_DRBG structure opaque.
338 */
339 static bool
340 nist_ctr_drbg_reseed_advised_p(NIST_CTR_DRBG *drbg)
341 {
342
343 return (drbg->reseed_counter > (NIST_CTR_DRBG_RESEED_INTERVAL / 2));
344 }
345
346 static bool
347 nist_ctr_drbg_reseed_needed_p(NIST_CTR_DRBG *drbg)
348 {
349
350 return (drbg->reseed_counter >= NIST_CTR_DRBG_RESEED_INTERVAL);
351 }
352
353 /*
354 * Generate some data from the underlying generator.
355 */
356 static void
357 cprng_strong_generate(struct cprng_strong *cprng, void *buffer, size_t bytes)
358 {
359 const uint32_t cc = cprng_counter();
360
361 KASSERT(bytes <= CPRNG_MAX_LEN);
362 KASSERT(mutex_owned(&cprng->cs_lock));
363
364 /*
365 * Generate some data from the NIST CTR_DRBG. Caller
366 * guarantees reseed if we're not ready, and if we exhaust the
367 * generator, we mark ourselves not ready. Consequently, this
368 * call to the CTR_DRBG should not fail.
369 */
370 if (__predict_false(nist_ctr_drbg_generate(&cprng->cs_drbg, buffer,
371 bytes, &cc, sizeof(cc))))
372 panic("cprng %s: NIST CTR_DRBG failed", cprng->cs_name);
373
374 /*
375 * If we've been seeing a lot of use, ask for some fresh
376 * entropy soon.
377 */
378 if (__predict_false(nist_ctr_drbg_reseed_advised_p(&cprng->cs_drbg)))
379 rndsink_schedule(cprng->cs_rndsink);
380
381 /*
382 * If we just exhausted the generator, inform the next user
383 * that we need a reseed.
384 */
385 if (__predict_false(nist_ctr_drbg_reseed_needed_p(&cprng->cs_drbg))) {
386 cprng->cs_ready = false;
387 rndsink_schedule(cprng->cs_rndsink); /* paranoia */
388 }
389 }
390
391 /*
392 * Reseed with whatever we can get from the system entropy pool right now.
393 */
394 static void
395 cprng_strong_reseed(struct cprng_strong *cprng)
396 {
397 uint8_t seed[NIST_BLOCK_KEYLEN_BYTES];
398
399 KASSERT(mutex_owned(&cprng->cs_lock));
400
401 const bool full_entropy = rndsink_request(cprng->cs_rndsink, seed,
402 sizeof(seed));
403 cprng_strong_reseed_from(cprng, seed, sizeof(seed), full_entropy);
404 explicit_memset(seed, 0, sizeof(seed));
405 }
406
407 /*
408 * Reseed with the given seed. If we now have full entropy, notify waiters.
409 */
410 static void
411 cprng_strong_reseed_from(struct cprng_strong *cprng,
412 const void *seed, size_t bytes, bool full_entropy)
413 {
414 const uint32_t cc = cprng_counter();
415
416 KASSERT(bytes == NIST_BLOCK_KEYLEN_BYTES);
417 KASSERT(mutex_owned(&cprng->cs_lock));
418
419 /*
420 * Notify anyone interested in the partiality of entropy in our
421 * seed -- anyone waiting for full entropy, or any system
422 * operators interested in knowing when the entropy pool is
423 * running on fumes.
424 */
425 if (full_entropy) {
426 if (!cprng->cs_ready) {
427 cprng->cs_ready = true;
428 cv_broadcast(&cprng->cs_cv);
429 selnotify(&cprng->cs_selq, (POLLIN | POLLRDNORM),
430 NOTE_SUBMIT);
431 }
432 } else {
433 /*
434 * XXX Is there is any harm in reseeding with partial
435 * entropy when we had full entropy before? If so,
436 * remove the conditional on this message.
437 */
438 if (!cprng->cs_ready &&
439 !ISSET(cprng->cs_flags, CPRNG_REKEY_ANY))
440 printf("cprng %s: reseeding with partial entropy\n",
441 cprng->cs_name);
442 }
443
444 if (nist_ctr_drbg_reseed(&cprng->cs_drbg, seed, bytes, &cc, sizeof(cc)))
445 /* XXX Fix nist_ctr_drbg API so this can't happen. */
446 panic("cprng %s: NIST CTR_DRBG reseed failed", cprng->cs_name);
447
448 #if DEBUG
449 cprng_strong_rngtest(cprng);
450 #endif
451 }
452
453 #if DEBUG
454 /*
455 * Generate some output and apply a statistical RNG test to it.
456 */
457 static void
458 cprng_strong_rngtest(struct cprng_strong *cprng)
459 {
460
461 KASSERT(mutex_owned(&cprng->cs_lock));
462
463 /* XXX Switch to a pool cache instead? */
464 rngtest_t *const rt = kmem_intr_alloc(sizeof(*rt), KM_NOSLEEP);
465 if (rt == NULL)
466 /* XXX Warn? */
467 return;
468
469 (void)strlcpy(rt->rt_name, cprng->cs_name, sizeof(rt->rt_name));
470
471 if (nist_ctr_drbg_generate(&cprng->cs_drbg, rt->rt_b, sizeof(rt->rt_b),
472 NULL, 0))
473 panic("cprng %s: NIST CTR_DRBG failed after reseed",
474 cprng->cs_name);
475
476 if (rngtest(rt)) {
477 printf("cprng %s: failed statistical RNG test\n",
478 cprng->cs_name);
479 /* XXX Not clear that this does any good... */
480 cprng->cs_ready = false;
481 rndsink_schedule(cprng->cs_rndsink);
482 }
483
484 explicit_memset(rt, 0, sizeof(*rt)); /* paranoia */
485 kmem_intr_free(rt, sizeof(*rt));
486 }
487 #endif
488
489 /*
490 * Feed entropy from an rndsink request into the CPRNG for which the
491 * request was issued.
492 */
493 static void
494 cprng_strong_rndsink_callback(void *context, const void *seed, size_t bytes)
495 {
496 struct cprng_strong *const cprng = context;
497
498 mutex_enter(&cprng->cs_lock);
499 /* Assume that rndsinks provide only full-entropy output. */
500 cprng_strong_reseed_from(cprng, seed, bytes, true);
501 mutex_exit(&cprng->cs_lock);
502 }
503
504 static cprng_strong_t *sysctl_prng;
505
506 static int
507 makeprng(void)
508 {
509
510 /* can't create in cprng_init(), too early */
511 sysctl_prng = cprng_strong_create("sysctl", IPL_NONE,
512 CPRNG_INIT_ANY|CPRNG_REKEY_ANY);
513 return 0;
514 }
515
516 /*
517 * sysctl helper routine for kern.urandom node. Picks a random number
518 * for you.
519 */
520 static int
521 sysctl_kern_urnd(SYSCTLFN_ARGS)
522 {
523 static ONCE_DECL(control);
524 int v, rv;
525
526 RUN_ONCE(&control, makeprng);
527 rv = cprng_strong(sysctl_prng, &v, sizeof(v), 0);
528 if (rv == sizeof(v)) {
529 struct sysctlnode node = *rnode;
530 node.sysctl_data = &v;
531 return (sysctl_lookup(SYSCTLFN_CALL(&node)));
532 }
533 else
534 return (EIO); /*XXX*/
535 }
536
537 /*
538 * sysctl helper routine for kern.arandom node. Fills the supplied
539 * structure with random data for you.
540 *
541 * This node was originally declared as type "int" but its implementation
542 * in OpenBSD, whence it came, would happily return up to 8K of data if
543 * requested. Evidently this was used to key RC4 in userspace.
544 *
545 * In NetBSD, the libc stack-smash-protection code reads 64 bytes
546 * from here at every program startup. So though it would be nice
547 * to make this node return only 32 or 64 bits, we can't. Too bad!
548 */
549 static int
550 sysctl_kern_arnd(SYSCTLFN_ARGS)
551 {
552 int error;
553 void *v;
554 struct sysctlnode node = *rnode;
555
556 switch (*oldlenp) {
557 case 0:
558 return 0;
559 default:
560 if (*oldlenp > 256) {
561 return E2BIG;
562 }
563 v = kmem_alloc(*oldlenp, KM_SLEEP);
564 cprng_fast(v, *oldlenp);
565 node.sysctl_data = v;
566 node.sysctl_size = *oldlenp;
567 error = sysctl_lookup(SYSCTLFN_CALL(&node));
568 kmem_free(v, *oldlenp);
569 return error;
570 }
571 }
572