pockle.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. #include <assert.h>
  2. #include "ssh.h"
  3. #include "sshkeygen.h"
  4. #include "mpint.h"
  5. #include "mpunsafe.h"
  6. #include "tree234.h"
  7. typedef struct PocklePrimeRecord PocklePrimeRecord;
  8. struct Pockle {
  9. tree234 *tree;
  10. PocklePrimeRecord **list;
  11. size_t nlist, listsize;
  12. };
  13. struct PocklePrimeRecord {
  14. mp_int *prime;
  15. PocklePrimeRecord **factors;
  16. size_t nfactors;
  17. mp_int *witness;
  18. size_t index; /* index in pockle->list */
  19. };
  20. static int ppr_cmp(void *av, void *bv)
  21. {
  22. PocklePrimeRecord *a = (PocklePrimeRecord *)av;
  23. PocklePrimeRecord *b = (PocklePrimeRecord *)bv;
  24. return mp_cmp_hs(a->prime, b->prime) - mp_cmp_hs(b->prime, a->prime);
  25. }
  26. static int ppr_find(void *av, void *bv)
  27. {
  28. mp_int *a = (mp_int *)av;
  29. PocklePrimeRecord *b = (PocklePrimeRecord *)bv;
  30. return mp_cmp_hs(a, b->prime) - mp_cmp_hs(b->prime, a);
  31. }
  32. Pockle *pockle_new(void)
  33. {
  34. Pockle *pockle = snew(Pockle);
  35. pockle->tree = newtree234(ppr_cmp);
  36. pockle->list = NULL;
  37. pockle->nlist = pockle->listsize = 0;
  38. return pockle;
  39. }
  40. void pockle_free(Pockle *pockle)
  41. {
  42. pockle_release(pockle, 0);
  43. assert(count234(pockle->tree) == 0);
  44. freetree234(pockle->tree);
  45. sfree(pockle->list);
  46. sfree(pockle);
  47. }
  48. static PockleStatus pockle_insert(Pockle *pockle, mp_int *p, mp_int **factors,
  49. size_t nfactors, mp_int *w)
  50. {
  51. PocklePrimeRecord *pr = snew(PocklePrimeRecord);
  52. pr->prime = mp_copy(p);
  53. PocklePrimeRecord *found = add234(pockle->tree, pr);
  54. if (pr != found) {
  55. /* it was already in there */
  56. mp_free(pr->prime);
  57. sfree(pr);
  58. return POCKLE_OK;
  59. }
  60. if (w) {
  61. pr->factors = snewn(nfactors, PocklePrimeRecord *);
  62. for (size_t i = 0; i < nfactors; i++) {
  63. pr->factors[i] = find234(pockle->tree, factors[i], ppr_find);
  64. assert(pr->factors[i]);
  65. }
  66. pr->nfactors = nfactors;
  67. pr->witness = mp_copy(w);
  68. } else {
  69. pr->factors = NULL;
  70. pr->nfactors = 0;
  71. pr->witness = NULL;
  72. }
  73. pr->index = pockle->nlist;
  74. sgrowarray(pockle->list, pockle->listsize, pockle->nlist);
  75. pockle->list[pockle->nlist++] = pr;
  76. return POCKLE_OK;
  77. }
  78. size_t pockle_mark(Pockle *pockle)
  79. {
  80. return pockle->nlist;
  81. }
  82. void pockle_release(Pockle *pockle, size_t mark)
  83. {
  84. while (pockle->nlist > mark) {
  85. PocklePrimeRecord *pr = pockle->list[--pockle->nlist];
  86. del234(pockle->tree, pr);
  87. mp_free(pr->prime);
  88. if (pr->witness)
  89. mp_free(pr->witness);
  90. sfree(pr->factors);
  91. sfree(pr);
  92. }
  93. }
  94. PockleStatus pockle_add_small_prime(Pockle *pockle, mp_int *p)
  95. {
  96. if (mp_hs_integer(p, (1ULL << 32)))
  97. return POCKLE_SMALL_PRIME_NOT_SMALL;
  98. uint32_t val = mp_get_integer(p);
  99. if (val < 2)
  100. return POCKLE_PRIME_SMALLER_THAN_2;
  101. init_smallprimes();
  102. for (size_t i = 0; i < NSMALLPRIMES; i++) {
  103. if (val == smallprimes[i])
  104. break; /* success */
  105. if (val % smallprimes[i] == 0)
  106. return POCKLE_SMALL_PRIME_NOT_PRIME;
  107. }
  108. return pockle_insert(pockle, p, NULL, 0, NULL);
  109. }
  110. PockleStatus pockle_add_prime(Pockle *pockle, mp_int *p,
  111. mp_int **factors, size_t nfactors,
  112. mp_int *witness)
  113. {
  114. MontyContext *mc = NULL;
  115. mp_int *x = NULL, *f = NULL, *w = NULL;
  116. PockleStatus status;
  117. /*
  118. * We're going to try to verify that p is prime by using
  119. * Pocklington's theorem. The idea is that we're given w such that
  120. * w^{p-1} == 1 (mod p) (1)
  121. * and for a collection of primes q | p-1,
  122. * w^{(p-1)/q} - 1 is coprime to p. (2)
  123. *
  124. * Suppose r is a prime factor of p itself. Consider the
  125. * multiplicative order of w mod r. By (1), r | w^{p-1}-1. But by
  126. * (2), r does not divide w^{(p-1)/q}-1. So the order of w mod r
  127. * is a factor of p-1, but not a factor of (p-1)/q. Hence, the
  128. * largest power of q that divides p-1 must also divide ord w.
  129. *
  130. * Repeating this reasoning for all q, we find that the product of
  131. * all the q (which we'll denote f) must divide ord w, which in
  132. * turn divides r-1. So f | r-1 for any r | p.
  133. *
  134. * In particular, this means f < r. That is, all primes r | p are
  135. * bigger than f. So if f > sqrt(p), then we've shown p is prime,
  136. * because otherwise it would have to be the product of at least
  137. * two factors bigger than its own square root.
  138. *
  139. * With an extra check, we can also show p to be prime even if
  140. * we're only given enough factors to make f > cbrt(p). See below
  141. * for that part, when we come to it.
  142. */
  143. /*
  144. * Start by checking p > 1. It certainly can't be prime otherwise!
  145. * (And since we're going to prove it prime by showing all its
  146. * prime factors are large, we do also have to know it _has_ at
  147. * least one prime factor for that to tell us anything.)
  148. */
  149. if (!mp_hs_integer(p, 2))
  150. return POCKLE_PRIME_SMALLER_THAN_2;
  151. /*
  152. * Check that all the factors we've been given really are primes
  153. * (in the sense that we already had them in our index). Make the
  154. * product f, and check it really does divide p-1.
  155. */
  156. x = mp_copy(p);
  157. mp_sub_integer_into(x, x, 1);
  158. f = mp_from_integer(1);
  159. for (size_t i = 0; i < nfactors; i++) {
  160. mp_int *q = factors[i];
  161. if (!find234(pockle->tree, q, ppr_find)) {
  162. status = POCKLE_FACTOR_NOT_KNOWN_PRIME;
  163. goto out;
  164. }
  165. mp_int *quotient = mp_new(mp_max_bits(x));
  166. mp_int *residue = mp_new(mp_max_bits(q));
  167. mp_divmod_into(x, q, quotient, residue);
  168. unsigned exact = mp_eq_integer(residue, 0);
  169. mp_free(residue);
  170. mp_free(x);
  171. x = quotient;
  172. if (!exact) {
  173. status = POCKLE_FACTOR_NOT_A_FACTOR;
  174. goto out;
  175. }
  176. mp_int *tmp = f;
  177. f = mp_unsafe_shrink(mp_mul(tmp, q));
  178. mp_free(tmp);
  179. }
  180. /*
  181. * Check that f > cbrt(p).
  182. */
  183. mp_int *f2 = mp_mul(f, f);
  184. mp_int *f3 = mp_mul(f2, f);
  185. bool too_big = mp_cmp_hs(p, f3);
  186. mp_free(f3);
  187. mp_free(f2);
  188. if (too_big) {
  189. status = POCKLE_PRODUCT_OF_FACTORS_TOO_SMALL;
  190. goto out;
  191. }
  192. /*
  193. * Now do the extra check that allows us to get away with only
  194. * having f > cbrt(p) instead of f > sqrt(p).
  195. *
  196. * If we can show that f | r-1 for any r | p, then we've ruled out
  197. * p being a product of _more_ than two primes (because then it
  198. * would be the product of at least three things bigger than its
  199. * own cube root). But we still have to rule out it being a
  200. * product of exactly two.
  201. *
  202. * Suppose for the sake of contradiction that p is the product of
  203. * two prime factors. We know both of those factors would have to
  204. * be congruent to 1 mod f. So we'd have to have
  205. *
  206. * p = (uf+1)(vf+1) = (uv)f^2 + (u+v)f + 1 (3)
  207. *
  208. * We can't have uv >= f, or else that expression would come to at
  209. * least f^3, i.e. it would exceed p. So uv < f. Hence, u,v < f as
  210. * well.
  211. *
  212. * Can we have u+v >= f? If we did, then we could write v >= f-u,
  213. * and hence f > uv >= u(f-u). That can be rearranged to show that
  214. * u^2 > (u-1)f; decrementing the LHS makes the inequality no
  215. * longer necessarily strict, so we have u^2-1 >= (u-1)f, and
  216. * dividing off u-1 gives u+1 >= f. But we know u < f, so the only
  217. * way this could happen would be if u=f-1, which makes v=1. But
  218. * _then_ (3) gives us p = (f-1)f^2 + f^2 + 1 = f^3+1. But that
  219. * can't be true if f^3 > p. So we can't have u+v >= f either, by
  220. * contradiction.
  221. *
  222. * After all that, what have we shown? We've shown that we can
  223. * write p = (uv)f^2 + (u+v)f + 1, with both uv and u+v strictly
  224. * less than f. In other words, if you write down p in base f, it
  225. * has exactly three digits, and they are uv, u+v and 1.
  226. *
  227. * But that means we can _find_ u and v: we know p and f, so we
  228. * can just extract those digits of p's base-f representation.
  229. * Once we've done so, they give the sum and product of the
  230. * potential u,v. And given the sum and product of two numbers,
  231. * you can make a quadratic which has those numbers as roots.
  232. *
  233. * We don't actually have to _solve_ the quadratic: all we have to
  234. * do is check if its discriminant is a perfect square. If not,
  235. * we'll know that no integers u,v can match this description.
  236. */
  237. {
  238. /* We already have x = (p-1)/f. So we just need to write x in
  239. * the form aF + b, and then we have a=uv and b=u+v. */
  240. mp_int *a = mp_new(mp_max_bits(x));
  241. mp_int *b = mp_new(mp_max_bits(f));
  242. mp_divmod_into(x, f, a, b);
  243. assert(!mp_cmp_hs(a, f));
  244. assert(!mp_cmp_hs(b, f));
  245. /* If a=0, then that means p < f^2, so we don't need to do
  246. * this check at all: the straightforward Pocklington theorem
  247. * is all we need. */
  248. if (!mp_eq_integer(a, 0)) {
  249. unsigned perfect_square = 0;
  250. mp_int *bsq = mp_mul(b, b);
  251. mp_lshift_fixed_into(a, a, 2);
  252. if (mp_cmp_hs(bsq, a)) {
  253. /* b^2-4a is non-negative, so it might be a square.
  254. * Check it. */
  255. mp_int *discriminant = mp_sub(bsq, a);
  256. mp_int *remainder = mp_new(mp_max_bits(discriminant));
  257. mp_int *root = mp_nthroot(discriminant, 2, remainder);
  258. perfect_square = mp_eq_integer(remainder, 0);
  259. mp_free(discriminant);
  260. mp_free(root);
  261. mp_free(remainder);
  262. }
  263. mp_free(bsq);
  264. if (perfect_square) {
  265. mp_free(b);
  266. mp_free(a);
  267. status = POCKLE_DISCRIMINANT_IS_SQUARE;
  268. goto out;
  269. }
  270. }
  271. mp_free(b);
  272. mp_free(a);
  273. }
  274. /*
  275. * Now we've done all the checks that are cheaper than a modpow,
  276. * so we've ruled out as many things as possible before having to
  277. * do any hard work. But there's nothing for it now: make a
  278. * MontyContext.
  279. */
  280. mc = monty_new(p);
  281. w = monty_import(mc, witness);
  282. /*
  283. * The initial Fermat check: is w^{p-1} itself congruent to 1 mod
  284. * p?
  285. */
  286. {
  287. mp_int *pm1 = mp_copy(p);
  288. mp_sub_integer_into(pm1, pm1, 1);
  289. mp_int *power = monty_pow(mc, w, pm1);
  290. unsigned fermat_pass = mp_cmp_eq(power, monty_identity(mc));
  291. mp_free(power);
  292. mp_free(pm1);
  293. if (!fermat_pass) {
  294. status = POCKLE_FERMAT_TEST_FAILED;
  295. goto out;
  296. }
  297. }
  298. /*
  299. * And now, for each factor q, is w^{(p-1)/q}-1 coprime to p?
  300. */
  301. for (size_t i = 0; i < nfactors; i++) {
  302. mp_int *q = factors[i];
  303. mp_int *exponent = mp_unsafe_shrink(mp_div(p, q));
  304. mp_int *power = monty_pow(mc, w, exponent);
  305. mp_int *power_extracted = monty_export(mc, power);
  306. mp_sub_integer_into(power_extracted, power_extracted, 1);
  307. unsigned coprime = mp_coprime(power_extracted, p);
  308. if (!coprime) {
  309. /*
  310. * If w^{(p-1)/q}-1 is not coprime to p, the test has
  311. * failed. But it makes a difference why. If the power of
  312. * w turned out to be 1, so that we took gcd(1-1,p) =
  313. * gcd(0,p) = p, that's like an inconclusive Fermat or M-R
  314. * test: it might just mean you picked a witness integer
  315. * that wasn't a primitive root. But if the power is any
  316. * _other_ value mod p that is not coprime to p, it means
  317. * we've detected that the number is *actually not prime*!
  318. */
  319. if (mp_eq_integer(power_extracted, 0))
  320. status = POCKLE_WITNESS_POWER_IS_1;
  321. else
  322. status = POCKLE_WITNESS_POWER_NOT_COPRIME;
  323. }
  324. mp_free(exponent);
  325. mp_free(power);
  326. mp_free(power_extracted);
  327. if (!coprime)
  328. goto out; /* with the status we set up above */
  329. }
  330. /*
  331. * Success! p is prime. Insert it into our tree234 of known
  332. * primes, so that future calls to this function can cite it in
  333. * evidence of larger numbers' primality.
  334. */
  335. status = pockle_insert(pockle, p, factors, nfactors, witness);
  336. out:
  337. if (x)
  338. mp_free(x);
  339. if (f)
  340. mp_free(f);
  341. if (w)
  342. mp_free(w);
  343. if (mc)
  344. monty_free(mc);
  345. return status;
  346. }
  347. static void mp_write_decimal(strbuf *sb, mp_int *x)
  348. {
  349. char *s = mp_get_decimal(x);
  350. ptrlen pl = ptrlen_from_asciz(s);
  351. put_datapl(sb, pl);
  352. smemclr(s, pl.len);
  353. sfree(s);
  354. }
  355. strbuf *pockle_mpu(Pockle *pockle, mp_int *p)
  356. {
  357. strbuf *sb = strbuf_new_nm();
  358. PocklePrimeRecord *pr = find234(pockle->tree, p, ppr_find);
  359. assert(pr);
  360. bool *needed = snewn(pockle->nlist, bool);
  361. memset(needed, 0, pockle->nlist * sizeof(bool));
  362. needed[pr->index] = true;
  363. put_fmt(sb, "[MPU - Primality Certificate]\nVersion 1.0\nBase 10\n\n"
  364. "Proof for:\nN ");
  365. mp_write_decimal(sb, p);
  366. put_fmt(sb, "\n");
  367. for (size_t index = pockle->nlist; index-- > 0 ;) {
  368. if (!needed[index])
  369. continue;
  370. pr = pockle->list[index];
  371. if (mp_get_nbits(pr->prime) <= 64) {
  372. put_fmt(sb, "\nType Small\nN ");
  373. mp_write_decimal(sb, pr->prime);
  374. put_fmt(sb, "\n");
  375. } else {
  376. assert(pr->witness);
  377. put_fmt(sb, "\nType BLS5\nN ");
  378. mp_write_decimal(sb, pr->prime);
  379. put_fmt(sb, "\n");
  380. for (size_t i = 0; i < pr->nfactors; i++) {
  381. put_fmt(sb, "Q[%"SIZEu"] ", i+1);
  382. mp_write_decimal(sb, pr->factors[i]->prime);
  383. assert(pr->factors[i]->index < index);
  384. needed[pr->factors[i]->index] = true;
  385. put_fmt(sb, "\n");
  386. }
  387. for (size_t i = 0; i < pr->nfactors + 1; i++) {
  388. put_fmt(sb, "A[%"SIZEu"] ", i);
  389. mp_write_decimal(sb, pr->witness);
  390. put_fmt(sb, "\n");
  391. }
  392. put_fmt(sb, "----\n");
  393. }
  394. }
  395. sfree(needed);
  396. return sb;
  397. }