xref: /freebsd/sys/dev/rndtest/rndtest.c (revision f81cdf24ba5436367377f7c8e8f51f6df2a75ca7)
1 /*	$OpenBSD$	*/
2 
3 /*-
4  * SPDX-License-Identifier: BSD-4-Clause
5  *
6  * Copyright (c) 2002 Jason L. Wright (jason@thought.net)
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. All advertising materials mentioning features or use of this software
18  *    must display the following acknowledgement:
19  *	This product includes software developed by Jason L. Wright
20  * 4. The name of the author may not be used to endorse or promote products
21  *    derived from this software without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
24  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
25  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
27  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
28  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
29  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
31  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
32  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33  * POSSIBILITY OF SUCH DAMAGE.
34  */
35 
36 #include <sys/param.h>
37 #include <sys/systm.h>
38 #include <sys/bus.h>
39 #include <sys/callout.h>
40 #include <sys/kernel.h>
41 #include <sys/malloc.h>
42 #include <sys/module.h>
43 #include <sys/random.h>
44 #include <sys/sysctl.h>
45 #include <machine/stdarg.h>
46 
47 #include <dev/rndtest/rndtest.h>
48 
49 static	void rndtest_test(struct rndtest_state *);
50 static	void rndtest_timeout(void *);
51 
52 /* The tests themselves */
53 static	int rndtest_monobit(struct rndtest_state *);
54 static	int rndtest_runs(struct rndtest_state *);
55 static	int rndtest_longruns(struct rndtest_state *);
56 static	int rndtest_chi_4(struct rndtest_state *);
57 
58 static	int rndtest_runs_check(struct rndtest_state *, int, int *);
59 static	void rndtest_runs_record(struct rndtest_state *, int, int *);
60 
61 static const struct rndtest_testfunc {
62 	int (*test)(struct rndtest_state *);
63 } rndtest_funcs[] = {
64 	{ rndtest_monobit },
65 	{ rndtest_runs },
66 	{ rndtest_chi_4 },
67 	{ rndtest_longruns },
68 };
69 
70 #define	RNDTEST_NTESTS	nitems(rndtest_funcs)
71 
72 static SYSCTL_NODE(_kern, OID_AUTO, rndtest, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
73     "RNG test parameters");
74 static	int rndtest_retest = 120;		/* interval in seconds */
75 SYSCTL_INT(_kern_rndtest, OID_AUTO, retest, CTLFLAG_RW, &rndtest_retest,
76 	    0, "retest interval (seconds)");
77 static struct rndtest_stats rndstats;
78 SYSCTL_STRUCT(_kern_rndtest, OID_AUTO, stats, CTLFLAG_RD, &rndstats,
79 	    rndtest_stats, "RNG test statistics");
80 static	int rndtest_verbose = 1;		/* report only failures */
81 SYSCTL_INT(_kern_rndtest, OID_AUTO, verbose, CTLFLAG_RW, &rndtest_verbose,
82 	    0, "display results on console");
83 
84 struct rndtest_state *
85 rndtest_attach(device_t dev)
86 {
87 	struct rndtest_state *rsp;
88 
89 	rsp = malloc(sizeof (*rsp), M_DEVBUF, M_NOWAIT);
90 	if (rsp != NULL) {
91 		rsp->rs_begin = rsp->rs_buf;
92 		rsp->rs_end = rsp->rs_buf + sizeof(rsp->rs_buf);
93 		rsp->rs_current = rsp->rs_begin;
94 		rsp->rs_discard = 1;
95 		rsp->rs_collect = 1;
96 		rsp->rs_parent = dev;
97 		callout_init(&rsp->rs_to, 1);
98 	} else
99 		device_printf(dev, "rndtest_init: no memory for state block\n");
100 	return (rsp);
101 }
102 
103 void
104 rndtest_detach(struct rndtest_state *rsp)
105 {
106 	callout_stop(&rsp->rs_to);
107 	free(rsp, M_DEVBUF);
108 }
109 
110 void
111 rndtest_harvest(struct rndtest_state *rsp, void *buf, u_int len)
112 {
113 	size_t i;
114 	/*
115 	 * If enabled, collect data and run tests when we have enough.
116 	 */
117 	if (rsp->rs_collect) {
118 		for (i = 0; i < len; i++) {
119 			*rsp->rs_current = ((u_char *) buf)[i];
120 			if (++rsp->rs_current == rsp->rs_end) {
121 				rndtest_test(rsp);
122 				rsp->rs_current = rsp->rs_begin;
123 				/*
124 				 * If tests passed, turn off collection and
125 				 * schedule another test. Otherwise we keep
126 				 * testing until the data looks ok.
127 				 */
128 				if (!rsp->rs_discard && rndtest_retest != 0) {
129 					rsp->rs_collect = 0;
130 					callout_reset(&rsp->rs_to,
131 						hz * rndtest_retest,
132 						rndtest_timeout, rsp);
133 					break;
134 				}
135 			}
136 		}
137 	}
138 	/*
139 	 * Only stir entropy that passes muster into the pool.
140 	 */
141 	if (rsp->rs_discard)
142 		rndstats.rst_discard += len;
143 	else
144 	/* MarkM: FIX!! Check that this does not swamp the harvester! */
145 	random_harvest_queue(buf, len, RANDOM_PURE_RNDTEST);
146 }
147 
148 static void
149 rndtest_test(struct rndtest_state *rsp)
150 {
151 	int i, rv = 0;
152 
153 	rndstats.rst_tests++;
154 	for (i = 0; i < RNDTEST_NTESTS; i++)
155 		rv |= (*rndtest_funcs[i].test)(rsp);
156 	rsp->rs_discard = (rv != 0);
157 }
158 
159 static void
160 rndtest_report(struct rndtest_state *rsp, int failure, const char *fmt, ...)
161 {
162 	char buf[80];
163 	va_list ap;
164 
165 	if (rndtest_verbose == 0)
166 		return;
167 	if (!failure && rndtest_verbose == 1)	/* don't report successes */
168 		return;
169 	va_start(ap, fmt);
170 	vsnprintf(buf, sizeof (buf), fmt, ap);
171 	va_end(ap);
172 	device_printf(rsp->rs_parent, "rndtest: %s\n", buf);
173 }
174 
175 #define	RNDTEST_MONOBIT_MINONES	9725
176 #define	RNDTEST_MONOBIT_MAXONES	10275
177 
178 static int
179 rndtest_monobit(struct rndtest_state *rsp)
180 {
181 	int i, ones = 0, j;
182 	u_int8_t r;
183 
184 	for (i = 0; i < RNDTEST_NBYTES; i++) {
185 		r = rsp->rs_buf[i];
186 		for (j = 0; j < 8; j++, r <<= 1)
187 			if (r & 0x80)
188 				ones++;
189 	}
190 	if (ones > RNDTEST_MONOBIT_MINONES &&
191 	    ones < RNDTEST_MONOBIT_MAXONES) {
192 		if (rndtest_verbose > 1)
193 			rndtest_report(rsp, 0, "monobit pass (%d < %d < %d)",
194 			    RNDTEST_MONOBIT_MINONES, ones,
195 			    RNDTEST_MONOBIT_MAXONES);
196 		return (0);
197 	} else {
198 		if (rndtest_verbose)
199 			rndtest_report(rsp, 1,
200 			    "monobit failed (%d ones)", ones);
201 		rndstats.rst_monobit++;
202 		return (-1);
203 	}
204 }
205 
206 #define	RNDTEST_RUNS_NINTERVAL	6
207 
208 static const struct rndtest_runs_tabs {
209 	u_int16_t min, max;
210 } rndtest_runs_tab[] = {
211 	{ 2343, 2657 },
212 	{ 1135, 1365 },
213 	{ 542, 708 },
214 	{ 251, 373 },
215 	{ 111, 201 },
216 	{ 111, 201 },
217 };
218 
219 static int
220 rndtest_runs(struct rndtest_state *rsp)
221 {
222 	int i, j, ones, zeros, rv = 0;
223 	int onei[RNDTEST_RUNS_NINTERVAL], zeroi[RNDTEST_RUNS_NINTERVAL];
224 	u_int8_t c;
225 
226 	bzero(onei, sizeof(onei));
227 	bzero(zeroi, sizeof(zeroi));
228 	ones = zeros = 0;
229 	for (i = 0; i < RNDTEST_NBYTES; i++) {
230 		c = rsp->rs_buf[i];
231 		for (j = 0; j < 8; j++, c <<= 1) {
232 			if (c & 0x80) {
233 				ones++;
234 				rndtest_runs_record(rsp, zeros, zeroi);
235 				zeros = 0;
236 			} else {
237 				zeros++;
238 				rndtest_runs_record(rsp, ones, onei);
239 				ones = 0;
240 			}
241 		}
242 	}
243 	rndtest_runs_record(rsp, ones, onei);
244 	rndtest_runs_record(rsp, zeros, zeroi);
245 
246 	rv |= rndtest_runs_check(rsp, 0, zeroi);
247 	rv |= rndtest_runs_check(rsp, 1, onei);
248 
249 	if (rv)
250 		rndstats.rst_runs++;
251 
252 	return (rv);
253 }
254 
255 static void
256 rndtest_runs_record(struct rndtest_state *rsp, int len, int *intrv)
257 {
258 	if (len == 0)
259 		return;
260 	if (len > RNDTEST_RUNS_NINTERVAL)
261 		len = RNDTEST_RUNS_NINTERVAL;
262 	len -= 1;
263 	intrv[len]++;
264 }
265 
266 static int
267 rndtest_runs_check(struct rndtest_state *rsp, int val, int *src)
268 {
269 	int i, rv = 0;
270 
271 	for (i = 0; i < RNDTEST_RUNS_NINTERVAL; i++) {
272 		if (src[i] < rndtest_runs_tab[i].min ||
273 		    src[i] > rndtest_runs_tab[i].max) {
274 			rndtest_report(rsp, 1,
275 			    "%s interval %d failed (%d, %d-%d)",
276 			    val ? "ones" : "zeros",
277 			    i + 1, src[i], rndtest_runs_tab[i].min,
278 			    rndtest_runs_tab[i].max);
279 			rv = -1;
280 		} else {
281 			rndtest_report(rsp, 0,
282 			    "runs pass %s interval %d (%d < %d < %d)",
283 			    val ? "ones" : "zeros",
284 			    i + 1, rndtest_runs_tab[i].min, src[i],
285 			    rndtest_runs_tab[i].max);
286 		}
287 	}
288 	return (rv);
289 }
290 
291 static int
292 rndtest_longruns(struct rndtest_state *rsp)
293 {
294 	int i, j, ones = 0, zeros = 0, maxones = 0, maxzeros = 0;
295 	u_int8_t c;
296 
297 	for (i = 0; i < RNDTEST_NBYTES; i++) {
298 		c = rsp->rs_buf[i];
299 		for (j = 0; j < 8; j++, c <<= 1) {
300 			if (c & 0x80) {
301 				zeros = 0;
302 				ones++;
303 				if (ones > maxones)
304 					maxones = ones;
305 			} else {
306 				ones = 0;
307 				zeros++;
308 				if (zeros > maxzeros)
309 					maxzeros = zeros;
310 			}
311 		}
312 	}
313 
314 	if (maxones < 26 && maxzeros < 26) {
315 		rndtest_report(rsp, 0, "longruns pass (%d ones, %d zeros)",
316 			maxones, maxzeros);
317 		return (0);
318 	} else {
319 		rndtest_report(rsp, 1, "longruns fail (%d ones, %d zeros)",
320 			maxones, maxzeros);
321 		rndstats.rst_longruns++;
322 		return (-1);
323 	}
324 }
325 
326 /*
327  * chi^2 test over 4 bits: (this is called the poker test in FIPS 140-2,
328  * but it is really the chi^2 test over 4 bits (the poker test as described
329  * by Knuth vol 2 is something different, and I take him as authoritative
330  * on nomenclature over NIST).
331  */
332 #define	RNDTEST_CHI4_K	16
333 #define	RNDTEST_CHI4_K_MASK	(RNDTEST_CHI4_K - 1)
334 
335 /*
336  * The unnormalized values are used so that we don't have to worry about
337  * fractional precision.  The "real" value is found by:
338  *	(V - 1562500) * (16 / 5000) = Vn   (where V is the unnormalized value)
339  */
340 #define	RNDTEST_CHI4_VMIN	1563181		/* 2.1792 */
341 #define	RNDTEST_CHI4_VMAX	1576929		/* 46.1728 */
342 
343 static int
344 rndtest_chi_4(struct rndtest_state *rsp)
345 {
346 	unsigned int freq[RNDTEST_CHI4_K], i, sum;
347 
348 	for (i = 0; i < RNDTEST_CHI4_K; i++)
349 		freq[i] = 0;
350 
351 	/* Get number of occurrences of each 4 bit pattern */
352 	for (i = 0; i < RNDTEST_NBYTES; i++) {
353 		freq[(rsp->rs_buf[i] >> 4) & RNDTEST_CHI4_K_MASK]++;
354 		freq[(rsp->rs_buf[i] >> 0) & RNDTEST_CHI4_K_MASK]++;
355 	}
356 
357 	for (i = 0, sum = 0; i < RNDTEST_CHI4_K; i++)
358 		sum += freq[i] * freq[i];
359 
360 	if (sum >= 1563181 && sum <= 1576929) {
361 		rndtest_report(rsp, 0, "chi^2(4): pass (sum %u)", sum);
362 		return (0);
363 	} else {
364 		rndtest_report(rsp, 1, "chi^2(4): failed (sum %u)", sum);
365 		rndstats.rst_chi++;
366 		return (-1);
367 	}
368 }
369 
370 static void
371 rndtest_timeout(void *xrsp)
372 {
373 	struct rndtest_state *rsp = xrsp;
374 
375 	rsp->rs_collect = 1;
376 }
377 
378 static int
379 rndtest_modevent(module_t mod, int type, void *unused)
380 {
381 	switch (type) {
382 	case MOD_LOAD:
383 		return 0;
384 	case MOD_UNLOAD:
385 		return 0;
386 	}
387 	return EINVAL;
388 }
389 
390 static moduledata_t rndtest_mod = {
391 	"rndtest",
392 	rndtest_modevent,
393 	0
394 };
395 DECLARE_MODULE(rndtest, rndtest_mod, SI_SUB_DRIVERS, SI_ORDER_ANY);
396 MODULE_VERSION(rndtest, 1);
397