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