xref: /freebsd/crypto/openssh/moduli.c (revision d056fa046c6a91b90cd98165face0e42a33a5173)
1 /* $OpenBSD: moduli.c,v 1.12 2005/07/17 07:17:55 djm Exp $ */
2 /*
3  * Copyright 1994 Phil Karn <karn@qualcomm.com>
4  * Copyright 1996-1998, 2003 William Allen Simpson <wsimpson@greendragon.com>
5  * Copyright 2000 Niels Provos <provos@citi.umich.edu>
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  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 /*
30  * Two-step process to generate safe primes for DHGEX
31  *
32  *  Sieve candidates for "safe" primes,
33  *  suitable for use as Diffie-Hellman moduli;
34  *  that is, where q = (p-1)/2 is also prime.
35  *
36  * First step: generate candidate primes (memory intensive)
37  * Second step: test primes' safety (processor intensive)
38  */
39 
40 #include "includes.h"
41 #include "xmalloc.h"
42 #include "log.h"
43 
44 #include <openssl/bn.h>
45 
46 /*
47  * File output defines
48  */
49 
50 /* need line long enough for largest moduli plus headers */
51 #define QLINESIZE		(100+8192)
52 
53 /* Type: decimal.
54  * Specifies the internal structure of the prime modulus.
55  */
56 #define QTYPE_UNKNOWN		(0)
57 #define QTYPE_UNSTRUCTURED	(1)
58 #define QTYPE_SAFE		(2)
59 #define QTYPE_SCHNORR		(3)
60 #define QTYPE_SOPHIE_GERMAIN	(4)
61 #define QTYPE_STRONG		(5)
62 
63 /* Tests: decimal (bit field).
64  * Specifies the methods used in checking for primality.
65  * Usually, more than one test is used.
66  */
67 #define QTEST_UNTESTED		(0x00)
68 #define QTEST_COMPOSITE		(0x01)
69 #define QTEST_SIEVE		(0x02)
70 #define QTEST_MILLER_RABIN	(0x04)
71 #define QTEST_JACOBI		(0x08)
72 #define QTEST_ELLIPTIC		(0x10)
73 
74 /*
75  * Size: decimal.
76  * Specifies the number of the most significant bit (0 to M).
77  * WARNING: internally, usually 1 to N.
78  */
79 #define QSIZE_MINIMUM		(511)
80 
81 /*
82  * Prime sieving defines
83  */
84 
85 /* Constant: assuming 8 bit bytes and 32 bit words */
86 #define SHIFT_BIT	(3)
87 #define SHIFT_BYTE	(2)
88 #define SHIFT_WORD	(SHIFT_BIT+SHIFT_BYTE)
89 #define SHIFT_MEGABYTE	(20)
90 #define SHIFT_MEGAWORD	(SHIFT_MEGABYTE-SHIFT_BYTE)
91 
92 /*
93  * Using virtual memory can cause thrashing.  This should be the largest
94  * number that is supported without a large amount of disk activity --
95  * that would increase the run time from hours to days or weeks!
96  */
97 #define LARGE_MINIMUM	(8UL)	/* megabytes */
98 
99 /*
100  * Do not increase this number beyond the unsigned integer bit size.
101  * Due to a multiple of 4, it must be LESS than 128 (yielding 2**30 bits).
102  */
103 #define LARGE_MAXIMUM	(127UL)	/* megabytes */
104 
105 /*
106  * Constant: when used with 32-bit integers, the largest sieve prime
107  * has to be less than 2**32.
108  */
109 #define SMALL_MAXIMUM	(0xffffffffUL)
110 
111 /* Constant: can sieve all primes less than 2**32, as 65537**2 > 2**32-1. */
112 #define TINY_NUMBER	(1UL<<16)
113 
114 /* Ensure enough bit space for testing 2*q. */
115 #define TEST_MAXIMUM	(1UL<<16)
116 #define TEST_MINIMUM	(QSIZE_MINIMUM + 1)
117 /* real TEST_MINIMUM	(1UL << (SHIFT_WORD - TEST_POWER)) */
118 #define TEST_POWER	(3)	/* 2**n, n < SHIFT_WORD */
119 
120 /* bit operations on 32-bit words */
121 #define BIT_CLEAR(a,n)	((a)[(n)>>SHIFT_WORD] &= ~(1L << ((n) & 31)))
122 #define BIT_SET(a,n)	((a)[(n)>>SHIFT_WORD] |= (1L << ((n) & 31)))
123 #define BIT_TEST(a,n)	((a)[(n)>>SHIFT_WORD] & (1L << ((n) & 31)))
124 
125 /*
126  * Prime testing defines
127  */
128 
129 /* Minimum number of primality tests to perform */
130 #define TRIAL_MINIMUM	(4)
131 
132 /*
133  * Sieving data (XXX - move to struct)
134  */
135 
136 /* sieve 2**16 */
137 static u_int32_t *TinySieve, tinybits;
138 
139 /* sieve 2**30 in 2**16 parts */
140 static u_int32_t *SmallSieve, smallbits, smallbase;
141 
142 /* sieve relative to the initial value */
143 static u_int32_t *LargeSieve, largewords, largetries, largenumbers;
144 static u_int32_t largebits, largememory;	/* megabytes */
145 static BIGNUM *largebase;
146 
147 int gen_candidates(FILE *, u_int32_t, u_int32_t, BIGNUM *);
148 int prime_test(FILE *, FILE *, u_int32_t, u_int32_t);
149 
150 /*
151  * print moduli out in consistent form,
152  */
153 static int
154 qfileout(FILE * ofile, u_int32_t otype, u_int32_t otests, u_int32_t otries,
155     u_int32_t osize, u_int32_t ogenerator, BIGNUM * omodulus)
156 {
157 	struct tm *gtm;
158 	time_t time_now;
159 	int res;
160 
161 	time(&time_now);
162 	gtm = gmtime(&time_now);
163 
164 	res = fprintf(ofile, "%04d%02d%02d%02d%02d%02d %u %u %u %u %x ",
165 	    gtm->tm_year + 1900, gtm->tm_mon + 1, gtm->tm_mday,
166 	    gtm->tm_hour, gtm->tm_min, gtm->tm_sec,
167 	    otype, otests, otries, osize, ogenerator);
168 
169 	if (res < 0)
170 		return (-1);
171 
172 	if (BN_print_fp(ofile, omodulus) < 1)
173 		return (-1);
174 
175 	res = fprintf(ofile, "\n");
176 	fflush(ofile);
177 
178 	return (res > 0 ? 0 : -1);
179 }
180 
181 
182 /*
183  ** Sieve p's and q's with small factors
184  */
185 static void
186 sieve_large(u_int32_t s)
187 {
188 	u_int32_t r, u;
189 
190 	debug3("sieve_large %u", s);
191 	largetries++;
192 	/* r = largebase mod s */
193 	r = BN_mod_word(largebase, s);
194 	if (r == 0)
195 		u = 0; /* s divides into largebase exactly */
196 	else
197 		u = s - r; /* largebase+u is first entry divisible by s */
198 
199 	if (u < largebits * 2) {
200 		/*
201 		 * The sieve omits p's and q's divisible by 2, so ensure that
202 		 * largebase+u is odd. Then, step through the sieve in
203 		 * increments of 2*s
204 		 */
205 		if (u & 0x1)
206 			u += s; /* Make largebase+u odd, and u even */
207 
208 		/* Mark all multiples of 2*s */
209 		for (u /= 2; u < largebits; u += s)
210 			BIT_SET(LargeSieve, u);
211 	}
212 
213 	/* r = p mod s */
214 	r = (2 * r + 1) % s;
215 	if (r == 0)
216 		u = 0; /* s divides p exactly */
217 	else
218 		u = s - r; /* p+u is first entry divisible by s */
219 
220 	if (u < largebits * 4) {
221 		/*
222 		 * The sieve omits p's divisible by 4, so ensure that
223 		 * largebase+u is not. Then, step through the sieve in
224 		 * increments of 4*s
225 		 */
226 		while (u & 0x3) {
227 			if (SMALL_MAXIMUM - u < s)
228 				return;
229 			u += s;
230 		}
231 
232 		/* Mark all multiples of 4*s */
233 		for (u /= 4; u < largebits; u += s)
234 			BIT_SET(LargeSieve, u);
235 	}
236 }
237 
238 /*
239  * list candidates for Sophie-Germain primes (where q = (p-1)/2)
240  * to standard output.
241  * The list is checked against small known primes (less than 2**30).
242  */
243 int
244 gen_candidates(FILE *out, u_int32_t memory, u_int32_t power, BIGNUM *start)
245 {
246 	BIGNUM *q;
247 	u_int32_t j, r, s, t;
248 	u_int32_t smallwords = TINY_NUMBER >> 6;
249 	u_int32_t tinywords = TINY_NUMBER >> 6;
250 	time_t time_start, time_stop;
251 	u_int32_t i;
252 	int ret = 0;
253 
254 	largememory = memory;
255 
256 	if (memory != 0 &&
257 	    (memory < LARGE_MINIMUM || memory > LARGE_MAXIMUM)) {
258 		error("Invalid memory amount (min %ld, max %ld)",
259 		    LARGE_MINIMUM, LARGE_MAXIMUM);
260 		return (-1);
261 	}
262 
263 	/*
264 	 * Set power to the length in bits of the prime to be generated.
265 	 * This is changed to 1 less than the desired safe prime moduli p.
266 	 */
267 	if (power > TEST_MAXIMUM) {
268 		error("Too many bits: %u > %lu", power, TEST_MAXIMUM);
269 		return (-1);
270 	} else if (power < TEST_MINIMUM) {
271 		error("Too few bits: %u < %u", power, TEST_MINIMUM);
272 		return (-1);
273 	}
274 	power--; /* decrement before squaring */
275 
276 	/*
277 	 * The density of ordinary primes is on the order of 1/bits, so the
278 	 * density of safe primes should be about (1/bits)**2. Set test range
279 	 * to something well above bits**2 to be reasonably sure (but not
280 	 * guaranteed) of catching at least one safe prime.
281 	 */
282 	largewords = ((power * power) >> (SHIFT_WORD - TEST_POWER));
283 
284 	/*
285 	 * Need idea of how much memory is available. We don't have to use all
286 	 * of it.
287 	 */
288 	if (largememory > LARGE_MAXIMUM) {
289 		logit("Limited memory: %u MB; limit %lu MB",
290 		    largememory, LARGE_MAXIMUM);
291 		largememory = LARGE_MAXIMUM;
292 	}
293 
294 	if (largewords <= (largememory << SHIFT_MEGAWORD)) {
295 		logit("Increased memory: %u MB; need %u bytes",
296 		    largememory, (largewords << SHIFT_BYTE));
297 		largewords = (largememory << SHIFT_MEGAWORD);
298 	} else if (largememory > 0) {
299 		logit("Decreased memory: %u MB; want %u bytes",
300 		    largememory, (largewords << SHIFT_BYTE));
301 		largewords = (largememory << SHIFT_MEGAWORD);
302 	}
303 
304 	TinySieve = calloc(tinywords, sizeof(u_int32_t));
305 	if (TinySieve == NULL) {
306 		error("Insufficient memory for tiny sieve: need %u bytes",
307 		    tinywords << SHIFT_BYTE);
308 		exit(1);
309 	}
310 	tinybits = tinywords << SHIFT_WORD;
311 
312 	SmallSieve = calloc(smallwords, sizeof(u_int32_t));
313 	if (SmallSieve == NULL) {
314 		error("Insufficient memory for small sieve: need %u bytes",
315 		    smallwords << SHIFT_BYTE);
316 		xfree(TinySieve);
317 		exit(1);
318 	}
319 	smallbits = smallwords << SHIFT_WORD;
320 
321 	/*
322 	 * dynamically determine available memory
323 	 */
324 	while ((LargeSieve = calloc(largewords, sizeof(u_int32_t))) == NULL)
325 		largewords -= (1L << (SHIFT_MEGAWORD - 2)); /* 1/4 MB chunks */
326 
327 	largebits = largewords << SHIFT_WORD;
328 	largenumbers = largebits * 2;	/* even numbers excluded */
329 
330 	/* validation check: count the number of primes tried */
331 	largetries = 0;
332 	q = BN_new();
333 
334 	/*
335 	 * Generate random starting point for subprime search, or use
336 	 * specified parameter.
337 	 */
338 	largebase = BN_new();
339 	if (start == NULL)
340 		BN_rand(largebase, power, 1, 1);
341 	else
342 		BN_copy(largebase, start);
343 
344 	/* ensure odd */
345 	BN_set_bit(largebase, 0);
346 
347 	time(&time_start);
348 
349 	logit("%.24s Sieve next %u plus %u-bit", ctime(&time_start),
350 	    largenumbers, power);
351 	debug2("start point: 0x%s", BN_bn2hex(largebase));
352 
353 	/*
354 	 * TinySieve
355 	 */
356 	for (i = 0; i < tinybits; i++) {
357 		if (BIT_TEST(TinySieve, i))
358 			continue; /* 2*i+3 is composite */
359 
360 		/* The next tiny prime */
361 		t = 2 * i + 3;
362 
363 		/* Mark all multiples of t */
364 		for (j = i + t; j < tinybits; j += t)
365 			BIT_SET(TinySieve, j);
366 
367 		sieve_large(t);
368 	}
369 
370 	/*
371 	 * Start the small block search at the next possible prime. To avoid
372 	 * fencepost errors, the last pass is skipped.
373 	 */
374 	for (smallbase = TINY_NUMBER + 3;
375 	    smallbase < (SMALL_MAXIMUM - TINY_NUMBER);
376 	    smallbase += TINY_NUMBER) {
377 		for (i = 0; i < tinybits; i++) {
378 			if (BIT_TEST(TinySieve, i))
379 				continue; /* 2*i+3 is composite */
380 
381 			/* The next tiny prime */
382 			t = 2 * i + 3;
383 			r = smallbase % t;
384 
385 			if (r == 0) {
386 				s = 0; /* t divides into smallbase exactly */
387 			} else {
388 				/* smallbase+s is first entry divisible by t */
389 				s = t - r;
390 			}
391 
392 			/*
393 			 * The sieve omits even numbers, so ensure that
394 			 * smallbase+s is odd. Then, step through the sieve
395 			 * in increments of 2*t
396 			 */
397 			if (s & 1)
398 				s += t; /* Make smallbase+s odd, and s even */
399 
400 			/* Mark all multiples of 2*t */
401 			for (s /= 2; s < smallbits; s += t)
402 				BIT_SET(SmallSieve, s);
403 		}
404 
405 		/*
406 		 * SmallSieve
407 		 */
408 		for (i = 0; i < smallbits; i++) {
409 			if (BIT_TEST(SmallSieve, i))
410 				continue; /* 2*i+smallbase is composite */
411 
412 			/* The next small prime */
413 			sieve_large((2 * i) + smallbase);
414 		}
415 
416 		memset(SmallSieve, 0, smallwords << SHIFT_BYTE);
417 	}
418 
419 	time(&time_stop);
420 
421 	logit("%.24s Sieved with %u small primes in %ld seconds",
422 	    ctime(&time_stop), largetries, (long) (time_stop - time_start));
423 
424 	for (j = r = 0; j < largebits; j++) {
425 		if (BIT_TEST(LargeSieve, j))
426 			continue; /* Definitely composite, skip */
427 
428 		debug2("test q = largebase+%u", 2 * j);
429 		BN_set_word(q, 2 * j);
430 		BN_add(q, q, largebase);
431 		if (qfileout(out, QTYPE_SOPHIE_GERMAIN, QTEST_SIEVE,
432 		    largetries, (power - 1) /* MSB */, (0), q) == -1) {
433 			ret = -1;
434 			break;
435 		}
436 
437 		r++; /* count q */
438 	}
439 
440 	time(&time_stop);
441 
442 	xfree(LargeSieve);
443 	xfree(SmallSieve);
444 	xfree(TinySieve);
445 
446 	logit("%.24s Found %u candidates", ctime(&time_stop), r);
447 
448 	return (ret);
449 }
450 
451 /*
452  * perform a Miller-Rabin primality test
453  * on the list of candidates
454  * (checking both q and p)
455  * The result is a list of so-call "safe" primes
456  */
457 int
458 prime_test(FILE *in, FILE *out, u_int32_t trials, u_int32_t generator_wanted)
459 {
460 	BIGNUM *q, *p, *a;
461 	BN_CTX *ctx;
462 	char *cp, *lp;
463 	u_int32_t count_in = 0, count_out = 0, count_possible = 0;
464 	u_int32_t generator_known, in_tests, in_tries, in_type, in_size;
465 	time_t time_start, time_stop;
466 	int res;
467 
468 	if (trials < TRIAL_MINIMUM) {
469 		error("Minimum primality trials is %d", TRIAL_MINIMUM);
470 		return (-1);
471 	}
472 
473 	time(&time_start);
474 
475 	p = BN_new();
476 	q = BN_new();
477 	ctx = BN_CTX_new();
478 
479 	debug2("%.24s Final %u Miller-Rabin trials (%x generator)",
480 	    ctime(&time_start), trials, generator_wanted);
481 
482 	res = 0;
483 	lp = xmalloc(QLINESIZE + 1);
484 	while (fgets(lp, QLINESIZE, in) != NULL) {
485 		int ll = strlen(lp);
486 
487 		count_in++;
488 		if (ll < 14 || *lp == '!' || *lp == '#') {
489 			debug2("%10u: comment or short line", count_in);
490 			continue;
491 		}
492 
493 		/* XXX - fragile parser */
494 		/* time */
495 		cp = &lp[14];	/* (skip) */
496 
497 		/* type */
498 		in_type = strtoul(cp, &cp, 10);
499 
500 		/* tests */
501 		in_tests = strtoul(cp, &cp, 10);
502 
503 		if (in_tests & QTEST_COMPOSITE) {
504 			debug2("%10u: known composite", count_in);
505 			continue;
506 		}
507 
508 		/* tries */
509 		in_tries = strtoul(cp, &cp, 10);
510 
511 		/* size (most significant bit) */
512 		in_size = strtoul(cp, &cp, 10);
513 
514 		/* generator (hex) */
515 		generator_known = strtoul(cp, &cp, 16);
516 
517 		/* Skip white space */
518 		cp += strspn(cp, " ");
519 
520 		/* modulus (hex) */
521 		switch (in_type) {
522 		case QTYPE_SOPHIE_GERMAIN:
523 			debug2("%10u: (%u) Sophie-Germain", count_in, in_type);
524 			a = q;
525 			BN_hex2bn(&a, cp);
526 			/* p = 2*q + 1 */
527 			BN_lshift(p, q, 1);
528 			BN_add_word(p, 1);
529 			in_size += 1;
530 			generator_known = 0;
531 			break;
532 		case QTYPE_UNSTRUCTURED:
533 		case QTYPE_SAFE:
534 		case QTYPE_SCHNORR:
535 		case QTYPE_STRONG:
536 		case QTYPE_UNKNOWN:
537 			debug2("%10u: (%u)", count_in, in_type);
538 			a = p;
539 			BN_hex2bn(&a, cp);
540 			/* q = (p-1) / 2 */
541 			BN_rshift(q, p, 1);
542 			break;
543 		default:
544 			debug2("Unknown prime type");
545 			break;
546 		}
547 
548 		/*
549 		 * due to earlier inconsistencies in interpretation, check
550 		 * the proposed bit size.
551 		 */
552 		if ((u_int32_t)BN_num_bits(p) != (in_size + 1)) {
553 			debug2("%10u: bit size %u mismatch", count_in, in_size);
554 			continue;
555 		}
556 		if (in_size < QSIZE_MINIMUM) {
557 			debug2("%10u: bit size %u too short", count_in, in_size);
558 			continue;
559 		}
560 
561 		if (in_tests & QTEST_MILLER_RABIN)
562 			in_tries += trials;
563 		else
564 			in_tries = trials;
565 
566 		/*
567 		 * guess unknown generator
568 		 */
569 		if (generator_known == 0) {
570 			if (BN_mod_word(p, 24) == 11)
571 				generator_known = 2;
572 			else if (BN_mod_word(p, 12) == 5)
573 				generator_known = 3;
574 			else {
575 				u_int32_t r = BN_mod_word(p, 10);
576 
577 				if (r == 3 || r == 7)
578 					generator_known = 5;
579 			}
580 		}
581 		/*
582 		 * skip tests when desired generator doesn't match
583 		 */
584 		if (generator_wanted > 0 &&
585 		    generator_wanted != generator_known) {
586 			debug2("%10u: generator %d != %d",
587 			    count_in, generator_known, generator_wanted);
588 			continue;
589 		}
590 
591 		/*
592 		 * Primes with no known generator are useless for DH, so
593 		 * skip those.
594 		 */
595 		if (generator_known == 0) {
596 			debug2("%10u: no known generator", count_in);
597 			continue;
598 		}
599 
600 		count_possible++;
601 
602 		/*
603 		 * The (1/4)^N performance bound on Miller-Rabin is
604 		 * extremely pessimistic, so don't spend a lot of time
605 		 * really verifying that q is prime until after we know
606 		 * that p is also prime. A single pass will weed out the
607 		 * vast majority of composite q's.
608 		 */
609 		if (BN_is_prime(q, 1, NULL, ctx, NULL) <= 0) {
610 			debug("%10u: q failed first possible prime test",
611 			    count_in);
612 			continue;
613 		}
614 
615 		/*
616 		 * q is possibly prime, so go ahead and really make sure
617 		 * that p is prime. If it is, then we can go back and do
618 		 * the same for q. If p is composite, chances are that
619 		 * will show up on the first Rabin-Miller iteration so it
620 		 * doesn't hurt to specify a high iteration count.
621 		 */
622 		if (!BN_is_prime(p, trials, NULL, ctx, NULL)) {
623 			debug("%10u: p is not prime", count_in);
624 			continue;
625 		}
626 		debug("%10u: p is almost certainly prime", count_in);
627 
628 		/* recheck q more rigorously */
629 		if (!BN_is_prime(q, trials - 1, NULL, ctx, NULL)) {
630 			debug("%10u: q is not prime", count_in);
631 			continue;
632 		}
633 		debug("%10u: q is almost certainly prime", count_in);
634 
635 		if (qfileout(out, QTYPE_SAFE, (in_tests | QTEST_MILLER_RABIN),
636 		    in_tries, in_size, generator_known, p)) {
637 			res = -1;
638 			break;
639 		}
640 
641 		count_out++;
642 	}
643 
644 	time(&time_stop);
645 	xfree(lp);
646 	BN_free(p);
647 	BN_free(q);
648 	BN_CTX_free(ctx);
649 
650 	logit("%.24s Found %u safe primes of %u candidates in %ld seconds",
651 	    ctime(&time_stop), count_out, count_possible,
652 	    (long) (time_stop - time_start));
653 
654 	return (res);
655 }
656