gcm.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. /******************************************************************************
  2. *
  3. * THIS SOURCE CODE IS HEREBY PLACED INTO THE PUBLIC DOMAIN FOR THE GOOD OF ALL
  4. *
  5. * This is a simple and straightforward implementation of AES-GCM authenticated
  6. * encryption. The focus of this work was correctness & accuracy. It is written
  7. * in straight 'C' without any particular focus upon optimization or speed. It
  8. * should be endian (memory byte order) neutral since the few places that care
  9. * are handled explicitly.
  10. *
  11. * This implementation of AES-GCM was created by Steven M. Gibson of GRC.com.
  12. *
  13. * It is intended for general purpose use, but was written in support of GRC's
  14. * reference implementation of the SQRL (Secure Quick Reliable Login) client.
  15. *
  16. * See: http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf
  17. * http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/
  18. * gcm/gcm-revised-spec.pdf
  19. *
  20. * NO COPYRIGHT IS CLAIMED IN THIS WORK, HOWEVER, NEITHER IS ANY WARRANTY MADE
  21. * REGARDING ITS FITNESS FOR ANY PARTICULAR PURPOSE. USE IT AT YOUR OWN RISK.
  22. *
  23. *******************************************************************************/
  24. #include "gcm.h"
  25. #include "aes.h"
  26. /******************************************************************************
  27. * ==== IMPLEMENTATION WARNING ====
  28. *
  29. * This code was developed for use within SQRL's fixed environmnent. Thus, it
  30. * is somewhat less "general purpose" than it would be if it were designed as
  31. * a general purpose AES-GCM library. Specifically, it bothers with almost NO
  32. * error checking on parameter limits, buffer bounds, etc. It assumes that it
  33. * is being invoked by its author or by someone who understands the values it
  34. * expects to receive. Its behavior will be undefined otherwise.
  35. *
  36. * All functions that might fail are defined to return 'ints' to indicate a
  37. * problem. Most do not do so now. But this allows for error propagation out
  38. * of internal functions if robust error checking should ever be desired.
  39. *
  40. ******************************************************************************/
  41. /* Calculating the "GHASH"
  42. *
  43. * There are many ways of calculating the so-called GHASH in software, each with
  44. * a traditional size vs performance tradeoff. The GHASH (Galois field hash) is
  45. * an intriguing construction which takes two 128-bit strings (also the cipher's
  46. * block size and the fundamental operation size for the system) and hashes them
  47. * into a third 128-bit result.
  48. *
  49. * Many implementation solutions have been worked out that use large precomputed
  50. * table lookups in place of more time consuming bit fiddling, and this approach
  51. * can be scaled easily upward or downward as needed to change the time/space
  52. * tradeoff. It's been studied extensively and there's a solid body of theory and
  53. * practice. For example, without using any lookup tables an implementation
  54. * might obtain 119 cycles per byte throughput, whereas using a simple, though
  55. * large, key-specific 64 kbyte 8-bit lookup table the performance jumps to 13
  56. * cycles per byte.
  57. *
  58. * And Intel's processors have, since 2010, included an instruction which does
  59. * the entire 128x128->128 bit job in just several 64x64->128 bit pieces.
  60. *
  61. * Since SQRL is interactive, and only processing a few 128-bit blocks, I've
  62. * settled upon a relatively slower but appealing small-table compromise which
  63. * folds a bunch of not only time consuming but also bit twiddling into a simple
  64. * 16-entry table which is attributed to Victor Shoup's 1996 work while at
  65. * Bellcore: "On Fast and Provably Secure MessageAuthentication Based on
  66. * Universal Hashing." See: http://www.shoup.net/papers/macs.pdf
  67. * See, also section 4.1 of the "gcm-revised-spec" cited above.
  68. */
  69. /*
  70. * This 16-entry table of pre-computed constants is used by the
  71. * GHASH multiplier to improve over a strictly table-free but
  72. * significantly slower 128x128 bit multiple within GF(2^128).
  73. */
  74. static const uint64_t last4[16] = {
  75. 0x0000,
  76. 0x1c20,
  77. 0x3840,
  78. 0x2460,
  79. 0x7080,
  80. 0x6ca0,
  81. 0x48c0,
  82. 0x54e0,
  83. 0xe100,
  84. 0xfd20,
  85. 0xd940,
  86. 0xc560,
  87. 0x9180,
  88. 0x8da0,
  89. 0xa9c0,
  90. 0xb5e0};
  91. /*
  92. * Platform Endianness Neutralizing Load and Store Macro definitions
  93. * GCM wants platform-neutral Big Endian (BE) byte ordering
  94. */
  95. #define GET_UINT32_BE(n, b, i) \
  96. { \
  97. (n) = ((uint32_t)(b)[(i)] << 24) | ((uint32_t)(b)[(i) + 1] << 16) | \
  98. ((uint32_t)(b)[(i) + 2] << 8) | ((uint32_t)(b)[(i) + 3]); \
  99. }
  100. #define PUT_UINT32_BE(n, b, i) \
  101. { \
  102. (b)[(i)] = (uchar)((n) >> 24); \
  103. (b)[(i) + 1] = (uchar)((n) >> 16); \
  104. (b)[(i) + 2] = (uchar)((n) >> 8); \
  105. (b)[(i) + 3] = (uchar)((n)); \
  106. }
  107. /******************************************************************************
  108. *
  109. * GCM_INITIALIZE
  110. *
  111. * Must be called once to initialize the GCM library.
  112. *
  113. * At present, this only calls the AES keygen table generator, which expands
  114. * the AES keying tables for use. This is NOT A THREAD-SAFE function, so it
  115. * MUST be called during system initialization before a multi-threading
  116. * environment is running.
  117. *
  118. ******************************************************************************/
  119. int gcm_initialize(void) {
  120. aes_init_keygen_tables();
  121. return (0);
  122. }
  123. /******************************************************************************
  124. *
  125. * GCM_MULT
  126. *
  127. * Performs a GHASH operation on the 128-bit input vector 'x', setting
  128. * the 128-bit output vector to 'x' times H using our precomputed tables.
  129. * 'x' and 'output' are seen as elements of GCM's GF(2^128) Galois field.
  130. *
  131. ******************************************************************************/
  132. static void gcm_mult(
  133. gcm_context* ctx, // pointer to established context
  134. const uchar x[16], // pointer to 128-bit input vector
  135. uchar output[16]) // pointer to 128-bit output vector
  136. {
  137. int i;
  138. uchar lo, hi, rem;
  139. uint64_t zh, zl;
  140. lo = (uchar)(x[15] & 0x0f);
  141. hi = (uchar)(x[15] >> 4);
  142. zh = ctx->HH[lo];
  143. zl = ctx->HL[lo];
  144. for(i = 15; i >= 0; i--) {
  145. lo = (uchar)(x[i] & 0x0f);
  146. hi = (uchar)(x[i] >> 4);
  147. if(i != 15) {
  148. rem = (uchar)(zl & 0x0f);
  149. zl = (zh << 60) | (zl >> 4);
  150. zh = (zh >> 4);
  151. zh ^= (uint64_t)last4[rem] << 48;
  152. zh ^= ctx->HH[lo];
  153. zl ^= ctx->HL[lo];
  154. }
  155. rem = (uchar)(zl & 0x0f);
  156. zl = (zh << 60) | (zl >> 4);
  157. zh = (zh >> 4);
  158. zh ^= (uint64_t)last4[rem] << 48;
  159. zh ^= ctx->HH[hi];
  160. zl ^= ctx->HL[hi];
  161. }
  162. PUT_UINT32_BE(zh >> 32, output, 0);
  163. PUT_UINT32_BE(zh, output, 4);
  164. PUT_UINT32_BE(zl >> 32, output, 8);
  165. PUT_UINT32_BE(zl, output, 12);
  166. }
  167. /******************************************************************************
  168. *
  169. * GCM_SETKEY
  170. *
  171. * This is called to set the AES-GCM key. It initializes the AES key
  172. * and populates the gcm context's pre-calculated HTables.
  173. *
  174. ******************************************************************************/
  175. int gcm_setkey(
  176. gcm_context* ctx, // pointer to caller-provided gcm context
  177. const uchar* key, // pointer to the AES encryption key
  178. const uint keysize) // size in bytes (must be 16, 24, 32 for
  179. // 128, 192 or 256-bit keys respectively)
  180. {
  181. int ret, i, j;
  182. uint64_t hi, lo;
  183. uint64_t vl, vh;
  184. unsigned char h[16];
  185. memset(ctx, 0, sizeof(gcm_context)); // zero caller-provided GCM context
  186. memset(h, 0, 16); // initialize the block to encrypt
  187. // encrypt the null 128-bit block to generate a key-based value
  188. // which is then used to initialize our GHASH lookup tables
  189. if((ret = aes_setkey(&ctx->aes_ctx, ENCRYPT, key, keysize)) != 0) return (ret);
  190. if((ret = aes_cipher(&ctx->aes_ctx, h, h)) != 0) return (ret);
  191. GET_UINT32_BE(hi, h, 0); // pack h as two 64-bit ints, big-endian
  192. GET_UINT32_BE(lo, h, 4);
  193. vh = (uint64_t)hi << 32 | lo;
  194. GET_UINT32_BE(hi, h, 8);
  195. GET_UINT32_BE(lo, h, 12);
  196. vl = (uint64_t)hi << 32 | lo;
  197. ctx->HL[8] = vl; // 8 = 1000 corresponds to 1 in GF(2^128)
  198. ctx->HH[8] = vh;
  199. ctx->HH[0] = 0; // 0 corresponds to 0 in GF(2^128)
  200. ctx->HL[0] = 0;
  201. for(i = 4; i > 0; i >>= 1) {
  202. uint32_t T = (uint32_t)(vl & 1) * 0xe1000000U;
  203. vl = (vh << 63) | (vl >> 1);
  204. vh = (vh >> 1) ^ ((uint64_t)T << 32);
  205. ctx->HL[i] = vl;
  206. ctx->HH[i] = vh;
  207. }
  208. for(i = 2; i < 16; i <<= 1) {
  209. uint64_t *HiL = ctx->HL + i, *HiH = ctx->HH + i;
  210. vh = *HiH;
  211. vl = *HiL;
  212. for(j = 1; j < i; j++) {
  213. HiH[j] = vh ^ ctx->HH[j];
  214. HiL[j] = vl ^ ctx->HL[j];
  215. }
  216. }
  217. return (0);
  218. }
  219. /******************************************************************************
  220. *
  221. * GCM processing occurs four phases: SETKEY, START, UPDATE and FINISH.
  222. *
  223. * SETKEY:
  224. *
  225. * START: Sets the Encryption/Decryption mode.
  226. * Accepts the initialization vector and additional data.
  227. *
  228. * UPDATE: Encrypts or decrypts the plaintext or ciphertext.
  229. *
  230. * FINISH: Performs a final GHASH to generate the authentication tag.
  231. *
  232. ******************************************************************************
  233. *
  234. * GCM_START
  235. *
  236. * Given a user-provided GCM context, this initializes it, sets the encryption
  237. * mode, and preprocesses the initialization vector and additional AEAD data.
  238. *
  239. ******************************************************************************/
  240. int gcm_start(
  241. gcm_context* ctx, // pointer to user-provided GCM context
  242. int mode, // GCM_ENCRYPT or GCM_DECRYPT
  243. const uchar* iv, // pointer to initialization vector
  244. size_t iv_len, // IV length in bytes (should == 12)
  245. const uchar* add, // ptr to additional AEAD data (NULL if none)
  246. size_t add_len) // length of additional AEAD data (bytes)
  247. {
  248. int ret; // our error return if the AES encrypt fails
  249. uchar work_buf[16]; // XOR source built from provided IV if len != 16
  250. const uchar* p; // general purpose array pointer
  251. size_t use_len; // byte count to process, up to 16 bytes
  252. size_t i; // local loop iterator
  253. // since the context might be reused under the same key
  254. // we zero the working buffers for this next new process
  255. memset(ctx->y, 0x00, sizeof(ctx->y));
  256. memset(ctx->buf, 0x00, sizeof(ctx->buf));
  257. ctx->len = 0;
  258. ctx->add_len = 0;
  259. ctx->mode = mode; // set the GCM encryption/decryption mode
  260. ctx->aes_ctx.mode = ENCRYPT; // GCM *always* runs AES in ENCRYPTION mode
  261. if(iv_len == 12) { // GCM natively uses a 12-byte, 96-bit IV
  262. memcpy(ctx->y, iv, iv_len); // copy the IV to the top of the 'y' buff
  263. ctx->y[15] = 1; // start "counting" from 1 (not 0)
  264. } else // if we don't have a 12-byte IV, we GHASH whatever we've been given
  265. {
  266. memset(work_buf, 0x00, 16); // clear the working buffer
  267. PUT_UINT32_BE(iv_len * 8, work_buf, 12); // place the IV into buffer
  268. p = iv;
  269. while(iv_len > 0) {
  270. use_len = (iv_len < 16) ? iv_len : 16;
  271. for(i = 0; i < use_len; i++)
  272. ctx->y[i] ^= p[i];
  273. gcm_mult(ctx, ctx->y, ctx->y);
  274. iv_len -= use_len;
  275. p += use_len;
  276. }
  277. for(i = 0; i < 16; i++)
  278. ctx->y[i] ^= work_buf[i];
  279. gcm_mult(ctx, ctx->y, ctx->y);
  280. }
  281. if((ret = aes_cipher(&ctx->aes_ctx, ctx->y, ctx->base_ectr)) != 0) return (ret);
  282. ctx->add_len = add_len;
  283. p = add;
  284. while(add_len > 0) {
  285. use_len = (add_len < 16) ? add_len : 16;
  286. for(i = 0; i < use_len; i++)
  287. ctx->buf[i] ^= p[i];
  288. gcm_mult(ctx, ctx->buf, ctx->buf);
  289. add_len -= use_len;
  290. p += use_len;
  291. }
  292. return (0);
  293. }
  294. /******************************************************************************
  295. *
  296. * GCM_UPDATE
  297. *
  298. * This is called once or more to process bulk plaintext or ciphertext data.
  299. * We give this some number of bytes of input and it returns the same number
  300. * of output bytes. If called multiple times (which is fine) all but the final
  301. * invocation MUST be called with length mod 16 == 0. (Only the final call can
  302. * have a partial block length of < 128 bits.)
  303. *
  304. ******************************************************************************/
  305. int gcm_update(
  306. gcm_context* ctx, // pointer to user-provided GCM context
  307. size_t length, // length, in bytes, of data to process
  308. const uchar* input, // pointer to source data
  309. uchar* output) // pointer to destination data
  310. {
  311. int ret; // our error return if the AES encrypt fails
  312. uchar ectr[16]; // counter-mode cipher output for XORing
  313. size_t use_len; // byte count to process, up to 16 bytes
  314. size_t i; // local loop iterator
  315. ctx->len += length; // bump the GCM context's running length count
  316. while(length > 0) {
  317. // clamp the length to process at 16 bytes
  318. use_len = (length < 16) ? length : 16;
  319. // increment the context's 128-bit IV||Counter 'y' vector
  320. for(i = 16; i > 12; i--)
  321. if(++ctx->y[i - 1] != 0) break;
  322. // encrypt the context's 'y' vector under the established key
  323. if((ret = aes_cipher(&ctx->aes_ctx, ctx->y, ectr)) != 0) return (ret);
  324. // encrypt or decrypt the input to the output
  325. if(ctx->mode == ENCRYPT) {
  326. for(i = 0; i < use_len; i++) {
  327. // XOR the cipher's ouptut vector (ectr) with our input
  328. output[i] = (uchar)(ectr[i] ^ input[i]);
  329. // now we mix in our data into the authentication hash.
  330. // if we're ENcrypting we XOR in the post-XOR (output)
  331. // results, but if we're DEcrypting we XOR in the input
  332. // data
  333. ctx->buf[i] ^= output[i];
  334. }
  335. } else {
  336. for(i = 0; i < use_len; i++) {
  337. // but if we're DEcrypting we XOR in the input data first,
  338. // i.e. before saving to ouput data, otherwise if the input
  339. // and output buffer are the same (inplace decryption) we
  340. // would not get the correct auth tag
  341. ctx->buf[i] ^= input[i];
  342. // XOR the cipher's ouptut vector (ectr) with our input
  343. output[i] = (uchar)(ectr[i] ^ input[i]);
  344. }
  345. }
  346. gcm_mult(ctx, ctx->buf, ctx->buf); // perform a GHASH operation
  347. length -= use_len; // drop the remaining byte count to process
  348. input += use_len; // bump our input pointer forward
  349. output += use_len; // bump our output pointer forward
  350. }
  351. return (0);
  352. }
  353. /******************************************************************************
  354. *
  355. * GCM_FINISH
  356. *
  357. * This is called once after all calls to GCM_UPDATE to finalize the GCM.
  358. * It performs the final GHASH to produce the resulting authentication TAG.
  359. *
  360. ******************************************************************************/
  361. int gcm_finish(
  362. gcm_context* ctx, // pointer to user-provided GCM context
  363. uchar* tag, // pointer to buffer which receives the tag
  364. size_t tag_len) // length, in bytes, of the tag-receiving buf
  365. {
  366. uchar work_buf[16];
  367. uint64_t orig_len = ctx->len * 8;
  368. uint64_t orig_add_len = ctx->add_len * 8;
  369. size_t i;
  370. if(tag_len != 0) memcpy(tag, ctx->base_ectr, tag_len);
  371. if(orig_len || orig_add_len) {
  372. memset(work_buf, 0x00, 16);
  373. PUT_UINT32_BE((orig_add_len >> 32), work_buf, 0);
  374. PUT_UINT32_BE((orig_add_len), work_buf, 4);
  375. PUT_UINT32_BE((orig_len >> 32), work_buf, 8);
  376. PUT_UINT32_BE((orig_len), work_buf, 12);
  377. for(i = 0; i < 16; i++)
  378. ctx->buf[i] ^= work_buf[i];
  379. gcm_mult(ctx, ctx->buf, ctx->buf);
  380. for(i = 0; i < tag_len; i++)
  381. tag[i] ^= ctx->buf[i];
  382. }
  383. return (0);
  384. }
  385. /******************************************************************************
  386. *
  387. * GCM_CRYPT_AND_TAG
  388. *
  389. * This either encrypts or decrypts the user-provided data and, either
  390. * way, generates an authentication tag of the requested length. It must be
  391. * called with a GCM context whose key has already been set with GCM_SETKEY.
  392. *
  393. * The user would typically call this explicitly to ENCRYPT a buffer of data
  394. * and optional associated data, and produce its an authentication tag.
  395. *
  396. * To reverse the process the user would typically call the companion
  397. * GCM_AUTH_DECRYPT function to decrypt data and verify a user-provided
  398. * authentication tag. The GCM_AUTH_DECRYPT function calls this function
  399. * to perform its decryption and tag generation, which it then compares.
  400. *
  401. ******************************************************************************/
  402. int gcm_crypt_and_tag(
  403. gcm_context* ctx, // gcm context with key already setup
  404. int mode, // cipher direction: GCM_ENCRYPT or GCM_DECRYPT
  405. const uchar* iv, // pointer to the 12-byte initialization vector
  406. size_t iv_len, // byte length if the IV. should always be 12
  407. const uchar* add, // pointer to the non-ciphered additional data
  408. size_t add_len, // byte length of the additional AEAD data
  409. const uchar* input, // pointer to the cipher data source
  410. uchar* output, // pointer to the cipher data destination
  411. size_t length, // byte length of the cipher data
  412. uchar* tag, // pointer to the tag to be generated
  413. size_t tag_len) // byte length of the tag to be generated
  414. { /*
  415. assuming that the caller has already invoked gcm_setkey to
  416. prepare the gcm context with the keying material, we simply
  417. invoke each of the three GCM sub-functions in turn...
  418. */
  419. gcm_start(ctx, mode, iv, iv_len, add, add_len);
  420. gcm_update(ctx, length, input, output);
  421. gcm_finish(ctx, tag, tag_len);
  422. return (0);
  423. }
  424. /******************************************************************************
  425. *
  426. * GCM_AUTH_DECRYPT
  427. *
  428. * This DECRYPTS a user-provided data buffer with optional associated data.
  429. * It then verifies a user-supplied authentication tag against the tag just
  430. * re-created during decryption to verify that the data has not been altered.
  431. *
  432. * This function calls GCM_CRYPT_AND_TAG (above) to perform the decryption
  433. * and authentication tag generation.
  434. *
  435. ******************************************************************************/
  436. int gcm_auth_decrypt(
  437. gcm_context* ctx, // gcm context with key already setup
  438. const uchar* iv, // pointer to the 12-byte initialization vector
  439. size_t iv_len, // byte length if the IV. should always be 12
  440. const uchar* add, // pointer to the non-ciphered additional data
  441. size_t add_len, // byte length of the additional AEAD data
  442. const uchar* input, // pointer to the cipher data source
  443. uchar* output, // pointer to the cipher data destination
  444. size_t length, // byte length of the cipher data
  445. const uchar* tag, // pointer to the tag to be authenticated
  446. size_t tag_len) // byte length of the tag <= 16
  447. {
  448. uchar check_tag[16]; // the tag generated and returned by decryption
  449. int diff; // an ORed flag to detect authentication errors
  450. size_t i; // our local iterator
  451. /*
  452. we use GCM_DECRYPT_AND_TAG (above) to perform our decryption
  453. (which is an identical XORing to reverse the previous one)
  454. and also to re-generate the matching authentication tag
  455. */
  456. gcm_crypt_and_tag(
  457. ctx, DECRYPT, iv, iv_len, add, add_len, input, output, length, check_tag, tag_len);
  458. // now we verify the authentication tag in 'constant time'
  459. for(diff = 0, i = 0; i < tag_len; i++)
  460. diff |= tag[i] ^ check_tag[i];
  461. if(diff != 0) { // see whether any bits differed?
  462. memset(output, 0, length); // if so... wipe the output data
  463. return (GCM_AUTH_FAILURE); // return GCM_AUTH_FAILURE
  464. }
  465. return (0);
  466. }
  467. /******************************************************************************
  468. *
  469. * GCM_ZERO_CTX
  470. *
  471. * The GCM context contains both the GCM context and the AES context.
  472. * This includes keying and key-related material which is security-
  473. * sensitive, so it MUST be zeroed after use. This function does that.
  474. *
  475. ******************************************************************************/
  476. void gcm_zero_ctx(gcm_context* ctx) {
  477. // zero the context originally provided to us
  478. memset(ctx, 0, sizeof(gcm_context));
  479. }