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