No empty .Rs/.Re
[netbsd-mini2440.git] / crypto / external / bsd / openssh / dist / moduli.c
blob8fc4dc03ef8a1e3fdfbff491a5f5971167b4f5f9
1 /* $NetBSD$ */
2 /* $OpenBSD: moduli.c,v 1.21 2008/06/26 09:19:40 djm Exp $ */
3 /*
4 * Copyright 1994 Phil Karn <karn@qualcomm.com>
5 * Copyright 1996-1998, 2003 William Allen Simpson <wsimpson@greendragon.com>
6 * Copyright 2000 Niels Provos <provos@citi.umich.edu>
7 * All rights reserved.
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.
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.
31 * Two-step process to generate safe primes for DHGEX
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.
37 * First step: generate candidate primes (memory intensive)
38 * Second step: test primes' safety (processor intensive)
40 #include "includes.h"
41 __RCSID("$NetBSD: moduli.c,v 1.6 2009/02/16 20:53:54 christos Exp $");
43 #include <sys/types.h>
45 #include <openssl/bn.h>
46 #include <openssl/dh.h>
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <stdarg.h>
52 #include <time.h>
54 #include "xmalloc.h"
55 #include "dh.h"
56 #include "log.h"
59 * File output defines
62 /* need line long enough for largest moduli plus headers */
63 #define QLINESIZE (100+8192)
66 * Size: decimal.
67 * Specifies the number of the most significant bit (0 to M).
68 * WARNING: internally, usually 1 to N.
70 #define QSIZE_MINIMUM (511)
73 * Prime sieving defines
76 /* Constant: assuming 8 bit bytes and 32 bit words */
77 #define SHIFT_BIT (3)
78 #define SHIFT_BYTE (2)
79 #define SHIFT_WORD (SHIFT_BIT+SHIFT_BYTE)
80 #define SHIFT_MEGABYTE (20)
81 #define SHIFT_MEGAWORD (SHIFT_MEGABYTE-SHIFT_BYTE)
84 * Using virtual memory can cause thrashing. This should be the largest
85 * number that is supported without a large amount of disk activity --
86 * that would increase the run time from hours to days or weeks!
88 #define LARGE_MINIMUM (8UL) /* megabytes */
91 * Do not increase this number beyond the unsigned integer bit size.
92 * Due to a multiple of 4, it must be LESS than 128 (yielding 2**30 bits).
94 #define LARGE_MAXIMUM (127UL) /* megabytes */
97 * Constant: when used with 32-bit integers, the largest sieve prime
98 * has to be less than 2**32.
100 #define SMALL_MAXIMUM (0xffffffffUL)
102 /* Constant: can sieve all primes less than 2**32, as 65537**2 > 2**32-1. */
103 #define TINY_NUMBER (1UL<<16)
105 /* Ensure enough bit space for testing 2*q. */
106 #define TEST_MAXIMUM (1UL<<16)
107 #define TEST_MINIMUM (QSIZE_MINIMUM + 1)
108 /* real TEST_MINIMUM (1UL << (SHIFT_WORD - TEST_POWER)) */
109 #define TEST_POWER (3) /* 2**n, n < SHIFT_WORD */
111 /* bit operations on 32-bit words */
112 #define BIT_CLEAR(a,n) ((a)[(n)>>SHIFT_WORD] &= ~(1L << ((n) & 31)))
113 #define BIT_SET(a,n) ((a)[(n)>>SHIFT_WORD] |= (1L << ((n) & 31)))
114 #define BIT_TEST(a,n) ((a)[(n)>>SHIFT_WORD] & (1L << ((n) & 31)))
117 * Prime testing defines
120 /* Minimum number of primality tests to perform */
121 #define TRIAL_MINIMUM (4)
124 * Sieving data (XXX - move to struct)
127 /* sieve 2**16 */
128 static u_int32_t *TinySieve, tinybits;
130 /* sieve 2**30 in 2**16 parts */
131 static u_int32_t *SmallSieve, smallbits, smallbase;
133 /* sieve relative to the initial value */
134 static u_int32_t *LargeSieve, largewords, largetries, largenumbers;
135 static u_int32_t largebits, largememory; /* megabytes */
136 static BIGNUM *largebase;
138 int gen_candidates(FILE *, u_int32_t, u_int32_t, BIGNUM *);
139 int prime_test(FILE *, FILE *, u_int32_t, u_int32_t);
142 * print moduli out in consistent form,
144 static int
145 qfileout(FILE * ofile, u_int32_t otype, u_int32_t otests, u_int32_t otries,
146 u_int32_t osize, u_int32_t ogenerator, BIGNUM * omodulus)
148 struct tm *gtm;
149 time_t time_now;
150 int res;
152 time(&time_now);
153 gtm = gmtime(&time_now);
155 res = fprintf(ofile, "%04d%02d%02d%02d%02d%02d %u %u %u %u %x ",
156 gtm->tm_year + 1900, gtm->tm_mon + 1, gtm->tm_mday,
157 gtm->tm_hour, gtm->tm_min, gtm->tm_sec,
158 otype, otests, otries, osize, ogenerator);
160 if (res < 0)
161 return (-1);
163 if (BN_print_fp(ofile, omodulus) < 1)
164 return (-1);
166 res = fprintf(ofile, "\n");
167 fflush(ofile);
169 return (res > 0 ? 0 : -1);
174 ** Sieve p's and q's with small factors
176 static void
177 sieve_large(u_int32_t s)
179 u_int32_t r, u;
181 debug3("sieve_large %u", s);
182 largetries++;
183 /* r = largebase mod s */
184 r = BN_mod_word(largebase, s);
185 if (r == 0)
186 u = 0; /* s divides into largebase exactly */
187 else
188 u = s - r; /* largebase+u is first entry divisible by s */
190 if (u < largebits * 2) {
192 * The sieve omits p's and q's divisible by 2, so ensure that
193 * largebase+u is odd. Then, step through the sieve in
194 * increments of 2*s
196 if (u & 0x1)
197 u += s; /* Make largebase+u odd, and u even */
199 /* Mark all multiples of 2*s */
200 for (u /= 2; u < largebits; u += s)
201 BIT_SET(LargeSieve, u);
204 /* r = p mod s */
205 r = (2 * r + 1) % s;
206 if (r == 0)
207 u = 0; /* s divides p exactly */
208 else
209 u = s - r; /* p+u is first entry divisible by s */
211 if (u < largebits * 4) {
213 * The sieve omits p's divisible by 4, so ensure that
214 * largebase+u is not. Then, step through the sieve in
215 * increments of 4*s
217 while (u & 0x3) {
218 if (SMALL_MAXIMUM - u < s)
219 return;
220 u += s;
223 /* Mark all multiples of 4*s */
224 for (u /= 4; u < largebits; u += s)
225 BIT_SET(LargeSieve, u);
230 * list candidates for Sophie-Germain primes (where q = (p-1)/2)
231 * to standard output.
232 * The list is checked against small known primes (less than 2**30).
235 gen_candidates(FILE *out, u_int32_t memory, u_int32_t power, BIGNUM *start)
237 BIGNUM *q;
238 u_int32_t j, r, s, t;
239 u_int32_t smallwords = TINY_NUMBER >> 6;
240 u_int32_t tinywords = TINY_NUMBER >> 6;
241 time_t time_start, time_stop;
242 u_int32_t i;
243 int ret = 0;
245 largememory = memory;
247 if (memory != 0 &&
248 (memory < LARGE_MINIMUM || memory > LARGE_MAXIMUM)) {
249 error("Invalid memory amount (min %ld, max %ld)",
250 LARGE_MINIMUM, LARGE_MAXIMUM);
251 return (-1);
255 * Set power to the length in bits of the prime to be generated.
256 * This is changed to 1 less than the desired safe prime moduli p.
258 if (power > TEST_MAXIMUM) {
259 error("Too many bits: %u > %lu", power, TEST_MAXIMUM);
260 return (-1);
261 } else if (power < TEST_MINIMUM) {
262 error("Too few bits: %u < %u", power, TEST_MINIMUM);
263 return (-1);
265 power--; /* decrement before squaring */
268 * The density of ordinary primes is on the order of 1/bits, so the
269 * density of safe primes should be about (1/bits)**2. Set test range
270 * to something well above bits**2 to be reasonably sure (but not
271 * guaranteed) of catching at least one safe prime.
273 largewords = ((power * power) >> (SHIFT_WORD - TEST_POWER));
276 * Need idea of how much memory is available. We don't have to use all
277 * of it.
279 if (largememory > LARGE_MAXIMUM) {
280 logit("Limited memory: %u MB; limit %lu MB",
281 largememory, LARGE_MAXIMUM);
282 largememory = LARGE_MAXIMUM;
285 if (largewords <= (largememory << SHIFT_MEGAWORD)) {
286 logit("Increased memory: %u MB; need %u bytes",
287 largememory, (largewords << SHIFT_BYTE));
288 largewords = (largememory << SHIFT_MEGAWORD);
289 } else if (largememory > 0) {
290 logit("Decreased memory: %u MB; want %u bytes",
291 largememory, (largewords << SHIFT_BYTE));
292 largewords = (largememory << SHIFT_MEGAWORD);
295 TinySieve = xcalloc(tinywords, sizeof(u_int32_t));
296 tinybits = tinywords << SHIFT_WORD;
298 SmallSieve = xcalloc(smallwords, sizeof(u_int32_t));
299 smallbits = smallwords << SHIFT_WORD;
302 * dynamically determine available memory
304 while ((LargeSieve = calloc(largewords, sizeof(u_int32_t))) == NULL)
305 largewords -= (1L << (SHIFT_MEGAWORD - 2)); /* 1/4 MB chunks */
307 largebits = largewords << SHIFT_WORD;
308 largenumbers = largebits * 2; /* even numbers excluded */
310 /* validation check: count the number of primes tried */
311 largetries = 0;
312 if ((q = BN_new()) == NULL)
313 fatal("BN_new failed");
316 * Generate random starting point for subprime search, or use
317 * specified parameter.
319 if ((largebase = BN_new()) == NULL)
320 fatal("BN_new failed");
321 if (start == NULL) {
322 if (BN_rand(largebase, power, 1, 1) == 0)
323 fatal("BN_rand failed");
324 } else {
325 if (BN_copy(largebase, start) == NULL)
326 fatal("BN_copy: failed");
329 /* ensure odd */
330 if (BN_set_bit(largebase, 0) == 0)
331 fatal("BN_set_bit: failed");
333 time(&time_start);
335 logit("%.24s Sieve next %u plus %u-bit", ctime(&time_start),
336 largenumbers, power);
337 debug2("start point: 0x%s", BN_bn2hex(largebase));
340 * TinySieve
342 for (i = 0; i < tinybits; i++) {
343 if (BIT_TEST(TinySieve, i))
344 continue; /* 2*i+3 is composite */
346 /* The next tiny prime */
347 t = 2 * i + 3;
349 /* Mark all multiples of t */
350 for (j = i + t; j < tinybits; j += t)
351 BIT_SET(TinySieve, j);
353 sieve_large(t);
357 * Start the small block search at the next possible prime. To avoid
358 * fencepost errors, the last pass is skipped.
360 for (smallbase = TINY_NUMBER + 3;
361 smallbase < (SMALL_MAXIMUM - TINY_NUMBER);
362 smallbase += TINY_NUMBER) {
363 for (i = 0; i < tinybits; i++) {
364 if (BIT_TEST(TinySieve, i))
365 continue; /* 2*i+3 is composite */
367 /* The next tiny prime */
368 t = 2 * i + 3;
369 r = smallbase % t;
371 if (r == 0) {
372 s = 0; /* t divides into smallbase exactly */
373 } else {
374 /* smallbase+s is first entry divisible by t */
375 s = t - r;
379 * The sieve omits even numbers, so ensure that
380 * smallbase+s is odd. Then, step through the sieve
381 * in increments of 2*t
383 if (s & 1)
384 s += t; /* Make smallbase+s odd, and s even */
386 /* Mark all multiples of 2*t */
387 for (s /= 2; s < smallbits; s += t)
388 BIT_SET(SmallSieve, s);
392 * SmallSieve
394 for (i = 0; i < smallbits; i++) {
395 if (BIT_TEST(SmallSieve, i))
396 continue; /* 2*i+smallbase is composite */
398 /* The next small prime */
399 sieve_large((2 * i) + smallbase);
402 memset(SmallSieve, 0, smallwords << SHIFT_BYTE);
405 time(&time_stop);
407 logit("%.24s Sieved with %u small primes in %ld seconds",
408 ctime(&time_stop), largetries, (long) (time_stop - time_start));
410 for (j = r = 0; j < largebits; j++) {
411 if (BIT_TEST(LargeSieve, j))
412 continue; /* Definitely composite, skip */
414 debug2("test q = largebase+%u", 2 * j);
415 if (BN_set_word(q, 2 * j) == 0)
416 fatal("BN_set_word failed");
417 if (BN_add(q, q, largebase) == 0)
418 fatal("BN_add failed");
419 if (qfileout(out, MODULI_TYPE_SOPHIE_GERMAIN,
420 MODULI_TESTS_SIEVE, largetries,
421 (power - 1) /* MSB */, (0), q) == -1) {
422 ret = -1;
423 break;
426 r++; /* count q */
429 time(&time_stop);
431 xfree(LargeSieve);
432 xfree(SmallSieve);
433 xfree(TinySieve);
435 logit("%.24s Found %u candidates", ctime(&time_stop), r);
437 return (ret);
441 * perform a Miller-Rabin primality test
442 * on the list of candidates
443 * (checking both q and p)
444 * The result is a list of so-call "safe" primes
447 prime_test(FILE *in, FILE *out, u_int32_t trials, u_int32_t generator_wanted)
449 BIGNUM *q, *p, *a;
450 BN_CTX *ctx;
451 char *cp, *lp;
452 u_int32_t count_in = 0, count_out = 0, count_possible = 0;
453 u_int32_t generator_known, in_tests, in_tries, in_type, in_size;
454 time_t time_start, time_stop;
455 int res;
457 if (trials < TRIAL_MINIMUM) {
458 error("Minimum primality trials is %d", TRIAL_MINIMUM);
459 return (-1);
462 time(&time_start);
464 if ((p = BN_new()) == NULL)
465 fatal("BN_new failed");
466 if ((q = BN_new()) == NULL)
467 fatal("BN_new failed");
468 if ((ctx = BN_CTX_new()) == NULL)
469 fatal("BN_CTX_new failed");
471 debug2("%.24s Final %u Miller-Rabin trials (%x generator)",
472 ctime(&time_start), trials, generator_wanted);
474 res = 0;
475 lp = xmalloc(QLINESIZE + 1);
476 while (fgets(lp, QLINESIZE + 1, in) != NULL) {
477 count_in++;
478 if (strlen(lp) < 14 || *lp == '!' || *lp == '#') {
479 debug2("%10u: comment or short line", count_in);
480 continue;
483 /* XXX - fragile parser */
484 /* time */
485 cp = &lp[14]; /* (skip) */
487 /* type */
488 in_type = strtoul(cp, &cp, 10);
490 /* tests */
491 in_tests = strtoul(cp, &cp, 10);
493 if (in_tests & MODULI_TESTS_COMPOSITE) {
494 debug2("%10u: known composite", count_in);
495 continue;
498 /* tries */
499 in_tries = strtoul(cp, &cp, 10);
501 /* size (most significant bit) */
502 in_size = strtoul(cp, &cp, 10);
504 /* generator (hex) */
505 generator_known = strtoul(cp, &cp, 16);
507 /* Skip white space */
508 cp += strspn(cp, " ");
510 /* modulus (hex) */
511 switch (in_type) {
512 case MODULI_TYPE_SOPHIE_GERMAIN:
513 debug2("%10u: (%u) Sophie-Germain", count_in, in_type);
514 a = q;
515 if (BN_hex2bn(&a, cp) == 0)
516 fatal("BN_hex2bn failed");
517 /* p = 2*q + 1 */
518 if (BN_lshift(p, q, 1) == 0)
519 fatal("BN_lshift failed");
520 if (BN_add_word(p, 1) == 0)
521 fatal("BN_add_word failed");
522 in_size += 1;
523 generator_known = 0;
524 break;
525 case MODULI_TYPE_UNSTRUCTURED:
526 case MODULI_TYPE_SAFE:
527 case MODULI_TYPE_SCHNORR:
528 case MODULI_TYPE_STRONG:
529 case MODULI_TYPE_UNKNOWN:
530 debug2("%10u: (%u)", count_in, in_type);
531 a = p;
532 if (BN_hex2bn(&a, cp) == 0)
533 fatal("BN_hex2bn failed");
534 /* q = (p-1) / 2 */
535 if (BN_rshift(q, p, 1) == 0)
536 fatal("BN_rshift failed");
537 break;
538 default:
539 debug2("Unknown prime type");
540 break;
544 * due to earlier inconsistencies in interpretation, check
545 * the proposed bit size.
547 if ((u_int32_t)BN_num_bits(p) != (in_size + 1)) {
548 debug2("%10u: bit size %u mismatch", count_in, in_size);
549 continue;
551 if (in_size < QSIZE_MINIMUM) {
552 debug2("%10u: bit size %u too short", count_in, in_size);
553 continue;
556 if (in_tests & MODULI_TESTS_MILLER_RABIN)
557 in_tries += trials;
558 else
559 in_tries = trials;
562 * guess unknown generator
564 if (generator_known == 0) {
565 if (BN_mod_word(p, 24) == 11)
566 generator_known = 2;
567 else if (BN_mod_word(p, 12) == 5)
568 generator_known = 3;
569 else {
570 u_int32_t r = BN_mod_word(p, 10);
572 if (r == 3 || r == 7)
573 generator_known = 5;
577 * skip tests when desired generator doesn't match
579 if (generator_wanted > 0 &&
580 generator_wanted != generator_known) {
581 debug2("%10u: generator %d != %d",
582 count_in, generator_known, generator_wanted);
583 continue;
587 * Primes with no known generator are useless for DH, so
588 * skip those.
590 if (generator_known == 0) {
591 debug2("%10u: no known generator", count_in);
592 continue;
595 count_possible++;
598 * The (1/4)^N performance bound on Miller-Rabin is
599 * extremely pessimistic, so don't spend a lot of time
600 * really verifying that q is prime until after we know
601 * that p is also prime. A single pass will weed out the
602 * vast majority of composite q's.
604 if (BN_is_prime(q, 1, NULL, ctx, NULL) <= 0) {
605 debug("%10u: q failed first possible prime test",
606 count_in);
607 continue;
611 * q is possibly prime, so go ahead and really make sure
612 * that p is prime. If it is, then we can go back and do
613 * the same for q. If p is composite, chances are that
614 * will show up on the first Rabin-Miller iteration so it
615 * doesn't hurt to specify a high iteration count.
617 if (!BN_is_prime(p, trials, NULL, ctx, NULL)) {
618 debug("%10u: p is not prime", count_in);
619 continue;
621 debug("%10u: p is almost certainly prime", count_in);
623 /* recheck q more rigorously */
624 if (!BN_is_prime(q, trials - 1, NULL, ctx, NULL)) {
625 debug("%10u: q is not prime", count_in);
626 continue;
628 debug("%10u: q is almost certainly prime", count_in);
630 if (qfileout(out, MODULI_TYPE_SAFE,
631 in_tests | MODULI_TESTS_MILLER_RABIN,
632 in_tries, in_size, generator_known, p)) {
633 res = -1;
634 break;
637 count_out++;
640 time(&time_stop);
641 xfree(lp);
642 BN_free(p);
643 BN_free(q);
644 BN_CTX_free(ctx);
646 logit("%.24s Found %u safe primes of %u candidates in %ld seconds",
647 ctime(&time_stop), count_out, count_possible,
648 (long) (time_stop - time_start));
650 return (res);