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