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