Home | History | Annotate | Line # | Download | only in dist
moduli.c revision 1.3.2.1
      1 /*	$NetBSD: moduli.c,v 1.3.2.1 2012/05/23 10:07:05 yamt Exp $	*/
      2 /* $OpenBSD: moduli.c,v 1.25 2011/10/19 00:06:10 djm Exp $ */
      3 /*
      4  * Copyright 1994 Phil Karn <karn (at) qualcomm.com>
      5  * Copyright 1996-1998, 2003 William Allen Simpson <wsimpson (at) greendragon.com>
      6  * Copyright 2000 Niels Provos <provos (at) citi.umich.edu>
      7  * All rights reserved.
      8  *
      9  * Redistribution and use in source and binary forms, with or without
     10  * modification, are permitted provided that the following conditions
     11  * are met:
     12  * 1. Redistributions of source code must retain the above copyright
     13  *    notice, this list of conditions and the following disclaimer.
     14  * 2. Redistributions in binary form must reproduce the above copyright
     15  *    notice, this list of conditions and the following disclaimer in the
     16  *    documentation and/or other materials provided with the distribution.
     17  *
     18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     21  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     23  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     28  */
     29 
     30 /*
     31  * Two-step process to generate safe primes for DHGEX
     32  *
     33  *  Sieve candidates for "safe" primes,
     34  *  suitable for use as Diffie-Hellman moduli;
     35  *  that is, where q = (p-1)/2 is also prime.
     36  *
     37  * First step: generate candidate primes (memory intensive)
     38  * Second step: test primes' safety (processor intensive)
     39  */
     40 #include "includes.h"
     41 __RCSID("$NetBSD: moduli.c,v 1.3.2.1 2012/05/23 10:07:05 yamt Exp $");
     42 
     43 #include <sys/param.h>
     44 #include <sys/types.h>
     45 
     46 #include <openssl/bn.h>
     47 #include <openssl/dh.h>
     48 
     49 #include <errno.h>
     50 #include <stdio.h>
     51 #include <stdlib.h>
     52 #include <string.h>
     53 #include <stdarg.h>
     54 #include <time.h>
     55 #include <unistd.h>
     56 
     57 #include "xmalloc.h"
     58 #include "dh.h"
     59 #include "log.h"
     60 
     61 /*
     62  * File output defines
     63  */
     64 
     65 /* need line long enough for largest moduli plus headers */
     66 #define QLINESIZE		(100+8192)
     67 
     68 /*
     69  * Size: decimal.
     70  * Specifies the number of the most significant bit (0 to M).
     71  * WARNING: internally, usually 1 to N.
     72  */
     73 #define QSIZE_MINIMUM		(511)
     74 
     75 /*
     76  * Prime sieving defines
     77  */
     78 
     79 /* Constant: assuming 8 bit bytes and 32 bit words */
     80 #define SHIFT_BIT	(3)
     81 #define SHIFT_BYTE	(2)
     82 #define SHIFT_WORD	(SHIFT_BIT+SHIFT_BYTE)
     83 #define SHIFT_MEGABYTE	(20)
     84 #define SHIFT_MEGAWORD	(SHIFT_MEGABYTE-SHIFT_BYTE)
     85 
     86 /*
     87  * Using virtual memory can cause thrashing.  This should be the largest
     88  * number that is supported without a large amount of disk activity --
     89  * that would increase the run time from hours to days or weeks!
     90  */
     91 #define LARGE_MINIMUM	(8UL)	/* megabytes */
     92 
     93 /*
     94  * Do not increase this number beyond the unsigned integer bit size.
     95  * Due to a multiple of 4, it must be LESS than 128 (yielding 2**30 bits).
     96  */
     97 #define LARGE_MAXIMUM	(127UL)	/* megabytes */
     98 
     99 /*
    100  * Constant: when used with 32-bit integers, the largest sieve prime
    101  * has to be less than 2**32.
    102  */
    103 #define SMALL_MAXIMUM	(0xffffffffUL)
    104 
    105 /* Constant: can sieve all primes less than 2**32, as 65537**2 > 2**32-1. */
    106 #define TINY_NUMBER	(1UL<<16)
    107 
    108 /* Ensure enough bit space for testing 2*q. */
    109 #define TEST_MAXIMUM	(1UL<<16)
    110 #define TEST_MINIMUM	(QSIZE_MINIMUM + 1)
    111 /* real TEST_MINIMUM	(1UL << (SHIFT_WORD - TEST_POWER)) */
    112 #define TEST_POWER	(3)	/* 2**n, n < SHIFT_WORD */
    113 
    114 /* bit operations on 32-bit words */
    115 #define BIT_CLEAR(a,n)	((a)[(n)>>SHIFT_WORD] &= ~(1L << ((n) & 31)))
    116 #define BIT_SET(a,n)	((a)[(n)>>SHIFT_WORD] |= (1L << ((n) & 31)))
    117 #define BIT_TEST(a,n)	((a)[(n)>>SHIFT_WORD] & (1L << ((n) & 31)))
    118 
    119 /*
    120  * Prime testing defines
    121  */
    122 
    123 /* Minimum number of primality tests to perform */
    124 #define TRIAL_MINIMUM	(4)
    125 
    126 /*
    127  * Sieving data (XXX - move to struct)
    128  */
    129 
    130 /* sieve 2**16 */
    131 static u_int32_t *TinySieve, tinybits;
    132 
    133 /* sieve 2**30 in 2**16 parts */
    134 static u_int32_t *SmallSieve, smallbits, smallbase;
    135 
    136 /* sieve relative to the initial value */
    137 static u_int32_t *LargeSieve, largewords, largetries, largenumbers;
    138 static u_int32_t largebits, largememory;	/* megabytes */
    139 static BIGNUM *largebase;
    140 
    141 int gen_candidates(FILE *, u_int32_t, u_int32_t, BIGNUM *);
    142 int prime_test(FILE *, FILE *, u_int32_t, u_int32_t, char *);
    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 	xfree(LargeSieve);
    435 	xfree(SmallSieve);
    436 	xfree(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[MAXPATHLEN];
    448 	int r;
    449 
    450 	r = snprintf(tmp, sizeof(tmp), "%s.XXXXXXXXXX", cpfile);
    451 	if (r == -1 || r >= MAXPATHLEN) {
    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 		close(r);
    462 		return;
    463 	}
    464 	if (fprintf(fp, "%lu\n", (unsigned long)lineno) > 0 && fclose(fp) == 0
    465 	    && rename(tmp, cpfile) == 0)
    466 		debug3("wrote checkpoint line %lu to '%s'",
    467 		    (unsigned long)lineno, cpfile);
    468 	else
    469 		logit("failed to write to checkpoint file '%s': %s", cpfile,
    470 		    strerror(errno));
    471 }
    472 
    473 static unsigned long
    474 read_checkpoint(char *cpfile)
    475 {
    476 	FILE *fp;
    477 	unsigned long lineno = 0;
    478 
    479 	if ((fp = fopen(cpfile, "r")) == NULL)
    480 		return 0;
    481 	if (fscanf(fp, "%lu\n", &lineno) < 1)
    482 		logit("Failed to load checkpoint from '%s'", cpfile);
    483 	else
    484 		logit("Loaded checkpoint from '%s' line %lu", cpfile, lineno);
    485 	fclose(fp);
    486 	return lineno;
    487 }
    488 
    489 /*
    490  * perform a Miller-Rabin primality test
    491  * on the list of candidates
    492  * (checking both q and p)
    493  * The result is a list of so-call "safe" primes
    494  */
    495 int
    496 prime_test(FILE *in, FILE *out, u_int32_t trials, u_int32_t generator_wanted,
    497     char *checkpoint_file)
    498 {
    499 	BIGNUM *q, *p, *a;
    500 	BN_CTX *ctx;
    501 	char *cp, *lp;
    502 	u_int32_t count_in = 0, count_out = 0, count_possible = 0;
    503 	u_int32_t generator_known, in_tests, in_tries, in_type, in_size;
    504 	unsigned long last_processed = 0;
    505 	time_t time_start, time_stop;
    506 	int res;
    507 
    508 	if (trials < TRIAL_MINIMUM) {
    509 		error("Minimum primality trials is %d", TRIAL_MINIMUM);
    510 		return (-1);
    511 	}
    512 
    513 	time(&time_start);
    514 
    515 	if ((p = BN_new()) == NULL)
    516 		fatal("BN_new failed");
    517 	if ((q = BN_new()) == NULL)
    518 		fatal("BN_new failed");
    519 	if ((ctx = BN_CTX_new()) == NULL)
    520 		fatal("BN_CTX_new failed");
    521 
    522 	debug2("%.24s Final %u Miller-Rabin trials (%x generator)",
    523 	    ctime(&time_start), trials, generator_wanted);
    524 
    525 	if (checkpoint_file != NULL)
    526 		last_processed = read_checkpoint(checkpoint_file);
    527 
    528 	res = 0;
    529 	lp = xmalloc(QLINESIZE + 1);
    530 	while (fgets(lp, QLINESIZE + 1, in) != NULL) {
    531 		count_in++;
    532 		if (checkpoint_file != NULL) {
    533 			if (count_in <= last_processed) {
    534 				debug3("skipping line %u, before checkpoint",
    535 				    count_in);
    536 				continue;
    537 			}
    538 			write_checkpoint(checkpoint_file, count_in);
    539 		}
    540 		if (strlen(lp) < 14 || *lp == '!' || *lp == '#') {
    541 			debug2("%10u: comment or short line", count_in);
    542 			continue;
    543 		}
    544 
    545 		/* XXX - fragile parser */
    546 		/* time */
    547 		cp = &lp[14];	/* (skip) */
    548 
    549 		/* type */
    550 		in_type = strtoul(cp, &cp, 10);
    551 
    552 		/* tests */
    553 		in_tests = strtoul(cp, &cp, 10);
    554 
    555 		if (in_tests & MODULI_TESTS_COMPOSITE) {
    556 			debug2("%10u: known composite", count_in);
    557 			continue;
    558 		}
    559 
    560 		/* tries */
    561 		in_tries = strtoul(cp, &cp, 10);
    562 
    563 		/* size (most significant bit) */
    564 		in_size = strtoul(cp, &cp, 10);
    565 
    566 		/* generator (hex) */
    567 		generator_known = strtoul(cp, &cp, 16);
    568 
    569 		/* Skip white space */
    570 		cp += strspn(cp, " ");
    571 
    572 		/* modulus (hex) */
    573 		switch (in_type) {
    574 		case MODULI_TYPE_SOPHIE_GERMAIN:
    575 			debug2("%10u: (%u) Sophie-Germain", count_in, in_type);
    576 			a = q;
    577 			if (BN_hex2bn(&a, cp) == 0)
    578 				fatal("BN_hex2bn failed");
    579 			/* p = 2*q + 1 */
    580 			if (BN_lshift(p, q, 1) == 0)
    581 				fatal("BN_lshift failed");
    582 			if (BN_add_word(p, 1) == 0)
    583 				fatal("BN_add_word failed");
    584 			in_size += 1;
    585 			generator_known = 0;
    586 			break;
    587 		case MODULI_TYPE_UNSTRUCTURED:
    588 		case MODULI_TYPE_SAFE:
    589 		case MODULI_TYPE_SCHNORR:
    590 		case MODULI_TYPE_STRONG:
    591 		case MODULI_TYPE_UNKNOWN:
    592 			debug2("%10u: (%u)", count_in, in_type);
    593 			a = p;
    594 			if (BN_hex2bn(&a, cp) == 0)
    595 				fatal("BN_hex2bn failed");
    596 			/* q = (p-1) / 2 */
    597 			if (BN_rshift(q, p, 1) == 0)
    598 				fatal("BN_rshift failed");
    599 			break;
    600 		default:
    601 			debug2("Unknown prime type");
    602 			break;
    603 		}
    604 
    605 		/*
    606 		 * due to earlier inconsistencies in interpretation, check
    607 		 * the proposed bit size.
    608 		 */
    609 		if ((u_int32_t)BN_num_bits(p) != (in_size + 1)) {
    610 			debug2("%10u: bit size %u mismatch", count_in, in_size);
    611 			continue;
    612 		}
    613 		if (in_size < QSIZE_MINIMUM) {
    614 			debug2("%10u: bit size %u too short", count_in, in_size);
    615 			continue;
    616 		}
    617 
    618 		if (in_tests & MODULI_TESTS_MILLER_RABIN)
    619 			in_tries += trials;
    620 		else
    621 			in_tries = trials;
    622 
    623 		/*
    624 		 * guess unknown generator
    625 		 */
    626 		if (generator_known == 0) {
    627 			if (BN_mod_word(p, 24) == 11)
    628 				generator_known = 2;
    629 			else if (BN_mod_word(p, 12) == 5)
    630 				generator_known = 3;
    631 			else {
    632 				u_int32_t r = BN_mod_word(p, 10);
    633 
    634 				if (r == 3 || r == 7)
    635 					generator_known = 5;
    636 			}
    637 		}
    638 		/*
    639 		 * skip tests when desired generator doesn't match
    640 		 */
    641 		if (generator_wanted > 0 &&
    642 		    generator_wanted != generator_known) {
    643 			debug2("%10u: generator %d != %d",
    644 			    count_in, generator_known, generator_wanted);
    645 			continue;
    646 		}
    647 
    648 		/*
    649 		 * Primes with no known generator are useless for DH, so
    650 		 * skip those.
    651 		 */
    652 		if (generator_known == 0) {
    653 			debug2("%10u: no known generator", count_in);
    654 			continue;
    655 		}
    656 
    657 		count_possible++;
    658 
    659 		/*
    660 		 * The (1/4)^N performance bound on Miller-Rabin is
    661 		 * extremely pessimistic, so don't spend a lot of time
    662 		 * really verifying that q is prime until after we know
    663 		 * that p is also prime. A single pass will weed out the
    664 		 * vast majority of composite q's.
    665 		 */
    666 		if (BN_is_prime_ex(q, 1, ctx, NULL) <= 0) {
    667 			debug("%10u: q failed first possible prime test",
    668 			    count_in);
    669 			continue;
    670 		}
    671 
    672 		/*
    673 		 * q is possibly prime, so go ahead and really make sure
    674 		 * that p is prime. If it is, then we can go back and do
    675 		 * the same for q. If p is composite, chances are that
    676 		 * will show up on the first Rabin-Miller iteration so it
    677 		 * doesn't hurt to specify a high iteration count.
    678 		 */
    679 		if (!BN_is_prime_ex(p, trials, ctx, NULL)) {
    680 			debug("%10u: p is not prime", count_in);
    681 			continue;
    682 		}
    683 		debug("%10u: p is almost certainly prime", count_in);
    684 
    685 		/* recheck q more rigorously */
    686 		if (!BN_is_prime_ex(q, trials - 1, ctx, NULL)) {
    687 			debug("%10u: q is not prime", count_in);
    688 			continue;
    689 		}
    690 		debug("%10u: q is almost certainly prime", count_in);
    691 
    692 		if (qfileout(out, MODULI_TYPE_SAFE,
    693 		    in_tests | MODULI_TESTS_MILLER_RABIN,
    694 		    in_tries, in_size, generator_known, p)) {
    695 			res = -1;
    696 			break;
    697 		}
    698 
    699 		count_out++;
    700 	}
    701 
    702 	time(&time_stop);
    703 	xfree(lp);
    704 	BN_free(p);
    705 	BN_free(q);
    706 	BN_CTX_free(ctx);
    707 
    708 	if (checkpoint_file != NULL)
    709 		unlink(checkpoint_file);
    710 
    711 	logit("%.24s Found %u safe primes of %u candidates in %ld seconds",
    712 	    ctime(&time_stop), count_out, count_possible,
    713 	    (long) (time_stop - time_start));
    714 
    715 	return (res);
    716 }
    717