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