Add qemu 2.4.0
[kvmfornfv.git] / qemu / roms / ipxe / src / crypto / entropy.c
1 /*
2  * Copyright (C) 2012 Michael Brown <mbrown@fensystems.co.uk>.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License as
6  * published by the Free Software Foundation; either version 2 of the
7  * License, or any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17  * 02110-1301, USA.
18  */
19
20 FILE_LICENCE ( GPL2_OR_LATER );
21
22 /** @file
23  *
24  * Entropy source
25  *
26  * This algorithm is designed to comply with ANS X9.82 Part 4 (April
27  * 2011 Draft) Section 13.3.  This standard is unfortunately not
28  * freely available.
29  */
30
31 #include <stdint.h>
32 #include <assert.h>
33 #include <string.h>
34 #include <errno.h>
35 #include <ipxe/crypto.h>
36 #include <ipxe/hash_df.h>
37 #include <ipxe/entropy.h>
38
39 /* Disambiguate the various error causes */
40 #define EPIPE_REPETITION_COUNT_TEST \
41         __einfo_error ( EINFO_EPIPE_REPETITION_COUNT_TEST )
42 #define EINFO_EPIPE_REPETITION_COUNT_TEST \
43         __einfo_uniqify ( EINFO_EPIPE, 0x01, "Repetition count test failed" )
44 #define EPIPE_ADAPTIVE_PROPORTION_TEST \
45         __einfo_error ( EINFO_EPIPE_ADAPTIVE_PROPORTION_TEST )
46 #define EINFO_EPIPE_ADAPTIVE_PROPORTION_TEST \
47         __einfo_uniqify ( EINFO_EPIPE, 0x02, "Adaptive proportion test failed" )
48
49 /**
50  * Calculate cutoff value for the repetition count test
51  *
52  * @ret cutoff          Cutoff value
53  *
54  * This is the cutoff value for the Repetition Count Test defined in
55  * ANS X9.82 Part 2 (October 2011 Draft) Section 8.5.2.1.2.
56  */
57 static inline __attribute__ (( always_inline )) unsigned int
58 repetition_count_cutoff ( void ) {
59         double max_repetitions;
60         unsigned int cutoff;
61
62         /* The cutoff formula for the repetition test is:
63          *
64          *   C = ( 1 + ( -log2(W) / H_min ) )
65          *
66          * where W is set at 2^(-30) (in ANS X9.82 Part 2 (October
67          * 2011 Draft) Section 8.5.2.1.3.1).
68          */
69         max_repetitions = ( 1 + ( 30 / min_entropy_per_sample() ) );
70
71         /* Round up to a whole number of repetitions.  We don't have
72          * the ceil() function available, so do the rounding by hand.
73          */
74         cutoff = max_repetitions;
75         if ( cutoff < max_repetitions )
76                 cutoff++;
77         linker_assert ( ( cutoff >= max_repetitions ), rounding_error );
78
79         /* Floating-point operations are not allowed in iPXE since we
80          * never set up a suitable environment.  Abort the build
81          * unless the calculated number of repetitions is a
82          * compile-time constant.
83          */
84         linker_assert ( __builtin_constant_p ( cutoff ),
85                         repetition_count_cutoff_not_constant );
86
87         return cutoff;
88 }
89
90 /**
91  * Perform repetition count test
92  *
93  * @v sample            Noise sample
94  * @ret rc              Return status code
95  *
96  * This is the Repetition Count Test defined in ANS X9.82 Part 2
97  * (October 2011 Draft) Section 8.5.2.1.2.
98  */
99 static int repetition_count_test ( noise_sample_t sample ) {
100         static noise_sample_t most_recent_sample;
101         static unsigned int repetition_count = 0;
102
103         /* A = the most recently seen sample value
104          * B = the number of times that value A has been seen in a row
105          * C = the cutoff value above which the repetition test should fail
106          */
107
108         /* 1.  For each new sample processed:
109          *
110          * (Note that the test for "repetition_count > 0" ensures that
111          * the initial value of most_recent_sample is treated as being
112          * undefined.)
113          */
114         if ( ( sample == most_recent_sample ) && ( repetition_count > 0 ) ) {
115
116                 /* a) If the new sample = A, then B is incremented by one. */
117                 repetition_count++;
118
119                 /*    i.  If B >= C, then an error condition is raised
120                  *        due to a failure of the test
121                  */
122                 if ( repetition_count >= repetition_count_cutoff() )
123                         return -EPIPE_REPETITION_COUNT_TEST;
124
125         } else {
126
127                 /* b) Else:
128                  *    i.  A = new sample
129                  */
130                 most_recent_sample = sample;
131
132                 /*    ii. B = 1 */
133                 repetition_count = 1;
134         }
135
136         return 0;
137 }
138
139 /**
140  * Window size for the adaptive proportion test
141  *
142  * ANS X9.82 Part 2 (October 2011 Draft) Section 8.5.2.1.3.1.1 allows
143  * five possible window sizes: 16, 64, 256, 4096 and 65536.
144  *
145  * We expect to generate relatively few (<256) entropy samples during
146  * a typical iPXE run; the use of a large window size would mean that
147  * the test would never complete a single cycle.  We use a window size
148  * of 64, which is the smallest window size that permits values of
149  * H_min down to one bit per sample.
150  */
151 #define ADAPTIVE_PROPORTION_WINDOW_SIZE 64
152
153 /**
154  * Combine adaptive proportion test window size and min-entropy
155  *
156  * @v n                 N (window size)
157  * @v h                 H (min-entropy)
158  * @ret n_h             (N,H) combined value
159  */
160 #define APC_N_H( n, h ) ( ( (n) << 8 ) | (h) )
161
162 /**
163  * Define a row of the adaptive proportion cutoff table
164  *
165  * @v h                 H (min-entropy)
166  * @v c16               Cutoff for N=16
167  * @v c64               Cutoff for N=64
168  * @v c256              Cutoff for N=256
169  * @v c4096             Cutoff for N=4096
170  * @v c65536            Cutoff for N=65536
171  */
172 #define APC_TABLE_ROW( h, c16, c64, c256, c4096, c65536)           \
173         case APC_N_H ( 16, h ) :        return c16;                \
174         case APC_N_H ( 64, h ) :        return c64;                \
175         case APC_N_H ( 256, h ) :       return c256;               \
176         case APC_N_H ( 4096, h ) :      return c4096;              \
177         case APC_N_H ( 65536, h ) :     return c65536;
178
179 /** Value used to represent "N/A" in adaptive proportion cutoff table */
180 #define APC_NA 0
181
182 /**
183  * Look up value in adaptive proportion test cutoff table
184  *
185  * @v n                 N (window size)
186  * @v h                 H (min-entropy)
187  * @ret cutoff          Cutoff
188  *
189  * This is the table of cutoff values defined in ANS X9.82 Part 2
190  * (October 2011 Draft) Section 8.5.2.1.3.1.2.
191  */
192 static inline __attribute__ (( always_inline )) unsigned int
193 adaptive_proportion_cutoff_lookup ( unsigned int n, unsigned int h ) {
194         switch ( APC_N_H ( n, h ) ) {
195                 APC_TABLE_ROW (  1, APC_NA,     51,    168,   2240,  33537 );
196                 APC_TABLE_ROW (  2, APC_NA,     35,    100,   1193,  17053 );
197                 APC_TABLE_ROW (  3,     10,     24,     61,    643,   8705 );
198                 APC_TABLE_ROW (  4,      8,     16,     38,    354,   4473 );
199                 APC_TABLE_ROW (  5,      6,     12,     25,    200,   2321 );
200                 APC_TABLE_ROW (  6,      5,      9,     17,    117,   1220 );
201                 APC_TABLE_ROW (  7,      4,      7,     15,     71,    653 );
202                 APC_TABLE_ROW (  8,      4,      5,      9,     45,    358 );
203                 APC_TABLE_ROW (  9,      3,      4,      7,     30,    202 );
204                 APC_TABLE_ROW ( 10,      3,      4,      5,     21,    118 );
205                 APC_TABLE_ROW ( 11,      2,      3,      4,     15,     71 );
206                 APC_TABLE_ROW ( 12,      2,      3,      4,     11,     45 );
207                 APC_TABLE_ROW ( 13,      2,      2,      3,      9,     30 );
208                 APC_TABLE_ROW ( 14,      2,      2,      3,      7,     21 );
209                 APC_TABLE_ROW ( 15,      1,      2,      2,      6,     15 );
210                 APC_TABLE_ROW ( 16,      1,      2,      2,      5,     11 );
211                 APC_TABLE_ROW ( 17,      1,      1,      2,      4,      9 );
212                 APC_TABLE_ROW ( 18,      1,      1,      2,      4,      7 );
213                 APC_TABLE_ROW ( 19,      1,      1,      1,      3,      6 );
214                 APC_TABLE_ROW ( 20,      1,      1,      1,      3,      5 );
215         default:
216                 return APC_NA;
217         }
218 }
219
220 /**
221  * Calculate cutoff value for the adaptive proportion test
222  *
223  * @ret cutoff          Cutoff value
224  *
225  * This is the cutoff value for the Adaptive Proportion Test defined
226  * in ANS X9.82 Part 2 (October 2011 Draft) Section 8.5.2.1.3.1.2.
227  */
228 static inline __attribute__ (( always_inline )) unsigned int
229 adaptive_proportion_cutoff ( void ) {
230         unsigned int h;
231         unsigned int n;
232         unsigned int cutoff;
233
234         /* Look up cutoff value in cutoff table */
235         n = ADAPTIVE_PROPORTION_WINDOW_SIZE;
236         h = min_entropy_per_sample();
237         cutoff = adaptive_proportion_cutoff_lookup ( n, h );
238
239         /* Fail unless cutoff value is a build-time constant */
240         linker_assert ( __builtin_constant_p ( cutoff ),
241                         adaptive_proportion_cutoff_not_constant );
242
243         /* Fail if cutoff value is N/A */
244         linker_assert ( ( cutoff != APC_NA ),
245                         adaptive_proportion_cutoff_not_applicable );
246
247         return cutoff;
248 }
249
250 /**
251  * Perform adaptive proportion test
252  *
253  * @v sample            Noise sample
254  * @ret rc              Return status code
255  *
256  * This is the Adaptive Proportion Test for the Most Common Value
257  * defined in ANS X9.82 Part 2 (October 2011 Draft) Section 8.5.2.1.3.
258  */
259 static int adaptive_proportion_test ( noise_sample_t sample ) {
260         static noise_sample_t current_counted_sample;
261         static unsigned int sample_count = ADAPTIVE_PROPORTION_WINDOW_SIZE;
262         static unsigned int repetition_count;
263
264         /* A = the sample value currently being counted
265          * B = the number of samples examined in this run of the test so far
266          * N = the total number of samples that must be observed in
267          *     one run of the test, also known as the "window size" of
268          *     the test
269          * B = the current number of times that S (sic) has been seen
270          *     in the W (sic) samples examined so far
271          * C = the cutoff value above which the repetition test should fail
272          * W = the probability of a false positive: 2^-30
273          */
274
275         /* 1.  The entropy source draws the current sample from the
276          *     noise source.
277          *
278          * (Nothing to do; we already have the current sample.)
279          */
280
281         /* 2.  If S = N, then a new run of the test begins: */
282         if ( sample_count == ADAPTIVE_PROPORTION_WINDOW_SIZE ) {
283
284                 /* a.  A = the current sample */
285                 current_counted_sample = sample;
286
287                 /* b.  S = 0 */
288                 sample_count = 0;
289
290                 /* c. B = 0 */
291                 repetition_count = 0;
292
293         } else {
294
295                 /* Else: (the test is already running)
296                  * a.  S = S + 1
297                  */
298                 sample_count++;
299
300                 /* b.  If A = the current sample, then: */
301                 if ( sample == current_counted_sample ) {
302
303                         /* i.   B = B + 1 */
304                         repetition_count++;
305
306                         /* ii.  If S (sic) > C then raise an error
307                          *      condition, because the test has
308                          *      detected a failure
309                          */
310                         if ( repetition_count > adaptive_proportion_cutoff() )
311                                 return -EPIPE_ADAPTIVE_PROPORTION_TEST;
312
313                 }
314         }
315
316         return 0;
317 }
318
319 /**
320  * Get entropy sample
321  *
322  * @ret entropy         Entropy sample
323  * @ret rc              Return status code
324  *
325  * This is the GetEntropy function defined in ANS X9.82 Part 2
326  * (October 2011 Draft) Section 6.5.1.
327  */
328 static int get_entropy ( entropy_sample_t *entropy ) {
329         static int rc = 0;
330         noise_sample_t noise;
331
332         /* Any failure is permanent */
333         if ( rc != 0 )
334                 return rc;
335
336         /* Get noise sample */
337         if ( ( rc = get_noise ( &noise ) ) != 0 )
338                 return rc;
339
340         /* Perform Repetition Count Test and Adaptive Proportion Test
341          * as mandated by ANS X9.82 Part 2 (October 2011 Draft)
342          * Section 8.5.2.1.1.
343          */
344         if ( ( rc = repetition_count_test ( noise ) ) != 0 )
345                 return rc;
346         if ( ( rc = adaptive_proportion_test ( noise ) ) != 0 )
347                 return rc;
348
349         /* We do not use any optional conditioning component */
350         *entropy = noise;
351
352         return 0;
353 }
354
355 /**
356  * Calculate number of samples required for startup tests
357  *
358  * @ret num_samples     Number of samples required
359  *
360  * ANS X9.82 Part 2 (October 2011 Draft) Section 8.5.2.1.5 requires
361  * that at least one full cycle of the continuous tests must be
362  * performed at start-up.
363  */
364 static inline __attribute__ (( always_inline )) unsigned int
365 startup_test_count ( void ) {
366         unsigned int num_samples;
367
368         /* At least max(N,C) samples shall be generated by the noise
369          * source for start-up testing.
370          */
371         num_samples = repetition_count_cutoff();
372         if ( num_samples < adaptive_proportion_cutoff() )
373                 num_samples = adaptive_proportion_cutoff();
374         linker_assert ( __builtin_constant_p ( num_samples ),
375                         startup_test_count_not_constant );
376
377         return num_samples;
378 }
379
380 /**
381  * Create next nonce value
382  *
383  * @ret nonce           Nonce
384  *
385  * This is the MakeNextNonce function defined in ANS X9.82 Part 4
386  * (April 2011 Draft) Section 13.3.4.2.
387  */
388 static uint32_t make_next_nonce ( void ) {
389         static uint32_t nonce;
390
391         /* The simplest implementation of a nonce uses a large counter */
392         nonce++;
393
394         return nonce;
395 }
396
397 /**
398  * Obtain entropy input temporary buffer
399  *
400  * @v num_samples       Number of entropy samples
401  * @v tmp               Temporary buffer
402  * @v tmp_len           Length of temporary buffer
403  * @ret rc              Return status code
404  *
405  * This is (part of) the implementation of the Get_entropy_input
406  * function (using an entropy source as the source of entropy input
407  * and condensing each entropy source output after each GetEntropy
408  * call) as defined in ANS X9.82 Part 4 (April 2011 Draft) Section
409  * 13.3.4.2.
410  *
411  * To minimise code size, the number of samples required is calculated
412  * at compilation time.
413  */
414 int get_entropy_input_tmp ( unsigned int num_samples, uint8_t *tmp,
415                             size_t tmp_len ) {
416         static unsigned int startup_tested = 0;
417         struct {
418                 uint32_t nonce;
419                 entropy_sample_t sample;
420         } __attribute__ (( packed )) data;;
421         uint8_t df_buf[tmp_len];
422         unsigned int i;
423         int rc;
424
425         /* Enable entropy gathering */
426         if ( ( rc = entropy_enable() ) != 0 )
427                 return rc;
428
429         /* Perform mandatory startup tests, if not yet performed */
430         for ( ; startup_tested < startup_test_count() ; startup_tested++ ) {
431                 if ( ( rc = get_entropy ( &data.sample ) ) != 0 )
432                         goto err_get_entropy;
433         }
434
435         /* 3.  entropy_total = 0
436          *
437          * (Nothing to do; the number of entropy samples required has
438          * already been precalculated.)
439          */
440
441         /* 4.  tmp = a fixed n-bit value, such as 0^n */
442         memset ( tmp, 0, tmp_len );
443
444         /* 5.  While ( entropy_total < min_entropy ) */
445         while ( num_samples-- ) {
446                 /* 5.1.  ( status, entropy_bitstring, assessed_entropy )
447                  *       = GetEntropy()
448                  * 5.2.  If status indicates an error, return ( status, Null )
449                  */
450                 if ( ( rc = get_entropy ( &data.sample ) ) != 0 )
451                         goto err_get_entropy;
452
453                 /* 5.3.  nonce = MakeNextNonce() */
454                 data.nonce = make_next_nonce();
455
456                 /* 5.4.  tmp = tmp XOR
457                  *             df ( ( nonce || entropy_bitstring ), n )
458                  */
459                 hash_df ( &entropy_hash_df_algorithm, &data, sizeof ( data ),
460                           df_buf, sizeof ( df_buf ) );
461                 for ( i = 0 ; i < tmp_len ; i++ )
462                         tmp[i] ^= df_buf[i];
463
464                 /* 5.5.  entropy_total = entropy_total + assessed_entropy
465                  *
466                  * (Nothing to do; the number of entropy samples
467                  * required has already been precalculated.)
468                  */
469         }
470
471         /* Disable entropy gathering */
472         entropy_disable();
473
474         return 0;
475
476  err_get_entropy:
477         entropy_disable();
478         return rc;
479 }