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