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