sha3.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. /*
  2. * SHA-3, as defined in FIPS PUB 202.
  3. */
  4. #include <assert.h>
  5. #include <string.h>
  6. #include "ssh.h"
  7. static inline uint64_t rol(uint64_t x, unsigned shift)
  8. {
  9. unsigned L = (+shift) & 63;
  10. #pragma option push -w-ngu // WINSCP
  11. unsigned R = (-shift) & 63;
  12. #pragma option pop // WINSCP
  13. return (x << L) | (x >> R);
  14. }
  15. /*
  16. * General Keccak is defined such that its state is a 5x5 array of
  17. * words which can be any power-of-2 size from 1 up to 64. SHA-3 fixes
  18. * on 64, and so do we.
  19. *
  20. * The number of rounds is defined as 12 + 2k if the word size is 2^k.
  21. * Here we have 64-bit words only, so k=6, so 24 rounds always.
  22. */
  23. typedef uint64_t keccak_core_state[5][5];
  24. #define NROUNDS 24 /* would differ for other word sizes */
  25. static const uint64_t round_constants[NROUNDS];
  26. static const unsigned rotation_counts[5][5];
  27. /*
  28. * Core Keccak transform: just squodge the state around internally,
  29. * without adding or extracting any data from it.
  30. */
  31. static void keccak_transform(keccak_core_state A)
  32. {
  33. union {
  34. uint64_t C[5];
  35. uint64_t B[5][5];
  36. } u;
  37. unsigned round; // WINSCP
  38. for (round = 0; round < NROUNDS; round++) {
  39. /* theta step */
  40. unsigned x; // WINSCP
  41. for (x = 0; x < 5; x++)
  42. u.C[x] = A[x][0] ^ A[x][1] ^ A[x][2] ^ A[x][3] ^ A[x][4];
  43. for (x = 0; x < 5; x++) { // WINSCP
  44. uint64_t D = rol(u.C[(x+1) % 5], 1) ^ u.C[(x+4) % 5];
  45. { // WINSCP
  46. unsigned y; // WINSCP
  47. for (y = 0; y < 5; y++)
  48. A[x][y] ^= D;
  49. } // WINSCP
  50. }
  51. /* rho and pi steps */
  52. for (x = 0; x < 5; x++) // WINSCP
  53. { // WINSCP
  54. unsigned y; // WINSCP
  55. for (y = 0; y < 5; y++)
  56. u.B[y][(2*x+3*y) % 5] = rol(A[x][y], rotation_counts[x][y]);
  57. } // WINSCP
  58. /* chi step */
  59. for (x = 0; x < 5; x++) // WINSCP
  60. { // WINSCP
  61. unsigned y; // WINSCP
  62. for (y = 0; y < 5; y++)
  63. A[x][y] = u.B[x][y] ^ (u.B[(x+2)%5][y] & ~u.B[(x+1)%5][y]);
  64. } // WINSCP
  65. /* iota step */
  66. A[0][0] ^= round_constants[round];
  67. }
  68. smemclr(&u, sizeof(u));
  69. }
  70. typedef struct {
  71. keccak_core_state A;
  72. unsigned char bytes[25*8];
  73. unsigned char first_pad_byte;
  74. size_t bytes_got, bytes_wanted, hash_bytes;
  75. } keccak_state;
  76. /*
  77. * Keccak accumulation function: given a piece of message, add it to
  78. * the hash.
  79. */
  80. static void keccak_accumulate(keccak_state *s, const void *vdata, size_t len)
  81. {
  82. const unsigned char *data = (const unsigned char *)vdata;
  83. while (len >= s->bytes_wanted - s->bytes_got) {
  84. size_t b = s->bytes_wanted - s->bytes_got;
  85. memcpy(s->bytes + s->bytes_got, data, b);
  86. len -= b;
  87. data += b;
  88. { // WINSCP
  89. size_t n = 0;
  90. unsigned y; // WINSCP
  91. for (y = 0; y < 5; y++) {
  92. unsigned x; // WINSCP
  93. for (x = 0; x < 5; x++) {
  94. if (n >= s->bytes_wanted)
  95. break;
  96. s->A[x][y] ^= GET_64BIT_LSB_FIRST(s->bytes + n);
  97. n += 8;
  98. }
  99. }
  100. keccak_transform(s->A);
  101. s->bytes_got = 0;
  102. } // WINSCP
  103. }
  104. memcpy(s->bytes + s->bytes_got, data, len);
  105. s->bytes_got += len;
  106. }
  107. /*
  108. * Keccak output function.
  109. */
  110. static void keccak_output(keccak_state *s, void *voutput)
  111. {
  112. unsigned char *output = (unsigned char *)voutput;
  113. /*
  114. * Add message padding.
  115. */
  116. {
  117. unsigned char padding[25*8];
  118. size_t len = s->bytes_wanted - s->bytes_got;
  119. if (len == 0)
  120. len = s->bytes_wanted;
  121. memset(padding, 0, len);
  122. padding[0] |= s->first_pad_byte;
  123. padding[len-1] |= 0x80;
  124. keccak_accumulate(s, padding, len);
  125. }
  126. { // WINSCP
  127. size_t n = 0;
  128. unsigned y; // WINSCP
  129. for (y = 0; y < 5; y++) {
  130. unsigned x; // WINSCP
  131. for (x = 0; x < 5; x++) {
  132. size_t to_copy = s->hash_bytes - n;
  133. if (to_copy == 0)
  134. break;
  135. if (to_copy > 8)
  136. to_copy = 8;
  137. { // WINSCP
  138. unsigned char outbytes[8];
  139. PUT_64BIT_LSB_FIRST(outbytes, s->A[x][y]);
  140. memcpy(output + n, outbytes, to_copy);
  141. n += to_copy;
  142. } // WINSCP
  143. }
  144. }
  145. } // WINSCP
  146. }
  147. static void keccak_init(keccak_state *s, unsigned hashbits, unsigned ratebits,
  148. unsigned char first_pad_byte)
  149. {
  150. int x, y;
  151. assert(hashbits % 8 == 0);
  152. assert(ratebits % 8 == 0);
  153. s->hash_bytes = hashbits / 8;
  154. s->bytes_wanted = (25 * 64 - ratebits) / 8;
  155. s->bytes_got = 0;
  156. s->first_pad_byte = first_pad_byte;
  157. assert(s->bytes_wanted % 8 == 0);
  158. for (y = 0; y < 5; y++)
  159. for (x = 0; x < 5; x++)
  160. s->A[x][y] = 0;
  161. }
  162. static void keccak_sha3_init(keccak_state *s, int hashbits)
  163. {
  164. keccak_init(s, hashbits, hashbits * 2, 0x06);
  165. }
  166. static void keccak_shake_init(keccak_state *s, int parambits, int hashbits)
  167. {
  168. keccak_init(s, hashbits, parambits * 2, 0x1f);
  169. }
  170. /*
  171. * Keccak round constants, generated via the LFSR specified in the
  172. * Keccak reference by the following piece of Python:
  173. import textwrap
  174. from functools import reduce
  175. rbytes = [1]
  176. while len(rbytes) < 7*24:
  177. k = rbytes[-1] * 2
  178. rbytes.append(k ^ (0x171 * (k >> 8)))
  179. rbits = [byte & 1 for byte in rbytes]
  180. rwords = [sum(rbits[i+j] << ((1 << j) - 1) for j in range(7))
  181. for i in range(0, len(rbits), 7)]
  182. print(textwrap.indent("\n".join(textwrap.wrap(", ".join(
  183. map("0x{:016x}".format, rwords)))), " "*4))
  184. */
  185. static const uint64_t round_constants[24] = {
  186. // WINSCP (ULL)
  187. 0x0000000000000001ULL, 0x0000000000008082ULL, 0x800000000000808aULL,
  188. 0x8000000080008000ULL, 0x000000000000808bULL, 0x0000000080000001ULL,
  189. 0x8000000080008081ULL, 0x8000000000008009ULL, 0x000000000000008aULL,
  190. 0x0000000000000088ULL, 0x0000000080008009ULL, 0x000000008000000aULL,
  191. 0x000000008000808bULL, 0x800000000000008bULL, 0x8000000000008089ULL,
  192. 0x8000000000008003ULL, 0x8000000000008002ULL, 0x8000000000000080ULL,
  193. 0x000000000000800aULL, 0x800000008000000aULL, 0x8000000080008081ULL,
  194. 0x8000000000008080ULL, 0x0000000080000001ULL, 0x8000000080008008ULL
  195. };
  196. /*
  197. * Keccak per-element rotation counts, generated from the matrix
  198. * formula in the Keccak reference by the following piece of Python:
  199. coords = [1, 0]
  200. while len(coords) < 26:
  201. coords.append((2*coords[-2] + 3*coords[-1]) % 5)
  202. matrix = { (coords[i], coords[i+1]) : i for i in range(24) }
  203. matrix[0,0] = -1
  204. f = lambda t: (t+1) * (t+2) // 2 % 64
  205. for y in range(5):
  206. print(" {{{}}},".format(", ".join("{:2d}".format(f(matrix[y,x]))
  207. for x in range(5))))
  208. */
  209. static const unsigned rotation_counts[5][5] = {
  210. { 0, 36, 3, 41, 18},
  211. { 1, 44, 10, 45, 2},
  212. {62, 6, 43, 15, 61},
  213. {28, 55, 25, 21, 56},
  214. {27, 20, 39, 8, 14},
  215. };
  216. /*
  217. * The PuTTY ssh_hashalg abstraction.
  218. */
  219. struct keccak_hash {
  220. keccak_state state;
  221. ssh_hash hash;
  222. BinarySink_IMPLEMENTATION;
  223. };
  224. static void keccak_BinarySink_write(BinarySink *bs, const void *p, size_t len)
  225. {
  226. struct keccak_hash *kh = BinarySink_DOWNCAST(bs, struct keccak_hash);
  227. keccak_accumulate(&kh->state, p, len);
  228. }
  229. static ssh_hash *keccak_new(const ssh_hashalg *alg)
  230. {
  231. struct keccak_hash *kh = snew(struct keccak_hash);
  232. kh->hash.vt = alg;
  233. BinarySink_INIT(kh, keccak_BinarySink_write);
  234. BinarySink_DELEGATE_INIT(&kh->hash, kh);
  235. return ssh_hash_reset(&kh->hash);
  236. }
  237. static void keccak_free(ssh_hash *hash)
  238. {
  239. struct keccak_hash *kh = container_of(hash, struct keccak_hash, hash);
  240. smemclr(kh, sizeof(*kh));
  241. sfree(kh);
  242. }
  243. static void keccak_copyfrom(ssh_hash *hnew, ssh_hash *hold)
  244. {
  245. struct keccak_hash *khold = container_of(hold, struct keccak_hash, hash);
  246. struct keccak_hash *khnew = container_of(hnew, struct keccak_hash, hash);
  247. khnew->state = khold->state;
  248. }
  249. static void keccak_digest(ssh_hash *hash, unsigned char *output)
  250. {
  251. struct keccak_hash *kh = container_of(hash, struct keccak_hash, hash);
  252. keccak_output(&kh->state, output);
  253. }
  254. static void sha3_reset(ssh_hash *hash)
  255. {
  256. struct keccak_hash *kh = container_of(hash, struct keccak_hash, hash);
  257. keccak_sha3_init(&kh->state, hash->vt->hlen * 8);
  258. }
  259. #define DEFINE_SHA3(bits) \
  260. const ssh_hashalg ssh_sha3_##bits = { \
  261. /* WINSCP */ \
  262. /*.new =*/ keccak_new, \
  263. /*.reset =*/ sha3_reset, \
  264. /*.copyfrom =*/ keccak_copyfrom, \
  265. /*.digest =*/ keccak_digest, \
  266. /*.free =*/ keccak_free, \
  267. /*.hlen =*/ bits/8, \
  268. /*.blocklen =*/ 200 - 2*(bits/8), \
  269. HASHALG_NAMES_BARE("SHA3-" #bits), \
  270. NULL, /* WINSCP */ \
  271. }
  272. DEFINE_SHA3(224);
  273. DEFINE_SHA3(256);
  274. DEFINE_SHA3(384);
  275. DEFINE_SHA3(512);
  276. static void shake256_reset(ssh_hash *hash)
  277. {
  278. struct keccak_hash *kh = container_of(hash, struct keccak_hash, hash);
  279. keccak_shake_init(&kh->state, 256, hash->vt->hlen * 8);
  280. }
  281. /*
  282. * There is some confusion over the output length parameter for the
  283. * SHAKE functions. By my reading, FIPS PUB 202 defines SHAKE256(M,d)
  284. * to generate d _bits_ of output. But RFC 8032 (defining Ed448) talks
  285. * about "SHAKE256(x,114)" in a context where it definitely means
  286. * generating 114 _bytes_ of output.
  287. *
  288. * Our internal ID therefore suffixes the output length with "bytes",
  289. * to be clear which we're talking about
  290. */
  291. #define DEFINE_SHAKE(param, hashbytes) \
  292. const ssh_hashalg ssh_shake##param##_##hashbytes##bytes = { \
  293. /* WINSCP */ \
  294. /*.new =*/ keccak_new, \
  295. /*.reset =*/ shake##param##_reset, \
  296. /*.copyfrom =*/ keccak_copyfrom, \
  297. /*.digest =*/ keccak_digest, \
  298. /*.free =*/ keccak_free, \
  299. /*.hlen =*/ hashbytes, \
  300. /*.blocklen =*/ 0, \
  301. HASHALG_NAMES_BARE("SHAKE" #param), \
  302. NULL, /*NULL*/ \
  303. }
  304. DEFINE_SHAKE(256, 114); /* used by Ed448 */
  305. DEFINE_SHAKE(256, 32); /* used by ML-KEM */
  306. struct ShakeXOF {
  307. keccak_state state;
  308. unsigned char *buf;
  309. size_t bytes_per_transform, pos;
  310. };
  311. static ShakeXOF *shake_xof_from_input(unsigned bits, ptrlen data)
  312. {
  313. ShakeXOF *sx = snew_plus(ShakeXOF, 200 * 64);
  314. sx->buf = snew_plus_get_aux(sx);
  315. /* Initialise as if we were generating 0 bytes of hash. That way,
  316. * keccak_output will do the final accumulation but generate no data. */
  317. keccak_shake_init(&sx->state, bits, 0);
  318. keccak_accumulate(&sx->state, data.ptr, data.len);
  319. keccak_output(&sx->state, NULL);
  320. sx->bytes_per_transform = 200 - bits/4;
  321. sx->pos = 0;
  322. return sx;
  323. }
  324. ShakeXOF *shake128_xof_from_input(ptrlen data)
  325. {
  326. return shake_xof_from_input(128, data);
  327. }
  328. ShakeXOF *shake256_xof_from_input(ptrlen data)
  329. {
  330. return shake_xof_from_input(256, data);
  331. }
  332. void shake_xof_read(ShakeXOF *sx, void *output_v, size_t size)
  333. {
  334. unsigned char *output = (unsigned char *)output_v;
  335. while (size > 0) {
  336. if (sx->pos == 0) {
  337. /* Copy the 64-bit words from the Keccak state into the
  338. * output buffer of bytes */
  339. unsigned y, x; // WINSCP
  340. for (y = 0; y < 5; y++)
  341. for (x = 0; x < 5; x++)
  342. PUT_64BIT_LSB_FIRST(sx->buf + 8 * (5*y+x),
  343. sx->state.A[x][y]);
  344. }
  345. /* Read a chunk from the byte buffer */
  346. { // WINSCP
  347. size_t this_size = sx->bytes_per_transform - sx->pos;
  348. if (this_size > size)
  349. this_size = size;
  350. memcpy(output, sx->buf + sx->pos, this_size);
  351. sx->pos += this_size;
  352. output += this_size;
  353. size -= this_size;
  354. /* Retransform the Keccak state if we've run out of data */
  355. if (sx->pos >= sx->bytes_per_transform) {
  356. keccak_transform(sx->state.A);
  357. sx->pos = 0;
  358. }
  359. } // WINSCP
  360. }
  361. }
  362. void shake_xof_free(ShakeXOF *sx)
  363. {
  364. smemclr(sx->buf, 200 * 64);
  365. smemclr(sx, sizeof(*sx));
  366. sfree(sx);
  367. }