]> andersk Git - openssh.git/blame - moduli.c
- dtucker@cvs.openbsd.org 2003/12/09 13:52:55
[openssh.git] / moduli.c
CommitLineData
eb7a33b8 1/* $OpenBSD: moduli.c,v 1.4 2003/12/09 13:52:55 dtucker Exp $ */
5ae3dc68 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 "moduli.h"
42#include "xmalloc.h"
43#include "log.h"
44
45#include <openssl/bn.h>
46
5ae3dc68 47/*
48 * File output defines
49 */
50
51/* need line long enough for largest moduli plus headers */
52#define QLINESIZE (100+8192)
53
54/* Type: decimal.
55 * Specifies the internal structure of the prime modulus.
56 */
57#define QTYPE_UNKNOWN (0)
58#define QTYPE_UNSTRUCTURED (1)
59#define QTYPE_SAFE (2)
60#define QTYPE_SCHNOOR (3)
61#define QTYPE_SOPHIE_GERMAINE (4)
62#define QTYPE_STRONG (5)
63
64/* Tests: decimal (bit field).
65 * Specifies the methods used in checking for primality.
66 * Usually, more than one test is used.
67 */
68#define QTEST_UNTESTED (0x00)
69#define QTEST_COMPOSITE (0x01)
70#define QTEST_SIEVE (0x02)
71#define QTEST_MILLER_RABIN (0x04)
72#define QTEST_JACOBI (0x08)
73#define QTEST_ELLIPTIC (0x10)
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 * Constant: when used with 32-bit integers, the largest sieve prime
94 * has to be less than 2**32.
95 */
96#define SMALL_MAXIMUM (0xffffffffUL)
97
98/* Constant: can sieve all primes less than 2**32, as 65537**2 > 2**32-1. */
99#define TINY_NUMBER (1UL<<16)
100
101/* Ensure enough bit space for testing 2*q. */
102#define TEST_MAXIMUM (1UL<<16)
103#define TEST_MINIMUM (QSIZE_MINIMUM + 1)
104/* real TEST_MINIMUM (1UL << (SHIFT_WORD - TEST_POWER)) */
105#define TEST_POWER (3) /* 2**n, n < SHIFT_WORD */
106
107/* bit operations on 32-bit words */
108#define BIT_CLEAR(a,n) ((a)[(n)>>SHIFT_WORD] &= ~(1L << ((n) & 31)))
109#define BIT_SET(a,n) ((a)[(n)>>SHIFT_WORD] |= (1L << ((n) & 31)))
110#define BIT_TEST(a,n) ((a)[(n)>>SHIFT_WORD] & (1L << ((n) & 31)))
111
112/*
113 * Prime testing defines
114 */
115
116/*
117 * Sieving data (XXX - move to struct)
118 */
119
120/* sieve 2**16 */
121static u_int32_t *TinySieve, tinybits;
122
123/* sieve 2**30 in 2**16 parts */
124static u_int32_t *SmallSieve, smallbits, smallbase;
125
126/* sieve relative to the initial value */
127static u_int32_t *LargeSieve, largewords, largetries, largenumbers;
128static u_int32_t largebits, largememory; /* megabytes */
129static BIGNUM *largebase;
130
131
132/*
133 * print moduli out in consistent form,
134 */
135static int
136qfileout(FILE * ofile, u_int32_t otype, u_int32_t otests, u_int32_t otries,
137 u_int32_t osize, u_int32_t ogenerator, BIGNUM * omodulus)
138{
139 struct tm *gtm;
140 time_t time_now;
141 int res;
142
143 time(&time_now);
144 gtm = gmtime(&time_now);
b6453d99 145
5ae3dc68 146 res = fprintf(ofile, "%04d%02d%02d%02d%02d%02d %u %u %u %u %x ",
147 gtm->tm_year + 1900, gtm->tm_mon + 1, gtm->tm_mday,
148 gtm->tm_hour, gtm->tm_min, gtm->tm_sec,
149 otype, otests, otries, osize, ogenerator);
150
151 if (res < 0)
152 return (-1);
153
154 if (BN_print_fp(ofile, omodulus) < 1)
155 return (-1);
156
157 res = fprintf(ofile, "\n");
158 fflush(ofile);
159
160 return (res > 0 ? 0 : -1);
161}
162
163
164/*
165 ** Sieve p's and q's with small factors
166 */
167static void
168sieve_large(u_int32_t s)
169{
170 u_int32_t r, u;
171
172 debug2("sieve_large %u", s);
173 largetries++;
174 /* r = largebase mod s */
175 r = BN_mod_word(largebase, s);
176 if (r == 0)
177 u = 0; /* s divides into largebase exactly */
178 else
179 u = s - r; /* largebase+u is first entry divisible by s */
180
181 if (u < largebits * 2) {
182 /*
183 * The sieve omits p's and q's divisible by 2, so ensure that
184 * largebase+u is odd. Then, step through the sieve in
185 * increments of 2*s
186 */
187 if (u & 0x1)
188 u += s; /* Make largebase+u odd, and u even */
189
190 /* Mark all multiples of 2*s */
191 for (u /= 2; u < largebits; u += s)
192 BIT_SET(LargeSieve, u);
193 }
194
195 /* r = p mod s */
196 r = (2 * r + 1) % s;
197 if (r == 0)
198 u = 0; /* s divides p exactly */
199 else
200 u = s - r; /* p+u is first entry divisible by s */
201
202 if (u < largebits * 4) {
203 /*
204 * The sieve omits p's divisible by 4, so ensure that
205 * largebase+u is not. Then, step through the sieve in
206 * increments of 4*s
207 */
208 while (u & 0x3) {
209 if (SMALL_MAXIMUM - u < s)
210 return;
211 u += s;
212 }
213
214 /* Mark all multiples of 4*s */
215 for (u /= 4; u < largebits; u += s)
216 BIT_SET(LargeSieve, u);
217 }
218}
219
220/*
221 * list candidates for Sophie-Germaine primes (where q = (p-1)/2)
222 * to standard output.
223 * The list is checked against small known primes (less than 2**30).
224 */
225int
226gen_candidates(FILE *out, int memory, int power, BIGNUM *start)
227{
228 BIGNUM *q;
229 u_int32_t j, r, s, t;
230 u_int32_t smallwords = TINY_NUMBER >> 6;
231 u_int32_t tinywords = TINY_NUMBER >> 6;
232 time_t time_start, time_stop;
233 int i, ret = 0;
234
235 largememory = memory;
236
237 /*
aff51935 238 * Set power to the length in bits of the prime to be generated.
239 * This is changed to 1 less than the desired safe prime moduli p.
240 */
5ae3dc68 241 if (power > TEST_MAXIMUM) {
242 error("Too many bits: %u > %lu", power, TEST_MAXIMUM);
243 return (-1);
244 } else if (power < TEST_MINIMUM) {
245 error("Too few bits: %u < %u", power, TEST_MINIMUM);
246 return (-1);
247 }
248 power--; /* decrement before squaring */
249
250 /*
aff51935 251 * The density of ordinary primes is on the order of 1/bits, so the
252 * density of safe primes should be about (1/bits)**2. Set test range
253 * to something well above bits**2 to be reasonably sure (but not
254 * guaranteed) of catching at least one safe prime.
5ae3dc68 255 */
256 largewords = ((power * power) >> (SHIFT_WORD - TEST_POWER));
257
258 /*
aff51935 259 * Need idea of how much memory is available. We don't have to use all
260 * of it.
5ae3dc68 261 */
262 if (largememory > LARGE_MAXIMUM) {
263 logit("Limited memory: %u MB; limit %lu MB",
264 largememory, LARGE_MAXIMUM);
265 largememory = LARGE_MAXIMUM;
266 }
267
268 if (largewords <= (largememory << SHIFT_MEGAWORD)) {
269 logit("Increased memory: %u MB; need %u bytes",
270 largememory, (largewords << SHIFT_BYTE));
271 largewords = (largememory << SHIFT_MEGAWORD);
272 } else if (largememory > 0) {
273 logit("Decreased memory: %u MB; want %u bytes",
274 largememory, (largewords << SHIFT_BYTE));
275 largewords = (largememory << SHIFT_MEGAWORD);
276 }
277
278 TinySieve = calloc(tinywords, sizeof(u_int32_t));
279 if (TinySieve == NULL) {
280 error("Insufficient memory for tiny sieve: need %u bytes",
281 tinywords << SHIFT_BYTE);
282 exit(1);
283 }
284 tinybits = tinywords << SHIFT_WORD;
285
286 SmallSieve = calloc(smallwords, sizeof(u_int32_t));
287 if (SmallSieve == NULL) {
288 error("Insufficient memory for small sieve: need %u bytes",
289 smallwords << SHIFT_BYTE);
290 xfree(TinySieve);
291 exit(1);
292 }
293 smallbits = smallwords << SHIFT_WORD;
294
295 /*
296 * dynamically determine available memory
297 */
298 while ((LargeSieve = calloc(largewords, sizeof(u_int32_t))) == NULL)
299 largewords -= (1L << (SHIFT_MEGAWORD - 2)); /* 1/4 MB chunks */
300
301 largebits = largewords << SHIFT_WORD;
302 largenumbers = largebits * 2; /* even numbers excluded */
303
304 /* validation check: count the number of primes tried */
305 largetries = 0;
306 q = BN_new();
307
308 /*
aff51935 309 * Generate random starting point for subprime search, or use
310 * specified parameter.
5ae3dc68 311 */
312 largebase = BN_new();
313 if (start == NULL)
314 BN_rand(largebase, power, 1, 1);
315 else
316 BN_copy(largebase, start);
317
318 /* ensure odd */
319 BN_set_bit(largebase, 0);
320
321 time(&time_start);
322
aff51935 323 logit("%.24s Sieve next %u plus %u-bit", ctime(&time_start),
5ae3dc68 324 largenumbers, power);
325 debug2("start point: 0x%s", BN_bn2hex(largebase));
326
327 /*
aff51935 328 * TinySieve
329 */
5ae3dc68 330 for (i = 0; i < tinybits; i++) {
331 if (BIT_TEST(TinySieve, i))
332 continue; /* 2*i+3 is composite */
333
334 /* The next tiny prime */
335 t = 2 * i + 3;
336
337 /* Mark all multiples of t */
338 for (j = i + t; j < tinybits; j += t)
339 BIT_SET(TinySieve, j);
340
341 sieve_large(t);
342 }
343
344 /*
aff51935 345 * Start the small block search at the next possible prime. To avoid
346 * fencepost errors, the last pass is skipped.
347 */
5ae3dc68 348 for (smallbase = TINY_NUMBER + 3;
349 smallbase < (SMALL_MAXIMUM - TINY_NUMBER);
350 smallbase += TINY_NUMBER) {
351 for (i = 0; i < tinybits; i++) {
352 if (BIT_TEST(TinySieve, i))
353 continue; /* 2*i+3 is composite */
354
355 /* The next tiny prime */
356 t = 2 * i + 3;
357 r = smallbase % t;
358
359 if (r == 0) {
360 s = 0; /* t divides into smallbase exactly */
361 } else {
362 /* smallbase+s is first entry divisible by t */
363 s = t - r;
364 }
365
366 /*
367 * The sieve omits even numbers, so ensure that
368 * smallbase+s is odd. Then, step through the sieve
369 * in increments of 2*t
370 */
371 if (s & 1)
372 s += t; /* Make smallbase+s odd, and s even */
373
374 /* Mark all multiples of 2*t */
375 for (s /= 2; s < smallbits; s += t)
376 BIT_SET(SmallSieve, s);
377 }
378
379 /*
aff51935 380 * SmallSieve
381 */
5ae3dc68 382 for (i = 0; i < smallbits; i++) {
383 if (BIT_TEST(SmallSieve, i))
384 continue; /* 2*i+smallbase is composite */
385
386 /* The next small prime */
387 sieve_large((2 * i) + smallbase);
388 }
389
390 memset(SmallSieve, 0, smallwords << SHIFT_BYTE);
391 }
392
393 time(&time_stop);
394
395 logit("%.24s Sieved with %u small primes in %ld seconds",
396 ctime(&time_stop), largetries, (long) (time_stop - time_start));
397
398 for (j = r = 0; j < largebits; j++) {
399 if (BIT_TEST(LargeSieve, j))
400 continue; /* Definitely composite, skip */
401
402 debug2("test q = largebase+%u", 2 * j);
403 BN_set_word(q, 2 * j);
404 BN_add(q, q, largebase);
405 if (qfileout(out, QTYPE_SOPHIE_GERMAINE, QTEST_SIEVE,
406 largetries, (power - 1) /* MSB */, (0), q) == -1) {
407 ret = -1;
408 break;
409 }
410
411 r++; /* count q */
412 }
413
414 time(&time_stop);
415
416 xfree(LargeSieve);
417 xfree(SmallSieve);
418 xfree(TinySieve);
419
420 logit("%.24s Found %u candidates", ctime(&time_stop), r);
421
422 return (ret);
423}
424
425/*
426 * perform a Miller-Rabin primality test
427 * on the list of candidates
428 * (checking both q and p)
429 * The result is a list of so-call "safe" primes
430 */
431int
aff51935 432prime_test(FILE *in, FILE *out, u_int32_t trials,
5ae3dc68 433 u_int32_t generator_wanted)
434{
435 BIGNUM *q, *p, *a;
436 BN_CTX *ctx;
437 char *cp, *lp;
438 u_int32_t count_in = 0, count_out = 0, count_possible = 0;
439 u_int32_t generator_known, in_tests, in_tries, in_type, in_size;
440 time_t time_start, time_stop;
441 int res;
442
443 time(&time_start);
444
445 p = BN_new();
446 q = BN_new();
447 ctx = BN_CTX_new();
448
449 debug2("%.24s Final %u Miller-Rabin trials (%x generator)",
450 ctime(&time_start), trials, generator_wanted);
451
452 res = 0;
453 lp = xmalloc(QLINESIZE + 1);
454 while (fgets(lp, QLINESIZE, in) != NULL) {
455 int ll = strlen(lp);
456
457 count_in++;
458 if (ll < 14 || *lp == '!' || *lp == '#') {
459 debug2("%10u: comment or short line", count_in);
460 continue;
461 }
462
463 /* XXX - fragile parser */
464 /* time */
465 cp = &lp[14]; /* (skip) */
466
467 /* type */
468 in_type = strtoul(cp, &cp, 10);
469
470 /* tests */
471 in_tests = strtoul(cp, &cp, 10);
472
473 if (in_tests & QTEST_COMPOSITE) {
474 debug2("%10u: known composite", count_in);
475 continue;
476 }
477 /* tries */
478 in_tries = strtoul(cp, &cp, 10);
479
480 /* size (most significant bit) */
481 in_size = strtoul(cp, &cp, 10);
482
483 /* generator (hex) */
484 generator_known = strtoul(cp, &cp, 16);
485
486 /* Skip white space */
487 cp += strspn(cp, " ");
488
489 /* modulus (hex) */
490 switch (in_type) {
491 case QTYPE_SOPHIE_GERMAINE:
492 debug2("%10u: (%u) Sophie-Germaine", count_in, in_type);
493 a = q;
494 BN_hex2bn(&a, cp);
495 /* p = 2*q + 1 */
496 BN_lshift(p, q, 1);
497 BN_add_word(p, 1);
498 in_size += 1;
499 generator_known = 0;
500 break;
501 default:
502 debug2("%10u: (%u)", count_in, in_type);
503 a = p;
504 BN_hex2bn(&a, cp);
505 /* q = (p-1) / 2 */
506 BN_rshift(q, p, 1);
507 break;
508 }
509
510 /*
511 * due to earlier inconsistencies in interpretation, check
512 * the proposed bit size.
513 */
514 if (BN_num_bits(p) != (in_size + 1)) {
515 debug2("%10u: bit size %u mismatch", count_in, in_size);
516 continue;
517 }
518 if (in_size < QSIZE_MINIMUM) {
519 debug2("%10u: bit size %u too short", count_in, in_size);
520 continue;
521 }
522
523 if (in_tests & QTEST_MILLER_RABIN)
524 in_tries += trials;
525 else
526 in_tries = trials;
527 /*
528 * guess unknown generator
529 */
530 if (generator_known == 0) {
531 if (BN_mod_word(p, 24) == 11)
532 generator_known = 2;
533 else if (BN_mod_word(p, 12) == 5)
534 generator_known = 3;
535 else {
536 u_int32_t r = BN_mod_word(p, 10);
537
538 if (r == 3 || r == 7) {
539 generator_known = 5;
540 }
541 }
542 }
543 /*
544 * skip tests when desired generator doesn't match
545 */
546 if (generator_wanted > 0 &&
547 generator_wanted != generator_known) {
548 debug2("%10u: generator %d != %d",
549 count_in, generator_known, generator_wanted);
550 continue;
551 }
552
eb7a33b8 553 /*
554 * Primes with no known generator are useless for DH, so
555 * skip those.
556 */
557 if (generator_known == 0) {
558 debug2("%10u: no known generator", count_in);
559 continue;
560 }
561
5ae3dc68 562 count_possible++;
563
564 /*
aff51935 565 * The (1/4)^N performance bound on Miller-Rabin is
566 * extremely pessimistic, so don't spend a lot of time
567 * really verifying that q is prime until after we know
568 * that p is also prime. A single pass will weed out the
5ae3dc68 569 * vast majority of composite q's.
570 */
571 if (BN_is_prime(q, 1, NULL, ctx, NULL) <= 0) {
572 debug2("%10u: q failed first possible prime test",
573 count_in);
574 continue;
575 }
b6453d99 576
5ae3dc68 577 /*
aff51935 578 * q is possibly prime, so go ahead and really make sure
579 * that p is prime. If it is, then we can go back and do
580 * the same for q. If p is composite, chances are that
5ae3dc68 581 * will show up on the first Rabin-Miller iteration so it
582 * doesn't hurt to specify a high iteration count.
583 */
584 if (!BN_is_prime(p, trials, NULL, ctx, NULL)) {
585 debug2("%10u: p is not prime", count_in);
586 continue;
587 }
588 debug("%10u: p is almost certainly prime", count_in);
589
590 /* recheck q more rigorously */
591 if (!BN_is_prime(q, trials - 1, NULL, ctx, NULL)) {
592 debug("%10u: q is not prime", count_in);
593 continue;
594 }
595 debug("%10u: q is almost certainly prime", count_in);
596
aff51935 597 if (qfileout(out, QTYPE_SAFE, (in_tests | QTEST_MILLER_RABIN),
5ae3dc68 598 in_tries, in_size, generator_known, p)) {
599 res = -1;
600 break;
601 }
602
603 count_out++;
604 }
605
606 time(&time_stop);
607 xfree(lp);
608 BN_free(p);
609 BN_free(q);
610 BN_CTX_free(ctx);
611
612 logit("%.24s Found %u safe primes of %u candidates in %ld seconds",
aff51935 613 ctime(&time_stop), count_out, count_possible,
5ae3dc68 614 (long) (time_stop - time_start));
615
616 return (res);
617}
This page took 0.357978 seconds and 5 git commands to generate.