Debian Codegraph @

tests/isc/random_test.c

raw
1 /*
2 * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
3 *
4 * SPDX-License-Identifier: MPL-2.0
5 *
6 * This Source Code Form is subject to the terms of the Mozilla Public
7 * License, v. 2.0. If a copy of the MPL was not distributed with this
8 * file, you can obtain one at https://mozilla.org/MPL/2.0/.
9 *
10 * See the COPYRIGHT file distributed with this work for additional
11 * information regarding copyright ownership.
12 */
13
14 /*
15 * IMPORTANT NOTE:
16 * These tests work by generating a large number of pseudo-random numbers
17 * and then statistically analyzing them to determine whether they seem
18 * random. The test is expected to fail on occasion by random happenstance.
19 */
20
21 #include <inttypes.h>
22 #include <math.h>
23 #include <sched.h> /* IWYU pragma: keep */
24 #include <setjmp.h>
25 #include <stdarg.h>
26 #include <stddef.h>
27 #include <stdlib.h>
28 #include <string.h>
29
30 #define UNIT_TESTING
31 #include <cmocka.h>
32
33 #include <isc/commandline.h>
34 #include <isc/mem.h>
35 #include <isc/nonce.h>
36 #include <isc/random.h>
37 #include <isc/result.h>
38 #include <isc/util.h>
39
40 #include <tests/isc.h>
41
42 #define REPS 25000
43
44 typedef double(pvalue_func_t)(uint16_t *values, size_t length);
45
46 /* igamc(), igam(), etc. were adapted (and cleaned up) from the Cephes
47 * math library:
48 *
49 * Cephes Math Library Release 2.8: June, 2000
50 * Copyright 1985, 1987, 2000 by Stephen L. Moshier
51 *
52 * The Cephes math library was released into the public domain as part
53 * of netlib.
54 */
55
56 static double MACHEP = 1.11022302462515654042E-16;
57 static double MAXLOG = 7.09782712893383996843E2;
58 static double big = 4.503599627370496e15;
59 static double biginv = 2.22044604925031308085e-16;
60
61 static double
62 igamc(double a, double x);
63 static double
64 igam(double a, double x);
65
66 typedef enum {
67 ISC_RANDOM8,
68 ISC_RANDOM16,
69 ISC_RANDOM32,
70 ISC_RANDOM_BYTES,
71 ISC_RANDOM_UNIFORM,
72 ISC_NONCE_BYTES
73 } isc_random_func;
74
75 static double
76 igamc(double a, double x) {
77 double ans, ax, c, r, t, y, z;
78 double pkm1, pkm2, qkm1, qkm2;
79
80 if ((x <= 0) || (a <= 0)) {
81 return 1.0;
82 }
83
84 if ((x < 1.0) || (x < a)) {
85 return 1.0 - igam(a, x);
86 }
87
88 ax = a * log(x) - x - lgamma(a);
89 if (ax < -MAXLOG) {
90 print_error("# igamc: UNDERFLOW, ax=%f\n", ax);
91 return 0.0;
92 }
93 ax = exp(ax);
94
95 /* continued fraction */
96 y = 1.0 - a;
97 z = x + y + 1.0;
98 c = 0.0;
99 pkm2 = 1.0;
100 qkm2 = x;
101 pkm1 = x + 1.0;
102 qkm1 = z * x;
103 ans = pkm1 / qkm1;
104
105 do {
106 double yc, pk, qk;
107 c += 1.0;
108 y += 1.0;
109 z += 2.0;
110 yc = y * c;
111 pk = pkm1 * z - pkm2 * yc;
112 qk = qkm1 * z - qkm2 * yc;
113 if (qk != 0) {
114 r = pk / qk;
115 t = fabs((ans - r) / r);
116 ans = r;
117 } else {
118 t = 1.0;
119 }
120
121 pkm2 = pkm1;
122 pkm1 = pk;
123 qkm2 = qkm1;
124 qkm1 = qk;
125
126 if (fabs(pk) > big) {
127 pkm2 *= biginv;
128 pkm1 *= biginv;
129 qkm2 *= biginv;
130 qkm1 *= biginv;
131 }
132 } while (t > MACHEP);
133
134 return ans * ax;
135 }
136
137 static double
138 igam(double a, double x) {
139 double ans, ax, c, r;
140
141 if ((x <= 0) || (a <= 0)) {
142 return 0.0;
143 }
144
145 if ((x > 1.0) && (x > a)) {
146 return 1.0 - igamc(a, x);
147 }
148
149 /* Compute x**a * exp(-x) / md_gamma(a) */
150 ax = a * log(x) - x - lgamma(a);
151 if (ax < -MAXLOG) {
152 print_error("# igam: UNDERFLOW, ax=%f\n", ax);
153 return 0.0;
154 }
155 ax = exp(ax);
156
157 /* power series */
158 r = a;
159 c = 1.0;
160 ans = 1.0;
161
162 do {
163 r += 1.0;
164 c *= x / r;
165 ans += c;
166 } while (c / ans > MACHEP);
167
168 return ans * ax / a;
169 }
170
171 static int8_t scounts_table[65536];
172 static uint8_t bitcounts_table[65536];
173
174 static int8_t
175 scount_calculate(uint16_t n) {
176 int i;
177 int8_t sc;
178
179 sc = 0;
180 for (i = 0; i < 16; i++) {
181 uint16_t lsb;
182
183 lsb = n & 1;
184 if (lsb != 0) {
185 sc += 1;
186 } else {
187 sc -= 1;
188 }
189
190 n >>= 1;
191 }
192
193 return sc;
194 }
195
196 static uint8_t
197 bitcount_calculate(uint16_t n) {
198 int i;
199 uint8_t bc;
200
201 bc = 0;
202 for (i = 0; i < 16; i++) {
203 uint16_t lsb;
204
205 lsb = n & 1;
206 if (lsb != 0) {
207 bc += 1;
208 }
209
210 n >>= 1;
211 }
212
213 return bc;
214 }
215
216 static void
217 tables_init(void) {
218 uint32_t i;
219
220 for (i = 0; i < 65536; i++) {
221 scounts_table[i] = scount_calculate(i);
222 bitcounts_table[i] = bitcount_calculate(i);
223 }
224 }
225
226 /*
227 * The following code for computing Marsaglia's rank is based on the
228 * implementation in cdbinrnk.c from the diehard tests by George
229 * Marsaglia.
230 *
231 * This function destroys (modifies) the data passed in bits.
232 */
233 static uint32_t
234 matrix_binaryrank(uint32_t *bits, size_t rows, size_t cols) {
235 unsigned int rt = 0;
236 uint32_t rank = 0;
237 uint32_t tmp;
238
239 for (size_t k = 0; k < rows; k++) {
240 size_t i = k;
241
242 while (rt >= cols || ((bits[i] >> rt) & 1) == 0) {
243 i++;
244
245 if (i < rows) {
246 continue;
247 } else {
248 rt++;
249 if (rt < cols) {
250 i = k;
251 continue;
252 }
253 }
254
255 return rank;
256 }
257
258 rank++;
259 if (i != k) {
260 tmp = bits[i];
261 bits[i] = bits[k];
262 bits[k] = tmp;
263 }
264
265 for (size_t j = i + 1; j < rows; j++) {
266 if (((bits[j] >> rt) & 1) == 0) {
267 continue;
268 } else {
269 bits[j] ^= bits[k];
270 }
271 }
272
273 rt++;
274 }
275
276 return rank;
277 }
278
279 static void
280 random_test(pvalue_func_t *func, isc_random_func test_func) {
281 uint32_t m;
282 uint32_t j;
283 uint32_t histogram[11] = { 0 };
284 uint32_t passed;
285 double proportion;
286 double p_hat;
287 double lower_confidence, higher_confidence;
288 double chi_square;
289 double p_value_t;
290 double alpha;
291
292 tables_init();
293
294 m = 1000;
295 passed = 0;
296
297 for (j = 0; j < m; j++) {
298 uint32_t i;
299 uint32_t values[REPS];
300 uint16_t *uniform_values;
301 double p_value;
302
303 switch (test_func) {
304 case ISC_RANDOM8:
305 for (i = 0; i < (sizeof(values) / sizeof(*values)); i++)
306 {
307 values[i] = isc_random8();
308 }
309 break;
310 case ISC_RANDOM16:
311 for (i = 0; i < (sizeof(values) / sizeof(*values)); i++)
312 {
313 values[i] = isc_random16();
314 }
315 break;
316 case ISC_RANDOM32:
317 for (i = 0; i < (sizeof(values) / sizeof(*values)); i++)
318 {
319 values[i] = isc_random32();
320 }
321 break;
322 case ISC_RANDOM_BYTES:
323 isc_random_buf(values, sizeof(values));
324 break;
325 case ISC_RANDOM_UNIFORM:
326 uniform_values = (uint16_t *)values;
327 for (i = 0;
328 i < (sizeof(values) / (sizeof(*uniform_values)));
329 i++)
330 {
331 uniform_values[i] =
332 isc_random_uniform(UINT16_MAX);
333 }
334 break;
335 case ISC_NONCE_BYTES:
336 isc_nonce_buf(values, sizeof(values));
337 break;
338 }
339
340 p_value = (*func)((uint16_t *)values, REPS * 2);
341 if (p_value >= 0.01) {
342 passed++;
343 }
344
345 assert_in_range(p_value, 0.0, 1.0);
346
347 i = (int)floor(p_value * 10);
348 histogram[i]++;
349 }
350
351 /*
352 * Check proportion of sequences passing a test (see section
353 * 4.2.1 in NIST SP 800-22).
354 */
355 alpha = 0.01; /* the significance level */
356 proportion = (double)passed / (double)m;
357 p_hat = 1.0 - alpha;
358 lower_confidence = p_hat - (3.0 * sqrt((p_hat * (1.0 - p_hat)) / m));
359 higher_confidence = p_hat + (3.0 * sqrt((p_hat * (1.0 - p_hat)) / m));
360
361 assert_in_range(proportion, lower_confidence, higher_confidence);
362
363 /*
364 * Check uniform distribution of p-values (see section 4.2.2 in
365 * NIST SP 800-22).
366 */
367
368 /* Fold histogram[10] (p_value = 1.0) into histogram[9] for
369 * interval [0.9, 1.0]
370 */
371 histogram[9] += histogram[10];
372 histogram[10] = 0;
373
374 /* Pre-requisite that at least 55 sequences are processed. */
375 assert_true(m >= 55);
376
377 chi_square = 0.0;
378 for (j = 0; j < 10; j++) {
379 double numer;
380 double denom;
381
382 numer = (histogram[j] - (m / 10.0)) *
383 (histogram[j] - (m / 10.0));
384 denom = m / 10.0;
385 chi_square += numer / denom;
386 }
387
388 p_value_t = igamc(9 / 2.0, chi_square / 2.0);
389
390 assert_true(p_value_t >= 0.0001);
391 }
392
393 /*
394 * This is a frequency (monobits) test taken from the NIST SP 800-22
395 * RANDOM test suite.
396 */
397 static double
398 monobit(uint16_t *values, size_t length) {
399 size_t i;
400 int32_t scount;
401 uint32_t numbits;
402 double s_obs;
403 double p_value;
404
405 UNUSED(mctx);
406
407 numbits = length * sizeof(*values) * 8;
408 scount = 0;
409
410 for (i = 0; i < length; i++) {
411 scount += scounts_table[values[i]];
412 }
413
414 /* Preconditions (section 2.1.7 in NIST SP 800-22) */
415 assert_true(numbits >= 100);
416
417 s_obs = abs(scount) / sqrt(numbits);
418 p_value = erfc(s_obs / sqrt(2.0));
419
420 return p_value;
421 }
422
423 /*
424 * This is the runs test taken from the NIST SP 800-22 RNG test suite.
425 */
426 static double
427 runs(uint16_t *values, size_t length) {
428 size_t i;
429 uint32_t bcount;
430 uint32_t numbits;
431 double pi;
432 double tau;
433 uint32_t j;
434 uint32_t b;
435 uint8_t bit_prev;
436 uint32_t v_obs;
437 double numer;
438 double denom;
439 double p_value;
440
441 UNUSED(mctx);
442
443 numbits = length * sizeof(*values) * 8;
444 bcount = 0;
445
446 for (i = 0; i < length; i++) {
447 bcount += bitcounts_table[values[i]];
448 }
449
450 pi = (double)bcount / (double)numbits;
451 tau = 2.0 / sqrt(numbits);
452
453 /* Preconditions (section 2.3.7 in NIST SP 800-22) */
454 assert_true(numbits >= 100);
455
456 /*
457 * Pre-condition implied from the monobit test. This can fail
458 * for some sequences, and the p-value is taken as 0 in these
459 * cases.
460 */
461 if (fabs(pi - 0.5) >= tau) {
462 return 0.0;
463 }
464
465 /* Compute v_obs */
466 j = 0;
467 b = 14;
468 bit_prev = (values[j] & (1U << 15)) == 0 ? 0 : 1;
469
470 v_obs = 0;
471
472 for (i = 1; i < numbits; i++) {
473 uint8_t bit_this = (values[j] & (1U << b)) == 0 ? 0 : 1;
474 if (b == 0) {
475 b = 15;
476 j++;
477 } else {
478 b--;
479 }
480
481 v_obs += bit_this ^ bit_prev;
482
483 bit_prev = bit_this;
484 }
485
486 v_obs += 1;
487
488 numer = fabs(v_obs - (2.0 * numbits * pi * (1.0 - pi)));
489 denom = 2.0 * sqrt(2.0 * numbits) * pi * (1.0 - pi);
490
491 p_value = erfc(numer / denom);
492
493 return p_value;
494 }
495
496 /*
497 * This is the block frequency test taken from the NIST SP 800-22 RNG
498 * test suite.
499 */
500 static double
501 blockfrequency(uint16_t *values, size_t length) {
502 uint32_t i;
503 uint32_t numbits;
504 uint32_t mbits;
505 uint32_t mwords;
506 uint32_t numblocks;
507 double *pi;
508 double chi_square;
509 double p_value;
510
511 numbits = length * sizeof(*values) * 8;
512 mbits = 32000;
513 mwords = mbits / 16;
514 numblocks = numbits / mbits;
515
516 /* Preconditions (section 2.2.7 in NIST SP 800-22) */
517 assert_true(numbits >= 100);
518 assert_true(mbits >= 20);
519 assert_true((double)mbits > (0.01 * numbits));
520 assert_true(numblocks < 100);
521 assert_true(numbits >= (mbits * numblocks));
522
523 pi = isc_mem_cget(mctx, numblocks, sizeof(double));
524 assert_non_null(pi);
525
526 for (i = 0; i < numblocks; i++) {
527 uint32_t j;
528 pi[i] = 0.0;
529 for (j = 0; j < mwords; j++) {
530 uint32_t idx;
531
532 idx = i * mwords + j;
533 pi[i] += bitcounts_table[values[idx]];
534 }
535 pi[i] /= mbits;
536 }
537
538 /* Compute chi_square */
539 chi_square = 0.0;
540 for (i = 0; i < numblocks; i++) {
541 chi_square += (pi[i] - 0.5) * (pi[i] - 0.5);
542 }
543
544 chi_square *= 4 * mbits;
545
546 isc_mem_cput(mctx, pi, numblocks, sizeof(double));
547
548 p_value = igamc(numblocks * 0.5, chi_square * 0.5);
549
550 return p_value;
551 }
552
553 /*
554 * This is the binary matrix rank test taken from the NIST SP 800-22 RNG
555 * test suite.
556 */
557 static double
558 binarymatrixrank(uint16_t *values, size_t length) {
559 uint32_t i;
560 size_t matrix_m;
561 size_t matrix_q;
562 uint32_t num_matrices;
563 size_t numbits;
564 uint32_t fm_0;
565 uint32_t fm_1;
566 uint32_t fm_rest;
567 double term1;
568 double term2;
569 double term3;
570 double chi_square;
571 double p_value;
572
573 UNUSED(mctx);
574
575 matrix_m = 32;
576 matrix_q = 32;
577 num_matrices = length / ((matrix_m * matrix_q) / 16);
578 numbits = num_matrices * matrix_m * matrix_q;
579
580 /* Preconditions (section 2.5.7 in NIST SP 800-22) */
581 assert_int_equal(matrix_m, 32);
582 assert_int_equal(matrix_q, 32);
583 assert_true(numbits >= (38 * matrix_m * matrix_q));
584
585 fm_0 = 0;
586 fm_1 = 0;
587 fm_rest = 0;
588 for (i = 0; i < num_matrices; i++) {
589 /*
590 * Each uint32_t supplies 32 bits, so a 32x32 bit matrix
591 * takes up uint32_t array of size 32.
592 */
593 uint32_t bits[32];
594 int j;
595 uint32_t rank;
596
597 for (j = 0; j < 32; j++) {
598 size_t idx;
599 uint32_t r1;
600 uint32_t r2;
601
602 idx = i * ((matrix_m * matrix_q) / 16);
603 idx += j * 2;
604
605 r1 = values[idx];
606 r2 = values[idx + 1];
607 bits[j] = (r1 << 16) | r2;
608 }
609
610 rank = matrix_binaryrank(bits, matrix_m, matrix_q);
611
612 if (rank == matrix_m) {
613 fm_0++;
614 } else if (rank == (matrix_m - 1)) {
615 fm_1++;
616 } else {
617 fm_rest++;
618 }
619 }
620
621 /* Compute chi_square */
622 term1 = ((fm_0 - (0.2888 * num_matrices)) *
623 (fm_0 - (0.2888 * num_matrices))) /
624 (0.2888 * num_matrices);
625 term2 = ((fm_1 - (0.5776 * num_matrices)) *
626 (fm_1 - (0.5776 * num_matrices))) /
627 (0.5776 * num_matrices);
628 term3 = ((fm_rest - (0.1336 * num_matrices)) *
629 (fm_rest - (0.1336 * num_matrices))) /
630 (0.1336 * num_matrices);
631
632 chi_square = term1 + term2 + term3;
633
634 p_value = exp(-chi_square * 0.5);
635
636 return p_value;
637 }
638
639 /***
640 *** Tests for isc_random32() function
641 ***/
642
643 /* Ensure the RNG has been automatically seeded. */
644 ISC_RUN_TEST_IMPL(isc_random32_initialized) {
645 UNUSED(state);
646
647 assert_int_not_equal(isc_random32(), 0);
648 }
649
650 /* Monobit test for the RANDOM */
651 ISC_RUN_TEST_IMPL(isc_random32_monobit) {
652 UNUSED(state);
653
654 random_test(monobit, ISC_RANDOM32);
655 }
656
657 /* Runs test for the RANDOM */
658 ISC_RUN_TEST_IMPL(isc_random32_runs) {
659 UNUSED(state);
660
661 random_test(runs, ISC_RANDOM32);
662 }
663
664 /* Block frequency test for the RANDOM */
665 ISC_RUN_TEST_IMPL(isc_random32_blockfrequency) {
666 UNUSED(state);
667
668 random_test(blockfrequency, ISC_RANDOM32);
669 }
670
671 /* Binary matrix rank test for the RANDOM */
672 ISC_RUN_TEST_IMPL(isc_random32_binarymatrixrank) {
673 UNUSED(state);
674
675 random_test(binarymatrixrank, ISC_RANDOM32);
676 }
677
678 /***
679 *** Tests for isc_random_bytes() function
680 ***/
681
682 /* Monobit test for the RANDOM */
683 ISC_RUN_TEST_IMPL(isc_random_bytes_monobit) {
684 UNUSED(state);
685
686 random_test(monobit, ISC_RANDOM_BYTES);
687 }
688
689 /* Runs test for the RANDOM */
690 ISC_RUN_TEST_IMPL(isc_random_bytes_runs) {
691 UNUSED(state);
692
693 random_test(runs, ISC_RANDOM_BYTES);
694 }
695
696 /* Block frequency test for the RANDOM */
697 ISC_RUN_TEST_IMPL(isc_random_bytes_blockfrequency) {
698 UNUSED(state);
699
700 random_test(blockfrequency, ISC_RANDOM_BYTES);
701 }
702
703 /* Binary matrix rank test for the RANDOM */
704 ISC_RUN_TEST_IMPL(isc_random_bytes_binarymatrixrank) {
705 UNUSED(state);
706
707 random_test(binarymatrixrank, ISC_RANDOM_BYTES);
708 }
709
710 /***
711 *** Tests for isc_random_uniform() function:
712 ***/
713
714 /* Monobit test for the RANDOM */
715 ISC_RUN_TEST_IMPL(isc_random_uniform_monobit) {
716 UNUSED(state);
717
718 random_test(monobit, ISC_RANDOM_UNIFORM);
719 }
720
721 /* Runs test for the RANDOM */
722 ISC_RUN_TEST_IMPL(isc_random_uniform_runs) {
723 UNUSED(state);
724
725 random_test(runs, ISC_RANDOM_UNIFORM);
726 }
727
728 /* Block frequency test for the RANDOM */
729 ISC_RUN_TEST_IMPL(isc_random_uniform_blockfrequency) {
730 UNUSED(state);
731
732 random_test(blockfrequency, ISC_RANDOM_UNIFORM);
733 }
734
735 /* Binary matrix rank test for the RANDOM */
736 ISC_RUN_TEST_IMPL(isc_random_uniform_binarymatrixrank) {
737 UNUSED(state);
738
739 random_test(binarymatrixrank, ISC_RANDOM_UNIFORM);
740 }
741
742 /* Tests for isc_nonce_bytes() function */
743
744 /* Monobit test for the RANDOM */
745 ISC_RUN_TEST_IMPL(isc_nonce_bytes_monobit) {
746 UNUSED(state);
747
748 random_test(monobit, ISC_NONCE_BYTES);
749 }
750
751 /* Runs test for the RANDOM */
752 ISC_RUN_TEST_IMPL(isc_nonce_bytes_runs) {
753 UNUSED(state);
754
755 random_test(runs, ISC_NONCE_BYTES);
756 }
757
758 /* Block frequency test for the RANDOM */
759 ISC_RUN_TEST_IMPL(isc_nonce_bytes_blockfrequency) {
760 UNUSED(state);
761
762 random_test(blockfrequency, ISC_NONCE_BYTES);
763 }
764
765 /* Binary matrix rank test for the RANDOM */
766 ISC_RUN_TEST_IMPL(isc_nonce_bytes_binarymatrixrank) {
767 UNUSED(state);
768
769 random_test(binarymatrixrank, ISC_NONCE_BYTES);
770 }
771
772 ISC_TEST_LIST_START
773
774 ISC_TEST_ENTRY(isc_random32_initialized)
775 ISC_TEST_ENTRY(isc_random32_monobit)
776 ISC_TEST_ENTRY(isc_random32_runs)
777 ISC_TEST_ENTRY(isc_random32_blockfrequency)
778 ISC_TEST_ENTRY(isc_random32_binarymatrixrank)
779 ISC_TEST_ENTRY(isc_random_bytes_monobit)
780 ISC_TEST_ENTRY(isc_random_bytes_runs)
781 ISC_TEST_ENTRY(isc_random_bytes_blockfrequency)
782 ISC_TEST_ENTRY(isc_random_bytes_binarymatrixrank)
783 ISC_TEST_ENTRY(isc_random_uniform_monobit)
784 ISC_TEST_ENTRY(isc_random_uniform_runs)
785 ISC_TEST_ENTRY(isc_random_uniform_blockfrequency)
786 ISC_TEST_ENTRY(isc_random_uniform_binarymatrixrank)
787 ISC_TEST_ENTRY(isc_nonce_bytes_monobit)
788 ISC_TEST_ENTRY(isc_nonce_bytes_runs)
789 ISC_TEST_ENTRY(isc_nonce_bytes_blockfrequency)
790 ISC_TEST_ENTRY(isc_nonce_bytes_binarymatrixrank)
791
792 ISC_TEST_LIST_END
793
794 ISC_TEST_MAIN