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