aesce.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. /*
  2. * Armv8-A Cryptographic Extension support functions for Aarch64
  3. *
  4. * Copyright The Mbed TLS Contributors
  5. * SPDX-License-Identifier: Apache-2.0
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License"); you may
  8. * not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  15. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. */
  19. #if defined(__aarch64__) && !defined(__ARM_FEATURE_CRYPTO) && \
  20. defined(__clang__) && __clang_major__ >= 4
  21. /* TODO: Re-consider above after https://reviews.llvm.org/D131064 merged.
  22. *
  23. * The intrinsic declaration are guarded by predefined ACLE macros in clang:
  24. * these are normally only enabled by the -march option on the command line.
  25. * By defining the macros ourselves we gain access to those declarations without
  26. * requiring -march on the command line.
  27. *
  28. * `arm_neon.h` could be included by any header file, so we put these defines
  29. * at the top of this file, before any includes.
  30. */
  31. #define __ARM_FEATURE_CRYPTO 1
  32. /* See: https://arm-software.github.io/acle/main/acle.html#cryptographic-extensions
  33. *
  34. * `__ARM_FEATURE_CRYPTO` is deprecated, but we need to continue to specify it
  35. * for older compilers.
  36. */
  37. #define __ARM_FEATURE_AES 1
  38. #define MBEDTLS_ENABLE_ARM_CRYPTO_EXTENSIONS_COMPILER_FLAG
  39. #endif
  40. #include <string.h>
  41. #include "common.h"
  42. #if defined(MBEDTLS_AESCE_C)
  43. #include "aesce.h"
  44. #if defined(MBEDTLS_HAVE_ARM64)
  45. #if !defined(__ARM_FEATURE_AES) || defined(MBEDTLS_ENABLE_ARM_CRYPTO_EXTENSIONS_COMPILER_FLAG)
  46. # if defined(__clang__)
  47. # if __clang_major__ < 4
  48. # error "A more recent Clang is required for MBEDTLS_AESCE_C"
  49. # endif
  50. # pragma clang attribute push (__attribute__((target("crypto"))), apply_to=function)
  51. # define MBEDTLS_POP_TARGET_PRAGMA
  52. # elif defined(__GNUC__)
  53. # if __GNUC__ < 6
  54. # error "A more recent GCC is required for MBEDTLS_AESCE_C"
  55. # endif
  56. # pragma GCC push_options
  57. # pragma GCC target ("arch=armv8-a+crypto")
  58. # define MBEDTLS_POP_TARGET_PRAGMA
  59. # else
  60. # error "Only GCC and Clang supported for MBEDTLS_AESCE_C"
  61. # endif
  62. #endif /* !__ARM_FEATURE_AES || MBEDTLS_ENABLE_ARM_CRYPTO_EXTENSIONS_COMPILER_FLAG */
  63. #include <arm_neon.h>
  64. #if defined(__linux__)
  65. #include <asm/hwcap.h>
  66. #include <sys/auxv.h>
  67. #endif
  68. /*
  69. * AES instruction support detection routine
  70. */
  71. int mbedtls_aesce_has_support(void)
  72. {
  73. #if defined(__linux__)
  74. unsigned long auxval = getauxval(AT_HWCAP);
  75. return (auxval & (HWCAP_ASIMD | HWCAP_AES)) ==
  76. (HWCAP_ASIMD | HWCAP_AES);
  77. #else
  78. /* Assume AES instructions are supported. */
  79. return 1;
  80. #endif
  81. }
  82. static uint8x16_t aesce_encrypt_block(uint8x16_t block,
  83. unsigned char *keys,
  84. int rounds)
  85. {
  86. for (int i = 0; i < rounds - 1; i++) {
  87. /* AES AddRoundKey, SubBytes, ShiftRows (in this order).
  88. * AddRoundKey adds the round key for the previous round. */
  89. block = vaeseq_u8(block, vld1q_u8(keys + i * 16));
  90. /* AES mix columns */
  91. block = vaesmcq_u8(block);
  92. }
  93. /* AES AddRoundKey for the previous round.
  94. * SubBytes, ShiftRows for the final round. */
  95. block = vaeseq_u8(block, vld1q_u8(keys + (rounds -1) * 16));
  96. /* Final round: no MixColumns */
  97. /* Final AddRoundKey */
  98. block = veorq_u8(block, vld1q_u8(keys + rounds * 16));
  99. return block;
  100. }
  101. static uint8x16_t aesce_decrypt_block(uint8x16_t block,
  102. unsigned char *keys,
  103. int rounds)
  104. {
  105. for (int i = 0; i < rounds - 1; i++) {
  106. /* AES AddRoundKey, SubBytes, ShiftRows */
  107. block = vaesdq_u8(block, vld1q_u8(keys + i * 16));
  108. /* AES inverse MixColumns for the next round.
  109. *
  110. * This means that we switch the order of the inverse AddRoundKey and
  111. * inverse MixColumns operations. We have to do this as AddRoundKey is
  112. * done in an atomic instruction together with the inverses of SubBytes
  113. * and ShiftRows.
  114. *
  115. * It works because MixColumns is a linear operation over GF(2^8) and
  116. * AddRoundKey is an exclusive or, which is equivalent to addition over
  117. * GF(2^8). (The inverse of MixColumns needs to be applied to the
  118. * affected round keys separately which has been done when the
  119. * decryption round keys were calculated.) */
  120. block = vaesimcq_u8(block);
  121. }
  122. /* The inverses of AES AddRoundKey, SubBytes, ShiftRows finishing up the
  123. * last full round. */
  124. block = vaesdq_u8(block, vld1q_u8(keys + (rounds - 1) * 16));
  125. /* Inverse AddRoundKey for inverting the initial round key addition. */
  126. block = veorq_u8(block, vld1q_u8(keys + rounds * 16));
  127. return block;
  128. }
  129. /*
  130. * AES-ECB block en(de)cryption
  131. */
  132. int mbedtls_aesce_crypt_ecb(mbedtls_aes_context *ctx,
  133. int mode,
  134. const unsigned char input[16],
  135. unsigned char output[16])
  136. {
  137. uint8x16_t block = vld1q_u8(&input[0]);
  138. unsigned char *keys = (unsigned char *) (ctx->buf + ctx->rk_offset);
  139. if (mode == MBEDTLS_AES_ENCRYPT) {
  140. block = aesce_encrypt_block(block, keys, ctx->nr);
  141. } else {
  142. block = aesce_decrypt_block(block, keys, ctx->nr);
  143. }
  144. vst1q_u8(&output[0], block);
  145. return 0;
  146. }
  147. /*
  148. * Compute decryption round keys from encryption round keys
  149. */
  150. void mbedtls_aesce_inverse_key(unsigned char *invkey,
  151. const unsigned char *fwdkey,
  152. int nr)
  153. {
  154. int i, j;
  155. j = nr;
  156. vst1q_u8(invkey, vld1q_u8(fwdkey + j * 16));
  157. for (i = 1, j--; j > 0; i++, j--) {
  158. vst1q_u8(invkey + i * 16,
  159. vaesimcq_u8(vld1q_u8(fwdkey + j * 16)));
  160. }
  161. vst1q_u8(invkey + i * 16, vld1q_u8(fwdkey + j * 16));
  162. }
  163. static inline uint32_t aes_rot_word(uint32_t word)
  164. {
  165. return (word << (32 - 8)) | (word >> 8);
  166. }
  167. static inline uint32_t aes_sub_word(uint32_t in)
  168. {
  169. uint8x16_t v = vreinterpretq_u8_u32(vdupq_n_u32(in));
  170. uint8x16_t zero = vdupq_n_u8(0);
  171. /* vaeseq_u8 does both SubBytes and ShiftRows. Taking the first row yields
  172. * the correct result as ShiftRows doesn't change the first row. */
  173. v = vaeseq_u8(zero, v);
  174. return vgetq_lane_u32(vreinterpretq_u32_u8(v), 0);
  175. }
  176. /*
  177. * Key expansion function
  178. */
  179. static void aesce_setkey_enc(unsigned char *rk,
  180. const unsigned char *key,
  181. const size_t key_bit_length)
  182. {
  183. static uint8_t const rcon[] = { 0x01, 0x02, 0x04, 0x08, 0x10,
  184. 0x20, 0x40, 0x80, 0x1b, 0x36 };
  185. /* See https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.197.pdf
  186. * - Section 5, Nr = Nk + 6
  187. * - Section 5.2, the length of round keys is Nb*(Nr+1)
  188. */
  189. const uint32_t key_len_in_words = key_bit_length / 32; /* Nk */
  190. const size_t round_key_len_in_words = 4; /* Nb */
  191. const size_t rounds_needed = key_len_in_words + 6; /* Nr */
  192. const size_t round_keys_len_in_words =
  193. round_key_len_in_words * (rounds_needed + 1); /* Nb*(Nr+1) */
  194. const uint32_t *rko_end = (uint32_t *) rk + round_keys_len_in_words;
  195. memcpy(rk, key, key_len_in_words * 4);
  196. for (uint32_t *rki = (uint32_t *) rk;
  197. rki + key_len_in_words < rko_end;
  198. rki += key_len_in_words) {
  199. size_t iteration = (rki - (uint32_t *) rk) / key_len_in_words;
  200. uint32_t *rko;
  201. rko = rki + key_len_in_words;
  202. rko[0] = aes_rot_word(aes_sub_word(rki[key_len_in_words - 1]));
  203. rko[0] ^= rcon[iteration] ^ rki[0];
  204. rko[1] = rko[0] ^ rki[1];
  205. rko[2] = rko[1] ^ rki[2];
  206. rko[3] = rko[2] ^ rki[3];
  207. if (rko + key_len_in_words > rko_end) {
  208. /* Do not write overflow words.*/
  209. continue;
  210. }
  211. switch (key_bit_length) {
  212. case 128:
  213. break;
  214. case 192:
  215. rko[4] = rko[3] ^ rki[4];
  216. rko[5] = rko[4] ^ rki[5];
  217. break;
  218. case 256:
  219. rko[4] = aes_sub_word(rko[3]) ^ rki[4];
  220. rko[5] = rko[4] ^ rki[5];
  221. rko[6] = rko[5] ^ rki[6];
  222. rko[7] = rko[6] ^ rki[7];
  223. break;
  224. }
  225. }
  226. }
  227. /*
  228. * Key expansion, wrapper
  229. */
  230. int mbedtls_aesce_setkey_enc(unsigned char *rk,
  231. const unsigned char *key,
  232. size_t bits)
  233. {
  234. switch (bits) {
  235. case 128:
  236. case 192:
  237. case 256:
  238. aesce_setkey_enc(rk, key, bits);
  239. break;
  240. default:
  241. return MBEDTLS_ERR_AES_INVALID_KEY_LENGTH;
  242. }
  243. return 0;
  244. }
  245. #if defined(MBEDTLS_GCM_C)
  246. #if !defined(__clang__) && defined(__GNUC__) && __GNUC__ == 5
  247. /* Some intrinsics are not available for GCC 5.X. */
  248. #define vreinterpretq_p64_u8(a) ((poly64x2_t) a)
  249. #define vreinterpretq_u8_p128(a) ((uint8x16_t) a)
  250. static inline poly64_t vget_low_p64(poly64x2_t __a)
  251. {
  252. uint64x2_t tmp = (uint64x2_t) (__a);
  253. uint64x1_t lo = vcreate_u64(vgetq_lane_u64(tmp, 0));
  254. return (poly64_t) (lo);
  255. }
  256. #endif /* !__clang__ && __GNUC__ && __GNUC__ == 5*/
  257. /* vmull_p64/vmull_high_p64 wrappers.
  258. *
  259. * Older compilers miss some intrinsic functions for `poly*_t`. We use
  260. * uint8x16_t and uint8x16x3_t as input/output parameters.
  261. */
  262. static inline uint8x16_t pmull_low(uint8x16_t a, uint8x16_t b)
  263. {
  264. return vreinterpretq_u8_p128(
  265. vmull_p64(
  266. (poly64_t) vget_low_p64(vreinterpretq_p64_u8(a)),
  267. (poly64_t) vget_low_p64(vreinterpretq_p64_u8(b))));
  268. }
  269. static inline uint8x16_t pmull_high(uint8x16_t a, uint8x16_t b)
  270. {
  271. return vreinterpretq_u8_p128(
  272. vmull_high_p64(vreinterpretq_p64_u8(a),
  273. vreinterpretq_p64_u8(b)));
  274. }
  275. /* GHASH does 128b polynomial multiplication on block in GF(2^128) defined by
  276. * `x^128 + x^7 + x^2 + x + 1`.
  277. *
  278. * Arm64 only has 64b->128b polynomial multipliers, we need to do 4 64b
  279. * multiplies to generate a 128b.
  280. *
  281. * `poly_mult_128` executes polynomial multiplication and outputs 256b that
  282. * represented by 3 128b due to code size optimization.
  283. *
  284. * Output layout:
  285. * | | | |
  286. * |------------|-------------|-------------|
  287. * | ret.val[0] | h3:h2:00:00 | high 128b |
  288. * | ret.val[1] | :m2:m1:00 | middle 128b |
  289. * | ret.val[2] | : :l1:l0 | low 128b |
  290. */
  291. static inline uint8x16x3_t poly_mult_128(uint8x16_t a, uint8x16_t b)
  292. {
  293. uint8x16x3_t ret;
  294. uint8x16_t h, m, l; /* retval high/middle/low */
  295. uint8x16_t c, d, e;
  296. h = pmull_high(a, b); /* h3:h2:00:00 = a1*b1 */
  297. l = pmull_low(a, b); /* : :l1:l0 = a0*b0 */
  298. c = vextq_u8(b, b, 8); /* :c1:c0 = b0:b1 */
  299. d = pmull_high(a, c); /* :d2:d1:00 = a1*b0 */
  300. e = pmull_low(a, c); /* :e2:e1:00 = a0*b1 */
  301. m = veorq_u8(d, e); /* :m2:m1:00 = d + e */
  302. ret.val[0] = h;
  303. ret.val[1] = m;
  304. ret.val[2] = l;
  305. return ret;
  306. }
  307. /*
  308. * Modulo reduction.
  309. *
  310. * See: https://www.researchgate.net/publication/285612706_Implementing_GCM_on_ARMv8
  311. *
  312. * Section 4.3
  313. *
  314. * Modular reduction is slightly more complex. Write the GCM modulus as f(z) =
  315. * z^128 +r(z), where r(z) = z^7+z^2+z+ 1. The well known approach is to
  316. * consider that z^128 ≡r(z) (mod z^128 +r(z)), allowing us to write the 256-bit
  317. * operand to be reduced as a(z) = h(z)z^128 +l(z)≡h(z)r(z) + l(z). That is, we
  318. * simply multiply the higher part of the operand by r(z) and add it to l(z). If
  319. * the result is still larger than 128 bits, we reduce again.
  320. */
  321. static inline uint8x16_t poly_mult_reduce(uint8x16x3_t input)
  322. {
  323. uint8x16_t const ZERO = vdupq_n_u8(0);
  324. /* use 'asm' as an optimisation barrier to prevent loading MODULO from memory */
  325. uint64x2_t r = vreinterpretq_u64_u8(vdupq_n_u8(0x87));
  326. asm ("" : "+w" (r));
  327. uint8x16_t const MODULO = vreinterpretq_u8_u64(vshrq_n_u64(r, 64 - 8));
  328. uint8x16_t h, m, l; /* input high/middle/low 128b */
  329. uint8x16_t c, d, e, f, g, n, o;
  330. h = input.val[0]; /* h3:h2:00:00 */
  331. m = input.val[1]; /* :m2:m1:00 */
  332. l = input.val[2]; /* : :l1:l0 */
  333. c = pmull_high(h, MODULO); /* :c2:c1:00 = reduction of h3 */
  334. d = pmull_low(h, MODULO); /* : :d1:d0 = reduction of h2 */
  335. e = veorq_u8(c, m); /* :e2:e1:00 = m2:m1:00 + c2:c1:00 */
  336. f = pmull_high(e, MODULO); /* : :f1:f0 = reduction of e2 */
  337. g = vextq_u8(ZERO, e, 8); /* : :g1:00 = e1:00 */
  338. n = veorq_u8(d, l); /* : :n1:n0 = d1:d0 + l1:l0 */
  339. o = veorq_u8(n, f); /* o1:o0 = f1:f0 + n1:n0 */
  340. return veorq_u8(o, g); /* = o1:o0 + g1:00 */
  341. }
  342. /*
  343. * GCM multiplication: c = a times b in GF(2^128)
  344. */
  345. void mbedtls_aesce_gcm_mult(unsigned char c[16],
  346. const unsigned char a[16],
  347. const unsigned char b[16])
  348. {
  349. uint8x16_t va, vb, vc;
  350. va = vrbitq_u8(vld1q_u8(&a[0]));
  351. vb = vrbitq_u8(vld1q_u8(&b[0]));
  352. vc = vrbitq_u8(poly_mult_reduce(poly_mult_128(va, vb)));
  353. vst1q_u8(&c[0], vc);
  354. }
  355. #endif /* MBEDTLS_GCM_C */
  356. #if defined(MBEDTLS_POP_TARGET_PRAGMA)
  357. #if defined(__clang__)
  358. #pragma clang attribute pop
  359. #elif defined(__GNUC__)
  360. #pragma GCC pop_options
  361. #endif
  362. #undef MBEDTLS_POP_TARGET_PRAGMA
  363. #endif
  364. #endif /* MBEDTLS_HAVE_ARM64 */
  365. #endif /* MBEDTLS_AESCE_C */