HAMMER 18B/many: Stabilization pass
[dragonfly.git] / sys / kern / kern_nrandom.c
blob03d23fd63a1f892b82ea42e87287758359d4b75c
1 /*
2 * Copyright (c) 2004, 2005, 2006 Robin J Carey. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions, and the following disclaimer,
9 * without modification, immediately at the beginning of the file.
10 * 2. The name of the author may not be used to endorse or promote products
11 * derived from this software without specific prior written permission.
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
17 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23 * SUCH DAMAGE.
25 * $DragonFly: src/sys/kern/kern_nrandom.c,v 1.4 2006/09/10 01:26:39 dillon Exp $
27 /* --- NOTES ---
29 * Note: The word "entropy" is often incorrectly used to describe
30 * random data. The word "entropy" originates from the science of
31 * Physics. The correct descriptive definition would be something
32 * along the lines of "seed", "unpredictable numbers" or
33 * "unpredictable data".
35 * Note: Some /dev/[u]random implementations save "seed" between
36 * boots which represents a security hazard since an adversary
37 * could acquire this data (since it is stored in a file). If
38 * the unpredictable data used in the above routines is only
39 * generated during Kernel operation, then an adversary can only
40 * acquire that data through a Kernel security compromise and/or
41 * a cryptographic algorithm failure/cryptanalysis.
43 * Note: On FreeBSD-4.11, interrupts have to be manually enabled
44 * using the rndcontrol(8) command.
46 * --- DESIGN (FreeBSD-4.11 based) ---
48 * The rnddev module automatically initializes itself the first time
49 * it is used (client calls any public rnddev_*() interface routine).
50 * Both CSPRNGs are initially seeded from the precise nano[up]time() routines.
51 * Tests show this method produces good enough results, suitable for intended
52 * use. It is necessary for both CSPRNGs to be completely seeded, initially.
54 * After initialization and during Kernel operation the only suitable
55 * unpredictable data available is:
57 * (1) Keyboard scan-codes.
58 * (2) Nanouptime acquired by a Keyboard/Read-Event.
59 * (3) Suitable interrupt source; hard-disk/ATA-device.
61 * (X) Mouse-event (xyz-data unsuitable); NOT IMPLEMENTED.
63 * This data is added to both CSPRNGs in real-time as it happens/
64 * becomes-available. Additionally, unpredictable (?) data may be
65 * acquired from a true-random number generator if such a device is
66 * available to the system (not advisable !).
67 * Nanouptime() acquired by a Read-Event is a very important aspect of
68 * this design, since it ensures that unpredictable data is added to
69 * the CSPRNGs even if there are no other sources.
70 * The nanouptime() Kernel routine is used since time relative to
71 * boot is less adversary-known than time itself.
73 * This design has been thoroughly tested with debug logging
74 * and the output from both /dev/random and /dev/urandom has
75 * been tested with the DIEHARD test-suite; both pass.
77 * MODIFICATIONS MADE TO ORIGINAL "kern_random.c":
79 * 6th July 2005:
81 * o Changed ReadSeed() function to schedule future read-seed-events
82 * by at least one second. Previous implementation used a randomised
83 * scheduling { 0, 1, 2, 3 seconds }.
84 * o Changed SEED_NANOUP() function to use a "previous" accumulator
85 * algorithm similar to ReadSeed(). This ensures that there is no
86 * way that an adversary can tell what number is being added to the
87 * CSPRNGs, since the number added to the CSPRNGs at Event-Time is
88 * the sum of nanouptime()@Event and an unknown/secret number.
89 * o Changed rnddev_add_interrupt() function to schedule future
90 * interrupt-events by at least one second. Previous implementation
91 * had no scheduling algorithm which allowed an "interrupt storm"
92 * to occur resulting in skewed data entering into the CSPRNGs.
95 * 9th July 2005:
97 * o Some small cleanups and change all internal functions to be
98 * static/private.
99 * o Removed ReadSeed() since its functionality is already performed
100 * by another function { rnddev_add_interrupt_OR_read() } and remove
101 * the silly rndByte accumulator/feedback-thing (since multipying by
102 * rndByte could yield a value of 0).
103 * o Made IBAA/L14 public interface become static/private;
104 * Local to this file (not changed to that in the original C modules).
106 * 16th July 2005:
108 * o SEED_NANOUP() -> NANOUP_EVENT() function rename.
109 * o Make NANOUP_EVENT() handle the time-buffering directly so that all
110 * time-stamp-events use this single time-buffer (including keyboard).
111 * This removes dependancy on "time_second" Kernel variable.
112 * o Removed second-time-buffer code in rnddev_add_interrupt_OR_read (void).
113 * o Rewrote the time-buffering algorithm in NANOUP_EVENT() to use a
114 * randomised time-delay range.
116 * 12th Dec 2005:
118 * o Updated to (hopefully final) L15 algorithm.
120 * 12th June 2006:
122 * o Added missing (u_char *) cast in RnddevRead() function.
123 * o Changed copyright to 3-clause BSD license and cleaned up the layout
124 * of this file.
127 #include <sys/types.h>
128 #include <sys/kernel.h>
129 #include <sys/systm.h>
130 #include <sys/poll.h>
131 #include <sys/random.h>
132 #include <sys/systimer.h>
133 #include <sys/time.h>
134 #include <sys/proc.h>
135 #include <sys/lock.h>
136 #include <sys/sysctl.h>
137 #include <sys/spinlock.h>
138 #include <machine/clock.h>
140 #include <sys/thread2.h>
141 #include <sys/spinlock2.h>
144 * Portability note: The u_char/unsigned char type is used where
145 * uint8_t from <stdint.h> or u_int8_t from <sys/types.h> should really
146 * be being used. On FreeBSD, it is safe to make the assumption that these
147 * different types are equivalent (on all architectures).
148 * The FreeBSD <sys/crypto/rc4> module also makes this assumption.
151 /*------------------------------ IBAA ----------------------------------*/
153 /*-------------------------- IBAA CSPRNG -------------------------------*/
156 * NOTE: The original source code from which this source code (IBAA)
157 * was taken has no copyright/license. The algorithm has no patent
158 * and is freely/publicly available from:
160 * http://www.burtleburtle.net/bob/rand/isaac.html
164 * ^ means XOR, & means bitwise AND, a<<b means shift a by b.
165 * barrel(a) shifts a 19 bits to the left, and bits wrap around
166 * ind(x) is (x AND 255), or (x mod 256)
168 typedef u_int32_t u4; /* unsigned four bytes, 32 bits */
170 #define ALPHA (8)
171 #define SIZE (1 << ALPHA)
172 #define MASK (SIZE - 1)
173 #define ind(x) ((x) & (SIZE - 1))
174 #define barrel(a) (((a) << 19) ^ ((a) >> 13)) /* beta=32,shift=19 */
176 static void IBAA
178 u4 *m, /* Memory: array of SIZE ALPHA-bit terms */
179 u4 *r, /* Results: the sequence, same size as m */
180 u4 *aa, /* Accumulator: a single value */
181 u4 *bb /* the previous result */
184 u4 a, b, x, y, i;
186 a = *aa; b = *bb;
187 for (i = 0; i < SIZE; ++i) {
188 x = m[i];
189 a = barrel(a) + m[ind(i + (SIZE / 2))]; /* set a */
190 m[i] = y = m[ind(x)] + a + b; /* set m */
191 r[i] = b = m[ind(y >> ALPHA)] + x; /* set r */
193 *bb = b; *aa = a;
196 /*-------------------------- IBAA CSPRNG -------------------------------*/
199 static u4 IBAA_memory[SIZE];
200 static u4 IBAA_results[SIZE];
201 static u4 IBAA_aa;
202 static u4 IBAA_bb;
204 static volatile int IBAA_byte_index;
207 static void IBAA_Init(void);
208 static void IBAA_Call(void);
209 static void IBAA_Seed(const u_int32_t val);
210 static u_char IBAA_Byte(void);
213 * Initialize IBAA.
215 static void
216 IBAA_Init(void)
218 size_t i;
220 for (i = 0; i < SIZE; ++i) {
221 IBAA_memory[i] = i;
223 IBAA_aa = IBAA_bb = 0;
224 IBAA_byte_index = sizeof(IBAA_results); /* force IBAA_Call() */
228 * PRIVATE: Call IBAA to produce 256 32-bit u4 results.
230 static void
231 IBAA_Call (void)
233 IBAA(IBAA_memory, IBAA_results, &IBAA_aa, &IBAA_bb);
234 IBAA_byte_index = 0;
238 * Add a 32-bit u4 seed value into IBAAs memory. Mix the low 4 bits
239 * with 4 bits of PNG data to reduce the possibility of a seeding-based
240 * attack.
242 static void
243 IBAA_Seed (const u_int32_t val)
245 static int memIndex;
246 u4 *iptr;
248 iptr = &IBAA_memory[memIndex & MASK];
249 *iptr = ((*iptr << 3) | (*iptr >> 29)) + (val ^ (IBAA_Byte() & 15));
250 ++memIndex;
254 * Extract a byte from IBAAs 256 32-bit u4 results array.
256 * NOTE: This code is designed to prevent MP races from taking
257 * IBAA_byte_index out of bounds.
259 static u_char
260 IBAA_Byte(void)
262 u_char result;
263 int index;
265 index = IBAA_byte_index;
266 if (index == sizeof(IBAA_results)) {
267 IBAA_Call();
268 index = 0;
270 result = ((u_char *)IBAA_results)[index];
271 IBAA_byte_index = index + 1;
272 return result;
275 /*------------------------------ IBAA ----------------------------------*/
278 /*------------------------------- L15 ----------------------------------*/
281 * IMPORTANT NOTE: LByteType must be exactly 8-bits in size or this software
282 * will not function correctly.
284 typedef unsigned char LByteType;
286 #define L15_STATE_SIZE 256
288 static LByteType L15_x, L15_y;
289 static LByteType L15_start_x;
290 static LByteType L15_state[L15_STATE_SIZE];
293 * PRIVATE FUNCS:
296 static void L15_Swap(const LByteType pos1, const LByteType pos2);
297 static void L15_InitState(void);
298 static void L15_KSA(const LByteType * const key,
299 const size_t keyLen);
300 static void L15_Discard(const LByteType numCalls);
303 * PUBLIC INTERFACE:
305 static void L15(const LByteType * const key, const size_t keyLen);
306 static LByteType L15_Byte(void);
307 static void L15_Vector(const LByteType * const key,
308 const size_t keyLen);
310 static __inline void
311 L15_Swap(const LByteType pos1, const LByteType pos2)
313 const LByteType save1 = L15_state[pos1];
315 L15_state[pos1] = L15_state[pos2];
316 L15_state[pos2] = save1;
319 static void
320 L15_InitState (void)
322 size_t i;
323 for (i = 0; i < L15_STATE_SIZE; ++i)
324 L15_state[i] = i;
327 #define L_SCHEDULE(xx) \
329 for (i = 0; i < L15_STATE_SIZE; ++i) { \
330 L15_Swap(i, (stateIndex += (L15_state[i] + (xx)))); \
333 static void
334 L15_KSA (const LByteType * const key, const size_t keyLen)
336 size_t i, keyIndex;
337 LByteType stateIndex = 0;
339 L_SCHEDULE(keyLen);
340 for (keyIndex = 0; keyIndex < keyLen; ++keyIndex) {
341 L_SCHEDULE(key[keyIndex]);
345 static void
346 L15_Discard(const LByteType numCalls)
348 LByteType i;
349 for (i = 0; i < numCalls; ++i) {
350 (void)L15_Byte();
356 * PUBLIC INTERFACE:
358 static void
359 L15(const LByteType * const key, const size_t keyLen)
361 L15_x = L15_y = L15_start_x = 0;
362 L15_InitState();
363 L15_KSA(key, keyLen);
364 L15_Discard(L15_Byte());
367 static LByteType
368 L15_Byte(void)
370 LByteType z;
372 L15_Swap(L15_state[L15_x], L15_y);
373 z = (L15_state [L15_x++] + L15_state[L15_y--]);
374 if (L15_x == L15_start_x) {
375 --L15_y;
377 return (L15_state[z]);
380 static void
381 L15_Vector (const LByteType * const key, const size_t keyLen)
383 L15_KSA(key, keyLen);
386 /*------------------------------- L15 ----------------------------------*/
388 /************************************************************************
389 * KERNEL INTERFACE *
390 ************************************************************************
392 * By Robin J Carey and Matthew Dillon.
395 static int rand_thread_signal = 1;
396 static void NANOUP_EVENT(void);
397 static thread_t rand_td;
398 static struct spinlock rand_spin;
400 static int nrandevents;
401 SYSCTL_INT(_kern, OID_AUTO, nrandevents, CTLFLAG_RD, &nrandevents, 0, "");
402 static int seedenable;
403 SYSCTL_INT(_kern, OID_AUTO, seedenable, CTLFLAG_RW, &seedenable, 0, "");
406 * Called from early boot
408 void
409 rand_initialize(void)
411 struct timespec now;
412 int i;
414 spin_init(&rand_spin);
416 /* Initialize IBAA. */
417 IBAA_Init();
419 /* Initialize L15. */
420 nanouptime(&now);
421 L15((const LByteType *)&now.tv_nsec, sizeof(now.tv_nsec));
422 for (i = 0; i < (SIZE / 2); ++i) {
423 nanotime(&now);
424 IBAA_Seed(now.tv_nsec);
425 L15_Vector((const LByteType *)&now.tv_nsec,
426 sizeof(now.tv_nsec));
427 nanouptime(&now);
428 IBAA_Seed(now.tv_nsec);
429 L15_Vector((const LByteType *)&now.tv_nsec,
430 sizeof(now.tv_nsec));
435 * Keyboard events
437 void
438 add_keyboard_randomness(u_char scancode)
440 spin_lock_wr(&rand_spin);
441 L15_Vector((const LByteType *) &scancode, sizeof (scancode));
442 spin_unlock_wr(&rand_spin);
443 add_interrupt_randomness(0);
447 * Interrupt events
449 void
450 add_interrupt_randomness(int intr)
452 if (rand_thread_signal == 0) {
453 rand_thread_signal = 1;
454 lwkt_schedule(rand_td);
459 * True random number source
461 void
462 add_true_randomness(int val)
464 spin_lock_wr(&rand_spin);
465 IBAA_Seed(val);
466 L15_Vector((const LByteType *) &val, sizeof (val));
467 ++nrandevents;
468 spin_unlock_wr(&rand_spin);
472 add_buffer_randomness(const char *buf, int bytes)
474 int error;
476 if (seedenable && securelevel <= 0) {
477 while (bytes >= sizeof(int)) {
478 add_true_randomness(*(const int *)buf);
479 buf += sizeof(int);
480 bytes -= sizeof(int);
482 error = 0;
483 } else {
484 error = EPERM;
486 return (error);
490 * Poll (always succeeds)
493 random_poll(cdev_t dev, int events)
495 int revents = 0;
497 if (events & (POLLIN | POLLRDNORM))
498 revents |= events & (POLLIN | POLLRDNORM);
499 if (events & (POLLOUT | POLLWRNORM))
500 revents |= events & (POLLOUT | POLLWRNORM);
502 return (revents);
506 * Heavy weight random number generator. May return less then the
507 * requested number of bytes.
509 u_int
510 read_random(void *buf, u_int nbytes)
512 u_int i;
514 spin_lock_wr(&rand_spin);
515 for (i = 0; i < nbytes; ++i)
516 ((u_char *)buf)[i] = IBAA_Byte();
517 spin_unlock_wr(&rand_spin);
518 add_interrupt_randomness(0);
519 return(i);
523 * Lightweight random number generator. Must return requested number of
524 * bytes.
526 u_int
527 read_random_unlimited(void *buf, u_int nbytes)
529 u_int i;
531 spin_lock_wr(&rand_spin);
532 for (i = 0; i < nbytes; ++i)
533 ((u_char *)buf)[i] = L15_Byte();
534 spin_unlock_wr(&rand_spin);
535 add_interrupt_randomness(0);
536 return (i);
540 * Random number generator helper thread. This limits code overhead from
541 * high frequency events by delaying the clearing of rand_thread_signal.
543 static
544 void
545 rand_thread_loop(void *dummy)
547 int count;
549 for (;;) {
550 NANOUP_EVENT ();
551 spin_lock_wr(&rand_spin);
552 count = (int)(L15_Byte() * hz / (256 * 10) + hz / 10);
553 spin_unlock_wr(&rand_spin);
554 tsleep(rand_td, 0, "rwait", count);
555 rand_thread_signal = 0;
556 lwkt_deschedule_self(rand_td);
557 lwkt_switch();
561 static
562 void
563 rand_thread_init(void)
565 lwkt_create(rand_thread_loop, NULL, &rand_td, NULL, 0, 0, "random");
568 SYSINIT(rand, SI_SUB_HELPER_THREADS, SI_ORDER_ANY, rand_thread_init, 0);
571 * Time-buffered event time-stamping. This is necessary to cutoff higher
572 * event frequencies, e.g. an interrupt occuring at 25Hz. In such cases
573 * the CPU is being chewed and the timestamps are skewed (minimal variation).
574 * Use a nano-second time-delay to limit how many times an Event can occur
575 * in one second; <= 5Hz. Note that this doesn't prevent time-stamp skewing.
576 * This implementation randmoises the time-delay between events, which adds
577 * a layer of security/unpredictability with regard to read-events (a user
578 * controlled input).
580 * Note: now.tv_nsec should range [ 0 - 1000,000,000 ].
581 * Note: "ACCUM" is a security measure (result = capped-unknown + unknown),
582 * and also produces an uncapped (>=32-bit) value.
584 static void
585 NANOUP_EVENT(void)
587 static struct timespec ACCUM = { 0, 0 };
588 static struct timespec NEXT = { 0, 0 };
589 struct timespec now;
591 nanouptime(&now);
592 spin_lock_wr(&rand_spin);
593 if ((now.tv_nsec > NEXT.tv_nsec) || (now.tv_sec != NEXT.tv_sec)) {
595 * Randomised time-delay: 200e6 - 350e6 ns; 5 - 2.86 Hz.
597 unsigned long one_mil;
598 unsigned long timeDelay;
600 one_mil = 1000000UL; /* 0.001 s */
601 timeDelay = (one_mil * 200) + (((unsigned)ACCUM.tv_nsec % 151) * one_mil);
602 NEXT.tv_nsec = now.tv_nsec + timeDelay;
603 NEXT.tv_sec = now.tv_sec;
604 ACCUM.tv_nsec += now.tv_nsec;
607 * The TSC, if present, generally has an even higher
608 * resolution. Integrate a portion of it into our seed.
610 if (tsc_present)
611 ACCUM.tv_nsec ^= rdtsc() & 255;
613 IBAA_Seed(ACCUM.tv_nsec);
614 L15_Vector((const LByteType *)&ACCUM.tv_nsec,
615 sizeof(ACCUM.tv_nsec));
616 ++nrandevents;
618 spin_unlock_wr(&rand_spin);