ntru.c 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884
  1. /*
  2. * Implementation of OpenSSH 9.x's hybrid key exchange protocol
  3. * sntrup761x25519-sha512@openssh.com .
  4. *
  5. * This consists of the 'Streamlined NTRU Prime' quantum-resistant
  6. * cryptosystem, run in parallel with ordinary Curve25519 to generate
  7. * a shared secret combining the output of both systems.
  8. *
  9. * (Hence, even if you don't trust this newfangled NTRU Prime thing at
  10. * all, it's at least no _less_ secure than the kex you were using
  11. * already.)
  12. *
  13. * References for the NTRU Prime cryptosystem, up to and including
  14. * binary encodings of public and private keys and the exact preimages
  15. * of the hashes used in key exchange:
  16. *
  17. * https://ntruprime.cr.yp.to/
  18. * https://ntruprime.cr.yp.to/nist/ntruprime-20201007.pdf
  19. *
  20. * The SSH protocol layer is not documented anywhere I could find (as
  21. * of 2022-04-15, not even in OpenSSH's PROTOCOL.* files). I had to
  22. * read OpenSSH's source code to find out how it worked, and the
  23. * answer is as follows:
  24. *
  25. * This hybrid kex method is treated for SSH purposes as a form of
  26. * elliptic-curve Diffie-Hellman, and shares the same SSH message
  27. * sequence: client sends SSH2_MSG_KEX_ECDH_INIT containing its public
  28. * half, server responds with SSH2_MSG_KEX_ECDH_REPLY containing _its_
  29. * public half plus the host key and signature on the shared secret.
  30. *
  31. * (This is a bit of a fudge, because unlike actual ECDH, this kex
  32. * method is asymmetric: one side sends a public key, and the other
  33. * side encrypts something with it and sends the ciphertext back. So
  34. * while the normal ECDH implementations can compute the two sides
  35. * independently in parallel, this system reusing the same messages
  36. * has to be serial. But the order of the messages _is_ firmly
  37. * specified in SSH ECDH, so it works anyway.)
  38. *
  39. * For this kex method, SSH2_MSG_KEX_ECDH_INIT still contains a single
  40. * SSH 'string', which consists of the concatenation of a Streamlined
  41. * NTRU Prime public key with the Curve25519 public value. (Both of
  42. * these have fixed length in bytes, so there's no ambiguity in the
  43. * concatenation.)
  44. *
  45. * SSH2_MSG_KEX_ECDH_REPLY is mostly the same as usual. The only
  46. * string in the packet that varies is the second one, which would
  47. * normally contain the server's public elliptic curve point. Instead,
  48. * it now contains the concatenation of
  49. *
  50. * - a Streamlined NTRU Prime ciphertext
  51. * - the 'confirmation hash' specified in ntruprime-20201007.pdf,
  52. * hashing the plaintext of that ciphertext together with the
  53. * public key
  54. * - the Curve25519 public point as usual.
  55. *
  56. * Again, all three of those elements have fixed lengths.
  57. *
  58. * The client decrypts the ciphertext, checks the confirmation hash,
  59. * and if successful, generates the 'session hash' specified in
  60. * ntruprime-20201007.pdf, which is 32 bytes long and is the ultimate
  61. * output of the Streamlined NTRU Prime key exchange.
  62. *
  63. * The output of the hybrid kex method as a whole is an SSH 'string'
  64. * of length 64 containing the SHA-512 hash of the concatenatio of
  65. *
  66. * - the Streamlined NTRU Prime session hash (32 bytes)
  67. * - the Curve25519 shared secret (32 bytes).
  68. *
  69. * That string is included directly into the SSH exchange hash and key
  70. * derivation hashes, in place of the mpint that comes out of most
  71. * other kex methods.
  72. */
  73. #include <stdio.h>
  74. #include <stdlib.h>
  75. #include <assert.h>
  76. #include "putty.h"
  77. #include "ssh.h"
  78. #include "mpint.h"
  79. #include "ntru.h"
  80. /* ----------------------------------------------------------------------
  81. * Preliminaries: we're going to need to do modular arithmetic on
  82. * small values (considerably smaller than 2^16), and we need to do it
  83. * without using integer division which might not be time-safe.
  84. *
  85. * The strategy for this is the same as I used in
  86. * mp_mod_known_integer: see there for the proofs. The basic idea is
  87. * that we precompute the reciprocal of our modulus as a fixed-point
  88. * number, and use that to get an approximate quotient which we
  89. * subtract off. For these integer sizes, precomputing a fixed-point
  90. * reciprocal of the form (2^48 / modulus) leaves us at most off by 1
  91. * in the quotient, so there's a single (time-safe) trial subtraction
  92. * at the end.
  93. *
  94. * (It's possible that some speed could be gained by not reducing
  95. * fully at every step. But then you'd have to carefully identify all
  96. * the places in the algorithm where things are compared to zero. This
  97. * was the easiest way to get it all working in the first place.)
  98. */
  99. /* Precompute the reciprocal */
  100. static uint64_t reciprocal_for_reduction(uint16_t q)
  101. {
  102. return ((uint64_t)1 << 48) / q;
  103. }
  104. /* Reduce x mod q, assuming qrecip == reciprocal_for_reduction(q) */
  105. static uint16_t reduce(uint32_t x, uint16_t q, uint64_t qrecip)
  106. {
  107. uint64_t unshifted_quot = x * qrecip;
  108. uint64_t quot = unshifted_quot >> 48;
  109. uint16_t reduced = x - quot * q;
  110. reduced -= q * (1 & ((q-1 - reduced) >> 15));
  111. return reduced;
  112. }
  113. /* Reduce x mod q as above, but also return the quotient */
  114. static uint16_t reduce_with_quot(uint32_t x, uint32_t *quot_out,
  115. uint16_t q, uint64_t qrecip)
  116. {
  117. uint64_t unshifted_quot = x * qrecip;
  118. uint64_t quot = unshifted_quot >> 48;
  119. uint16_t reduced = x - quot * q;
  120. uint64_t extraquot = (1 & ((q-1 - reduced) >> 15));
  121. reduced -= extraquot * q;
  122. *quot_out = quot + extraquot;
  123. return reduced;
  124. }
  125. /* Invert x mod q, assuming it's nonzero. (For time-safety, no check
  126. * is made for zero; it just returns 0.) */
  127. static uint16_t invert(uint16_t x, uint16_t q, uint64_t qrecip)
  128. {
  129. /* Fermat inversion: compute x^(q-2), since x^(q-1) == 1. */
  130. uint32_t sq = x, bit = 1, acc = 1, exp = q-2;
  131. while (1) {
  132. if (exp & bit) {
  133. acc = reduce(acc * sq, q, qrecip);
  134. exp &= ~bit;
  135. if (!exp)
  136. return acc;
  137. }
  138. sq = reduce(sq * sq, q, qrecip);
  139. bit <<= 1;
  140. }
  141. }
  142. /* Check whether x == 0, time-safely, and return 1 if it is or 0 otherwise. */
  143. static unsigned iszero(uint16_t x)
  144. {
  145. return 1 & ~((x + 0xFFFF) >> 16);
  146. }
  147. /*
  148. * Handy macros to cut down on all those extra function parameters. In
  149. * the common case where a function is working mod the same modulus
  150. * throughout (and has called it q), you can just write 'SETUP;' at
  151. * the top and then call REDUCE(...) and INVERT(...) without having to
  152. * write out q and qrecip every time.
  153. */
  154. #define SETUP uint64_t qrecip = reciprocal_for_reduction(q)
  155. #define REDUCE(x) reduce(x, q, qrecip)
  156. #define INVERT(x) invert(x, q, qrecip)
  157. /* ----------------------------------------------------------------------
  158. * Quotient-ring functions.
  159. *
  160. * NTRU Prime works with two similar but different quotient rings:
  161. *
  162. * Z_q[x] / <x^p-x-1> where p,q are the prime parameters of the system
  163. * Z_3[x] / <x^p-x-1> with the same p, but coefficients mod 3.
  164. *
  165. * The former is a field (every nonzero element is invertible),
  166. * because the system parameters are chosen such that x^p-x-1 is
  167. * invertible over Z_q. The latter is not a field (or not necessarily,
  168. * and in particular, not for the value of p we use here).
  169. *
  170. * In these core functions, you pass in the modulus you want as the
  171. * parameter q, which is either the 'real' q specified in the system
  172. * parameters, or 3 if you're doing one of the mod-3 parts of the
  173. * algorithm.
  174. */
  175. /*
  176. * Multiply two elements of a quotient ring.
  177. *
  178. * 'a' and 'b' are arrays of exactly p coefficients, with constant
  179. * term first. 'out' is an array the same size to write the inverse
  180. * into.
  181. */
  182. void ntru_ring_multiply(uint16_t *out, const uint16_t *a, const uint16_t *b,
  183. unsigned p, unsigned q)
  184. {
  185. SETUP;
  186. /*
  187. * Strategy: just compute the full product with 2p coefficients,
  188. * and then reduce it mod x^p-x-1 by working downwards from the
  189. * top coefficient replacing x^{p+k} with (x+1)x^k for k = ...,1,0.
  190. *
  191. * Possibly some speed could be gained here by doing the recursive
  192. * Karatsuba optimisation for the initial multiplication? But I
  193. * haven't tried it.
  194. */
  195. uint32_t *unreduced = snewn(2*p, uint32_t);
  196. for (unsigned i = 0; i < 2*p; i++)
  197. unreduced[i] = 0;
  198. for (unsigned i = 0; i < p; i++)
  199. for (unsigned j = 0; j < p; j++)
  200. unreduced[i+j] = REDUCE(unreduced[i+j] + a[i] * b[j]);
  201. for (unsigned i = 2*p - 1; i >= p; i--) {
  202. unreduced[i-p] += unreduced[i];
  203. unreduced[i-p+1] += unreduced[i];
  204. unreduced[i] = 0;
  205. }
  206. for (unsigned i = 0; i < p; i++)
  207. out[i] = REDUCE(unreduced[i]);
  208. smemclr(unreduced, 2*p * sizeof(*unreduced));
  209. sfree(unreduced);
  210. }
  211. /*
  212. * Invert an element of the quotient ring.
  213. *
  214. * 'in' is an array of exactly p coefficients, with constant term
  215. * first. 'out' is an array the same size to write the inverse into.
  216. *
  217. * Method: essentially Stein's gcd algorithm, taking the gcd of the
  218. * input (regarded as an element of Z_q[x] proper) and x^p-x-1. Given
  219. * two polynomials over a field which are not both divisible by x, you
  220. * can find their gcd by iterating the following procedure:
  221. *
  222. * - if one is divisible by x, divide off x
  223. * - otherwise, subtract from the higher-degree one whatever scalar
  224. * multiple of the lower-degree one will make it divisible by x,
  225. * and _then_ divide off x
  226. *
  227. * Neither of these types of step changes the gcd of the two
  228. * polynomials.
  229. *
  230. * Each step reduces the sum of the two polynomials' degree by at
  231. * least one, as long as at least one of the degrees is positive.
  232. * (Maybe more than one if all the stars align in the second case, if
  233. * the subtraction cancels the leading term as well as the constant
  234. * term.) So in at most deg A + deg B steps, we must have reached the
  235. * situation where both polys are constants; in one more step after
  236. * that, one of them will be zero; and in one step after _that_, the
  237. * zero one will reliably be the one we're dividing by x. Or rather,
  238. * that's what happens in the case where A,B are coprime; if not, then
  239. * one hits zero while the other is still nonzero.
  240. *
  241. * In a normal gcd algorithm, you'd track a linear combination of the
  242. * two original polynomials that yields each working value, and end up
  243. * with a linear combination of the inputs that yields the gcd. In
  244. * this algorithm, the 'divide off x' step makes that awkward - but we
  245. * can solve that by instead multiplying by the inverse of x in the
  246. * ring that we want our answer to be valid in! And since the modulus
  247. * polynomial of the ring is x^p-x-1, the inverse of x is easy to
  248. * calculate, because it's always just x^{p-1} - 1, which is also very
  249. * easy to multiply by.
  250. */
  251. unsigned ntru_ring_invert(uint16_t *out, const uint16_t *in,
  252. unsigned p, unsigned q)
  253. {
  254. SETUP;
  255. /* Size of the polynomial arrays we'll work with */
  256. const size_t SIZE = p+1;
  257. /* Number of steps of the algorithm is the max possible value of
  258. * deg A + deg B + 2, where deg A <= p-1 and deg B = p */
  259. const size_t STEPS = 2*p + 1;
  260. /* Our two working polynomials */
  261. uint16_t *A = snewn(SIZE, uint16_t);
  262. uint16_t *B = snewn(SIZE, uint16_t);
  263. /* Coefficient of the input value in each one */
  264. uint16_t *Ac = snewn(SIZE, uint16_t);
  265. uint16_t *Bc = snewn(SIZE, uint16_t);
  266. /* Initialise A to the input, and Ac correspondingly to 1 */
  267. memcpy(A, in, p*sizeof(uint16_t));
  268. A[p] = 0;
  269. Ac[0] = 1;
  270. for (size_t i = 1; i < SIZE; i++)
  271. Ac[i] = 0;
  272. /* Initialise B to the quotient polynomial of the ring, x^p-x-1
  273. * And Bc = 0 */
  274. B[0] = B[1] = q-1;
  275. for (size_t i = 2; i < p; i++)
  276. B[i] = 0;
  277. B[p] = 1;
  278. for (size_t i = 0; i < SIZE; i++)
  279. Bc[i] = 0;
  280. /* Run the gcd-finding algorithm. */
  281. for (size_t i = 0; i < STEPS; i++) {
  282. /*
  283. * First swap round so that A is the one we'll be dividing by x.
  284. *
  285. * In the case where one of the two polys has a zero constant
  286. * term, it's that one. In the other case, it's the one of
  287. * smaller degree. We must compute both, and choose between
  288. * them in a side-channel-safe way.
  289. */
  290. unsigned x_divides_A = iszero(A[0]);
  291. unsigned x_divides_B = iszero(B[0]);
  292. unsigned B_is_bigger = 0;
  293. {
  294. unsigned not_seen_top_term_of_A = 1, not_seen_top_term_of_B = 1;
  295. for (size_t j = SIZE; j-- > 0 ;) {
  296. not_seen_top_term_of_A &= iszero(A[j]);
  297. not_seen_top_term_of_B &= iszero(B[j]);
  298. B_is_bigger |= (~not_seen_top_term_of_B &
  299. not_seen_top_term_of_A);
  300. }
  301. }
  302. unsigned need_swap = x_divides_B | (~x_divides_A & B_is_bigger);
  303. uint16_t swap_mask = -need_swap;
  304. for (size_t j = 0; j < SIZE; j++) {
  305. uint16_t diff = (A[j] ^ B[j]) & swap_mask;
  306. A[j] ^= diff;
  307. B[j] ^= diff;
  308. }
  309. for (size_t j = 0; j < SIZE; j++) {
  310. uint16_t diff = (Ac[j] ^ Bc[j]) & swap_mask;
  311. Ac[j] ^= diff;
  312. Bc[j] ^= diff;
  313. }
  314. /*
  315. * Replace A with a linear combination of both A and B that
  316. * has constant term zero, which we do by calculating
  317. *
  318. * (constant term of B) * A - (constant term of A) * B
  319. *
  320. * In one of the two cases, A's constant term is already zero,
  321. * so the coefficient of B will be zero too; hence, this will
  322. * do nothing useful (it will merely scale A by some scalar
  323. * value), but it will take the same length of time as doing
  324. * something, which is just what we want.
  325. */
  326. uint16_t Amult = B[0], Bmult = q - A[0];
  327. for (size_t j = 0; j < SIZE; j++)
  328. A[j] = REDUCE(Amult * A[j] + Bmult * B[j]);
  329. /* And do the same transformation to Ac */
  330. for (size_t j = 0; j < SIZE; j++)
  331. Ac[j] = REDUCE(Amult * Ac[j] + Bmult * Bc[j]);
  332. /*
  333. * Now divide A by x, and compensate by multiplying Ac by
  334. * x^{p-1}-1 mod x^p-x-1.
  335. *
  336. * That multiplication is particularly easy, precisely because
  337. * x^{p-1}-1 is the multiplicative inverse of x! Each x^n term
  338. * for n>0 just moves down to the x^{n-1} term, and only the
  339. * constant term has to be dealt with in an interesting way.
  340. */
  341. for (size_t j = 1; j < SIZE; j++)
  342. A[j-1] = A[j];
  343. A[SIZE-1] = 0;
  344. uint16_t Ac0 = Ac[0];
  345. for (size_t j = 1; j < p; j++)
  346. Ac[j-1] = Ac[j];
  347. Ac[p-1] = Ac0;
  348. Ac[0] = REDUCE(Ac[0] + q - Ac0);
  349. }
  350. /*
  351. * Now we expect that A is 0, and B is a constant. If so, then
  352. * they are coprime, and we're going to return success. If not,
  353. * they have a common factor.
  354. */
  355. unsigned success = iszero(A[0]) & (1 ^ iszero(B[0]));
  356. for (size_t j = 1; j < SIZE; j++)
  357. success &= iszero(A[j]) & iszero(B[j]);
  358. /*
  359. * So we're going to return Bc, but first, scale it by the
  360. * multiplicative inverse of the constant we ended up with in
  361. * B[0].
  362. */
  363. uint16_t scale = INVERT(B[0]);
  364. for (size_t i = 0; i < p; i++)
  365. out[i] = REDUCE(scale * Bc[i]);
  366. smemclr(A, SIZE * sizeof(*A));
  367. sfree(A);
  368. smemclr(B, SIZE * sizeof(*B));
  369. sfree(B);
  370. smemclr(Ac, SIZE * sizeof(*Ac));
  371. sfree(Ac);
  372. smemclr(Bc, SIZE * sizeof(*Bc));
  373. sfree(Bc);
  374. return success;
  375. }
  376. /*
  377. * Given an array of values mod q, convert each one to its
  378. * minimum-absolute-value representative, and then reduce mod 3.
  379. *
  380. * Output values are 0, 1 and 0xFFFF, representing -1.
  381. *
  382. * (Normally our arrays of uint16_t are in 'minimal non-negative
  383. * residue' form, so the output of this function is unusual. But it's
  384. * useful to have it in this form so that it can be reused by
  385. * ntru_round3. You can put it back to the usual representation using
  386. * ntru_normalise, below.)
  387. */
  388. void ntru_mod3(uint16_t *out, const uint16_t *in, unsigned p, unsigned q)
  389. {
  390. uint64_t qrecip = reciprocal_for_reduction(q);
  391. uint64_t recip3 = reciprocal_for_reduction(3);
  392. unsigned bias = q/2;
  393. uint16_t adjust = 3 - reduce(bias-1, 3, recip3);
  394. for (unsigned i = 0; i < p; i++) {
  395. uint16_t val = reduce(in[i] + bias, q, qrecip);
  396. uint16_t residue = reduce(val + adjust, 3, recip3);
  397. out[i] = residue - 1;
  398. }
  399. }
  400. /*
  401. * Given an array of values mod q, round each one to the nearest
  402. * multiple of 3 to its minimum-absolute-value representative.
  403. *
  404. * Output values are signed integers coerced to uint16_t, so again,
  405. * use ntru_normalise afterwards to put them back to normal.
  406. */
  407. void ntru_round3(uint16_t *out, const uint16_t *in, unsigned p, unsigned q)
  408. {
  409. SETUP;
  410. unsigned bias = q/2;
  411. ntru_mod3(out, in, p, q);
  412. for (unsigned i = 0; i < p; i++)
  413. out[i] = REDUCE(in[i] + bias) - bias - out[i];
  414. }
  415. /*
  416. * Given an array of signed integers coerced to uint16_t in the range
  417. * [-q/2,+q/2], normalise them back to mod q values.
  418. */
  419. static void ntru_normalise(uint16_t *out, const uint16_t *in,
  420. unsigned p, unsigned q)
  421. {
  422. for (unsigned i = 0; i < p; i++)
  423. out[i] = in[i] + q * (in[i] >> 15);
  424. }
  425. /*
  426. * Given an array of values mod q, add a constant to each one.
  427. */
  428. void ntru_bias(uint16_t *out, const uint16_t *in, unsigned bias,
  429. unsigned p, unsigned q)
  430. {
  431. SETUP;
  432. for (unsigned i = 0; i < p; i++)
  433. out[i] = REDUCE(in[i] + bias);
  434. }
  435. /*
  436. * Given an array of values mod q, multiply each one by a constant.
  437. */
  438. void ntru_scale(uint16_t *out, const uint16_t *in, uint16_t scale,
  439. unsigned p, unsigned q)
  440. {
  441. SETUP;
  442. for (unsigned i = 0; i < p; i++)
  443. out[i] = REDUCE(in[i] * scale);
  444. }
  445. /*
  446. * Given an array of values mod 3, convert them to values mod q in a
  447. * way that maps -1,0,+1 to -1,0,+1.
  448. */
  449. static void ntru_expand(
  450. uint16_t *out, const uint16_t *in, unsigned p, unsigned q)
  451. {
  452. for (size_t i = 0; i < p; i++) {
  453. uint16_t v = in[i];
  454. /* Map 2 to q-1, and leave 0 and 1 unchanged */
  455. v += (v >> 1) * (q-3);
  456. out[i] = v;
  457. }
  458. }
  459. /* ----------------------------------------------------------------------
  460. * Implement the binary encoding from ntruprime-20201007.pdf, which is
  461. * used to encode public keys and ciphertexts (though not plaintexts,
  462. * which are done in a much simpler way).
  463. *
  464. * The general idea is that your encoder takes as input a list of
  465. * small non-negative integers (r_i), and a sequence of limits (m_i)
  466. * such that 0 <= r_i < m_i, and emits a sequence of bytes that encode
  467. * all of these as tightly as reasonably possible.
  468. *
  469. * That's more general than is really needed, because in both the
  470. * actual uses of this encoding, the input m_i are all the same! But
  471. * the array of (r_i,m_i) pairs evolves during encoding, so they don't
  472. * _stay_ all the same, so you still have to have all the generality.
  473. *
  474. * The encoding process makes a number of passes along the list of
  475. * inputs. In each step, pairs of adjacent numbers are combined into
  476. * one larger one by turning (r_i,m_i) and (r_{i+1},m_{i+1}) into the
  477. * pair (r_i + m_i r_{i+1}, m_i m_{i+1}), i.e. so that the original
  478. * numbers could be recovered by taking the quotient and remaiinder of
  479. * the new r value by m_i. Then, if the new m_i is at least 2^14, we
  480. * emit the low 8 bits of r_i to the output stream and reduce r_i and
  481. * its limit correspondingly. So at the end of the pass, we've got
  482. * half as many numbers still to encode, they're all still not too
  483. * big, and we've emitted some amount of data into the output. Then do
  484. * another pass, keep going until there's only one number left, and
  485. * emit it little-endian.
  486. *
  487. * That's all very well, but how do you decode it again? DJB exhibits
  488. * a pair of recursive functions that are supposed to be mutually
  489. * inverse, but I didn't have any confidence that I'd be able to debug
  490. * them sensibly if they turned out not to be (or rather, if I
  491. * implemented one of them wrong). So I came up with my own strategy
  492. * instead.
  493. *
  494. * In my strategy, we start by processing just the (m_i) into an
  495. * 'encoding schedule' consisting of a sequence of simple
  496. * instructions. The instructions operate on a FIFO queue of numbers,
  497. * initialised to the original (r_i). The three instruction types are:
  498. *
  499. * - 'COMBINE': consume two numbers a,b from the head of the queue,
  500. * combine them by calculating a + m*b for some specified m, and
  501. * push the result on the tail of the queue.
  502. *
  503. * - 'BYTE': divide the tail element of the queue by 2^8 and emit the
  504. * low bits into the output stream.
  505. *
  506. * - 'COPY': pop a number from the head of the queue and push it
  507. * straight back on the tail. (Used for handling the leftover
  508. * element at the end of a pass if the input to the pass was a list
  509. * of odd length.)
  510. *
  511. * So we effectively implement DJB's encoding process in simulation,
  512. * and instead of actually processing a set of (r_i), we 'compile' the
  513. * process into a sequence of instructions that can be handed just the
  514. * (r_i) later and encode them in the right way. At the end of the
  515. * instructions, the queue is expected to have been reduced to length
  516. * 1 and contain the single integer 0.
  517. *
  518. * The nice thing about this system is that each of those three
  519. * instructions is easy to reverse. So you can also use the same
  520. * instructions for decoding: start with a queue containing 0, and
  521. * process the instructions in reverse order and reverse sense. So
  522. * BYTE means to _consume_ a byte from the encoded data (starting from
  523. * the rightmost end) and use it to make a queue element bigger; and
  524. * COMBINE run in reverse pops a single element from one end of the
  525. * queue, divides it by m, and pushes the quotient and remainder on
  526. * the other end.
  527. *
  528. * (So it's easy to debug, because the queue passes through the exact
  529. * same sequence of states during decoding that it did during
  530. * encoding, just in reverse order.)
  531. *
  532. * Also, the encoding schedule comes with information about the
  533. * expected size of the encoded data, because you can find that out
  534. * easily by just counting the BYTE commands.
  535. */
  536. enum {
  537. /*
  538. * Command values appearing in the 'ops' array. ENC_COPY and
  539. * ENC_BYTE are single values; values of the form
  540. * (ENC_COMBINE_BASE + m) represent a COMBINE command with
  541. * parameter m.
  542. */
  543. ENC_COPY, ENC_BYTE, ENC_COMBINE_BASE
  544. };
  545. struct NTRUEncodeSchedule {
  546. /*
  547. * Object representing a compiled set of encoding instructions.
  548. *
  549. * 'nvals' is the number of r_i we expect to encode. 'nops' is the
  550. * number of encoding commands in the 'ops' list; 'opsize' is the
  551. * physical size of the array, used during construction.
  552. *
  553. * 'endpos' is used to avoid a last-minute faff during decoding.
  554. * We implement our FIFO of integers as a ring buffer of size
  555. * 'nvals'. Encoding cycles round it some number of times, and the
  556. * final 0 element ends up at some random location in the array.
  557. * If we know _where_ the 0 ends up during encoding, we can put
  558. * the initial 0 there at the start of decoding, and then when we
  559. * finish reversing all the instructions, we'll end up with the
  560. * output numbers already arranged at their correct positions, so
  561. * that there's no need to rotate the array at the last minute.
  562. */
  563. size_t nvals, endpos, nops, opsize;
  564. uint32_t *ops;
  565. };
  566. static inline void sched_append(NTRUEncodeSchedule *sched, uint16_t op)
  567. {
  568. /* Helper function to append an operation to the schedule, and
  569. * update endpos. */
  570. sgrowarray(sched->ops, sched->opsize, sched->nops);
  571. sched->ops[sched->nops++] = op;
  572. if (op != ENC_BYTE)
  573. sched->endpos = (sched->endpos + 1) % sched->nvals;
  574. }
  575. /*
  576. * Take in the list of limit values (m_i) and compute the encoding
  577. * schedule.
  578. */
  579. NTRUEncodeSchedule *ntru_encode_schedule(const uint16_t *ms_in, size_t n)
  580. {
  581. NTRUEncodeSchedule *sched = snew(NTRUEncodeSchedule);
  582. sched->nvals = n;
  583. sched->endpos = n-1;
  584. sched->nops = sched->opsize = 0;
  585. sched->ops = NULL;
  586. assert(n != 0);
  587. /*
  588. * 'ms' is the list of (m_i) on input to the current pass.
  589. * 'ms_new' is the list output from the current pass. After each
  590. * pass we swap the arrays round.
  591. */
  592. uint32_t *ms = snewn(n, uint32_t);
  593. uint32_t *msnew = snewn(n, uint32_t);
  594. for (size_t i = 0; i < n; i++)
  595. ms[i] = ms_in[i];
  596. while (n > 1) {
  597. size_t nnew = 0;
  598. for (size_t i = 0; i < n; i += 2) {
  599. if (i+1 == n) {
  600. /*
  601. * Odd element at the end of the input list: just copy
  602. * it unchanged to the output.
  603. */
  604. sched_append(sched, ENC_COPY);
  605. msnew[nnew++] = ms[i];
  606. break;
  607. }
  608. /*
  609. * Normal case: consume two elements from the input list
  610. * and combine them.
  611. */
  612. uint32_t m1 = ms[i], m2 = ms[i+1], m = m1*m2;
  613. sched_append(sched, ENC_COMBINE_BASE + m1);
  614. /*
  615. * And then, as long as the combined limit is big enough,
  616. * emit an output byte from the bottom of it.
  617. */
  618. while (m >= (1<<14)) {
  619. sched_append(sched, ENC_BYTE);
  620. m = (m + 0xFF) >> 8;
  621. }
  622. /*
  623. * Whatever is left after that, we emit into the output
  624. * list and append to the fifo.
  625. */
  626. msnew[nnew++] = m;
  627. }
  628. /*
  629. * End of pass. The output list of (m_i) now becomes the input
  630. * list.
  631. */
  632. uint32_t *tmp = ms;
  633. ms = msnew;
  634. n = nnew;
  635. msnew = tmp;
  636. }
  637. /*
  638. * When that loop terminates, it's because there's exactly one
  639. * number left to encode. (Or, technically, _at most_ one - but we
  640. * don't support encoding a completely empty list in this
  641. * implementation, because what would be the point?) That number
  642. * is just emitted little-endian until its limit is 1 (meaning its
  643. * only possible actual value is 0).
  644. */
  645. assert(n == 1);
  646. uint32_t m = ms[0];
  647. while (m > 1) {
  648. sched_append(sched, ENC_BYTE);
  649. m = (m + 0xFF) >> 8;
  650. }
  651. sfree(ms);
  652. sfree(msnew);
  653. return sched;
  654. }
  655. void ntru_encode_schedule_free(NTRUEncodeSchedule *sched)
  656. {
  657. sfree(sched->ops);
  658. sfree(sched);
  659. }
  660. /*
  661. * Calculate the output length of the encoded data in bytes.
  662. */
  663. size_t ntru_encode_schedule_length(NTRUEncodeSchedule *sched)
  664. {
  665. size_t len = 0;
  666. for (size_t i = 0; i < sched->nops; i++)
  667. if (sched->ops[i] == ENC_BYTE)
  668. len++;
  669. return len;
  670. }
  671. /*
  672. * Retrieve the number of items encoded. (Used by testcrypt.)
  673. */
  674. size_t ntru_encode_schedule_nvals(NTRUEncodeSchedule *sched)
  675. {
  676. return sched->nvals;
  677. }
  678. /*
  679. * Actually encode a sequence of (r_i), emitting the output bytes to
  680. * an arbitrary BinarySink.
  681. */
  682. void ntru_encode(NTRUEncodeSchedule *sched, const uint16_t *rs_in,
  683. BinarySink *bs)
  684. {
  685. size_t n = sched->nvals;
  686. uint32_t *rs = snewn(n, uint32_t);
  687. for (size_t i = 0; i < n; i++)
  688. rs[i] = rs_in[i];
  689. /*
  690. * The head and tail pointers of the queue are both 'full'. That
  691. * is, rs[head] is the first element actually in the queue, and
  692. * rs[tail] is the last element.
  693. *
  694. * So you append to the queue by first advancing 'tail' and then
  695. * writing to rs[tail], whereas you consume from the queue by
  696. * first reading rs[head] and _then_ advancing 'head'.
  697. *
  698. * The more normal thing would be to make 'tail' point to the
  699. * first empty slot instead of the last full one. But then you'd
  700. * have to faff about with modular arithmetic to find the last
  701. * full slot for the BYTE command, so in this case, it's easier to
  702. * do it the less usual way.
  703. */
  704. size_t head = 0, tail = n-1;
  705. for (size_t i = 0; i < sched->nops; i++) {
  706. uint16_t op = sched->ops[i];
  707. switch (op) {
  708. case ENC_BYTE:
  709. put_byte(bs, rs[tail] & 0xFF);
  710. rs[tail] >>= 8;
  711. break;
  712. case ENC_COPY: {
  713. uint32_t r = rs[head];
  714. head = (head + 1) % n;
  715. tail = (tail + 1) % n;
  716. rs[tail] = r;
  717. break;
  718. }
  719. default: {
  720. uint32_t r1 = rs[head];
  721. head = (head + 1) % n;
  722. uint32_t r2 = rs[head];
  723. head = (head + 1) % n;
  724. tail = (tail + 1) % n;
  725. rs[tail] = r1 + (op - ENC_COMBINE_BASE) * r2;
  726. break;
  727. }
  728. }
  729. }
  730. /*
  731. * Expect that we've ended up with a single zero in the queue, at
  732. * exactly the position that the setup-time analysis predicted it.
  733. */
  734. assert(head == sched->endpos);
  735. assert(tail == sched->endpos);
  736. assert(rs[head] == 0);
  737. smemclr(rs, n * sizeof(*rs));
  738. sfree(rs);
  739. }
  740. /*
  741. * Decode a ptrlen of binary data into a sequence of (r_i). The data
  742. * is expected to be of exactly the right length (on pain of assertion
  743. * failure).
  744. */
  745. void ntru_decode(NTRUEncodeSchedule *sched, uint16_t *rs_out, ptrlen data)
  746. {
  747. size_t n = sched->nvals;
  748. const uint8_t *base = (const uint8_t *)data.ptr;
  749. const uint8_t *pos = base + data.len;
  750. /*
  751. * Initialise the queue to a single zero, at the 'endpos' position
  752. * that will mean the final output is correctly aligned.
  753. *
  754. * 'head' and 'tail' have the same meanings as in encoding. So
  755. * 'tail' is the location that BYTE modifies and COPY and COMBINE
  756. * consume from, and 'head' is the location that COPY and COMBINE
  757. * push on to. As in encoding, they both point at the extremal
  758. * full slots in the array.
  759. */
  760. uint32_t *rs = snewn(n, uint32_t);
  761. size_t head = sched->endpos, tail = head;
  762. rs[tail] = 0;
  763. for (size_t i = sched->nops; i-- > 0 ;) {
  764. uint16_t op = sched->ops[i];
  765. switch (op) {
  766. case ENC_BYTE: {
  767. assert(pos > base);
  768. uint8_t byte = *--pos;
  769. rs[tail] = (rs[tail] << 8) | byte;
  770. break;
  771. }
  772. case ENC_COPY: {
  773. uint32_t r = rs[tail];
  774. tail = (tail + n - 1) % n;
  775. head = (head + n - 1) % n;
  776. rs[head] = r;
  777. break;
  778. }
  779. default: {
  780. uint32_t r = rs[tail];
  781. tail = (tail + n - 1) % n;
  782. uint32_t m = op - ENC_COMBINE_BASE;
  783. uint64_t mrecip = reciprocal_for_reduction(m);
  784. uint32_t r1, r2;
  785. r1 = reduce_with_quot(r, &r2, m, mrecip);
  786. head = (head + n - 1) % n;
  787. rs[head] = r2;
  788. head = (head + n - 1) % n;
  789. rs[head] = r1;
  790. break;
  791. }
  792. }
  793. }
  794. assert(pos == base);
  795. assert(head == 0);
  796. assert(tail == n-1);
  797. for (size_t i = 0; i < n; i++)
  798. rs_out[i] = rs[i];
  799. smemclr(rs, n * sizeof(*rs));
  800. sfree(rs);
  801. }
  802. /* ----------------------------------------------------------------------
  803. * The actual public-key cryptosystem.
  804. */
  805. struct NTRUKeyPair {
  806. unsigned p, q, w;
  807. uint16_t *h; /* public key */
  808. uint16_t *f3, *ginv; /* private key */
  809. uint16_t *rho; /* for implicit rejection */
  810. };
  811. /* Helper function to free an array of uint16_t containing a ring
  812. * element, clearing it on the way since some of them are sensitive. */
  813. static void ring_free(uint16_t *val, unsigned p)
  814. {
  815. smemclr(val, p*sizeof(*val));
  816. sfree(val);
  817. }
  818. void ntru_keypair_free(NTRUKeyPair *keypair)
  819. {
  820. ring_free(keypair->h, keypair->p);
  821. ring_free(keypair->f3, keypair->p);
  822. ring_free(keypair->ginv, keypair->p);
  823. ring_free(keypair->rho, keypair->p);
  824. sfree(keypair);
  825. }
  826. /* Trivial accessors used by test programs. */
  827. unsigned ntru_keypair_p(NTRUKeyPair *keypair) { return keypair->p; }
  828. const uint16_t *ntru_pubkey(NTRUKeyPair *keypair) { return keypair->h; }
  829. /*
  830. * Generate a value of the class DJB describes as 'Short': it consists
  831. * of p terms that are all either 0 or +1 or -1, and exactly w of them
  832. * are not zero.
  833. *
  834. * Values of this kind are used for several purposes: part of the
  835. * private key, a plaintext, and the 'rho' fake-plaintext value used
  836. * for deliberately returning a duff but non-revealing session hash if
  837. * things go wrong.
  838. *
  839. * -1 is represented as 2 in the output array. So if you want these
  840. * numbers mod 3, then they come out already in the right form.
  841. * Otherwise, use ntru_expand.
  842. */
  843. void ntru_gen_short(uint16_t *v, unsigned p, unsigned w)
  844. {
  845. /*
  846. * Get enough random data to generate a polynomial all of whose p
  847. * terms are in {0,+1,-1}, and exactly w of them are nonzero.
  848. * We'll do this by making up a completely random sequence of
  849. * {+1,-1} and then setting a random subset of them to 0.
  850. *
  851. * So we'll need p random bits to choose the nonzero values, and
  852. * then (doing it the simplest way) log2(p!) bits to shuffle them,
  853. * plus say 128 bits to ensure any fluctuations in uniformity are
  854. * negligible.
  855. *
  856. * log2(p!) is a pain to calculate, so we'll bound it above by
  857. * p*log2(p), which we bound in turn by p*16.
  858. */
  859. size_t randbitpos = 17 * p + 128;
  860. mp_int *randdata = mp_resize(mp_random_bits(randbitpos), randbitpos + 32);
  861. /*
  862. * Initial value before zeroing out some terms: p randomly chosen
  863. * values in {1,2}.
  864. */
  865. for (size_t i = 0; i < p; i++)
  866. v[i] = 1 + mp_get_bit(randdata, --randbitpos);
  867. /*
  868. * Hereafter we're going to extract random bits by multiplication,
  869. * treating randdata as a large fixed-point number.
  870. */
  871. mp_reduce_mod_2to(randdata, randbitpos);
  872. /*
  873. * Zero out some terms, leaving a randomly selected w of them
  874. * nonzero.
  875. */
  876. uint32_t nonzeros_left = w;
  877. mp_int *x = mp_new(64);
  878. for (size_t i = p; i-- > 0 ;) {
  879. /*
  880. * Pick a random number out of the number of terms remaning.
  881. */
  882. mp_mul_integer_into(randdata, randdata, i+1);
  883. mp_rshift_fixed_into(x, randdata, randbitpos);
  884. mp_reduce_mod_2to(randdata, randbitpos);
  885. size_t j = mp_get_integer(x);
  886. /*
  887. * If that's less than nonzeros_left, then we're leaving this
  888. * number nonzero. Otherwise we're zeroing it out.
  889. */
  890. uint32_t keep = (uint32_t)(j - nonzeros_left) >> 31;
  891. v[i] &= -keep; /* clear this field if keep == 0 */
  892. nonzeros_left -= keep; /* decrement counter if keep == 1 */
  893. }
  894. mp_free(x);
  895. mp_free(randdata);
  896. }
  897. /*
  898. * Make a single attempt at generating a key pair. This involves
  899. * inventing random elements of both our quotient rings and hoping
  900. * they're both invertible.
  901. *
  902. * They may not be, if you're unlucky. The element of Z_q/<x^p-x-1>
  903. * will _almost_ certainly be invertible, because that is a field, so
  904. * invertibility can only fail if you were so unlucky as to choose the
  905. * all-0s element. But the element of Z_3/<x^p-x-1> may fail to be
  906. * invertible because it has a common factor with x^p-x-1 (which, over
  907. * Z_3, is not irreducible).
  908. *
  909. * So we can't guarantee to generate a key pair in constant time,
  910. * because there's no predicting how many retries we'll need. However,
  911. * this isn't a failure of side-channel safety, because we completely
  912. * discard all the random numbers and state from each failed attempt.
  913. * So if there were a side-channel leakage from a failure, the only
  914. * thing it would give away would be a bunch of random numbers that
  915. * turned out not to be used anyway.
  916. *
  917. * But a _successful_ call to this function should execute in a
  918. * secret-independent manner, and this 'make a single attempt'
  919. * function is exposed in the API so that 'testsc' can check that.
  920. */
  921. NTRUKeyPair *ntru_keygen_attempt(unsigned p, unsigned q, unsigned w)
  922. {
  923. /*
  924. * First invent g, which is the one more likely to fail to invert.
  925. * This is simply a uniformly random polynomial with p terms over
  926. * Z_3. So we need p*log2(3) random bits for it, plus 128 for
  927. * uniformity. It's easiest to bound log2(3) above by 2.
  928. */
  929. size_t randbitpos = 2 * p + 128;
  930. mp_int *randdata = mp_resize(mp_random_bits(randbitpos), randbitpos + 32);
  931. /*
  932. * Select p random values from {0,1,2}.
  933. */
  934. uint16_t *g = snewn(p, uint16_t);
  935. mp_int *x = mp_new(64);
  936. for (size_t i = 0; i < p; i++) {
  937. mp_mul_integer_into(randdata, randdata, 3);
  938. mp_rshift_fixed_into(x, randdata, randbitpos);
  939. mp_reduce_mod_2to(randdata, randbitpos);
  940. g[i] = mp_get_integer(x);
  941. }
  942. mp_free(x);
  943. mp_free(randdata);
  944. /*
  945. * Try to invert g over Z_3, and fail if it isn't invertible.
  946. */
  947. uint16_t *ginv = snewn(p, uint16_t);
  948. if (!ntru_ring_invert(ginv, g, p, 3)) {
  949. ring_free(g, p);
  950. ring_free(ginv, p);
  951. return NULL;
  952. }
  953. /*
  954. * Fine; we have g. Now make up an f, and convert it to a
  955. * polynomial over q.
  956. */
  957. uint16_t *f = snewn(p, uint16_t);
  958. ntru_gen_short(f, p, w);
  959. ntru_expand(f, f, p, q);
  960. /*
  961. * Multiply f by 3.
  962. */
  963. uint16_t *f3 = snewn(p, uint16_t);
  964. ntru_scale(f3, f, 3, p, q);
  965. /*
  966. * Invert 3*f over Z_q. This is guaranteed to succeed, since
  967. * Z_q/<x^p-x-1> is a field, so the only non-invertible value is
  968. * 0. And f is nonzero because it came from ntru_gen_short (hence,
  969. * w of its components are nonzero), hence so is 3*f.
  970. */
  971. uint16_t *f3inv = snewn(p, uint16_t);
  972. bool expect_always_success = ntru_ring_invert(f3inv, f3, p, q);
  973. assert(expect_always_success);
  974. /*
  975. * Make the public key, by converting g to a polynomial over q and
  976. * then multiplying by f3inv.
  977. */
  978. uint16_t *g_q = snewn(p, uint16_t);
  979. ntru_expand(g_q, g, p, q);
  980. uint16_t *h = snewn(p, uint16_t);
  981. ntru_ring_multiply(h, g_q, f3inv, p, q);
  982. /*
  983. * Make up rho, used to substitute for the plaintext in the
  984. * session hash in case of confirmation failure.
  985. */
  986. uint16_t *rho = snewn(p, uint16_t);
  987. ntru_gen_short(rho, p, w);
  988. /*
  989. * And we're done! Free everything except the pieces we're
  990. * returning.
  991. */
  992. NTRUKeyPair *keypair = snew(NTRUKeyPair);
  993. keypair->p = p;
  994. keypair->q = q;
  995. keypair->w = w;
  996. keypair->h = h;
  997. keypair->f3 = f3;
  998. keypair->ginv = ginv;
  999. keypair->rho = rho;
  1000. ring_free(f, p);
  1001. ring_free(f3inv, p);
  1002. ring_free(g, p);
  1003. ring_free(g_q, p);
  1004. return keypair;
  1005. }
  1006. /*
  1007. * The top-level key generation function for real use (as opposed to
  1008. * testsc): keep trying to make a key until you succeed.
  1009. */
  1010. NTRUKeyPair *ntru_keygen(unsigned p, unsigned q, unsigned w)
  1011. {
  1012. while (1) {
  1013. NTRUKeyPair *keypair = ntru_keygen_attempt(p, q, w);
  1014. if (keypair)
  1015. return keypair;
  1016. }
  1017. }
  1018. /*
  1019. * Public-key encryption.
  1020. */
  1021. void ntru_encrypt(uint16_t *ciphertext, const uint16_t *plaintext,
  1022. uint16_t *pubkey, unsigned p, unsigned q)
  1023. {
  1024. uint16_t *r_q = snewn(p, uint16_t);
  1025. ntru_expand(r_q, plaintext, p, q);
  1026. uint16_t *unrounded = snewn(p, uint16_t);
  1027. ntru_ring_multiply(unrounded, r_q, pubkey, p, q);
  1028. ntru_round3(ciphertext, unrounded, p, q);
  1029. ntru_normalise(ciphertext, ciphertext, p, q);
  1030. ring_free(r_q, p);
  1031. ring_free(unrounded, p);
  1032. }
  1033. /*
  1034. * Public-key decryption.
  1035. */
  1036. void ntru_decrypt(uint16_t *plaintext, const uint16_t *ciphertext,
  1037. NTRUKeyPair *keypair)
  1038. {
  1039. unsigned p = keypair->p, q = keypair->q, w = keypair->w;
  1040. uint16_t *tmp = snewn(p, uint16_t);
  1041. ntru_ring_multiply(tmp, ciphertext, keypair->f3, p, q);
  1042. ntru_mod3(tmp, tmp, p, q);
  1043. ntru_normalise(tmp, tmp, p, 3);
  1044. ntru_ring_multiply(plaintext, tmp, keypair->ginv, p, 3);
  1045. ring_free(tmp, p);
  1046. /*
  1047. * With luck, this should have recovered exactly the original
  1048. * plaintext. But, as per the spec, we check whether it has
  1049. * exactly w nonzero coefficients, and if not, then something has
  1050. * gone wrong - and in that situation we time-safely substitute a
  1051. * different output.
  1052. *
  1053. * (I don't know exactly why we do this, but I assume it's because
  1054. * otherwise the mis-decoded output could be made to disgorge a
  1055. * secret about the private key in some way.)
  1056. */
  1057. unsigned weight = p;
  1058. for (size_t i = 0; i < p; i++)
  1059. weight -= iszero(plaintext[i]);
  1060. unsigned ok = iszero(weight ^ w);
  1061. /*
  1062. * The default failure return value consists of w 1s followed by
  1063. * 0s.
  1064. */
  1065. unsigned mask = ok - 1;
  1066. for (size_t i = 0; i < w; i++) {
  1067. uint16_t diff = (1 ^ plaintext[i]) & mask;
  1068. plaintext[i] ^= diff;
  1069. }
  1070. for (size_t i = w; i < p; i++) {
  1071. uint16_t diff = (0 ^ plaintext[i]) & mask;
  1072. plaintext[i] ^= diff;
  1073. }
  1074. }
  1075. /* ----------------------------------------------------------------------
  1076. * Encode and decode public keys, ciphertexts and plaintexts.
  1077. *
  1078. * Public keys and ciphertexts use the complicated binary encoding
  1079. * system implemented above. In both cases, the inputs are regarded as
  1080. * symmetric about zero, and are first biased to map their most
  1081. * negative permitted value to 0, so that they become non-negative and
  1082. * hence suitable as inputs to the encoding system. In the case of a
  1083. * ciphertext, where the input coefficients have also been coerced to
  1084. * be multiples of 3, we divide by 3 as well, saving space by reducing
  1085. * the upper bounds (m_i) on all the encoded numbers.
  1086. */
  1087. /*
  1088. * Compute the encoding schedule for a public key.
  1089. */
  1090. static NTRUEncodeSchedule *ntru_encode_pubkey_schedule(unsigned p, unsigned q)
  1091. {
  1092. uint16_t *ms = snewn(p, uint16_t);
  1093. for (size_t i = 0; i < p; i++)
  1094. ms[i] = q;
  1095. NTRUEncodeSchedule *sched = ntru_encode_schedule(ms, p);
  1096. sfree(ms);
  1097. return sched;
  1098. }
  1099. /*
  1100. * Encode a public key.
  1101. */
  1102. void ntru_encode_pubkey(const uint16_t *pubkey, unsigned p, unsigned q,
  1103. BinarySink *bs)
  1104. {
  1105. /* Compute the biased version for encoding */
  1106. uint16_t *biased_pubkey = snewn(p, uint16_t);
  1107. ntru_bias(biased_pubkey, pubkey, q / 2, p, q);
  1108. /* Encode it */
  1109. NTRUEncodeSchedule *sched = ntru_encode_pubkey_schedule(p, q);
  1110. ntru_encode(sched, biased_pubkey, bs);
  1111. ntru_encode_schedule_free(sched);
  1112. ring_free(biased_pubkey, p);
  1113. }
  1114. /*
  1115. * Decode a public key and write it into 'pubkey'. We also return a
  1116. * ptrlen pointing at the chunk of data we removed from the
  1117. * BinarySource.
  1118. */
  1119. ptrlen ntru_decode_pubkey(uint16_t *pubkey, unsigned p, unsigned q,
  1120. BinarySource *src)
  1121. {
  1122. NTRUEncodeSchedule *sched = ntru_encode_pubkey_schedule(p, q);
  1123. /* Retrieve the right number of bytes from the source */
  1124. size_t len = ntru_encode_schedule_length(sched);
  1125. ptrlen encoded = get_data(src, len);
  1126. if (get_err(src)) {
  1127. /* If there wasn't enough data, give up and return all-zeroes
  1128. * purely for determinism. But that value should never be
  1129. * used, because the caller will also check get_err(src). */
  1130. memset(pubkey, 0, p*sizeof(*pubkey));
  1131. } else {
  1132. /* Do the decoding */
  1133. ntru_decode(sched, pubkey, encoded);
  1134. /* Unbias the coefficients */
  1135. ntru_bias(pubkey, pubkey, q-q/2, p, q);
  1136. }
  1137. ntru_encode_schedule_free(sched);
  1138. return encoded;
  1139. }
  1140. /*
  1141. * For ciphertext biasing: work out the largest absolute value a
  1142. * ciphertext element can take, which is given by taking q/2 and
  1143. * rounding it to the nearest multiple of 3.
  1144. */
  1145. static inline unsigned ciphertext_bias(unsigned q)
  1146. {
  1147. return (q/2+1) / 3;
  1148. }
  1149. /*
  1150. * The number of possible values of a ciphertext coefficient (for use
  1151. * as the m_i in encoding) ranges from +ciphertext_bias(q) to
  1152. * -ciphertext_bias(q) inclusive.
  1153. */
  1154. static inline unsigned ciphertext_m(unsigned q)
  1155. {
  1156. return 1 + 2 * ciphertext_bias(q);
  1157. }
  1158. /*
  1159. * Compute the encoding schedule for a ciphertext.
  1160. */
  1161. static NTRUEncodeSchedule *ntru_encode_ciphertext_schedule(
  1162. unsigned p, unsigned q)
  1163. {
  1164. unsigned m = ciphertext_m(q);
  1165. uint16_t *ms = snewn(p, uint16_t);
  1166. for (size_t i = 0; i < p; i++)
  1167. ms[i] = m;
  1168. NTRUEncodeSchedule *sched = ntru_encode_schedule(ms, p);
  1169. sfree(ms);
  1170. return sched;
  1171. }
  1172. /*
  1173. * Encode a ciphertext.
  1174. */
  1175. void ntru_encode_ciphertext(const uint16_t *ciphertext, unsigned p, unsigned q,
  1176. BinarySink *bs)
  1177. {
  1178. SETUP;
  1179. /*
  1180. * Bias the ciphertext, and scale down by 1/3, which we do by
  1181. * modular multiplication by the inverse of 3 mod q. (That only
  1182. * works if we know the inputs are all _exact_ multiples of 3
  1183. * - but we do!)
  1184. */
  1185. uint16_t *biased_ciphertext = snewn(p, uint16_t);
  1186. ntru_bias(biased_ciphertext, ciphertext, 3 * ciphertext_bias(q), p, q);
  1187. ntru_scale(biased_ciphertext, biased_ciphertext, INVERT(3), p, q);
  1188. /* Encode. */
  1189. NTRUEncodeSchedule *sched = ntru_encode_ciphertext_schedule(p, q);
  1190. ntru_encode(sched, biased_ciphertext, bs);
  1191. ntru_encode_schedule_free(sched);
  1192. ring_free(biased_ciphertext, p);
  1193. }
  1194. ptrlen ntru_decode_ciphertext(uint16_t *ct, NTRUKeyPair *keypair,
  1195. BinarySource *src)
  1196. {
  1197. unsigned p = keypair->p, q = keypair->q;
  1198. NTRUEncodeSchedule *sched = ntru_encode_ciphertext_schedule(p, q);
  1199. /* Retrieve the right number of bytes from the source */
  1200. size_t len = ntru_encode_schedule_length(sched);
  1201. ptrlen encoded = get_data(src, len);
  1202. if (get_err(src)) {
  1203. /* As above, return deterministic nonsense on failure */
  1204. memset(ct, 0, p*sizeof(*ct));
  1205. } else {
  1206. /* Do the decoding */
  1207. ntru_decode(sched, ct, encoded);
  1208. /* Undo the scaling and bias */
  1209. ntru_scale(ct, ct, 3, p, q);
  1210. ntru_bias(ct, ct, q - 3 * ciphertext_bias(q), p, q);
  1211. }
  1212. ntru_encode_schedule_free(sched);
  1213. return encoded; /* also useful to the caller, optionally */
  1214. }
  1215. /*
  1216. * Encode a plaintext.
  1217. *
  1218. * This is a much simpler encoding than the NTRUEncodeSchedule system:
  1219. * since elements of a plaintext are mod 3, we just encode each one in
  1220. * 2 bits, applying the usual bias so that {-1,0,+1} map to {0,1,2}
  1221. * respectively.
  1222. *
  1223. * There's no corresponding decode function, because plaintexts are
  1224. * never transmitted on the wire (the whole point is that they're too
  1225. * secret!). Plaintexts are only encoded in order to put them into
  1226. * hash preimages.
  1227. */
  1228. void ntru_encode_plaintext(const uint16_t *plaintext, unsigned p,
  1229. BinarySink *bs)
  1230. {
  1231. unsigned byte = 0, bitpos = 0;
  1232. for (size_t i = 0; i < p; i++) {
  1233. unsigned encoding = (plaintext[i] + 1) * iszero(plaintext[i] >> 1);
  1234. byte |= encoding << bitpos;
  1235. bitpos += 2;
  1236. if (bitpos == 8 || i+1 == p) {
  1237. put_byte(bs, byte);
  1238. byte = 0;
  1239. bitpos = 0;
  1240. }
  1241. }
  1242. }
  1243. /* ----------------------------------------------------------------------
  1244. * Compute the hashes required by the key exchange layer of NTRU Prime.
  1245. *
  1246. * There are two of these. The 'confirmation hash' is sent by the
  1247. * server along with the ciphertext, and the client can recalculate it
  1248. * to check whether the ciphertext was decrypted correctly. Then, the
  1249. * 'session hash' is the actual output of key exchange, and if the
  1250. * confirmation hash doesn't match, it gets deliberately corrupted.
  1251. */
  1252. /*
  1253. * Make the confirmation hash, whose inputs are the plaintext and the
  1254. * public key.
  1255. *
  1256. * This is defined as H(2 || H(3 || r) || H(4 || K)), where r is the
  1257. * plaintext and K is the public key (as encoded by the above
  1258. * functions), and the constants 2,3,4 are single bytes. The choice of
  1259. * hash function (H itself) is SHA-512 truncated to 256 bits.
  1260. *
  1261. * (To be clear: that is _not_ the thing that FIPS 180-4 6.7 defines
  1262. * as "SHA-512/256", which varies the initialisation vector of the
  1263. * SHA-512 algorithm as well as truncating the output. _This_
  1264. * algorithm uses the standard SHA-512 IV, and _just_ truncates the
  1265. * output, in the manner suggested by FIPS 180-4 section 7.)
  1266. *
  1267. * 'out' should therefore expect to receive 32 bytes of data.
  1268. */
  1269. static void ntru_confirmation_hash(
  1270. uint8_t *out, const uint16_t *plaintext,
  1271. const uint16_t *pubkey, unsigned p, unsigned q)
  1272. {
  1273. /* The outer hash object */
  1274. ssh_hash *hconfirm = ssh_hash_new(&ssh_sha512);
  1275. put_byte(hconfirm, 2); /* initial byte 2 */
  1276. uint8_t hashdata[64];
  1277. /* Compute H(3 || r) and add it to the main hash */
  1278. ssh_hash *h3r = ssh_hash_new(&ssh_sha512);
  1279. put_byte(h3r, 3);
  1280. ntru_encode_plaintext(plaintext, p, BinarySink_UPCAST(h3r));
  1281. ssh_hash_final(h3r, hashdata);
  1282. put_data(hconfirm, hashdata, 32);
  1283. /* Compute H(4 || K) and add it to the main hash */
  1284. ssh_hash *h4K = ssh_hash_new(&ssh_sha512);
  1285. put_byte(h4K, 4);
  1286. ntru_encode_pubkey(pubkey, p, q, BinarySink_UPCAST(h4K));
  1287. ssh_hash_final(h4K, hashdata);
  1288. put_data(hconfirm, hashdata, 32);
  1289. /* Compute the full output of the main SHA-512 hash */
  1290. ssh_hash_final(hconfirm, hashdata);
  1291. /* And copy the first 32 bytes into the caller's output array */
  1292. memcpy(out, hashdata, 32);
  1293. smemclr(hashdata, sizeof(hashdata));
  1294. }
  1295. /*
  1296. * Make the session hash, whose inputs are the plaintext, the
  1297. * ciphertext, and the confirmation hash (hence, transitively, a
  1298. * dependence on the public key as well).
  1299. *
  1300. * As computed by the server, and by the client if the confirmation
  1301. * hash matched, this is defined as
  1302. *
  1303. * H(1 || H(3 || r) || ciphertext || confirmation hash)
  1304. *
  1305. * but if the confirmation hash _didn't_ match, then the plaintext r
  1306. * is replaced with the dummy plaintext-shaped value 'rho' we invented
  1307. * during key generation (presumably to avoid leaking any information
  1308. * about our secrets), and the initial byte 1 is replaced with 0 (to
  1309. * ensure that the resulting hash preimage can't match any legitimate
  1310. * preimage). So in that case, you instead get
  1311. *
  1312. * H(0 || H(3 || rho) || ciphertext || confirmation hash)
  1313. *
  1314. * The inputs to this function include 'ok', which is the value to use
  1315. * as the initial byte (1 on success, 0 on failure), and 'plaintext'
  1316. * which should already have been substituted with rho in case of
  1317. * failure.
  1318. *
  1319. * The ciphertext is provided in already-encoded form.
  1320. */
  1321. static void ntru_session_hash(
  1322. uint8_t *out, unsigned ok, const uint16_t *plaintext,
  1323. unsigned p, ptrlen ciphertext, ptrlen confirmation_hash)
  1324. {
  1325. /* The outer hash object */
  1326. ssh_hash *hsession = ssh_hash_new(&ssh_sha512);
  1327. put_byte(hsession, ok); /* initial byte 1 or 0 */
  1328. uint8_t hashdata[64];
  1329. /* Compute H(3 || r), or maybe H(3 || rho), and add it to the main hash */
  1330. ssh_hash *h3r = ssh_hash_new(&ssh_sha512);
  1331. put_byte(h3r, 3);
  1332. ntru_encode_plaintext(plaintext, p, BinarySink_UPCAST(h3r));
  1333. ssh_hash_final(h3r, hashdata);
  1334. put_data(hsession, hashdata, 32);
  1335. /* Put the ciphertext and confirmation hash in */
  1336. put_datapl(hsession, ciphertext);
  1337. put_datapl(hsession, confirmation_hash);
  1338. /* Compute the full output of the main SHA-512 hash */
  1339. ssh_hash_final(hsession, hashdata);
  1340. /* And copy the first 32 bytes into the caller's output array */
  1341. memcpy(out, hashdata, 32);
  1342. smemclr(hashdata, sizeof(hashdata));
  1343. }
  1344. /* ----------------------------------------------------------------------
  1345. * Top-level key exchange and SSH integration.
  1346. *
  1347. * Although this system borrows the ECDH packet structure, it's unlike
  1348. * true ECDH in that it is completely asymmetric between client and
  1349. * server. So we have two separate vtables of methods for the two
  1350. * sides of the system, and a third vtable containing only the class
  1351. * methods, in particular a constructor which chooses which one to
  1352. * instantiate.
  1353. */
  1354. /*
  1355. * The parameters p,q,w for the system. There are other choices of
  1356. * these, but OpenSSH only specifies this set. (If that ever changes,
  1357. * we'll need to turn these into elements of the state structures.)
  1358. */
  1359. #define p_LIVE 761
  1360. #define q_LIVE 4591
  1361. #define w_LIVE 286
  1362. static char *ssh_ntru_description(const ssh_kex *kex)
  1363. {
  1364. return dupprintf("NTRU Prime / Curve25519 hybrid key exchange");
  1365. }
  1366. /*
  1367. * State structure for the client, which takes the role of inventing a
  1368. * key pair and decrypting a secret plaintext sent to it by the server.
  1369. */
  1370. typedef struct ntru_client_key {
  1371. NTRUKeyPair *keypair;
  1372. ecdh_key *curve25519;
  1373. ecdh_key ek;
  1374. } ntru_client_key;
  1375. static void ssh_ntru_client_free(ecdh_key *dh);
  1376. static void ssh_ntru_client_getpublic(ecdh_key *dh, BinarySink *bs);
  1377. static bool ssh_ntru_client_getkey(ecdh_key *dh, ptrlen remoteKey,
  1378. BinarySink *bs);
  1379. static const ecdh_keyalg ssh_ntru_client_vt = {
  1380. /* This vtable has no 'new' method, because it's constructed via
  1381. * the selector vt below */
  1382. .free = ssh_ntru_client_free,
  1383. .getpublic = ssh_ntru_client_getpublic,
  1384. .getkey = ssh_ntru_client_getkey,
  1385. .description = ssh_ntru_description,
  1386. };
  1387. static ecdh_key *ssh_ntru_client_new(void)
  1388. {
  1389. ntru_client_key *nk = snew(ntru_client_key);
  1390. nk->ek.vt = &ssh_ntru_client_vt;
  1391. nk->keypair = ntru_keygen(p_LIVE, q_LIVE, w_LIVE);
  1392. nk->curve25519 = ecdh_key_new(&ssh_ec_kex_curve25519, false);
  1393. return &nk->ek;
  1394. }
  1395. static void ssh_ntru_client_free(ecdh_key *dh)
  1396. {
  1397. ntru_client_key *nk = container_of(dh, ntru_client_key, ek);
  1398. ntru_keypair_free(nk->keypair);
  1399. ecdh_key_free(nk->curve25519);
  1400. sfree(nk);
  1401. }
  1402. static void ssh_ntru_client_getpublic(ecdh_key *dh, BinarySink *bs)
  1403. {
  1404. ntru_client_key *nk = container_of(dh, ntru_client_key, ek);
  1405. /*
  1406. * The client's public information is a single SSH string
  1407. * containing the NTRU public key and the Curve25519 public point
  1408. * concatenated. So write both of those into the output
  1409. * BinarySink.
  1410. */
  1411. ntru_encode_pubkey(nk->keypair->h, p_LIVE, q_LIVE, bs);
  1412. ecdh_key_getpublic(nk->curve25519, bs);
  1413. }
  1414. static bool ssh_ntru_client_getkey(ecdh_key *dh, ptrlen remoteKey,
  1415. BinarySink *bs)
  1416. {
  1417. ntru_client_key *nk = container_of(dh, ntru_client_key, ek);
  1418. /*
  1419. * We expect the server to have sent us a string containing a
  1420. * ciphertext, a confirmation hash, and a Curve25519 public point.
  1421. * Extract all three.
  1422. */
  1423. BinarySource src[1];
  1424. BinarySource_BARE_INIT_PL(src, remoteKey);
  1425. uint16_t *ciphertext = snewn(p_LIVE, uint16_t);
  1426. ptrlen ciphertext_encoded = ntru_decode_ciphertext(
  1427. ciphertext, nk->keypair, src);
  1428. ptrlen confirmation_hash = get_data(src, 32);
  1429. ptrlen curve25519_remoteKey = get_data(src, 32);
  1430. if (get_err(src) || get_avail(src)) {
  1431. /* Hard-fail if the input wasn't exactly the right length */
  1432. ring_free(ciphertext, p_LIVE);
  1433. return false;
  1434. }
  1435. /*
  1436. * Main hash object which will combine the NTRU and Curve25519
  1437. * outputs.
  1438. */
  1439. ssh_hash *h = ssh_hash_new(&ssh_sha512);
  1440. /* Reusable buffer for storing various hash outputs. */
  1441. uint8_t hashdata[64];
  1442. /*
  1443. * NTRU side.
  1444. */
  1445. {
  1446. /* Decrypt the ciphertext to recover the server's plaintext */
  1447. uint16_t *plaintext = snewn(p_LIVE, uint16_t);
  1448. ntru_decrypt(plaintext, ciphertext, nk->keypair);
  1449. /* Make the confirmation hash */
  1450. ntru_confirmation_hash(hashdata, plaintext, nk->keypair->h,
  1451. p_LIVE, q_LIVE);
  1452. /* Check it matches the one the server sent */
  1453. unsigned ok = smemeq(hashdata, confirmation_hash.ptr, 32);
  1454. /* If not, substitute in rho for the plaintext in the session hash */
  1455. unsigned mask = ok-1;
  1456. for (size_t i = 0; i < p_LIVE; i++)
  1457. plaintext[i] ^= mask & (plaintext[i] ^ nk->keypair->rho[i]);
  1458. /* Compute the session hash, whether or not we did that */
  1459. ntru_session_hash(hashdata, ok, plaintext, p_LIVE, ciphertext_encoded,
  1460. confirmation_hash);
  1461. /* Free temporary values */
  1462. ring_free(plaintext, p_LIVE);
  1463. ring_free(ciphertext, p_LIVE);
  1464. /* And put the NTRU session hash into the main hash object. */
  1465. put_data(h, hashdata, 32);
  1466. }
  1467. /*
  1468. * Curve25519 side.
  1469. */
  1470. {
  1471. strbuf *otherkey = strbuf_new_nm();
  1472. /* Call out to Curve25519 to compute the shared secret from that
  1473. * kex method */
  1474. bool ok = ecdh_key_getkey(nk->curve25519, curve25519_remoteKey,
  1475. BinarySink_UPCAST(otherkey));
  1476. /* If that failed (which only happens if the other end does
  1477. * something wrong, like sending a low-order curve point
  1478. * outside the subgroup it's supposed to), we might as well
  1479. * just abort and return failure. That's what we'd have done
  1480. * in standalone Curve25519. */
  1481. if (!ok) {
  1482. ssh_hash_free(h);
  1483. smemclr(hashdata, sizeof(hashdata));
  1484. strbuf_free(otherkey);
  1485. return false;
  1486. }
  1487. /*
  1488. * ecdh_key_getkey will have returned us a chunk of data
  1489. * containing an encoded mpint, which is how the Curve25519
  1490. * output normally goes into the exchange hash. But in this
  1491. * context we want to treat it as a fixed big-endian 32 bytes,
  1492. * so extract it from its encoding and put it into the main
  1493. * hash object in the new format.
  1494. */
  1495. BinarySource src[1];
  1496. BinarySource_BARE_INIT_PL(src, ptrlen_from_strbuf(otherkey));
  1497. mp_int *curvekey = get_mp_ssh2(src);
  1498. for (unsigned i = 32; i-- > 0 ;)
  1499. put_byte(h, mp_get_byte(curvekey, i));
  1500. mp_free(curvekey);
  1501. strbuf_free(otherkey);
  1502. }
  1503. /*
  1504. * Finish up: compute the final output hash (full 64 bytes of
  1505. * SHA-512 this time), and return it encoded as a string.
  1506. */
  1507. ssh_hash_final(h, hashdata);
  1508. put_stringpl(bs, make_ptrlen(hashdata, sizeof(hashdata)));
  1509. smemclr(hashdata, sizeof(hashdata));
  1510. return true;
  1511. }
  1512. /*
  1513. * State structure for the server, which takes the role of inventing a
  1514. * secret plaintext and sending it to the client encrypted with the
  1515. * public key the client sent.
  1516. */
  1517. typedef struct ntru_server_key {
  1518. uint16_t *plaintext;
  1519. strbuf *ciphertext_encoded, *confirmation_hash;
  1520. ecdh_key *curve25519;
  1521. ecdh_key ek;
  1522. } ntru_server_key;
  1523. static void ssh_ntru_server_free(ecdh_key *dh);
  1524. static void ssh_ntru_server_getpublic(ecdh_key *dh, BinarySink *bs);
  1525. static bool ssh_ntru_server_getkey(ecdh_key *dh, ptrlen remoteKey,
  1526. BinarySink *bs);
  1527. static const ecdh_keyalg ssh_ntru_server_vt = {
  1528. /* This vtable has no 'new' method, because it's constructed via
  1529. * the selector vt below */
  1530. .free = ssh_ntru_server_free,
  1531. .getpublic = ssh_ntru_server_getpublic,
  1532. .getkey = ssh_ntru_server_getkey,
  1533. .description = ssh_ntru_description,
  1534. };
  1535. static ecdh_key *ssh_ntru_server_new(void)
  1536. {
  1537. ntru_server_key *nk = snew(ntru_server_key);
  1538. nk->ek.vt = &ssh_ntru_server_vt;
  1539. nk->plaintext = snewn(p_LIVE, uint16_t);
  1540. nk->ciphertext_encoded = strbuf_new_nm();
  1541. nk->confirmation_hash = strbuf_new_nm();
  1542. ntru_gen_short(nk->plaintext, p_LIVE, w_LIVE);
  1543. nk->curve25519 = ecdh_key_new(&ssh_ec_kex_curve25519, false);
  1544. return &nk->ek;
  1545. }
  1546. static void ssh_ntru_server_free(ecdh_key *dh)
  1547. {
  1548. ntru_server_key *nk = container_of(dh, ntru_server_key, ek);
  1549. ring_free(nk->plaintext, p_LIVE);
  1550. strbuf_free(nk->ciphertext_encoded);
  1551. strbuf_free(nk->confirmation_hash);
  1552. ecdh_key_free(nk->curve25519);
  1553. sfree(nk);
  1554. }
  1555. static bool ssh_ntru_server_getkey(ecdh_key *dh, ptrlen remoteKey,
  1556. BinarySink *bs)
  1557. {
  1558. ntru_server_key *nk = container_of(dh, ntru_server_key, ek);
  1559. /*
  1560. * In the server, getkey is called first, with the public
  1561. * information received from the client. We expect the client to
  1562. * have sent us a string containing a public key and a Curve25519
  1563. * public point.
  1564. */
  1565. BinarySource src[1];
  1566. BinarySource_BARE_INIT_PL(src, remoteKey);
  1567. uint16_t *pubkey = snewn(p_LIVE, uint16_t);
  1568. ntru_decode_pubkey(pubkey, p_LIVE, q_LIVE, src);
  1569. ptrlen curve25519_remoteKey = get_data(src, 32);
  1570. if (get_err(src) || get_avail(src)) {
  1571. /* Hard-fail if the input wasn't exactly the right length */
  1572. ring_free(pubkey, p_LIVE);
  1573. return false;
  1574. }
  1575. /*
  1576. * Main hash object which will combine the NTRU and Curve25519
  1577. * outputs.
  1578. */
  1579. ssh_hash *h = ssh_hash_new(&ssh_sha512);
  1580. /* Reusable buffer for storing various hash outputs. */
  1581. uint8_t hashdata[64];
  1582. /*
  1583. * NTRU side.
  1584. */
  1585. {
  1586. /* Encrypt the plaintext we generated at construction time,
  1587. * and encode the ciphertext into a strbuf so we can reuse it
  1588. * for both the session hash and sending to the client. */
  1589. uint16_t *ciphertext = snewn(p_LIVE, uint16_t);
  1590. ntru_encrypt(ciphertext, nk->plaintext, pubkey, p_LIVE, q_LIVE);
  1591. ntru_encode_ciphertext(ciphertext, p_LIVE, q_LIVE,
  1592. BinarySink_UPCAST(nk->ciphertext_encoded));
  1593. ring_free(ciphertext, p_LIVE);
  1594. /* Compute the confirmation hash, and write it into another
  1595. * strbuf. */
  1596. ntru_confirmation_hash(hashdata, nk->plaintext, pubkey,
  1597. p_LIVE, q_LIVE);
  1598. put_data(nk->confirmation_hash, hashdata, 32);
  1599. /* Compute the session hash (which is easy on the server side,
  1600. * requiring no conditional substitution). */
  1601. ntru_session_hash(hashdata, 1, nk->plaintext, p_LIVE,
  1602. ptrlen_from_strbuf(nk->ciphertext_encoded),
  1603. ptrlen_from_strbuf(nk->confirmation_hash));
  1604. /* And put the NTRU session hash into the main hash object. */
  1605. put_data(h, hashdata, 32);
  1606. /* Now we can free the public key */
  1607. ring_free(pubkey, p_LIVE);
  1608. }
  1609. /*
  1610. * Curve25519 side.
  1611. */
  1612. {
  1613. strbuf *otherkey = strbuf_new_nm();
  1614. /* Call out to Curve25519 to compute the shared secret from that
  1615. * kex method */
  1616. bool ok = ecdh_key_getkey(nk->curve25519, curve25519_remoteKey,
  1617. BinarySink_UPCAST(otherkey));
  1618. /* As on the client side, abort if Curve25519 reported failure */
  1619. if (!ok) {
  1620. ssh_hash_free(h);
  1621. smemclr(hashdata, sizeof(hashdata));
  1622. strbuf_free(otherkey);
  1623. return false;
  1624. }
  1625. /* As on the client side, decode Curve25519's mpint so we can
  1626. * re-encode it appropriately for our hash preimage */
  1627. BinarySource src[1];
  1628. BinarySource_BARE_INIT_PL(src, ptrlen_from_strbuf(otherkey));
  1629. mp_int *curvekey = get_mp_ssh2(src);
  1630. for (unsigned i = 32; i-- > 0 ;)
  1631. put_byte(h, mp_get_byte(curvekey, i));
  1632. mp_free(curvekey);
  1633. strbuf_free(otherkey);
  1634. }
  1635. /*
  1636. * Finish up: compute the final output hash (full 64 bytes of
  1637. * SHA-512 this time), and return it encoded as a string.
  1638. */
  1639. ssh_hash_final(h, hashdata);
  1640. put_stringpl(bs, make_ptrlen(hashdata, sizeof(hashdata)));
  1641. smemclr(hashdata, sizeof(hashdata));
  1642. return true;
  1643. }
  1644. static void ssh_ntru_server_getpublic(ecdh_key *dh, BinarySink *bs)
  1645. {
  1646. ntru_server_key *nk = container_of(dh, ntru_server_key, ek);
  1647. /*
  1648. * In the server, this function is called after getkey, so we
  1649. * already have all our pieces prepared. Just concatenate them all
  1650. * into the 'server's public data' string to go in ECDH_REPLY.
  1651. */
  1652. put_datapl(bs, ptrlen_from_strbuf(nk->ciphertext_encoded));
  1653. put_datapl(bs, ptrlen_from_strbuf(nk->confirmation_hash));
  1654. ecdh_key_getpublic(nk->curve25519, bs);
  1655. }
  1656. /* ----------------------------------------------------------------------
  1657. * Selector vtable that instantiates the appropriate one of the above,
  1658. * depending on is_server.
  1659. */
  1660. static ecdh_key *ssh_ntru_new(const ssh_kex *kex, bool is_server)
  1661. {
  1662. if (is_server)
  1663. return ssh_ntru_server_new();
  1664. else
  1665. return ssh_ntru_client_new();
  1666. }
  1667. static const ecdh_keyalg ssh_ntru_selector_vt = {
  1668. /* This is a never-instantiated vtable which only implements the
  1669. * functions that don't require an instance. */
  1670. .new = ssh_ntru_new,
  1671. .description = ssh_ntru_description,
  1672. };
  1673. static const ssh_kex ssh_ntru_curve25519 = {
  1674. .name = "sntrup761x25519-sha512@openssh.com",
  1675. .main_type = KEXTYPE_ECDH,
  1676. .hash = &ssh_sha512,
  1677. .ecdh_vt = &ssh_ntru_selector_vt,
  1678. };
  1679. static const ssh_kex *const hybrid_list[] = {
  1680. &ssh_ntru_curve25519,
  1681. };
  1682. const ssh_kexes ssh_ntru_hybrid_kex = { lenof(hybrid_list), hybrid_list };