Back to home page

LXR

 
 

    


0001 /*
0002  * Non-physical true random number generator based on timing jitter --
0003  * Jitter RNG standalone code.
0004  *
0005  * Copyright Stephan Mueller <smueller@chronox.de>, 2015
0006  *
0007  * Design
0008  * ======
0009  *
0010  * See http://www.chronox.de/jent.html
0011  *
0012  * License
0013  * =======
0014  *
0015  * Redistribution and use in source and binary forms, with or without
0016  * modification, are permitted provided that the following conditions
0017  * are met:
0018  * 1. Redistributions of source code must retain the above copyright
0019  *    notice, and the entire permission notice in its entirety,
0020  *    including the disclaimer of warranties.
0021  * 2. Redistributions in binary form must reproduce the above copyright
0022  *    notice, this list of conditions and the following disclaimer in the
0023  *    documentation and/or other materials provided with the distribution.
0024  * 3. The name of the author may not be used to endorse or promote
0025  *    products derived from this software without specific prior
0026  *    written permission.
0027  *
0028  * ALTERNATIVELY, this product may be distributed under the terms of
0029  * the GNU General Public License, in which case the provisions of the GPL2 are
0030  * required INSTEAD OF the above restrictions.  (This clause is
0031  * necessary due to a potential bad interaction between the GPL and
0032  * the restrictions contained in a BSD-style copyright.)
0033  *
0034  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
0035  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
0036  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF
0037  * WHICH ARE HEREBY DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE
0038  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
0039  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
0040  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
0041  * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
0042  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
0043  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
0044  * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH
0045  * DAMAGE.
0046  */
0047 
0048 /*
0049  * This Jitterentropy RNG is based on the jitterentropy library
0050  * version 1.1.0 provided at http://www.chronox.de/jent.html
0051  */
0052 
0053 #ifdef __OPTIMIZE__
0054  #error "The CPU Jitter random number generator must not be compiled with optimizations. See documentation. Use the compiler switch -O0 for compiling jitterentropy.c."
0055 #endif
0056 
0057 typedef unsigned long long  __u64;
0058 typedef long long       __s64;
0059 typedef unsigned int        __u32;
0060 #define NULL    ((void *) 0)
0061 
0062 /* The entropy pool */
0063 struct rand_data {
0064     /* all data values that are vital to maintain the security
0065      * of the RNG are marked as SENSITIVE. A user must not
0066      * access that information while the RNG executes its loops to
0067      * calculate the next random value. */
0068     __u64 data;     /* SENSITIVE Actual random number */
0069     __u64 old_data;     /* SENSITIVE Previous random number */
0070     __u64 prev_time;    /* SENSITIVE Previous time stamp */
0071 #define DATA_SIZE_BITS ((sizeof(__u64)) * 8)
0072     __u64 last_delta;   /* SENSITIVE stuck test */
0073     __s64 last_delta2;  /* SENSITIVE stuck test */
0074     unsigned int stuck:1;   /* Time measurement stuck */
0075     unsigned int osr;   /* Oversample rate */
0076     unsigned int stir:1;        /* Post-processing stirring */
0077     unsigned int disable_unbias:1;  /* Deactivate Von-Neuman unbias */
0078 #define JENT_MEMORY_BLOCKS 64
0079 #define JENT_MEMORY_BLOCKSIZE 32
0080 #define JENT_MEMORY_ACCESSLOOPS 128
0081 #define JENT_MEMORY_SIZE (JENT_MEMORY_BLOCKS*JENT_MEMORY_BLOCKSIZE)
0082     unsigned char *mem; /* Memory access location with size of
0083                  * memblocks * memblocksize */
0084     unsigned int memlocation; /* Pointer to byte in *mem */
0085     unsigned int memblocks; /* Number of memory blocks in *mem */
0086     unsigned int memblocksize; /* Size of one memory block in bytes */
0087     unsigned int memaccessloops; /* Number of memory accesses per random
0088                       * bit generation */
0089 };
0090 
0091 /* Flags that can be used to initialize the RNG */
0092 #define JENT_DISABLE_STIR (1<<0) /* Disable stirring the entropy pool */
0093 #define JENT_DISABLE_UNBIAS (1<<1) /* Disable the Von-Neuman Unbiaser */
0094 #define JENT_DISABLE_MEMORY_ACCESS (1<<2) /* Disable memory access for more
0095                        * entropy, saves MEMORY_SIZE RAM for
0096                        * entropy collector */
0097 
0098 /* -- error codes for init function -- */
0099 #define JENT_ENOTIME        1 /* Timer service not available */
0100 #define JENT_ECOARSETIME    2 /* Timer too coarse for RNG */
0101 #define JENT_ENOMONOTONIC   3 /* Timer is not monotonic increasing */
0102 #define JENT_EMINVARIATION  4 /* Timer variations too small for RNG */
0103 #define JENT_EVARVAR        5 /* Timer does not produce variations of
0104                    * variations (2nd derivation of time is
0105                    * zero). */
0106 #define JENT_EMINVARVAR     6 /* Timer variations of variations is tooi
0107                    * small. */
0108 
0109 /***************************************************************************
0110  * Helper functions
0111  ***************************************************************************/
0112 
0113 void jent_get_nstime(__u64 *out);
0114 __u64 jent_rol64(__u64 word, unsigned int shift);
0115 void *jent_zalloc(unsigned int len);
0116 void jent_zfree(void *ptr);
0117 int jent_fips_enabled(void);
0118 void jent_panic(char *s);
0119 void jent_memcpy(void *dest, const void *src, unsigned int n);
0120 
0121 /**
0122  * Update of the loop count used for the next round of
0123  * an entropy collection.
0124  *
0125  * Input:
0126  * @ec entropy collector struct -- may be NULL
0127  * @bits is the number of low bits of the timer to consider
0128  * @min is the number of bits we shift the timer value to the right at
0129  *  the end to make sure we have a guaranteed minimum value
0130  *
0131  * @return Newly calculated loop counter
0132  */
0133 static __u64 jent_loop_shuffle(struct rand_data *ec,
0134                    unsigned int bits, unsigned int min)
0135 {
0136     __u64 time = 0;
0137     __u64 shuffle = 0;
0138     unsigned int i = 0;
0139     unsigned int mask = (1<<bits) - 1;
0140 
0141     jent_get_nstime(&time);
0142     /*
0143      * mix the current state of the random number into the shuffle
0144      * calculation to balance that shuffle a bit more
0145      */
0146     if (ec)
0147         time ^= ec->data;
0148     /*
0149      * we fold the time value as much as possible to ensure that as many
0150      * bits of the time stamp are included as possible
0151      */
0152     for (i = 0; (DATA_SIZE_BITS / bits) > i; i++) {
0153         shuffle ^= time & mask;
0154         time = time >> bits;
0155     }
0156 
0157     /*
0158      * We add a lower boundary value to ensure we have a minimum
0159      * RNG loop count.
0160      */
0161     return (shuffle + (1<<min));
0162 }
0163 
0164 /***************************************************************************
0165  * Noise sources
0166  ***************************************************************************/
0167 
0168 /**
0169  * CPU Jitter noise source -- this is the noise source based on the CPU
0170  *                execution time jitter
0171  *
0172  * This function folds the time into one bit units by iterating
0173  * through the DATA_SIZE_BITS bit time value as follows: assume our time value
0174  * is 0xabcd
0175  * 1st loop, 1st shift generates 0xd000
0176  * 1st loop, 2nd shift generates 0x000d
0177  * 2nd loop, 1st shift generates 0xcd00
0178  * 2nd loop, 2nd shift generates 0x000c
0179  * 3rd loop, 1st shift generates 0xbcd0
0180  * 3rd loop, 2nd shift generates 0x000b
0181  * 4th loop, 1st shift generates 0xabcd
0182  * 4th loop, 2nd shift generates 0x000a
0183  * Now, the values at the end of the 2nd shifts are XORed together.
0184  *
0185  * The code is deliberately inefficient and shall stay that way. This function
0186  * is the root cause why the code shall be compiled without optimization. This
0187  * function not only acts as folding operation, but this function's execution
0188  * is used to measure the CPU execution time jitter. Any change to the loop in
0189  * this function implies that careful retesting must be done.
0190  *
0191  * Input:
0192  * @ec entropy collector struct -- may be NULL
0193  * @time time stamp to be folded
0194  * @loop_cnt if a value not equal to 0 is set, use the given value as number of
0195  *       loops to perform the folding
0196  *
0197  * Output:
0198  * @folded result of folding operation
0199  *
0200  * @return Number of loops the folding operation is performed
0201  */
0202 static __u64 jent_fold_time(struct rand_data *ec, __u64 time,
0203                 __u64 *folded, __u64 loop_cnt)
0204 {
0205     unsigned int i;
0206     __u64 j = 0;
0207     __u64 new = 0;
0208 #define MAX_FOLD_LOOP_BIT 4
0209 #define MIN_FOLD_LOOP_BIT 0
0210     __u64 fold_loop_cnt =
0211         jent_loop_shuffle(ec, MAX_FOLD_LOOP_BIT, MIN_FOLD_LOOP_BIT);
0212 
0213     /*
0214      * testing purposes -- allow test app to set the counter, not
0215      * needed during runtime
0216      */
0217     if (loop_cnt)
0218         fold_loop_cnt = loop_cnt;
0219     for (j = 0; j < fold_loop_cnt; j++) {
0220         new = 0;
0221         for (i = 1; (DATA_SIZE_BITS) >= i; i++) {
0222             __u64 tmp = time << (DATA_SIZE_BITS - i);
0223 
0224             tmp = tmp >> (DATA_SIZE_BITS - 1);
0225             new ^= tmp;
0226         }
0227     }
0228     *folded = new;
0229     return fold_loop_cnt;
0230 }
0231 
0232 /**
0233  * Memory Access noise source -- this is a noise source based on variations in
0234  *               memory access times
0235  *
0236  * This function performs memory accesses which will add to the timing
0237  * variations due to an unknown amount of CPU wait states that need to be
0238  * added when accessing memory. The memory size should be larger than the L1
0239  * caches as outlined in the documentation and the associated testing.
0240  *
0241  * The L1 cache has a very high bandwidth, albeit its access rate is  usually
0242  * slower than accessing CPU registers. Therefore, L1 accesses only add minimal
0243  * variations as the CPU has hardly to wait. Starting with L2, significant
0244  * variations are added because L2 typically does not belong to the CPU any more
0245  * and therefore a wider range of CPU wait states is necessary for accesses.
0246  * L3 and real memory accesses have even a wider range of wait states. However,
0247  * to reliably access either L3 or memory, the ec->mem memory must be quite
0248  * large which is usually not desirable.
0249  *
0250  * Input:
0251  * @ec Reference to the entropy collector with the memory access data -- if
0252  *     the reference to the memory block to be accessed is NULL, this noise
0253  *     source is disabled
0254  * @loop_cnt if a value not equal to 0 is set, use the given value as number of
0255  *       loops to perform the folding
0256  *
0257  * @return Number of memory access operations
0258  */
0259 static unsigned int jent_memaccess(struct rand_data *ec, __u64 loop_cnt)
0260 {
0261     unsigned char *tmpval = NULL;
0262     unsigned int wrap = 0;
0263     __u64 i = 0;
0264 #define MAX_ACC_LOOP_BIT 7
0265 #define MIN_ACC_LOOP_BIT 0
0266     __u64 acc_loop_cnt =
0267         jent_loop_shuffle(ec, MAX_ACC_LOOP_BIT, MIN_ACC_LOOP_BIT);
0268 
0269     if (NULL == ec || NULL == ec->mem)
0270         return 0;
0271     wrap = ec->memblocksize * ec->memblocks;
0272 
0273     /*
0274      * testing purposes -- allow test app to set the counter, not
0275      * needed during runtime
0276      */
0277     if (loop_cnt)
0278         acc_loop_cnt = loop_cnt;
0279 
0280     for (i = 0; i < (ec->memaccessloops + acc_loop_cnt); i++) {
0281         tmpval = ec->mem + ec->memlocation;
0282         /*
0283          * memory access: just add 1 to one byte,
0284          * wrap at 255 -- memory access implies read
0285          * from and write to memory location
0286          */
0287         *tmpval = (*tmpval + 1) & 0xff;
0288         /*
0289          * Addition of memblocksize - 1 to pointer
0290          * with wrap around logic to ensure that every
0291          * memory location is hit evenly
0292          */
0293         ec->memlocation = ec->memlocation + ec->memblocksize - 1;
0294         ec->memlocation = ec->memlocation % wrap;
0295     }
0296     return i;
0297 }
0298 
0299 /***************************************************************************
0300  * Start of entropy processing logic
0301  ***************************************************************************/
0302 
0303 /**
0304  * Stuck test by checking the:
0305  *  1st derivation of the jitter measurement (time delta)
0306  *  2nd derivation of the jitter measurement (delta of time deltas)
0307  *  3rd derivation of the jitter measurement (delta of delta of time deltas)
0308  *
0309  * All values must always be non-zero.
0310  *
0311  * Input:
0312  * @ec Reference to entropy collector
0313  * @current_delta Jitter time delta
0314  *
0315  * @return
0316  *  0 jitter measurement not stuck (good bit)
0317  *  1 jitter measurement stuck (reject bit)
0318  */
0319 static void jent_stuck(struct rand_data *ec, __u64 current_delta)
0320 {
0321     __s64 delta2 = ec->last_delta - current_delta;
0322     __s64 delta3 = delta2 - ec->last_delta2;
0323 
0324     ec->last_delta = current_delta;
0325     ec->last_delta2 = delta2;
0326 
0327     if (!current_delta || !delta2 || !delta3)
0328         ec->stuck = 1;
0329 }
0330 
0331 /**
0332  * This is the heart of the entropy generation: calculate time deltas and
0333  * use the CPU jitter in the time deltas. The jitter is folded into one
0334  * bit. You can call this function the "random bit generator" as it
0335  * produces one random bit per invocation.
0336  *
0337  * WARNING: ensure that ->prev_time is primed before using the output
0338  *      of this function! This can be done by calling this function
0339  *      and not using its result.
0340  *
0341  * Input:
0342  * @entropy_collector Reference to entropy collector
0343  *
0344  * @return One random bit
0345  */
0346 static __u64 jent_measure_jitter(struct rand_data *ec)
0347 {
0348     __u64 time = 0;
0349     __u64 data = 0;
0350     __u64 current_delta = 0;
0351 
0352     /* Invoke one noise source before time measurement to add variations */
0353     jent_memaccess(ec, 0);
0354 
0355     /*
0356      * Get time stamp and calculate time delta to previous
0357      * invocation to measure the timing variations
0358      */
0359     jent_get_nstime(&time);
0360     current_delta = time - ec->prev_time;
0361     ec->prev_time = time;
0362 
0363     /* Now call the next noise sources which also folds the data */
0364     jent_fold_time(ec, current_delta, &data, 0);
0365 
0366     /*
0367      * Check whether we have a stuck measurement. The enforcement
0368      * is performed after the stuck value has been mixed into the
0369      * entropy pool.
0370      */
0371     jent_stuck(ec, current_delta);
0372 
0373     return data;
0374 }
0375 
0376 /**
0377  * Von Neuman unbias as explained in RFC 4086 section 4.2. As shown in the
0378  * documentation of that RNG, the bits from jent_measure_jitter are considered
0379  * independent which implies that the Von Neuman unbias operation is applicable.
0380  * A proof of the Von-Neumann unbias operation to remove skews is given in the
0381  * document "A proposal for: Functionality classes for random number
0382  * generators", version 2.0 by Werner Schindler, section 5.4.1.
0383  *
0384  * Input:
0385  * @entropy_collector Reference to entropy collector
0386  *
0387  * @return One random bit
0388  */
0389 static __u64 jent_unbiased_bit(struct rand_data *entropy_collector)
0390 {
0391     do {
0392         __u64 a = jent_measure_jitter(entropy_collector);
0393         __u64 b = jent_measure_jitter(entropy_collector);
0394 
0395         if (a == b)
0396             continue;
0397         if (1 == a)
0398             return 1;
0399         else
0400             return 0;
0401     } while (1);
0402 }
0403 
0404 /**
0405  * Shuffle the pool a bit by mixing some value with a bijective function (XOR)
0406  * into the pool.
0407  *
0408  * The function generates a mixer value that depends on the bits set and the
0409  * location of the set bits in the random number generated by the entropy
0410  * source. Therefore, based on the generated random number, this mixer value
0411  * can have 2**64 different values. That mixer value is initialized with the
0412  * first two SHA-1 constants. After obtaining the mixer value, it is XORed into
0413  * the random number.
0414  *
0415  * The mixer value is not assumed to contain any entropy. But due to the XOR
0416  * operation, it can also not destroy any entropy present in the entropy pool.
0417  *
0418  * Input:
0419  * @entropy_collector Reference to entropy collector
0420  */
0421 static void jent_stir_pool(struct rand_data *entropy_collector)
0422 {
0423     /*
0424      * to shut up GCC on 32 bit, we have to initialize the 64 variable
0425      * with two 32 bit variables
0426      */
0427     union c {
0428         __u64 u64;
0429         __u32 u32[2];
0430     };
0431     /*
0432      * This constant is derived from the first two 32 bit initialization
0433      * vectors of SHA-1 as defined in FIPS 180-4 section 5.3.1
0434      */
0435     union c constant;
0436     /*
0437      * The start value of the mixer variable is derived from the third
0438      * and fourth 32 bit initialization vector of SHA-1 as defined in
0439      * FIPS 180-4 section 5.3.1
0440      */
0441     union c mixer;
0442     unsigned int i = 0;
0443 
0444     /*
0445      * Store the SHA-1 constants in reverse order to make up the 64 bit
0446      * value -- this applies to a little endian system, on a big endian
0447      * system, it reverses as expected. But this really does not matter
0448      * as we do not rely on the specific numbers. We just pick the SHA-1
0449      * constants as they have a good mix of bit set and unset.
0450      */
0451     constant.u32[1] = 0x67452301;
0452     constant.u32[0] = 0xefcdab89;
0453     mixer.u32[1] = 0x98badcfe;
0454     mixer.u32[0] = 0x10325476;
0455 
0456     for (i = 0; i < DATA_SIZE_BITS; i++) {
0457         /*
0458          * get the i-th bit of the input random number and only XOR
0459          * the constant into the mixer value when that bit is set
0460          */
0461         if ((entropy_collector->data >> i) & 1)
0462             mixer.u64 ^= constant.u64;
0463         mixer.u64 = jent_rol64(mixer.u64, 1);
0464     }
0465     entropy_collector->data ^= mixer.u64;
0466 }
0467 
0468 /**
0469  * Generator of one 64 bit random number
0470  * Function fills rand_data->data
0471  *
0472  * Input:
0473  * @ec Reference to entropy collector
0474  */
0475 static void jent_gen_entropy(struct rand_data *ec)
0476 {
0477     unsigned int k = 0;
0478 
0479     /* priming of the ->prev_time value */
0480     jent_measure_jitter(ec);
0481 
0482     while (1) {
0483         __u64 data = 0;
0484 
0485         if (ec->disable_unbias == 1)
0486             data = jent_measure_jitter(ec);
0487         else
0488             data = jent_unbiased_bit(ec);
0489 
0490         /* enforcement of the jent_stuck test */
0491         if (ec->stuck) {
0492             /*
0493              * We only mix in the bit considered not appropriate
0494              * without the LSFR. The reason is that if we apply
0495              * the LSFR and we do not rotate, the 2nd bit with LSFR
0496              * will cancel out the first LSFR application on the
0497              * bad bit.
0498              *
0499              * And we do not rotate as we apply the next bit to the
0500              * current bit location again.
0501              */
0502             ec->data ^= data;
0503             ec->stuck = 0;
0504             continue;
0505         }
0506 
0507         /*
0508          * Fibonacci LSFR with polynom of
0509          *  x^64 + x^61 + x^56 + x^31 + x^28 + x^23 + 1 which is
0510          *  primitive according to
0511          *   http://poincare.matf.bg.ac.rs/~ezivkovm/publications/primpol1.pdf
0512          * (the shift values are the polynom values minus one
0513          * due to counting bits from 0 to 63). As the current
0514          * position is always the LSB, the polynom only needs
0515          * to shift data in from the left without wrap.
0516          */
0517         ec->data ^= data;
0518         ec->data ^= ((ec->data >> 63) & 1);
0519         ec->data ^= ((ec->data >> 60) & 1);
0520         ec->data ^= ((ec->data >> 55) & 1);
0521         ec->data ^= ((ec->data >> 30) & 1);
0522         ec->data ^= ((ec->data >> 27) & 1);
0523         ec->data ^= ((ec->data >> 22) & 1);
0524         ec->data = jent_rol64(ec->data, 1);
0525 
0526         /*
0527          * We multiply the loop value with ->osr to obtain the
0528          * oversampling rate requested by the caller
0529          */
0530         if (++k >= (DATA_SIZE_BITS * ec->osr))
0531             break;
0532     }
0533     if (ec->stir)
0534         jent_stir_pool(ec);
0535 }
0536 
0537 /**
0538  * The continuous test required by FIPS 140-2 -- the function automatically
0539  * primes the test if needed.
0540  *
0541  * Return:
0542  * 0 if FIPS test passed
0543  * < 0 if FIPS test failed
0544  */
0545 static void jent_fips_test(struct rand_data *ec)
0546 {
0547     if (!jent_fips_enabled())
0548         return;
0549 
0550     /* prime the FIPS test */
0551     if (!ec->old_data) {
0552         ec->old_data = ec->data;
0553         jent_gen_entropy(ec);
0554     }
0555 
0556     if (ec->data == ec->old_data)
0557         jent_panic("jitterentropy: Duplicate output detected\n");
0558 
0559     ec->old_data = ec->data;
0560 }
0561 
0562 /**
0563  * Entry function: Obtain entropy for the caller.
0564  *
0565  * This function invokes the entropy gathering logic as often to generate
0566  * as many bytes as requested by the caller. The entropy gathering logic
0567  * creates 64 bit per invocation.
0568  *
0569  * This function truncates the last 64 bit entropy value output to the exact
0570  * size specified by the caller.
0571  *
0572  * Input:
0573  * @ec Reference to entropy collector
0574  * @data pointer to buffer for storing random data -- buffer must already
0575  *   exist
0576  * @len size of the buffer, specifying also the requested number of random
0577  *  in bytes
0578  *
0579  * @return 0 when request is fulfilled or an error
0580  *
0581  * The following error codes can occur:
0582  *  -1  entropy_collector is NULL
0583  */
0584 int jent_read_entropy(struct rand_data *ec, unsigned char *data,
0585               unsigned int len)
0586 {
0587     unsigned char *p = data;
0588 
0589     if (!ec)
0590         return -1;
0591 
0592     while (0 < len) {
0593         unsigned int tocopy;
0594 
0595         jent_gen_entropy(ec);
0596         jent_fips_test(ec);
0597         if ((DATA_SIZE_BITS / 8) < len)
0598             tocopy = (DATA_SIZE_BITS / 8);
0599         else
0600             tocopy = len;
0601         jent_memcpy(p, &ec->data, tocopy);
0602 
0603         len -= tocopy;
0604         p += tocopy;
0605     }
0606 
0607     return 0;
0608 }
0609 
0610 /***************************************************************************
0611  * Initialization logic
0612  ***************************************************************************/
0613 
0614 struct rand_data *jent_entropy_collector_alloc(unsigned int osr,
0615                            unsigned int flags)
0616 {
0617     struct rand_data *entropy_collector;
0618 
0619     entropy_collector = jent_zalloc(sizeof(struct rand_data));
0620     if (!entropy_collector)
0621         return NULL;
0622 
0623     if (!(flags & JENT_DISABLE_MEMORY_ACCESS)) {
0624         /* Allocate memory for adding variations based on memory
0625          * access
0626          */
0627         entropy_collector->mem = jent_zalloc(JENT_MEMORY_SIZE);
0628         if (!entropy_collector->mem) {
0629             jent_zfree(entropy_collector);
0630             return NULL;
0631         }
0632         entropy_collector->memblocksize = JENT_MEMORY_BLOCKSIZE;
0633         entropy_collector->memblocks = JENT_MEMORY_BLOCKS;
0634         entropy_collector->memaccessloops = JENT_MEMORY_ACCESSLOOPS;
0635     }
0636 
0637     /* verify and set the oversampling rate */
0638     if (0 == osr)
0639         osr = 1; /* minimum sampling rate is 1 */
0640     entropy_collector->osr = osr;
0641 
0642     entropy_collector->stir = 1;
0643     if (flags & JENT_DISABLE_STIR)
0644         entropy_collector->stir = 0;
0645     if (flags & JENT_DISABLE_UNBIAS)
0646         entropy_collector->disable_unbias = 1;
0647 
0648     /* fill the data pad with non-zero values */
0649     jent_gen_entropy(entropy_collector);
0650 
0651     return entropy_collector;
0652 }
0653 
0654 void jent_entropy_collector_free(struct rand_data *entropy_collector)
0655 {
0656     jent_zfree(entropy_collector->mem);
0657     entropy_collector->mem = NULL;
0658     jent_zfree(entropy_collector);
0659     entropy_collector = NULL;
0660 }
0661 
0662 int jent_entropy_init(void)
0663 {
0664     int i;
0665     __u64 delta_sum = 0;
0666     __u64 old_delta = 0;
0667     int time_backwards = 0;
0668     int count_var = 0;
0669     int count_mod = 0;
0670 
0671     /* We could perform statistical tests here, but the problem is
0672      * that we only have a few loop counts to do testing. These
0673      * loop counts may show some slight skew and we produce
0674      * false positives.
0675      *
0676      * Moreover, only old systems show potentially problematic
0677      * jitter entropy that could potentially be caught here. But
0678      * the RNG is intended for hardware that is available or widely
0679      * used, but not old systems that are long out of favor. Thus,
0680      * no statistical tests.
0681      */
0682 
0683     /*
0684      * We could add a check for system capabilities such as clock_getres or
0685      * check for CONFIG_X86_TSC, but it does not make much sense as the
0686      * following sanity checks verify that we have a high-resolution
0687      * timer.
0688      */
0689     /*
0690      * TESTLOOPCOUNT needs some loops to identify edge systems. 100 is
0691      * definitely too little.
0692      */
0693 #define TESTLOOPCOUNT 300
0694 #define CLEARCACHE 100
0695     for (i = 0; (TESTLOOPCOUNT + CLEARCACHE) > i; i++) {
0696         __u64 time = 0;
0697         __u64 time2 = 0;
0698         __u64 folded = 0;
0699         __u64 delta = 0;
0700         unsigned int lowdelta = 0;
0701 
0702         jent_get_nstime(&time);
0703         jent_fold_time(NULL, time, &folded, 1<<MIN_FOLD_LOOP_BIT);
0704         jent_get_nstime(&time2);
0705 
0706         /* test whether timer works */
0707         if (!time || !time2)
0708             return JENT_ENOTIME;
0709         delta = time2 - time;
0710         /*
0711          * test whether timer is fine grained enough to provide
0712          * delta even when called shortly after each other -- this
0713          * implies that we also have a high resolution timer
0714          */
0715         if (!delta)
0716             return JENT_ECOARSETIME;
0717 
0718         /*
0719          * up to here we did not modify any variable that will be
0720          * evaluated later, but we already performed some work. Thus we
0721          * already have had an impact on the caches, branch prediction,
0722          * etc. with the goal to clear it to get the worst case
0723          * measurements.
0724          */
0725         if (CLEARCACHE > i)
0726             continue;
0727 
0728         /* test whether we have an increasing timer */
0729         if (!(time2 > time))
0730             time_backwards++;
0731 
0732         /*
0733          * Avoid modulo of 64 bit integer to allow code to compile
0734          * on 32 bit architectures.
0735          */
0736         lowdelta = time2 - time;
0737         if (!(lowdelta % 100))
0738             count_mod++;
0739 
0740         /*
0741          * ensure that we have a varying delta timer which is necessary
0742          * for the calculation of entropy -- perform this check
0743          * only after the first loop is executed as we need to prime
0744          * the old_data value
0745          */
0746         if (i) {
0747             if (delta != old_delta)
0748                 count_var++;
0749             if (delta > old_delta)
0750                 delta_sum += (delta - old_delta);
0751             else
0752                 delta_sum += (old_delta - delta);
0753         }
0754         old_delta = delta;
0755     }
0756 
0757     /*
0758      * we allow up to three times the time running backwards.
0759      * CLOCK_REALTIME is affected by adjtime and NTP operations. Thus,
0760      * if such an operation just happens to interfere with our test, it
0761      * should not fail. The value of 3 should cover the NTP case being
0762      * performed during our test run.
0763      */
0764     if (3 < time_backwards)
0765         return JENT_ENOMONOTONIC;
0766     /* Error if the time variances are always identical */
0767     if (!delta_sum)
0768         return JENT_EVARVAR;
0769 
0770     /*
0771      * Variations of deltas of time must on average be larger
0772      * than 1 to ensure the entropy estimation
0773      * implied with 1 is preserved
0774      */
0775     if (delta_sum <= 1)
0776         return JENT_EMINVARVAR;
0777 
0778     /*
0779      * Ensure that we have variations in the time stamp below 10 for at
0780      * least 10% of all checks -- on some platforms, the counter
0781      * increments in multiples of 100, but not always
0782      */
0783     if ((TESTLOOPCOUNT/10 * 9) < count_mod)
0784         return JENT_ECOARSETIME;
0785 
0786     return 0;
0787 }