argon2.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. /*
  2. * Implementation of the Argon2 password hash function.
  3. *
  4. * My sources for the algorithm description and test vectors (the latter in
  5. * test/cryptsuite.py) were the reference implementation on Github, and also
  6. * the Internet-Draft description:
  7. *
  8. * https://github.com/P-H-C/phc-winner-argon2
  9. * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-argon2-13
  10. */
  11. #include <assert.h>
  12. #include "putty.h"
  13. #include "ssh.h"
  14. #include "marshal.h"
  15. /* ----------------------------------------------------------------------
  16. * Argon2 uses data marshalling rules similar to SSH but with 32-bit integers
  17. * stored little-endian. Start with some local BinarySink routines for storing
  18. * a uint32 and a string in that fashion.
  19. */
  20. static void BinarySink_put_uint32_le(BinarySink *bs, unsigned long val)
  21. {
  22. unsigned char data[4];
  23. PUT_32BIT_LSB_FIRST(data, val);
  24. bs->write(bs, data, sizeof(data));
  25. }
  26. static void BinarySink_put_stringpl_le(BinarySink *bs, ptrlen pl)
  27. {
  28. /* Check that the string length fits in a uint32, without doing a
  29. * potentially implementation-defined shift of more than 31 bits */
  30. assert((pl.len >> 31) < 2);
  31. BinarySink_put_uint32_le(bs, pl.len);
  32. bs->write(bs, pl.ptr, pl.len);
  33. }
  34. #define put_uint32_le(bs, val) \
  35. BinarySink_put_uint32_le(BinarySink_UPCAST(bs), val)
  36. #define put_stringpl_le(bs, val) \
  37. BinarySink_put_stringpl_le(BinarySink_UPCAST(bs), val)
  38. /* ----------------------------------------------------------------------
  39. * Argon2 defines a hash-function family that's an extension of BLAKE2b to
  40. * generate longer output digests, by repeatedly outputting half of a BLAKE2
  41. * hash output and then re-hashing the whole thing until there are 64 or fewer
  42. * bytes left to output. The spec calls this H' (a variant of the original
  43. * hash it calls H, which is the unmodified BLAKE2b).
  44. */
  45. static ssh_hash *hprime_new(unsigned length)
  46. {
  47. ssh_hash *h = blake2b_new_general(length > 64 ? 64 : length);
  48. put_uint32_le(h, length);
  49. return h;
  50. }
  51. static void hprime_final(ssh_hash *h, unsigned length, void *vout)
  52. {
  53. uint8_t *out = (uint8_t *)vout;
  54. while (length > 64) {
  55. uint8_t hashbuf[64];
  56. ssh_hash_final(h, hashbuf);
  57. memcpy(out, hashbuf, 32);
  58. out += 32;
  59. length -= 32;
  60. h = blake2b_new_general(length > 64 ? 64 : length);
  61. put_data(h, hashbuf, 64);
  62. smemclr(hashbuf, sizeof(hashbuf));
  63. }
  64. ssh_hash_final(h, out);
  65. }
  66. /* Externally visible entry point for the long hash function. This is only
  67. * used by testcrypt, so it would be overkill to set it up like a proper
  68. * ssh_hash. */
  69. strbuf *argon2_long_hash(unsigned length, ptrlen data)
  70. {
  71. ssh_hash *h = hprime_new(length);
  72. put_datapl(h, data);
  73. strbuf *out = strbuf_new();
  74. hprime_final(h, length, strbuf_append(out, length));
  75. return out;
  76. }
  77. /* ----------------------------------------------------------------------
  78. * Argon2's own mixing function G, which operates on 1Kb blocks of data.
  79. *
  80. * The definition of G in the spec takes two 1Kb blocks as input and produces
  81. * a 1Kb output block. The first thing that happens to the input blocks is
  82. * that they get XORed together, and then only the XOR output is used, so you
  83. * could perfectly well regard G as a 1Kb->1Kb function.
  84. */
  85. static inline uint64_t ror(uint64_t x, unsigned rotation)
  86. {
  87. unsigned lshift = 63 & -rotation, rshift = 63 & rotation;
  88. return (x << lshift) | (x >> rshift);
  89. }
  90. static inline uint64_t trunc32(uint64_t x)
  91. {
  92. return x & 0xFFFFFFFF;
  93. }
  94. /* Internal function similar to the BLAKE2b round, which mixes up four 64-bit
  95. * words */
  96. static inline void GB(uint64_t *a, uint64_t *b, uint64_t *c, uint64_t *d)
  97. {
  98. *a += *b + 2 * trunc32(*a) * trunc32(*b);
  99. *d = ror(*d ^ *a, 32);
  100. *c += *d + 2 * trunc32(*c) * trunc32(*d);
  101. *b = ror(*b ^ *c, 24);
  102. *a += *b + 2 * trunc32(*a) * trunc32(*b);
  103. *d = ror(*d ^ *a, 16);
  104. *c += *d + 2 * trunc32(*c) * trunc32(*d);
  105. *b = ror(*b ^ *c, 63);
  106. }
  107. /* Higher-level internal function which mixes up sixteen 64-bit words. This is
  108. * applied to different subsets of the 128 words in a kilobyte block, and the
  109. * API here is designed to make it easy to apply in the circumstances the spec
  110. * requires. In every call, the sixteen words form eight pairs adjacent in
  111. * memory, whose addresses are in arithmetic progression. So the 16 input
  112. * words are in[0], in[1], in[instep], in[instep+1], ..., in[7*instep],
  113. * in[7*instep+1], and the 16 output words similarly. */
  114. static inline void P(uint64_t *out, unsigned outstep,
  115. uint64_t *in, unsigned instep)
  116. {
  117. for (unsigned i = 0; i < 8; i++) {
  118. out[i*outstep] = in[i*instep];
  119. out[i*outstep+1] = in[i*instep+1];
  120. }
  121. GB(out+0*outstep+0, out+2*outstep+0, out+4*outstep+0, out+6*outstep+0);
  122. GB(out+0*outstep+1, out+2*outstep+1, out+4*outstep+1, out+6*outstep+1);
  123. GB(out+1*outstep+0, out+3*outstep+0, out+5*outstep+0, out+7*outstep+0);
  124. GB(out+1*outstep+1, out+3*outstep+1, out+5*outstep+1, out+7*outstep+1);
  125. GB(out+0*outstep+0, out+2*outstep+1, out+5*outstep+0, out+7*outstep+1);
  126. GB(out+0*outstep+1, out+3*outstep+0, out+5*outstep+1, out+6*outstep+0);
  127. GB(out+1*outstep+0, out+3*outstep+1, out+4*outstep+0, out+6*outstep+1);
  128. GB(out+1*outstep+1, out+2*outstep+0, out+4*outstep+1, out+7*outstep+0);
  129. }
  130. /* The full G function, taking input blocks X and Y. The result of G is most
  131. * often XORed into an existing output block, so this API is designed with
  132. * that in mind: the mixing function's output is always XORed into whatever
  133. * 1Kb of data is already at 'out'. */
  134. static void G_xor(uint8_t *out, const uint8_t *X, const uint8_t *Y)
  135. {
  136. uint64_t R[128], Q[128], Z[128];
  137. for (unsigned i = 0; i < 128; i++)
  138. R[i] = GET_64BIT_LSB_FIRST(X + 8*i) ^ GET_64BIT_LSB_FIRST(Y + 8*i);
  139. for (unsigned i = 0; i < 8; i++)
  140. P(Q+16*i, 2, R+16*i, 2);
  141. for (unsigned i = 0; i < 8; i++)
  142. P(Z+2*i, 16, Q+2*i, 16);
  143. for (unsigned i = 0; i < 128; i++)
  144. PUT_64BIT_LSB_FIRST(out + 8*i,
  145. GET_64BIT_LSB_FIRST(out + 8*i) ^ R[i] ^ Z[i]);
  146. smemclr(R, sizeof(R));
  147. smemclr(Q, sizeof(Q));
  148. smemclr(Z, sizeof(Z));
  149. }
  150. /* ----------------------------------------------------------------------
  151. * The main Argon2 function.
  152. */
  153. static void argon2_internal(uint32_t p, uint32_t T, uint32_t m, uint32_t t,
  154. uint32_t y, ptrlen P, ptrlen S, ptrlen K, ptrlen X,
  155. uint8_t *out)
  156. {
  157. /*
  158. * Start by hashing all the input data together: the four string arguments
  159. * (password P, salt S, optional secret key K, optional associated data
  160. * X), plus all the parameters for the function's memory and time usage.
  161. *
  162. * The output of this hash is the sole input to the subsequent mixing
  163. * step: Argon2 does not preserve any more entropy from the inputs, it
  164. * just makes it extra painful to get the final answer.
  165. */
  166. uint8_t h0[64];
  167. {
  168. ssh_hash *h = blake2b_new_general(64);
  169. put_uint32_le(h, p);
  170. put_uint32_le(h, T);
  171. put_uint32_le(h, m);
  172. put_uint32_le(h, t);
  173. put_uint32_le(h, 0x13); /* hash function version number */
  174. put_uint32_le(h, y);
  175. put_stringpl_le(h, P);
  176. put_stringpl_le(h, S);
  177. put_stringpl_le(h, K);
  178. put_stringpl_le(h, X);
  179. ssh_hash_final(h, h0);
  180. }
  181. struct blk { uint8_t data[1024]; };
  182. /*
  183. * Array of 1Kb blocks. The total size is (approximately) m, the
  184. * caller-specified parameter for how much memory to use; the blocks are
  185. * regarded as a rectangular array of p rows ('lanes') by q columns, where
  186. * p is the 'parallelism' input parameter (the lanes can be processed
  187. * concurrently up to a point) and q is whatever makes the product pq come
  188. * to m.
  189. *
  190. * Additionally, each row is divided into four equal 'segments', which are
  191. * important to the way the algorithm decides which blocks to use as input
  192. * to each step of the function.
  193. *
  194. * The term 'slice' refers to a whole set of vertically aligned segments,
  195. * i.e. slice 0 is the whole left quarter of the array, and slice 3 the
  196. * whole right quarter.
  197. */
  198. size_t SL = m / (4*p); /* segment length: # of 1Kb blocks in a segment */
  199. size_t q = 4 * SL; /* width of the array: 4 segments times SL */
  200. size_t mprime = q * p; /* total size of the array, approximately m */
  201. /* Allocate the memory. */
  202. struct blk *B = snewn(mprime, struct blk);
  203. memset(B, 0, mprime * sizeof(struct blk));
  204. /*
  205. * Initial setup: fill the first two full columns of the array with data
  206. * expanded from the starting hash h0. Each block is the result of using
  207. * the long-output hash function H' to hash h0 itself plus the block's
  208. * coordinates in the array.
  209. */
  210. for (size_t i = 0; i < p; i++) {
  211. ssh_hash *h = hprime_new(1024);
  212. put_data(h, h0, 64);
  213. put_uint32_le(h, 0);
  214. put_uint32_le(h, i);
  215. hprime_final(h, 1024, B[i].data);
  216. }
  217. for (size_t i = 0; i < p; i++) {
  218. ssh_hash *h = hprime_new(1024);
  219. put_data(h, h0, 64);
  220. put_uint32_le(h, 1);
  221. put_uint32_le(h, i);
  222. hprime_final(h, 1024, B[i+p].data);
  223. }
  224. /*
  225. * Declarations for the main loop.
  226. *
  227. * The basic structure of the main loop is going to involve processing the
  228. * array one whole slice (vertically divided quarter) at a time. Usually
  229. * we'll write a new value into every single block in the slice, except
  230. * that in the initial slice on the first pass, we've already written
  231. * values into the first two columns during the initial setup above. So
  232. * 'jstart' indicates the starting index in each segment we process; it
  233. * starts off as 2 so that we don't overwrite the initial setup, and then
  234. * after the first slice is done, we set it to 0, and it stays there.
  235. *
  236. * d_mode indicates whether we're being data-dependent (true) or
  237. * data-independent (false). In the hybrid Argon2id mode, we start off
  238. * independent, and then once we've mixed things up enough, switch over to
  239. * dependent mode to force long serial chains of computation.
  240. */
  241. size_t jstart = 2;
  242. bool d_mode = (y == 0);
  243. struct blk out2i, tmp2i, in2i;
  244. /* Outermost loop: t whole passes from left to right over the array */
  245. for (size_t pass = 0; pass < t; pass++) {
  246. /* Within that, we process the array in its four main slices */
  247. for (unsigned slice = 0; slice < 4; slice++) {
  248. /* In Argon2id mode, if we're half way through the first pass,
  249. * this is the moment to switch d_mode from false to true */
  250. if (pass == 0 && slice == 2 && y == 2)
  251. d_mode = true;
  252. /* Loop over every segment in the slice (i.e. every row). So i is
  253. * the y-coordinate of each block we process. */
  254. for (size_t i = 0; i < p; i++) {
  255. /* And within that segment, process the blocks from left to
  256. * right, starting at 'jstart' (usually 0, but 2 in the first
  257. * slice). */
  258. for (size_t jpre = jstart; jpre < SL; jpre++) {
  259. /* j is the x-coordinate of each block we process, made up
  260. * of the slice number and the index 'jpre' within the
  261. * segment. */
  262. size_t j = slice * SL + jpre;
  263. /* jm1 is j-1 (mod q) */
  264. uint32_t jm1 = (j == 0 ? q-1 : j-1);
  265. /*
  266. * Construct two 32-bit pseudorandom integers J1 and J2.
  267. * This is the part of the algorithm that varies between
  268. * the data-dependent and independent modes.
  269. */
  270. uint32_t J1, J2;
  271. if (d_mode) {
  272. /*
  273. * Data-dependent: grab the first 64 bits of the block
  274. * to the left of this one.
  275. */
  276. J1 = GET_32BIT_LSB_FIRST(B[i + p * jm1].data);
  277. J2 = GET_32BIT_LSB_FIRST(B[i + p * jm1].data + 4);
  278. } else {
  279. /*
  280. * Data-independent: generate pseudorandom data by
  281. * hashing a sequence of preimage blocks that include
  282. * all our input parameters, plus the coordinates of
  283. * this point in the algorithm (array position and
  284. * pass number) to make all the hash outputs distinct.
  285. *
  286. * The hash we use is G itself, applied twice. So we
  287. * generate 1Kb of data at a time, which is enough for
  288. * 128 (J1,J2) pairs. Hence we only need to do the
  289. * hashing if our index within the segment is a
  290. * multiple of 128, or if we're at the very start of
  291. * the algorithm (in which case we started at 2 rather
  292. * than 0). After that we can just keep picking data
  293. * out of our most recent hash output.
  294. */
  295. if (jpre == jstart || jpre % 128 == 0) {
  296. /*
  297. * Hash preimage is mostly zeroes, with a
  298. * collection of assorted integer values we had
  299. * anyway.
  300. */
  301. memset(in2i.data, 0, sizeof(in2i.data));
  302. PUT_64BIT_LSB_FIRST(in2i.data + 0, pass);
  303. PUT_64BIT_LSB_FIRST(in2i.data + 8, i);
  304. PUT_64BIT_LSB_FIRST(in2i.data + 16, slice);
  305. PUT_64BIT_LSB_FIRST(in2i.data + 24, mprime);
  306. PUT_64BIT_LSB_FIRST(in2i.data + 32, t);
  307. PUT_64BIT_LSB_FIRST(in2i.data + 40, y);
  308. PUT_64BIT_LSB_FIRST(in2i.data + 48, jpre / 128 + 1);
  309. /*
  310. * Now apply G twice to generate the hash output
  311. * in out2i.
  312. */
  313. memset(tmp2i.data, 0, sizeof(tmp2i.data));
  314. G_xor(tmp2i.data, tmp2i.data, in2i.data);
  315. memset(out2i.data, 0, sizeof(out2i.data));
  316. G_xor(out2i.data, out2i.data, tmp2i.data);
  317. }
  318. /*
  319. * Extract J1 and J2 from the most recent hash output
  320. * (whether we've just computed it or not).
  321. */
  322. J1 = GET_32BIT_LSB_FIRST(
  323. out2i.data + 8 * (jpre % 128));
  324. J2 = GET_32BIT_LSB_FIRST(
  325. out2i.data + 8 * (jpre % 128) + 4);
  326. }
  327. /*
  328. * Now convert J1 and J2 into the index of an existing
  329. * block of the array to use as input to this step. This
  330. * is fairly fiddly.
  331. *
  332. * The easy part: the y-coordinate of the input block is
  333. * obtained by reducing J2 mod p, except that at the very
  334. * start of the algorithm (processing the first slice on
  335. * the first pass) we simply use the same y-coordinate as
  336. * our output block.
  337. *
  338. * Note that it's safe to use the ordinary % operator
  339. * here, without any concern for timing side channels: in
  340. * data-independent mode J2 is not correlated to any
  341. * secrets, and in data-dependent mode we're going to be
  342. * giving away side-channel data _anyway_ when we use it
  343. * as an array index (and by assumption we don't care,
  344. * because it's already massively randomised from the real
  345. * inputs).
  346. */
  347. uint32_t index_l = (pass == 0 && slice == 0) ? i : J2 % p;
  348. /*
  349. * The hard part: which block in this array row do we use?
  350. *
  351. * First, we decide what the possible candidates are. This
  352. * requires some case analysis, and depends on whether the
  353. * array row is the same one we're writing into or not.
  354. *
  355. * If it's not the same row: we can't use any block from
  356. * the current slice (because the segments within a slice
  357. * have to be processable in parallel, so in a concurrent
  358. * implementation those blocks are potentially in the
  359. * process of being overwritten by other threads). But the
  360. * other three slices are fair game, except that in the
  361. * first pass, slices to the right of us won't have had
  362. * any values written into them yet at all.
  363. *
  364. * If it is the same row, we _are_ allowed to use blocks
  365. * from the current slice, but only the ones before our
  366. * current position.
  367. *
  368. * In both cases, we also exclude the individual _column_
  369. * just to the left of the current one. (The block
  370. * immediately to our left is going to be the _other_
  371. * input to G, but the spec also says that we avoid that
  372. * column even in a different row.)
  373. *
  374. * All of this means that we end up choosing from a
  375. * cyclically contiguous interval of blocks within this
  376. * lane, but the start and end points require some thought
  377. * to get them right.
  378. */
  379. /* Start position is the beginning of the _next_ slice
  380. * (containing data from the previous pass), unless we're
  381. * on pass 0, where the start position has to be 0. */
  382. uint32_t Wstart = (pass == 0 ? 0 : (slice + 1) % 4 * SL);
  383. /* End position splits up by cases. */
  384. uint32_t Wend;
  385. if (index_l == i) {
  386. /* Same lane as output: we can use anything up to (but
  387. * not including) the block immediately left of us. */
  388. Wend = jm1;
  389. } else {
  390. /* Different lane from output: we can use anything up
  391. * to the previous slice boundary, or one less than
  392. * that if we're at the very left edge of our slice
  393. * right now. */
  394. Wend = SL * slice;
  395. if (jpre == 0)
  396. Wend = (Wend + q-1) % q;
  397. }
  398. /* Total number of blocks available to choose from */
  399. uint32_t Wsize = (Wend + q - Wstart) % q;
  400. /* Fiddly computation from the spec that chooses from the
  401. * available blocks, in a deliberately non-uniform
  402. * fashion, using J1 as pseudorandom input data. Output is
  403. * zz which is the index within our contiguous interval. */
  404. uint32_t x = ((uint64_t)J1 * J1) >> 32;
  405. uint32_t y = ((uint64_t)Wsize * x) >> 32;
  406. uint32_t zz = Wsize - 1 - y;
  407. /* And index_z is the actual x coordinate of the block we
  408. * want. */
  409. uint32_t index_z = (Wstart + zz) % q;
  410. /* Phew! Combine that block with the one immediately to
  411. * our left, and XOR over the top of whatever is already
  412. * in our current output block. */
  413. G_xor(B[i + p * j].data, B[i + p * jm1].data,
  414. B[index_l + p * index_z].data);
  415. }
  416. }
  417. /* We've finished processing a slice. Reset jstart to 0. It will
  418. * onily _not_ have been 0 if this was pass 0 slice 0, in which
  419. * case it still had its initial value of 2 to avoid the starting
  420. * data. */
  421. jstart = 0;
  422. }
  423. }
  424. /*
  425. * The main output is all done. Final output works by taking the XOR of
  426. * all the blocks in the rightmost column of the array, and then using
  427. * that as input to our long hash H'. The output of _that_ is what we
  428. * deliver to the caller.
  429. */
  430. struct blk C = B[p * (q-1)];
  431. for (size_t i = 1; i < p; i++)
  432. memxor(C.data, C.data, B[i + p * (q-1)].data, 1024);
  433. {
  434. ssh_hash *h = hprime_new(T);
  435. put_data(h, C.data, 1024);
  436. hprime_final(h, T, out);
  437. }
  438. /*
  439. * Clean up.
  440. */
  441. smemclr(out2i.data, sizeof(out2i.data));
  442. smemclr(tmp2i.data, sizeof(tmp2i.data));
  443. smemclr(in2i.data, sizeof(in2i.data));
  444. smemclr(C.data, sizeof(C.data));
  445. smemclr(B, mprime * sizeof(struct blk));
  446. sfree(B);
  447. }
  448. /*
  449. * Wrapper function that appends to a strbuf (which sshpubk.c will want).
  450. */
  451. void argon2(Argon2Flavour flavour, uint32_t mem, uint32_t passes,
  452. uint32_t parallel, uint32_t taglen,
  453. ptrlen P, ptrlen S, ptrlen K, ptrlen X, strbuf *out)
  454. {
  455. argon2_internal(parallel, taglen, mem, passes, flavour,
  456. P, S, K, X, strbuf_append(out, taglen));
  457. }
  458. /*
  459. * Wrapper function which dynamically chooses the number of passes to run in
  460. * order to hit an approximate total amount of CPU time. Writes the result
  461. * into 'passes'.
  462. */
  463. void argon2_choose_passes(
  464. Argon2Flavour flavour, uint32_t mem,
  465. uint32_t milliseconds, uint32_t *passes,
  466. uint32_t parallel, uint32_t taglen,
  467. ptrlen P, ptrlen S, ptrlen K, ptrlen X,
  468. strbuf *out)
  469. {
  470. unsigned long desired_time = (TICKSPERSEC * milliseconds) / 1000;
  471. /*
  472. * We only need the time taken to be approximately right, so we
  473. * scale up the number of passes geometrically, which avoids
  474. * taking O(t^2) time to find a pass count taking time t.
  475. *
  476. * Using the Fibonacci numbers is slightly nicer than the obvious
  477. * approach of powers of 2, because it's still very easy to
  478. * compute, and grows less fast (powers of 1.6 instead of 2), so
  479. * you get just a touch more precision.
  480. */
  481. uint32_t a = 1, b = 1;
  482. while (true) {
  483. unsigned long start_time = GETTICKCOUNT();
  484. argon2(flavour, mem, b, parallel, taglen, P, S, K, X, out);
  485. unsigned long ticks = GETTICKCOUNT() - start_time;
  486. /* But just in case computers get _too_ fast, we have to cap
  487. * the growth before it gets past the uint32_t upper bound! So
  488. * if computing a+b would overflow, stop here. */
  489. if (ticks >= desired_time || a > (uint32_t)~b) {
  490. *passes = b;
  491. return;
  492. } else {
  493. strbuf_clear(out);
  494. /* Next Fibonacci number: replace (a, b) with (b, a+b) */
  495. b += a;
  496. a = b - a;
  497. }
  498. }
  499. }