moduli.c 21 KB

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