sshaes.c 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914
  1. /*
  2. * sshaes.c - implementation of AES
  3. */
  4. #include <assert.h>
  5. #include <stdlib.h>
  6. #include "ssh.h"
  7. #include "mpint_i.h" /* we reuse the BignumInt system */
  8. /*
  9. * Start by deciding whether we can support hardware AES at all.
  10. */
  11. #define HW_AES_NONE 0
  12. #define HW_AES_NI 1
  13. #define HW_AES_NEON 2
  14. #ifdef _FORCE_AES_NI
  15. # define HW_AES HW_AES_NI
  16. #elif defined(__clang__)
  17. # if __has_attribute(target) && __has_include(<wmmintrin.h>) && \
  18. (defined(__x86_64__) || defined(__i386))
  19. # define HW_AES HW_AES_NI
  20. # endif
  21. #elif defined(__GNUC__)
  22. # if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)) && \
  23. (defined(__x86_64__) || defined(__i386))
  24. # define HW_AES HW_AES_NI
  25. # endif
  26. #elif defined (_MSC_VER)
  27. # if (defined(_M_X64) || defined(_M_IX86)) && _MSC_FULL_VER >= 150030729
  28. # define HW_AES HW_AES_NI
  29. # endif
  30. #endif
  31. #ifdef _FORCE_AES_NEON
  32. # define HW_AES HW_AES_NEON
  33. #elif defined __BYTE_ORDER__ && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
  34. /* Arm can potentially support both endiannesses, but this code
  35. * hasn't been tested on anything but little. If anyone wants to
  36. * run big-endian, they'll need to fix it first. */
  37. #elif defined __ARM_FEATURE_CRYPTO
  38. /* If the Arm crypto extension is available already, we can
  39. * support NEON AES without having to enable anything by hand */
  40. # define HW_AES HW_AES_NEON
  41. #elif defined(__clang__)
  42. # if __has_attribute(target) && __has_include(<arm_neon.h>) && \
  43. (defined(__aarch64__))
  44. /* clang can enable the crypto extension in AArch64 using
  45. * __attribute__((target)) */
  46. # define HW_AES HW_AES_NEON
  47. # define USE_CLANG_ATTR_TARGET_AARCH64
  48. # endif
  49. #elif defined _MSC_VER
  50. # if defined _M_ARM64
  51. # define HW_AES HW_AES_NEON
  52. /* 64-bit Visual Studio uses the header <arm64_neon.h> in place
  53. * of the standard <arm_neon.h> */
  54. # define USE_ARM64_NEON_H
  55. # elif defined _M_ARM
  56. # define HW_AES HW_AES_NEON
  57. /* 32-bit Visual Studio uses the right header name, but requires
  58. * this #define to enable a set of intrinsic definitions that
  59. * do not omit one of the parameters for vaes[ed]q_u8 */
  60. # define _ARM_USE_NEW_NEON_INTRINSICS
  61. # endif
  62. #endif
  63. #if defined _FORCE_SOFTWARE_AES || !defined HW_AES
  64. # undef HW_AES
  65. # define HW_AES HW_AES_NONE
  66. #endif
  67. #if HW_AES == HW_AES_NI
  68. #define HW_NAME_SUFFIX " (AES-NI accelerated)"
  69. #elif HW_AES == HW_AES_NEON
  70. #define HW_NAME_SUFFIX " (NEON accelerated)"
  71. #else
  72. #define HW_NAME_SUFFIX " (!NONEXISTENT ACCELERATED VERSION!)"
  73. #endif
  74. /*
  75. * Vtable collection for AES. For each SSH-level cipher id (i.e.
  76. * combination of key length and cipher mode), we provide three
  77. * vtables: one for the pure software implementation, one using
  78. * hardware acceleration (if available), and a top-level one which is
  79. * never actually instantiated, and only contains a new() method whose
  80. * job is to decide which of the other two to return an actual
  81. * instance of.
  82. */
  83. static ssh_cipher *aes_select(const ssh_cipheralg *alg);
  84. static ssh_cipher *aes_sw_new(const ssh_cipheralg *alg);
  85. static void aes_sw_free(ssh_cipher *);
  86. static void aes_sw_setiv_cbc(ssh_cipher *, const void *iv);
  87. static void aes_sw_setiv_sdctr(ssh_cipher *, const void *iv);
  88. static void aes_sw_setkey(ssh_cipher *, const void *key);
  89. static ssh_cipher *aes_hw_new(const ssh_cipheralg *alg);
  90. static void aes_hw_free(ssh_cipher *);
  91. static void aes_hw_setiv_cbc(ssh_cipher *, const void *iv);
  92. static void aes_hw_setiv_sdctr(ssh_cipher *, const void *iv);
  93. static void aes_hw_setkey(ssh_cipher *, const void *key);
  94. struct aes_extra {
  95. const ssh_cipheralg *sw, *hw;
  96. };
  97. #define VTABLES_INNER(cid, pid, bits, name, encsuffix, \
  98. decsuffix, setivsuffix, flagsval) \
  99. static void cid##_sw##encsuffix(ssh_cipher *, void *blk, int len); \
  100. static void cid##_sw##decsuffix(ssh_cipher *, void *blk, int len); \
  101. const ssh_cipheralg ssh_##cid##_sw = { \
  102. .new = aes_sw_new, \
  103. .free = aes_sw_free, \
  104. .setiv = aes_sw_##setivsuffix, \
  105. .setkey = aes_sw_setkey, \
  106. .encrypt = cid##_sw##encsuffix, \
  107. .decrypt = cid##_sw##decsuffix, \
  108. .ssh2_id = pid, \
  109. .blksize = 16, \
  110. .real_keybits = bits, \
  111. .padded_keybytes = bits/8, \
  112. .flags = flagsval, \
  113. .text_name = name " (unaccelerated)", \
  114. }; \
  115. \
  116. static void cid##_hw##encsuffix(ssh_cipher *, void *blk, int len); \
  117. static void cid##_hw##decsuffix(ssh_cipher *, void *blk, int len); \
  118. const ssh_cipheralg ssh_##cid##_hw = { \
  119. .new = aes_hw_new, \
  120. .free = aes_hw_free, \
  121. .setiv = aes_hw_##setivsuffix, \
  122. .setkey = aes_hw_setkey, \
  123. .encrypt = cid##_hw##encsuffix, \
  124. .decrypt = cid##_hw##decsuffix, \
  125. .ssh2_id = pid, \
  126. .blksize = 16, \
  127. .real_keybits = bits, \
  128. .padded_keybytes = bits/8, \
  129. .flags = flagsval, \
  130. .text_name = name HW_NAME_SUFFIX, \
  131. }; \
  132. \
  133. static const struct aes_extra extra_##cid = { \
  134. &ssh_##cid##_sw, &ssh_##cid##_hw }; \
  135. \
  136. const ssh_cipheralg ssh_##cid = { \
  137. .new = aes_select, \
  138. .ssh2_id = pid, \
  139. .blksize = 16, \
  140. .real_keybits = bits, \
  141. .padded_keybytes = bits/8, \
  142. .flags = flagsval, \
  143. .text_name = name " (dummy selector vtable)", \
  144. .extra = &extra_##cid \
  145. }; \
  146. #define VTABLES(keylen) \
  147. VTABLES_INNER(aes ## keylen ## _cbc, "aes" #keylen "-cbc", \
  148. keylen, "AES-" #keylen " CBC", _encrypt, _decrypt, \
  149. setiv_cbc, SSH_CIPHER_IS_CBC) \
  150. VTABLES_INNER(aes ## keylen ## _sdctr, "aes" #keylen "-ctr", \
  151. keylen, "AES-" #keylen " SDCTR",,, setiv_sdctr, 0)
  152. VTABLES(128)
  153. VTABLES(192)
  154. VTABLES(256)
  155. static const ssh_cipheralg ssh_rijndael_lysator = {
  156. /* Same as aes256_cbc, but with a different protocol ID */
  157. .new = aes_select,
  158. .ssh2_id = "rijndael-cbc@lysator.liu.se",
  159. .blksize = 16,
  160. .real_keybits = 256,
  161. .padded_keybytes = 256/8,
  162. .flags = 0,
  163. .text_name = "AES-256 CBC (dummy selector vtable)",
  164. .extra = &extra_aes256_cbc,
  165. };
  166. static const ssh_cipheralg *const aes_list[] = {
  167. &ssh_aes256_sdctr,
  168. &ssh_aes256_cbc,
  169. &ssh_rijndael_lysator,
  170. &ssh_aes192_sdctr,
  171. &ssh_aes192_cbc,
  172. &ssh_aes128_sdctr,
  173. &ssh_aes128_cbc,
  174. };
  175. const ssh2_ciphers ssh2_aes = { lenof(aes_list), aes_list };
  176. /*
  177. * The actual query function that asks if hardware acceleration is
  178. * available.
  179. */
  180. static bool aes_hw_available(void);
  181. /*
  182. * The top-level selection function, caching the results of
  183. * aes_hw_available() so it only has to run once.
  184. */
  185. static bool aes_hw_available_cached(void)
  186. {
  187. static bool initialised = false;
  188. static bool hw_available;
  189. if (!initialised) {
  190. hw_available = aes_hw_available();
  191. initialised = true;
  192. }
  193. return hw_available;
  194. }
  195. static ssh_cipher *aes_select(const ssh_cipheralg *alg)
  196. {
  197. const struct aes_extra *extra = (const struct aes_extra *)alg->extra;
  198. const ssh_cipheralg *real_alg =
  199. aes_hw_available_cached() ? extra->hw : extra->sw;
  200. return ssh_cipher_new(real_alg);
  201. }
  202. /* ----------------------------------------------------------------------
  203. * Definitions likely to be helpful to multiple implementations.
  204. */
  205. #define REP2(x) x x
  206. #define REP4(x) REP2(REP2(x))
  207. #define REP8(x) REP2(REP4(x))
  208. #define REP9(x) REP8(x) x
  209. #define REP11(x) REP8(x) REP2(x) x
  210. #define REP13(x) REP8(x) REP4(x) x
  211. static const uint8_t key_setup_round_constants[] = {
  212. /* The first few powers of X in GF(2^8), used during key setup.
  213. * This can safely be a lookup table without side channel risks,
  214. * because key setup iterates through it once in a standard way
  215. * regardless of the key. */
  216. 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36,
  217. };
  218. #define MAXROUNDKEYS 15
  219. /* ----------------------------------------------------------------------
  220. * Software implementation of AES.
  221. *
  222. * This implementation uses a bit-sliced representation. Instead of
  223. * the obvious approach of storing the cipher state so that each byte
  224. * (or field element, or entry in the cipher matrix) occupies 8
  225. * contiguous bits in a machine integer somewhere, we organise the
  226. * cipher state as an array of 8 integers, in such a way that each
  227. * logical byte of the cipher state occupies one bit in each integer,
  228. * all at the same position. This allows us to do parallel logic on
  229. * all bytes of the state by doing bitwise operations between the 8
  230. * integers; in particular, the S-box (SubBytes) lookup is done this
  231. * way, which takes about 110 operations - but for those 110 bitwise
  232. * ops you get 64 S-box lookups, not just one.
  233. */
  234. #define SLICE_PARALLELISM (BIGNUM_INT_BYTES / 2)
  235. #ifdef BITSLICED_DEBUG
  236. /* Dump function that undoes the bitslicing transform, so you can see
  237. * the logical data represented by a set of slice words. */
  238. static inline void dumpslices_uint16_t(
  239. const char *prefix, const uint16_t slices[8])
  240. {
  241. printf("%-30s", prefix);
  242. for (unsigned byte = 0; byte < 16; byte++) {
  243. unsigned byteval = 0;
  244. for (unsigned bit = 0; bit < 8; bit++)
  245. byteval |= (1 & (slices[bit] >> byte)) << bit;
  246. printf("%02x", byteval);
  247. }
  248. printf("\n");
  249. }
  250. static inline void dumpslices_BignumInt(
  251. const char *prefix, const BignumInt slices[8])
  252. {
  253. printf("%-30s", prefix);
  254. for (unsigned iter = 0; iter < SLICE_PARALLELISM; iter++) {
  255. for (unsigned byte = 0; byte < 16; byte++) {
  256. unsigned byteval = 0;
  257. for (unsigned bit = 0; bit < 8; bit++)
  258. byteval |= (1 & (slices[bit] >> (iter*16+byte))) << bit;
  259. printf("%02x", byteval);
  260. }
  261. if (iter+1 < SLICE_PARALLELISM)
  262. printf(" ");
  263. }
  264. printf("\n");
  265. }
  266. #else
  267. #define dumpslices_uintN_t(prefix, slices) ((void)0)
  268. #define dumpslices_BignumInt(prefix, slices) ((void)0)
  269. #endif
  270. /* -----
  271. * Bit-slicing transformation: convert between an array of 16 uint8_t
  272. * and an array of 8 uint16_t, so as to interchange the bit index
  273. * within each element and the element index within the array. (That
  274. * is, bit j of input[i] == bit i of output[j].
  275. */
  276. #define SWAPWORDS(shift) do \
  277. { \
  278. uint64_t mask = ~(uint64_t)0 / ((1ULL << shift) + 1); \
  279. uint64_t diff = ((i0 >> shift) ^ i1) & mask; \
  280. i0 ^= diff << shift; \
  281. i1 ^= diff; \
  282. } while (0)
  283. #define SWAPINWORD(i, bigshift, smallshift) do \
  284. { \
  285. uint64_t mask = ~(uint64_t)0; \
  286. mask /= ((1ULL << bigshift) + 1); \
  287. mask /= ((1ULL << smallshift) + 1); \
  288. mask <<= smallshift; \
  289. unsigned shift = bigshift - smallshift; \
  290. uint64_t diff = ((i >> shift) ^ i) & mask; \
  291. i ^= diff ^ (diff << shift); \
  292. } while (0)
  293. #define TO_BITSLICES(slices, bytes, uintN_t, assign_op, shift) do \
  294. { \
  295. uint64_t i0 = GET_64BIT_LSB_FIRST(bytes); \
  296. uint64_t i1 = GET_64BIT_LSB_FIRST(bytes + 8); \
  297. SWAPINWORD(i0, 8, 1); \
  298. SWAPINWORD(i1, 8, 1); \
  299. SWAPINWORD(i0, 16, 2); \
  300. SWAPINWORD(i1, 16, 2); \
  301. SWAPINWORD(i0, 32, 4); \
  302. SWAPINWORD(i1, 32, 4); \
  303. SWAPWORDS(8); \
  304. slices[0] assign_op (uintN_t)((i0 >> 0) & 0xFFFF) << (shift); \
  305. slices[2] assign_op (uintN_t)((i0 >> 16) & 0xFFFF) << (shift); \
  306. slices[4] assign_op (uintN_t)((i0 >> 32) & 0xFFFF) << (shift); \
  307. slices[6] assign_op (uintN_t)((i0 >> 48) & 0xFFFF) << (shift); \
  308. slices[1] assign_op (uintN_t)((i1 >> 0) & 0xFFFF) << (shift); \
  309. slices[3] assign_op (uintN_t)((i1 >> 16) & 0xFFFF) << (shift); \
  310. slices[5] assign_op (uintN_t)((i1 >> 32) & 0xFFFF) << (shift); \
  311. slices[7] assign_op (uintN_t)((i1 >> 48) & 0xFFFF) << (shift); \
  312. } while (0)
  313. #define FROM_BITSLICES(bytes, slices, shift) do \
  314. { \
  315. uint64_t i1 = ((slices[7] >> (shift)) & 0xFFFF); \
  316. i1 = (i1 << 16) | ((slices[5] >> (shift)) & 0xFFFF); \
  317. i1 = (i1 << 16) | ((slices[3] >> (shift)) & 0xFFFF); \
  318. i1 = (i1 << 16) | ((slices[1] >> (shift)) & 0xFFFF); \
  319. uint64_t i0 = ((slices[6] >> (shift)) & 0xFFFF); \
  320. i0 = (i0 << 16) | ((slices[4] >> (shift)) & 0xFFFF); \
  321. i0 = (i0 << 16) | ((slices[2] >> (shift)) & 0xFFFF); \
  322. i0 = (i0 << 16) | ((slices[0] >> (shift)) & 0xFFFF); \
  323. SWAPWORDS(8); \
  324. SWAPINWORD(i0, 32, 4); \
  325. SWAPINWORD(i1, 32, 4); \
  326. SWAPINWORD(i0, 16, 2); \
  327. SWAPINWORD(i1, 16, 2); \
  328. SWAPINWORD(i0, 8, 1); \
  329. SWAPINWORD(i1, 8, 1); \
  330. PUT_64BIT_LSB_FIRST(bytes, i0); \
  331. PUT_64BIT_LSB_FIRST((bytes) + 8, i1); \
  332. } while (0)
  333. /* -----
  334. * Some macros that will be useful repeatedly.
  335. */
  336. /* Iterate a unary transformation over all 8 slices. */
  337. #define ITERATE(MACRO, output, input, uintN_t) do \
  338. { \
  339. MACRO(output[0], input[0], uintN_t); \
  340. MACRO(output[1], input[1], uintN_t); \
  341. MACRO(output[2], input[2], uintN_t); \
  342. MACRO(output[3], input[3], uintN_t); \
  343. MACRO(output[4], input[4], uintN_t); \
  344. MACRO(output[5], input[5], uintN_t); \
  345. MACRO(output[6], input[6], uintN_t); \
  346. MACRO(output[7], input[7], uintN_t); \
  347. } while (0)
  348. /* Simply add (i.e. XOR) two whole sets of slices together. */
  349. #define BITSLICED_ADD(output, lhs, rhs) do \
  350. { \
  351. output[0] = lhs[0] ^ rhs[0]; \
  352. output[1] = lhs[1] ^ rhs[1]; \
  353. output[2] = lhs[2] ^ rhs[2]; \
  354. output[3] = lhs[3] ^ rhs[3]; \
  355. output[4] = lhs[4] ^ rhs[4]; \
  356. output[5] = lhs[5] ^ rhs[5]; \
  357. output[6] = lhs[6] ^ rhs[6]; \
  358. output[7] = lhs[7] ^ rhs[7]; \
  359. } while (0)
  360. /* -----
  361. * The AES S-box, in pure bitwise logic so that it can be run in
  362. * parallel on whole words full of bit-sliced field elements.
  363. *
  364. * Source: 'A new combinational logic minimization technique with
  365. * applications to cryptology', https://eprint.iacr.org/2009/191
  366. *
  367. * As a minor speed optimisation, I use a modified version of the
  368. * S-box which omits the additive constant 0x63, i.e. this S-box
  369. * consists of only the field inversion and linear map components.
  370. * Instead, the addition of the constant is deferred until after the
  371. * subsequent ShiftRows and MixColumns stages, so that it happens at
  372. * the same time as adding the next round key - and then we just make
  373. * it _part_ of the round key, so it doesn't cost any extra
  374. * instructions to add.
  375. *
  376. * (Obviously adding a constant to each byte commutes with ShiftRows,
  377. * which only permutes the bytes. It also commutes with MixColumns:
  378. * that's not quite so obvious, but since the effect of MixColumns is
  379. * to multiply a constant polynomial M into each column, it is obvious
  380. * that adding some polynomial K and then multiplying by M is
  381. * equivalent to multiplying by M and then adding the product KM. And
  382. * in fact, since the coefficients of M happen to sum to 1, it turns
  383. * out that KM = K, so we don't even have to change the constant when
  384. * we move it to the far side of MixColumns.)
  385. *
  386. * Of course, one knock-on effect of this is that the use of the S-box
  387. * *during* key setup has to be corrected by manually adding on the
  388. * constant afterwards!
  389. */
  390. /* Initial linear transformation for the forward S-box, from Fig 2 of
  391. * the paper. */
  392. #define SBOX_FORWARD_TOP_TRANSFORM(input, uintN_t) \
  393. uintN_t y14 = input[4] ^ input[2]; \
  394. uintN_t y13 = input[7] ^ input[1]; \
  395. uintN_t y9 = input[7] ^ input[4]; \
  396. uintN_t y8 = input[7] ^ input[2]; \
  397. uintN_t t0 = input[6] ^ input[5]; \
  398. uintN_t y1 = t0 ^ input[0]; \
  399. uintN_t y4 = y1 ^ input[4]; \
  400. uintN_t y12 = y13 ^ y14; \
  401. uintN_t y2 = y1 ^ input[7]; \
  402. uintN_t y5 = y1 ^ input[1]; \
  403. uintN_t y3 = y5 ^ y8; \
  404. uintN_t t1 = input[3] ^ y12; \
  405. uintN_t y15 = t1 ^ input[2]; \
  406. uintN_t y20 = t1 ^ input[6]; \
  407. uintN_t y6 = y15 ^ input[0]; \
  408. uintN_t y10 = y15 ^ t0; \
  409. uintN_t y11 = y20 ^ y9; \
  410. uintN_t y7 = input[0] ^ y11; \
  411. uintN_t y17 = y10 ^ y11; \
  412. uintN_t y19 = y10 ^ y8; \
  413. uintN_t y16 = t0 ^ y11; \
  414. uintN_t y21 = y13 ^ y16; \
  415. uintN_t y18 = input[7] ^ y16; \
  416. /* Make a copy of input[0] under a new name, because the core
  417. * will refer to it, and in the inverse version of the S-box
  418. * the corresponding value will be one of the calculated ones
  419. * and not in input[0] itself. */ \
  420. uintN_t i0 = input[0]; \
  421. /* end */
  422. /* Core nonlinear component, from Fig 3 of the paper. */
  423. #define SBOX_CORE(uintN_t) \
  424. uintN_t t2 = y12 & y15; \
  425. uintN_t t3 = y3 & y6; \
  426. uintN_t t4 = t3 ^ t2; \
  427. uintN_t t5 = y4 & i0; \
  428. uintN_t t6 = t5 ^ t2; \
  429. uintN_t t7 = y13 & y16; \
  430. uintN_t t8 = y5 & y1; \
  431. uintN_t t9 = t8 ^ t7; \
  432. uintN_t t10 = y2 & y7; \
  433. uintN_t t11 = t10 ^ t7; \
  434. uintN_t t12 = y9 & y11; \
  435. uintN_t t13 = y14 & y17; \
  436. uintN_t t14 = t13 ^ t12; \
  437. uintN_t t15 = y8 & y10; \
  438. uintN_t t16 = t15 ^ t12; \
  439. uintN_t t17 = t4 ^ t14; \
  440. uintN_t t18 = t6 ^ t16; \
  441. uintN_t t19 = t9 ^ t14; \
  442. uintN_t t20 = t11 ^ t16; \
  443. uintN_t t21 = t17 ^ y20; \
  444. uintN_t t22 = t18 ^ y19; \
  445. uintN_t t23 = t19 ^ y21; \
  446. uintN_t t24 = t20 ^ y18; \
  447. uintN_t t25 = t21 ^ t22; \
  448. uintN_t t26 = t21 & t23; \
  449. uintN_t t27 = t24 ^ t26; \
  450. uintN_t t28 = t25 & t27; \
  451. uintN_t t29 = t28 ^ t22; \
  452. uintN_t t30 = t23 ^ t24; \
  453. uintN_t t31 = t22 ^ t26; \
  454. uintN_t t32 = t31 & t30; \
  455. uintN_t t33 = t32 ^ t24; \
  456. uintN_t t34 = t23 ^ t33; \
  457. uintN_t t35 = t27 ^ t33; \
  458. uintN_t t36 = t24 & t35; \
  459. uintN_t t37 = t36 ^ t34; \
  460. uintN_t t38 = t27 ^ t36; \
  461. uintN_t t39 = t29 & t38; \
  462. uintN_t t40 = t25 ^ t39; \
  463. uintN_t t41 = t40 ^ t37; \
  464. uintN_t t42 = t29 ^ t33; \
  465. uintN_t t43 = t29 ^ t40; \
  466. uintN_t t44 = t33 ^ t37; \
  467. uintN_t t45 = t42 ^ t41; \
  468. uintN_t z0 = t44 & y15; \
  469. uintN_t z1 = t37 & y6; \
  470. uintN_t z2 = t33 & i0; \
  471. uintN_t z3 = t43 & y16; \
  472. uintN_t z4 = t40 & y1; \
  473. uintN_t z5 = t29 & y7; \
  474. uintN_t z6 = t42 & y11; \
  475. uintN_t z7 = t45 & y17; \
  476. uintN_t z8 = t41 & y10; \
  477. uintN_t z9 = t44 & y12; \
  478. uintN_t z10 = t37 & y3; \
  479. uintN_t z11 = t33 & y4; \
  480. uintN_t z12 = t43 & y13; \
  481. uintN_t z13 = t40 & y5; \
  482. uintN_t z14 = t29 & y2; \
  483. uintN_t z15 = t42 & y9; \
  484. uintN_t z16 = t45 & y14; \
  485. uintN_t z17 = t41 & y8; \
  486. /* end */
  487. /* Final linear transformation for the forward S-box, from Fig 4 of
  488. * the paper. */
  489. #define SBOX_FORWARD_BOTTOM_TRANSFORM(output, uintN_t) \
  490. uintN_t t46 = z15 ^ z16; \
  491. uintN_t t47 = z10 ^ z11; \
  492. uintN_t t48 = z5 ^ z13; \
  493. uintN_t t49 = z9 ^ z10; \
  494. uintN_t t50 = z2 ^ z12; \
  495. uintN_t t51 = z2 ^ z5; \
  496. uintN_t t52 = z7 ^ z8; \
  497. uintN_t t53 = z0 ^ z3; \
  498. uintN_t t54 = z6 ^ z7; \
  499. uintN_t t55 = z16 ^ z17; \
  500. uintN_t t56 = z12 ^ t48; \
  501. uintN_t t57 = t50 ^ t53; \
  502. uintN_t t58 = z4 ^ t46; \
  503. uintN_t t59 = z3 ^ t54; \
  504. uintN_t t60 = t46 ^ t57; \
  505. uintN_t t61 = z14 ^ t57; \
  506. uintN_t t62 = t52 ^ t58; \
  507. uintN_t t63 = t49 ^ t58; \
  508. uintN_t t64 = z4 ^ t59; \
  509. uintN_t t65 = t61 ^ t62; \
  510. uintN_t t66 = z1 ^ t63; \
  511. output[7] = t59 ^ t63; \
  512. output[1] = t56 ^ t62; \
  513. output[0] = t48 ^ t60; \
  514. uintN_t t67 = t64 ^ t65; \
  515. output[4] = t53 ^ t66; \
  516. output[3] = t51 ^ t66; \
  517. output[2] = t47 ^ t65; \
  518. output[6] = t64 ^ output[4]; \
  519. output[5] = t55 ^ t67; \
  520. /* end */
  521. #define BITSLICED_SUBBYTES(output, input, uintN_t) do { \
  522. SBOX_FORWARD_TOP_TRANSFORM(input, uintN_t); \
  523. SBOX_CORE(uintN_t); \
  524. SBOX_FORWARD_BOTTOM_TRANSFORM(output, uintN_t); \
  525. } while (0)
  526. /*
  527. * Initial and final linear transformations for the backward S-box. I
  528. * generated these myself, by implementing the linear-transform
  529. * optimisation algorithm in the paper, and applying it to the
  530. * matrices calculated by _their_ top and bottom transformations, pre-
  531. * and post-multiplied as appropriate by the linear map in the inverse
  532. * S_box.
  533. */
  534. #define SBOX_BACKWARD_TOP_TRANSFORM(input, uintN_t) \
  535. uintN_t y5 = input[4] ^ input[6]; \
  536. uintN_t y19 = input[3] ^ input[0]; \
  537. uintN_t itmp8 = y5 ^ input[0]; \
  538. uintN_t y4 = itmp8 ^ input[1]; \
  539. uintN_t y9 = input[4] ^ input[3]; \
  540. uintN_t y2 = y9 ^ y4; \
  541. uintN_t itmp9 = y2 ^ input[7]; \
  542. uintN_t y1 = y9 ^ input[0]; \
  543. uintN_t y6 = y5 ^ input[7]; \
  544. uintN_t y18 = y9 ^ input[5]; \
  545. uintN_t y7 = y18 ^ y2; \
  546. uintN_t y16 = y7 ^ y1; \
  547. uintN_t y21 = y7 ^ input[1]; \
  548. uintN_t y3 = input[4] ^ input[7]; \
  549. uintN_t y13 = y16 ^ y21; \
  550. uintN_t y8 = input[4] ^ y6; \
  551. uintN_t y10 = y8 ^ y19; \
  552. uintN_t y14 = y8 ^ y9; \
  553. uintN_t y20 = itmp9 ^ input[2]; \
  554. uintN_t y11 = y9 ^ y20; \
  555. uintN_t i0 = y11 ^ y7; \
  556. uintN_t y15 = i0 ^ y6; \
  557. uintN_t y17 = y16 ^ y15; \
  558. uintN_t y12 = itmp9 ^ input[3]; \
  559. /* end */
  560. #define SBOX_BACKWARD_BOTTOM_TRANSFORM(output, uintN_t) \
  561. uintN_t otmp18 = z15 ^ z6; \
  562. uintN_t otmp19 = z13 ^ otmp18; \
  563. uintN_t otmp20 = z12 ^ otmp19; \
  564. uintN_t otmp21 = z16 ^ otmp20; \
  565. uintN_t otmp22 = z8 ^ otmp21; \
  566. uintN_t otmp23 = z0 ^ otmp22; \
  567. uintN_t otmp24 = otmp22 ^ z3; \
  568. uintN_t otmp25 = otmp24 ^ z4; \
  569. uintN_t otmp26 = otmp25 ^ z2; \
  570. uintN_t otmp27 = z1 ^ otmp26; \
  571. uintN_t otmp28 = z14 ^ otmp27; \
  572. uintN_t otmp29 = otmp28 ^ z10; \
  573. output[4] = z2 ^ otmp23; \
  574. output[7] = z5 ^ otmp24; \
  575. uintN_t otmp30 = z11 ^ otmp29; \
  576. output[5] = z13 ^ otmp30; \
  577. uintN_t otmp31 = otmp25 ^ z8; \
  578. output[1] = z7 ^ otmp31; \
  579. uintN_t otmp32 = z11 ^ z9; \
  580. uintN_t otmp33 = z17 ^ otmp32; \
  581. uintN_t otmp34 = otmp30 ^ otmp33; \
  582. output[0] = z15 ^ otmp33; \
  583. uintN_t otmp35 = z12 ^ otmp34; \
  584. output[6] = otmp35 ^ z16; \
  585. uintN_t otmp36 = z1 ^ otmp23; \
  586. uintN_t otmp37 = z5 ^ otmp36; \
  587. output[2] = z4 ^ otmp37; \
  588. uintN_t otmp38 = z11 ^ output[1]; \
  589. uintN_t otmp39 = z2 ^ otmp38; \
  590. uintN_t otmp40 = z17 ^ otmp39; \
  591. uintN_t otmp41 = z0 ^ otmp40; \
  592. uintN_t otmp42 = z5 ^ otmp41; \
  593. uintN_t otmp43 = otmp42 ^ z10; \
  594. uintN_t otmp44 = otmp43 ^ z3; \
  595. output[3] = otmp44 ^ z16; \
  596. /* end */
  597. #define BITSLICED_INVSUBBYTES(output, input, uintN_t) do { \
  598. SBOX_BACKWARD_TOP_TRANSFORM(input, uintN_t); \
  599. SBOX_CORE(uintN_t); \
  600. SBOX_BACKWARD_BOTTOM_TRANSFORM(output, uintN_t); \
  601. } while (0)
  602. /* -----
  603. * The ShiftRows transformation. This operates independently on each
  604. * bit slice.
  605. */
  606. #define SINGLE_BITSLICE_SHIFTROWS(output, input, uintN_t) do \
  607. { \
  608. uintN_t mask, mask2, mask3, diff, x = (input); \
  609. /* Rotate rows 2 and 3 by 16 bits */ \
  610. mask = 0x00CC * (((uintN_t)~(uintN_t)0) / 0xFFFF); \
  611. diff = ((x >> 8) ^ x) & mask; \
  612. x ^= diff ^ (diff << 8); \
  613. /* Rotate rows 1 and 3 by 8 bits */ \
  614. mask = 0x0AAA * (((uintN_t)~(uintN_t)0) / 0xFFFF); \
  615. mask2 = 0xA000 * (((uintN_t)~(uintN_t)0) / 0xFFFF); \
  616. mask3 = 0x5555 * (((uintN_t)~(uintN_t)0) / 0xFFFF); \
  617. x = ((x >> 4) & mask) | ((x << 12) & mask2) | (x & mask3); \
  618. /* Write output */ \
  619. (output) = x; \
  620. } while (0)
  621. #define SINGLE_BITSLICE_INVSHIFTROWS(output, input, uintN_t) do \
  622. { \
  623. uintN_t mask, mask2, mask3, diff, x = (input); \
  624. /* Rotate rows 2 and 3 by 16 bits */ \
  625. mask = 0x00CC * (((uintN_t)~(uintN_t)0) / 0xFFFF); \
  626. diff = ((x >> 8) ^ x) & mask; \
  627. x ^= diff ^ (diff << 8); \
  628. /* Rotate rows 1 and 3 by 8 bits, the opposite way to ShiftRows */ \
  629. mask = 0x000A * (((uintN_t)~(uintN_t)0) / 0xFFFF); \
  630. mask2 = 0xAAA0 * (((uintN_t)~(uintN_t)0) / 0xFFFF); \
  631. mask3 = 0x5555 * (((uintN_t)~(uintN_t)0) / 0xFFFF); \
  632. x = ((x >> 12) & mask) | ((x << 4) & mask2) | (x & mask3); \
  633. /* Write output */ \
  634. (output) = x; \
  635. } while (0)
  636. #define BITSLICED_SHIFTROWS(output, input, uintN_t) do \
  637. { \
  638. ITERATE(SINGLE_BITSLICE_SHIFTROWS, output, input, uintN_t); \
  639. } while (0)
  640. #define BITSLICED_INVSHIFTROWS(output, input, uintN_t) do \
  641. { \
  642. ITERATE(SINGLE_BITSLICE_INVSHIFTROWS, output, input, uintN_t); \
  643. } while (0)
  644. /* -----
  645. * The MixColumns transformation. This has to operate on all eight bit
  646. * slices at once, and also passes data back and forth between the
  647. * bits in an adjacent group of 4 within each slice.
  648. *
  649. * Notation: let F = GF(2)[X]/<X^8+X^4+X^3+X+1> be the finite field
  650. * used in AES, and let R = F[Y]/<Y^4+1> be the ring whose elements
  651. * represent the possible contents of a column of the matrix. I use X
  652. * and Y below in those senses, i.e. X is the value in F that
  653. * represents the byte 0x02, and Y is the value in R that cycles the
  654. * four bytes around by one if you multiply by it.
  655. */
  656. /* Multiply every column by Y^3, i.e. cycle it round one place to the
  657. * right. Operates on one bit slice at a time; you have to wrap it in
  658. * ITERATE to affect all the data at once. */
  659. #define BITSLICED_MUL_BY_Y3(output, input, uintN_t) do \
  660. { \
  661. uintN_t mask, mask2, x; \
  662. mask = 0x8 * (((uintN_t)~(uintN_t)0) / 0xF); \
  663. mask2 = 0x7 * (((uintN_t)~(uintN_t)0) / 0xF); \
  664. x = input; \
  665. output = ((x << 3) & mask) ^ ((x >> 1) & mask2); \
  666. } while (0)
  667. /* Multiply every column by Y^2. */
  668. #define BITSLICED_MUL_BY_Y2(output, input, uintN_t) do \
  669. { \
  670. uintN_t mask, mask2, x; \
  671. mask = 0xC * (((uintN_t)~(uintN_t)0) / 0xF); \
  672. mask2 = 0x3 * (((uintN_t)~(uintN_t)0) / 0xF); \
  673. x = input; \
  674. output = ((x << 2) & mask) ^ ((x >> 2) & mask2); \
  675. } while (0)
  676. #define BITSLICED_MUL_BY_1_Y3(output, input, uintN_t) do \
  677. { \
  678. uintN_t tmp = input; \
  679. BITSLICED_MUL_BY_Y3(tmp, input, uintN_t); \
  680. output = input ^ tmp; \
  681. } while (0)
  682. /* Multiply every column by 1+Y^2. */
  683. #define BITSLICED_MUL_BY_1_Y2(output, input, uintN_t) do \
  684. { \
  685. uintN_t tmp = input; \
  686. BITSLICED_MUL_BY_Y2(tmp, input, uintN_t); \
  687. output = input ^ tmp; \
  688. } while (0)
  689. /* Multiply every field element by X. This has to feed data between
  690. * slices, so it does the whole job in one go without needing ITERATE. */
  691. #define BITSLICED_MUL_BY_X(output, input, uintN_t) do \
  692. { \
  693. uintN_t bit7 = input[7]; \
  694. output[7] = input[6]; \
  695. output[6] = input[5]; \
  696. output[5] = input[4]; \
  697. output[4] = input[3] ^ bit7; \
  698. output[3] = input[2] ^ bit7; \
  699. output[2] = input[1]; \
  700. output[1] = input[0] ^ bit7; \
  701. output[0] = bit7; \
  702. } while (0)
  703. /*
  704. * The MixColumns constant is
  705. * M = X + Y + Y^2 + (X+1)Y^3
  706. * which we construct by rearranging it into
  707. * M = 1 + (1+Y^3) [ X + (1+Y^2) ]
  708. */
  709. #define BITSLICED_MIXCOLUMNS(output, input, uintN_t) do \
  710. { \
  711. uintN_t a[8], aX[8], b[8]; \
  712. /* a = input * (1+Y^3) */ \
  713. ITERATE(BITSLICED_MUL_BY_1_Y3, a, input, uintN_t); \
  714. /* aX = a * X */ \
  715. BITSLICED_MUL_BY_X(aX, a, uintN_t); \
  716. /* b = a * (1+Y^2) = input * (1+Y+Y^2+Y^3) */ \
  717. ITERATE(BITSLICED_MUL_BY_1_Y2, b, a, uintN_t); \
  718. /* output = input + aX + b (reusing a as a temp */ \
  719. BITSLICED_ADD(a, aX, b); \
  720. BITSLICED_ADD(output, input, a); \
  721. } while (0)
  722. /*
  723. * The InvMixColumns constant, written out longhand, is
  724. * I = (X^3+X^2+X) + (X^3+1)Y + (X^3+X^2+1)Y^2 + (X^3+X+1)Y^3
  725. * We represent this as
  726. * I = (X^3+X^2+X+1)(Y^3+Y^2+Y+1) + 1 + X(Y+Y^2) + X^2(Y+Y^3)
  727. */
  728. #define BITSLICED_INVMIXCOLUMNS(output, input, uintN_t) do \
  729. { \
  730. /* We need input * X^i for i=1,...,3 */ \
  731. uintN_t X[8], X2[8], X3[8]; \
  732. BITSLICED_MUL_BY_X(X, input, uintN_t); \
  733. BITSLICED_MUL_BY_X(X2, X, uintN_t); \
  734. BITSLICED_MUL_BY_X(X3, X2, uintN_t); \
  735. /* Sum them all and multiply by 1+Y+Y^2+Y^3. */ \
  736. uintN_t S[8]; \
  737. BITSLICED_ADD(S, input, X); \
  738. BITSLICED_ADD(S, S, X2); \
  739. BITSLICED_ADD(S, S, X3); \
  740. ITERATE(BITSLICED_MUL_BY_1_Y3, S, S, uintN_t); \
  741. ITERATE(BITSLICED_MUL_BY_1_Y2, S, S, uintN_t); \
  742. /* Compute the X(Y+Y^2) term. */ \
  743. uintN_t A[8]; \
  744. ITERATE(BITSLICED_MUL_BY_1_Y3, A, X, uintN_t); \
  745. ITERATE(BITSLICED_MUL_BY_Y2, A, A, uintN_t); \
  746. /* Compute the X^2(Y+Y^3) term. */ \
  747. uintN_t B[8]; \
  748. ITERATE(BITSLICED_MUL_BY_1_Y2, B, X2, uintN_t); \
  749. ITERATE(BITSLICED_MUL_BY_Y3, B, B, uintN_t); \
  750. /* And add all the pieces together. */ \
  751. BITSLICED_ADD(S, S, input); \
  752. BITSLICED_ADD(S, S, A); \
  753. BITSLICED_ADD(output, S, B); \
  754. } while (0)
  755. /* -----
  756. * Put it all together into a cipher round.
  757. */
  758. /* Dummy macro to get rid of the MixColumns in the final round. */
  759. #define NO_MIXCOLUMNS(out, in, uintN_t) do {} while (0)
  760. #define ENCRYPT_ROUND_FN(suffix, uintN_t, mixcol_macro) \
  761. static void aes_sliced_round_e_##suffix( \
  762. uintN_t output[8], const uintN_t input[8], const uintN_t roundkey[8]) \
  763. { \
  764. BITSLICED_SUBBYTES(output, input, uintN_t); \
  765. BITSLICED_SHIFTROWS(output, output, uintN_t); \
  766. mixcol_macro(output, output, uintN_t); \
  767. BITSLICED_ADD(output, output, roundkey); \
  768. }
  769. ENCRYPT_ROUND_FN(serial, uint16_t, BITSLICED_MIXCOLUMNS)
  770. ENCRYPT_ROUND_FN(serial_last, uint16_t, NO_MIXCOLUMNS)
  771. ENCRYPT_ROUND_FN(parallel, BignumInt, BITSLICED_MIXCOLUMNS)
  772. ENCRYPT_ROUND_FN(parallel_last, BignumInt, NO_MIXCOLUMNS)
  773. #define DECRYPT_ROUND_FN(suffix, uintN_t, mixcol_macro) \
  774. static void aes_sliced_round_d_##suffix( \
  775. uintN_t output[8], const uintN_t input[8], const uintN_t roundkey[8]) \
  776. { \
  777. BITSLICED_ADD(output, input, roundkey); \
  778. mixcol_macro(output, output, uintN_t); \
  779. BITSLICED_INVSUBBYTES(output, output, uintN_t); \
  780. BITSLICED_INVSHIFTROWS(output, output, uintN_t); \
  781. }
  782. #if 0 /* no cipher mode we support requires serial decryption */
  783. DECRYPT_ROUND_FN(serial, uint16_t, BITSLICED_INVMIXCOLUMNS)
  784. DECRYPT_ROUND_FN(serial_first, uint16_t, NO_MIXCOLUMNS)
  785. #endif
  786. DECRYPT_ROUND_FN(parallel, BignumInt, BITSLICED_INVMIXCOLUMNS)
  787. DECRYPT_ROUND_FN(parallel_first, BignumInt, NO_MIXCOLUMNS)
  788. /* -----
  789. * Key setup function.
  790. */
  791. typedef struct aes_sliced_key aes_sliced_key;
  792. struct aes_sliced_key {
  793. BignumInt roundkeys_parallel[MAXROUNDKEYS * 8];
  794. uint16_t roundkeys_serial[MAXROUNDKEYS * 8];
  795. unsigned rounds;
  796. };
  797. static void aes_sliced_key_setup(
  798. aes_sliced_key *sk, const void *vkey, size_t keybits)
  799. {
  800. const unsigned char *key = (const unsigned char *)vkey;
  801. size_t key_words = keybits / 32;
  802. sk->rounds = key_words + 6;
  803. size_t sched_words = (sk->rounds + 1) * 4;
  804. unsigned rconpos = 0;
  805. uint16_t *outslices = sk->roundkeys_serial;
  806. unsigned outshift = 0;
  807. memset(sk->roundkeys_serial, 0, sizeof(sk->roundkeys_serial));
  808. uint8_t inblk[16];
  809. memset(inblk, 0, 16);
  810. uint16_t slices[8];
  811. for (size_t i = 0; i < sched_words; i++) {
  812. /*
  813. * Prepare a word of round key in the low 4 bits of each
  814. * integer in slices[].
  815. */
  816. if (i < key_words) {
  817. memcpy(inblk, key + 4*i, 4);
  818. TO_BITSLICES(slices, inblk, uint16_t, =, 0);
  819. } else {
  820. unsigned wordindex, bitshift;
  821. uint16_t *prevslices;
  822. /* Fetch the (i-1)th key word */
  823. wordindex = i-1;
  824. bitshift = 4 * (wordindex & 3);
  825. prevslices = sk->roundkeys_serial + 8 * (wordindex >> 2);
  826. for (size_t i = 0; i < 8; i++)
  827. slices[i] = prevslices[i] >> bitshift;
  828. /* Decide what we're doing in this expansion stage */
  829. bool rotate_and_round_constant = (i % key_words == 0);
  830. bool sub = rotate_and_round_constant ||
  831. (key_words == 8 && i % 8 == 4);
  832. if (rotate_and_round_constant) {
  833. for (size_t i = 0; i < 8; i++)
  834. slices[i] = ((slices[i] << 3) | (slices[i] >> 1)) & 0xF;
  835. }
  836. if (sub) {
  837. /* Apply the SubBytes transform to the key word. But
  838. * here we need to apply the _full_ SubBytes from the
  839. * spec, including the constant which our S-box leaves
  840. * out. */
  841. BITSLICED_SUBBYTES(slices, slices, uint16_t);
  842. slices[0] ^= 0xFFFF;
  843. slices[1] ^= 0xFFFF;
  844. slices[5] ^= 0xFFFF;
  845. slices[6] ^= 0xFFFF;
  846. }
  847. if (rotate_and_round_constant) {
  848. assert(rconpos < lenof(key_setup_round_constants));
  849. uint8_t rcon = key_setup_round_constants[rconpos++];
  850. for (size_t i = 0; i < 8; i++)
  851. slices[i] ^= 1 & (rcon >> i);
  852. }
  853. /* Combine with the (i-Nk)th key word */
  854. wordindex = i - key_words;
  855. bitshift = 4 * (wordindex & 3);
  856. prevslices = sk->roundkeys_serial + 8 * (wordindex >> 2);
  857. for (size_t i = 0; i < 8; i++)
  858. slices[i] ^= prevslices[i] >> bitshift;
  859. }
  860. /*
  861. * Now copy it into sk.
  862. */
  863. for (unsigned b = 0; b < 8; b++)
  864. outslices[b] |= (slices[b] & 0xF) << outshift;
  865. outshift += 4;
  866. if (outshift == 16) {
  867. outshift = 0;
  868. outslices += 8;
  869. }
  870. }
  871. smemclr(inblk, sizeof(inblk));
  872. smemclr(slices, sizeof(slices));
  873. /*
  874. * Add the S-box constant to every round key after the first one,
  875. * compensating for it being left out in the main cipher.
  876. */
  877. for (size_t i = 8; i < 8 * (sched_words/4); i += 8) {
  878. sk->roundkeys_serial[i+0] ^= 0xFFFF;
  879. sk->roundkeys_serial[i+1] ^= 0xFFFF;
  880. sk->roundkeys_serial[i+5] ^= 0xFFFF;
  881. sk->roundkeys_serial[i+6] ^= 0xFFFF;
  882. }
  883. /*
  884. * Replicate that set of round keys into larger integers for the
  885. * parallel versions of the cipher.
  886. */
  887. for (size_t i = 0; i < 8 * (sched_words / 4); i++) {
  888. sk->roundkeys_parallel[i] = sk->roundkeys_serial[i] *
  889. ((BignumInt)~(BignumInt)0 / 0xFFFF);
  890. }
  891. }
  892. /* -----
  893. * The full cipher primitive, including transforming the input and
  894. * output to/from bit-sliced form.
  895. */
  896. #define ENCRYPT_FN(suffix, uintN_t, nblocks) \
  897. static void aes_sliced_e_##suffix( \
  898. uint8_t *output, const uint8_t *input, const aes_sliced_key *sk) \
  899. { \
  900. uintN_t state[8]; \
  901. TO_BITSLICES(state, input, uintN_t, =, 0); \
  902. for (unsigned i = 1; i < nblocks; i++) { \
  903. input += 16; \
  904. TO_BITSLICES(state, input, uintN_t, |=, i*16); \
  905. } \
  906. const uintN_t *keys = sk->roundkeys_##suffix; \
  907. BITSLICED_ADD(state, state, keys); \
  908. keys += 8; \
  909. for (unsigned i = 0; i < sk->rounds-1; i++) { \
  910. aes_sliced_round_e_##suffix(state, state, keys); \
  911. keys += 8; \
  912. } \
  913. aes_sliced_round_e_##suffix##_last(state, state, keys); \
  914. for (unsigned i = 0; i < nblocks; i++) { \
  915. FROM_BITSLICES(output, state, i*16); \
  916. output += 16; \
  917. } \
  918. }
  919. #define DECRYPT_FN(suffix, uintN_t, nblocks) \
  920. static void aes_sliced_d_##suffix( \
  921. uint8_t *output, const uint8_t *input, const aes_sliced_key *sk) \
  922. { \
  923. uintN_t state[8]; \
  924. TO_BITSLICES(state, input, uintN_t, =, 0); \
  925. for (unsigned i = 1; i < nblocks; i++) { \
  926. input += 16; \
  927. TO_BITSLICES(state, input, uintN_t, |=, i*16); \
  928. } \
  929. const uintN_t *keys = sk->roundkeys_##suffix + 8*sk->rounds; \
  930. aes_sliced_round_d_##suffix##_first(state, state, keys); \
  931. keys -= 8; \
  932. for (unsigned i = 0; i < sk->rounds-1; i++) { \
  933. aes_sliced_round_d_##suffix(state, state, keys); \
  934. keys -= 8; \
  935. } \
  936. BITSLICED_ADD(state, state, keys); \
  937. for (unsigned i = 0; i < nblocks; i++) { \
  938. FROM_BITSLICES(output, state, i*16); \
  939. output += 16; \
  940. } \
  941. }
  942. ENCRYPT_FN(serial, uint16_t, 1)
  943. #if 0 /* no cipher mode we support requires serial decryption */
  944. DECRYPT_FN(serial, uint16_t, 1)
  945. #endif
  946. ENCRYPT_FN(parallel, BignumInt, SLICE_PARALLELISM)
  947. DECRYPT_FN(parallel, BignumInt, SLICE_PARALLELISM)
  948. /* -----
  949. * The SSH interface and the cipher modes.
  950. */
  951. #define SDCTR_WORDS (16 / BIGNUM_INT_BYTES)
  952. typedef struct aes_sw_context aes_sw_context;
  953. struct aes_sw_context {
  954. aes_sliced_key sk;
  955. union {
  956. struct {
  957. /* In CBC mode, the IV is just a copy of the last seen
  958. * cipher block. */
  959. uint8_t prevblk[16];
  960. } cbc;
  961. struct {
  962. /* In SDCTR mode, we keep the counter itself in a form
  963. * that's easy to increment. We also use the parallel
  964. * version of the core AES function, so we'll encrypt
  965. * multiple counter values in one go. That won't align
  966. * nicely with the sizes of data we're asked to encrypt,
  967. * so we must also store a cache of the last set of
  968. * keystream blocks we generated, and our current position
  969. * within that cache. */
  970. BignumInt counter[SDCTR_WORDS];
  971. uint8_t keystream[SLICE_PARALLELISM * 16];
  972. uint8_t *keystream_pos;
  973. } sdctr;
  974. } iv;
  975. ssh_cipher ciph;
  976. };
  977. static ssh_cipher *aes_sw_new(const ssh_cipheralg *alg)
  978. {
  979. aes_sw_context *ctx = snew(aes_sw_context);
  980. ctx->ciph.vt = alg;
  981. return &ctx->ciph;
  982. }
  983. static void aes_sw_free(ssh_cipher *ciph)
  984. {
  985. aes_sw_context *ctx = container_of(ciph, aes_sw_context, ciph);
  986. smemclr(ctx, sizeof(*ctx));
  987. sfree(ctx);
  988. }
  989. static void aes_sw_setkey(ssh_cipher *ciph, const void *vkey)
  990. {
  991. aes_sw_context *ctx = container_of(ciph, aes_sw_context, ciph);
  992. aes_sliced_key_setup(&ctx->sk, vkey, ctx->ciph.vt->real_keybits);
  993. }
  994. static void aes_sw_setiv_cbc(ssh_cipher *ciph, const void *iv)
  995. {
  996. aes_sw_context *ctx = container_of(ciph, aes_sw_context, ciph);
  997. memcpy(ctx->iv.cbc.prevblk, iv, 16);
  998. }
  999. static void aes_sw_setiv_sdctr(ssh_cipher *ciph, const void *viv)
  1000. {
  1001. aes_sw_context *ctx = container_of(ciph, aes_sw_context, ciph);
  1002. const uint8_t *iv = (const uint8_t *)viv;
  1003. /* Import the initial counter value into the internal representation */
  1004. for (unsigned i = 0; i < SDCTR_WORDS; i++)
  1005. ctx->iv.sdctr.counter[i] =
  1006. GET_BIGNUMINT_MSB_FIRST(
  1007. iv + 16 - BIGNUM_INT_BYTES - i*BIGNUM_INT_BYTES);
  1008. /* Set keystream_pos to indicate that the keystream cache is
  1009. * currently empty */
  1010. ctx->iv.sdctr.keystream_pos =
  1011. ctx->iv.sdctr.keystream + sizeof(ctx->iv.sdctr.keystream);
  1012. }
  1013. typedef void (*aes_sw_fn)(uint32_t v[4], const uint32_t *keysched);
  1014. static inline void memxor16(void *vout, const void *vlhs, const void *vrhs)
  1015. {
  1016. uint8_t *out = (uint8_t *)vout;
  1017. const uint8_t *lhs = (const uint8_t *)vlhs, *rhs = (const uint8_t *)vrhs;
  1018. uint64_t w;
  1019. w = GET_64BIT_LSB_FIRST(lhs);
  1020. w ^= GET_64BIT_LSB_FIRST(rhs);
  1021. PUT_64BIT_LSB_FIRST(out, w);
  1022. w = GET_64BIT_LSB_FIRST(lhs + 8);
  1023. w ^= GET_64BIT_LSB_FIRST(rhs + 8);
  1024. PUT_64BIT_LSB_FIRST(out + 8, w);
  1025. }
  1026. static inline void aes_cbc_sw_encrypt(
  1027. ssh_cipher *ciph, void *vblk, int blklen)
  1028. {
  1029. aes_sw_context *ctx = container_of(ciph, aes_sw_context, ciph);
  1030. /*
  1031. * CBC encryption has to be done serially, because the input to
  1032. * each run of the cipher includes the output from the previous
  1033. * run.
  1034. */
  1035. for (uint8_t *blk = (uint8_t *)vblk, *finish = blk + blklen;
  1036. blk < finish; blk += 16) {
  1037. /*
  1038. * We use the IV array itself as the location for the
  1039. * encryption, because there's no reason not to.
  1040. */
  1041. /* XOR the new plaintext block into the previous cipher block */
  1042. memxor16(ctx->iv.cbc.prevblk, ctx->iv.cbc.prevblk, blk);
  1043. /* Run the cipher over the result, which leaves it
  1044. * conveniently already stored in ctx->iv */
  1045. aes_sliced_e_serial(
  1046. ctx->iv.cbc.prevblk, ctx->iv.cbc.prevblk, &ctx->sk);
  1047. /* Copy it to the output location */
  1048. memcpy(blk, ctx->iv.cbc.prevblk, 16);
  1049. }
  1050. }
  1051. static inline void aes_cbc_sw_decrypt(
  1052. ssh_cipher *ciph, void *vblk, int blklen)
  1053. {
  1054. aes_sw_context *ctx = container_of(ciph, aes_sw_context, ciph);
  1055. uint8_t *blk = (uint8_t *)vblk;
  1056. /*
  1057. * CBC decryption can run in parallel, because all the
  1058. * _ciphertext_ blocks are already available.
  1059. */
  1060. size_t blocks_remaining = blklen / 16;
  1061. uint8_t data[SLICE_PARALLELISM * 16];
  1062. /* Zeroing the data array is probably overcautious, but it avoids
  1063. * technically undefined behaviour from leaving it uninitialised
  1064. * if our very first iteration doesn't include enough cipher
  1065. * blocks to populate it fully */
  1066. memset(data, 0, sizeof(data));
  1067. while (blocks_remaining > 0) {
  1068. /* Number of blocks we'll handle in this iteration. If we're
  1069. * dealing with fewer than the maximum, it doesn't matter -
  1070. * it's harmless to run the full parallel cipher function
  1071. * anyway. */
  1072. size_t blocks = (blocks_remaining < SLICE_PARALLELISM ?
  1073. blocks_remaining : SLICE_PARALLELISM);
  1074. /* Parallel-decrypt the input, in a separate array so we still
  1075. * have the cipher stream available for XORing. */
  1076. memcpy(data, blk, 16 * blocks);
  1077. aes_sliced_d_parallel(data, data, &ctx->sk);
  1078. /* Write the output and update the IV */
  1079. for (size_t i = 0; i < blocks; i++) {
  1080. uint8_t *decrypted = data + 16*i;
  1081. uint8_t *output = blk + 16*i;
  1082. memxor16(decrypted, decrypted, ctx->iv.cbc.prevblk);
  1083. memcpy(ctx->iv.cbc.prevblk, output, 16);
  1084. memcpy(output, decrypted, 16);
  1085. }
  1086. /* Advance the input pointer. */
  1087. blk += 16 * blocks;
  1088. blocks_remaining -= blocks;
  1089. }
  1090. smemclr(data, sizeof(data));
  1091. }
  1092. static inline void aes_sdctr_sw(
  1093. ssh_cipher *ciph, void *vblk, int blklen)
  1094. {
  1095. aes_sw_context *ctx = container_of(ciph, aes_sw_context, ciph);
  1096. /*
  1097. * SDCTR encrypt/decrypt loops round one block at a time XORing
  1098. * the keystream into the user's data, and periodically has to run
  1099. * a parallel encryption operation to get more keystream.
  1100. */
  1101. uint8_t *keystream_end =
  1102. ctx->iv.sdctr.keystream + sizeof(ctx->iv.sdctr.keystream);
  1103. for (uint8_t *blk = (uint8_t *)vblk, *finish = blk + blklen;
  1104. blk < finish; blk += 16) {
  1105. if (ctx->iv.sdctr.keystream_pos == keystream_end) {
  1106. /*
  1107. * Generate some keystream.
  1108. */
  1109. for (uint8_t *block = ctx->iv.sdctr.keystream;
  1110. block < keystream_end; block += 16) {
  1111. /* Format the counter value into the buffer. */
  1112. for (unsigned i = 0; i < SDCTR_WORDS; i++)
  1113. PUT_BIGNUMINT_MSB_FIRST(
  1114. block + 16 - BIGNUM_INT_BYTES - i*BIGNUM_INT_BYTES,
  1115. ctx->iv.sdctr.counter[i]);
  1116. /* Increment the counter. */
  1117. BignumCarry carry = 1;
  1118. for (unsigned i = 0; i < SDCTR_WORDS; i++)
  1119. BignumADC(ctx->iv.sdctr.counter[i], carry,
  1120. ctx->iv.sdctr.counter[i], 0, carry);
  1121. }
  1122. /* Encrypt all those counter blocks. */
  1123. aes_sliced_e_parallel(ctx->iv.sdctr.keystream,
  1124. ctx->iv.sdctr.keystream, &ctx->sk);
  1125. /* Reset keystream_pos to the start of the buffer. */
  1126. ctx->iv.sdctr.keystream_pos = ctx->iv.sdctr.keystream;
  1127. }
  1128. memxor16(blk, blk, ctx->iv.sdctr.keystream_pos);
  1129. ctx->iv.sdctr.keystream_pos += 16;
  1130. }
  1131. }
  1132. #define SW_ENC_DEC(len) \
  1133. static void aes##len##_cbc_sw_encrypt( \
  1134. ssh_cipher *ciph, void *vblk, int blklen) \
  1135. { aes_cbc_sw_encrypt(ciph, vblk, blklen); } \
  1136. static void aes##len##_cbc_sw_decrypt( \
  1137. ssh_cipher *ciph, void *vblk, int blklen) \
  1138. { aes_cbc_sw_decrypt(ciph, vblk, blklen); } \
  1139. static void aes##len##_sdctr_sw( \
  1140. ssh_cipher *ciph, void *vblk, int blklen) \
  1141. { aes_sdctr_sw(ciph, vblk, blklen); }
  1142. SW_ENC_DEC(128)
  1143. SW_ENC_DEC(192)
  1144. SW_ENC_DEC(256)
  1145. /* ----------------------------------------------------------------------
  1146. * Hardware-accelerated implementation of AES using x86 AES-NI.
  1147. */
  1148. #if HW_AES == HW_AES_NI
  1149. /*
  1150. * Set target architecture for Clang and GCC
  1151. */
  1152. #if !defined(__clang__) && defined(__GNUC__)
  1153. # pragma GCC target("aes")
  1154. # pragma GCC target("sse4.1")
  1155. #endif
  1156. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)))
  1157. # define FUNC_ISA __attribute__ ((target("sse4.1,aes")))
  1158. #else
  1159. # define FUNC_ISA
  1160. #endif
  1161. #include <wmmintrin.h>
  1162. #include <smmintrin.h>
  1163. #if defined(__clang__) || defined(__GNUC__)
  1164. #include <cpuid.h>
  1165. #define GET_CPU_ID(out) __cpuid(1, (out)[0], (out)[1], (out)[2], (out)[3])
  1166. #else
  1167. #define GET_CPU_ID(out) __cpuid(out, 1)
  1168. #endif
  1169. bool aes_hw_available(void)
  1170. {
  1171. /*
  1172. * Determine if AES is available on this CPU, by checking that
  1173. * both AES itself and SSE4.1 are supported.
  1174. */
  1175. unsigned int CPUInfo[4];
  1176. GET_CPU_ID(CPUInfo);
  1177. return (CPUInfo[2] & (1 << 25)) && (CPUInfo[2] & (1 << 19));
  1178. }
  1179. /*
  1180. * Core AES-NI encrypt/decrypt functions, one per length and direction.
  1181. */
  1182. #define NI_CIPHER(len, dir, dirlong, repmacro) \
  1183. static FUNC_ISA inline __m128i aes_ni_##len##_##dir( \
  1184. __m128i v, const __m128i *keysched) \
  1185. { \
  1186. v = _mm_xor_si128(v, *keysched++); \
  1187. repmacro(v = _mm_aes##dirlong##_si128(v, *keysched++);); \
  1188. return _mm_aes##dirlong##last_si128(v, *keysched); \
  1189. }
  1190. NI_CIPHER(128, e, enc, REP9)
  1191. NI_CIPHER(128, d, dec, REP9)
  1192. NI_CIPHER(192, e, enc, REP11)
  1193. NI_CIPHER(192, d, dec, REP11)
  1194. NI_CIPHER(256, e, enc, REP13)
  1195. NI_CIPHER(256, d, dec, REP13)
  1196. /*
  1197. * The main key expansion.
  1198. */
  1199. static FUNC_ISA void aes_ni_key_expand(
  1200. const unsigned char *key, size_t key_words,
  1201. __m128i *keysched_e, __m128i *keysched_d)
  1202. {
  1203. size_t rounds = key_words + 6;
  1204. size_t sched_words = (rounds + 1) * 4;
  1205. /*
  1206. * Store the key schedule as 32-bit integers during expansion, so
  1207. * that it's easy to refer back to individual previous words. We
  1208. * collect them into the final __m128i form at the end.
  1209. */
  1210. uint32_t sched[MAXROUNDKEYS * 4];
  1211. unsigned rconpos = 0;
  1212. for (size_t i = 0; i < sched_words; i++) {
  1213. if (i < key_words) {
  1214. sched[i] = GET_32BIT_LSB_FIRST(key + 4 * i);
  1215. } else {
  1216. uint32_t temp = sched[i - 1];
  1217. bool rotate_and_round_constant = (i % key_words == 0);
  1218. bool only_sub = (key_words == 8 && i % 8 == 4);
  1219. if (rotate_and_round_constant) {
  1220. __m128i v = _mm_setr_epi32(0,temp,0,0);
  1221. v = _mm_aeskeygenassist_si128(v, 0);
  1222. temp = _mm_extract_epi32(v, 1);
  1223. assert(rconpos < lenof(key_setup_round_constants));
  1224. temp ^= key_setup_round_constants[rconpos++];
  1225. } else if (only_sub) {
  1226. __m128i v = _mm_setr_epi32(0,temp,0,0);
  1227. v = _mm_aeskeygenassist_si128(v, 0);
  1228. temp = _mm_extract_epi32(v, 0);
  1229. }
  1230. sched[i] = sched[i - key_words] ^ temp;
  1231. }
  1232. }
  1233. /*
  1234. * Combine the key schedule words into __m128i vectors and store
  1235. * them in the output context.
  1236. */
  1237. for (size_t round = 0; round <= rounds; round++)
  1238. keysched_e[round] = _mm_setr_epi32(
  1239. sched[4*round ], sched[4*round+1],
  1240. sched[4*round+2], sched[4*round+3]);
  1241. smemclr(sched, sizeof(sched));
  1242. /*
  1243. * Now prepare the modified keys for the inverse cipher.
  1244. */
  1245. for (size_t eround = 0; eround <= rounds; eround++) {
  1246. size_t dround = rounds - eround;
  1247. __m128i rkey = keysched_e[eround];
  1248. if (eround && dround) /* neither first nor last */
  1249. rkey = _mm_aesimc_si128(rkey);
  1250. keysched_d[dround] = rkey;
  1251. }
  1252. }
  1253. /*
  1254. * Auxiliary routine to increment the 128-bit counter used in SDCTR
  1255. * mode.
  1256. */
  1257. static FUNC_ISA inline __m128i aes_ni_sdctr_increment(__m128i v)
  1258. {
  1259. const __m128i ONE = _mm_setr_epi32(1,0,0,0);
  1260. const __m128i ZERO = _mm_setzero_si128();
  1261. /* Increment the low-order 64 bits of v */
  1262. v = _mm_add_epi64(v, ONE);
  1263. /* Check if they've become zero */
  1264. __m128i cmp = _mm_cmpeq_epi64(v, ZERO);
  1265. /* If so, the low half of cmp is all 1s. Pack that into the high
  1266. * half of addend with zero in the low half. */
  1267. __m128i addend = _mm_unpacklo_epi64(ZERO, cmp);
  1268. /* And subtract that from v, which increments the high 64 bits iff
  1269. * the low 64 wrapped round. */
  1270. v = _mm_sub_epi64(v, addend);
  1271. return v;
  1272. }
  1273. /*
  1274. * Auxiliary routine to reverse the byte order of a vector, so that
  1275. * the SDCTR IV can be made big-endian for feeding to the cipher.
  1276. */
  1277. static FUNC_ISA inline __m128i aes_ni_sdctr_reverse(__m128i v)
  1278. {
  1279. v = _mm_shuffle_epi8(
  1280. v, _mm_setr_epi8(15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0));
  1281. return v;
  1282. }
  1283. /*
  1284. * The SSH interface and the cipher modes.
  1285. */
  1286. typedef struct aes_ni_context aes_ni_context;
  1287. struct aes_ni_context {
  1288. __m128i keysched_e[MAXROUNDKEYS], keysched_d[MAXROUNDKEYS], iv;
  1289. void *pointer_to_free;
  1290. ssh_cipher ciph;
  1291. };
  1292. static ssh_cipher *aes_hw_new(const ssh_cipheralg *alg)
  1293. {
  1294. if (!aes_hw_available_cached())
  1295. return NULL;
  1296. /*
  1297. * The __m128i variables in the context structure need to be
  1298. * 16-byte aligned, but not all malloc implementations that this
  1299. * code has to work with will guarantee to return a 16-byte
  1300. * aligned pointer. So we over-allocate, manually realign the
  1301. * pointer ourselves, and store the original one inside the
  1302. * context so we know how to free it later.
  1303. */
  1304. void *allocation = smalloc(sizeof(aes_ni_context) + 15);
  1305. uintptr_t alloc_address = (uintptr_t)allocation;
  1306. uintptr_t aligned_address = (alloc_address + 15) & ~15;
  1307. aes_ni_context *ctx = (aes_ni_context *)aligned_address;
  1308. ctx->ciph.vt = alg;
  1309. ctx->pointer_to_free = allocation;
  1310. return &ctx->ciph;
  1311. }
  1312. static void aes_hw_free(ssh_cipher *ciph)
  1313. {
  1314. aes_ni_context *ctx = container_of(ciph, aes_ni_context, ciph);
  1315. void *allocation = ctx->pointer_to_free;
  1316. smemclr(ctx, sizeof(*ctx));
  1317. sfree(allocation);
  1318. }
  1319. static void aes_hw_setkey(ssh_cipher *ciph, const void *vkey)
  1320. {
  1321. aes_ni_context *ctx = container_of(ciph, aes_ni_context, ciph);
  1322. const unsigned char *key = (const unsigned char *)vkey;
  1323. aes_ni_key_expand(key, ctx->ciph.vt->real_keybits / 32,
  1324. ctx->keysched_e, ctx->keysched_d);
  1325. }
  1326. static FUNC_ISA void aes_hw_setiv_cbc(ssh_cipher *ciph, const void *iv)
  1327. {
  1328. aes_ni_context *ctx = container_of(ciph, aes_ni_context, ciph);
  1329. ctx->iv = _mm_loadu_si128(iv);
  1330. }
  1331. static FUNC_ISA void aes_hw_setiv_sdctr(ssh_cipher *ciph, const void *iv)
  1332. {
  1333. aes_ni_context *ctx = container_of(ciph, aes_ni_context, ciph);
  1334. __m128i counter = _mm_loadu_si128(iv);
  1335. ctx->iv = aes_ni_sdctr_reverse(counter);
  1336. }
  1337. typedef __m128i (*aes_ni_fn)(__m128i v, const __m128i *keysched);
  1338. static FUNC_ISA inline void aes_cbc_ni_encrypt(
  1339. ssh_cipher *ciph, void *vblk, int blklen, aes_ni_fn encrypt)
  1340. {
  1341. aes_ni_context *ctx = container_of(ciph, aes_ni_context, ciph);
  1342. for (uint8_t *blk = (uint8_t *)vblk, *finish = blk + blklen;
  1343. blk < finish; blk += 16) {
  1344. __m128i plaintext = _mm_loadu_si128((const __m128i *)blk);
  1345. __m128i cipher_input = _mm_xor_si128(plaintext, ctx->iv);
  1346. __m128i ciphertext = encrypt(cipher_input, ctx->keysched_e);
  1347. _mm_storeu_si128((__m128i *)blk, ciphertext);
  1348. ctx->iv = ciphertext;
  1349. }
  1350. }
  1351. static FUNC_ISA inline void aes_cbc_ni_decrypt(
  1352. ssh_cipher *ciph, void *vblk, int blklen, aes_ni_fn decrypt)
  1353. {
  1354. aes_ni_context *ctx = container_of(ciph, aes_ni_context, ciph);
  1355. for (uint8_t *blk = (uint8_t *)vblk, *finish = blk + blklen;
  1356. blk < finish; blk += 16) {
  1357. __m128i ciphertext = _mm_loadu_si128((const __m128i *)blk);
  1358. __m128i decrypted = decrypt(ciphertext, ctx->keysched_d);
  1359. __m128i plaintext = _mm_xor_si128(decrypted, ctx->iv);
  1360. _mm_storeu_si128((__m128i *)blk, plaintext);
  1361. ctx->iv = ciphertext;
  1362. }
  1363. }
  1364. static FUNC_ISA inline void aes_sdctr_ni(
  1365. ssh_cipher *ciph, void *vblk, int blklen, aes_ni_fn encrypt)
  1366. {
  1367. aes_ni_context *ctx = container_of(ciph, aes_ni_context, ciph);
  1368. for (uint8_t *blk = (uint8_t *)vblk, *finish = blk + blklen;
  1369. blk < finish; blk += 16) {
  1370. __m128i counter = aes_ni_sdctr_reverse(ctx->iv);
  1371. __m128i keystream = encrypt(counter, ctx->keysched_e);
  1372. __m128i input = _mm_loadu_si128((const __m128i *)blk);
  1373. __m128i output = _mm_xor_si128(input, keystream);
  1374. _mm_storeu_si128((__m128i *)blk, output);
  1375. ctx->iv = aes_ni_sdctr_increment(ctx->iv);
  1376. }
  1377. }
  1378. #define NI_ENC_DEC(len) \
  1379. static FUNC_ISA void aes##len##_cbc_hw_encrypt( \
  1380. ssh_cipher *ciph, void *vblk, int blklen) \
  1381. { aes_cbc_ni_encrypt(ciph, vblk, blklen, aes_ni_##len##_e); } \
  1382. static FUNC_ISA void aes##len##_cbc_hw_decrypt( \
  1383. ssh_cipher *ciph, void *vblk, int blklen) \
  1384. { aes_cbc_ni_decrypt(ciph, vblk, blklen, aes_ni_##len##_d); } \
  1385. static FUNC_ISA void aes##len##_sdctr_hw( \
  1386. ssh_cipher *ciph, void *vblk, int blklen) \
  1387. { aes_sdctr_ni(ciph, vblk, blklen, aes_ni_##len##_e); } \
  1388. NI_ENC_DEC(128)
  1389. NI_ENC_DEC(192)
  1390. NI_ENC_DEC(256)
  1391. /* ----------------------------------------------------------------------
  1392. * Hardware-accelerated implementation of AES using Arm NEON.
  1393. */
  1394. #elif HW_AES == HW_AES_NEON
  1395. /*
  1396. * Manually set the target architecture, if we decided above that we
  1397. * need to.
  1398. */
  1399. #ifdef USE_CLANG_ATTR_TARGET_AARCH64
  1400. /*
  1401. * A spot of cheating: redefine some ACLE feature macros before
  1402. * including arm_neon.h. Otherwise we won't get the AES intrinsics
  1403. * defined by that header, because it will be looking at the settings
  1404. * for the whole translation unit rather than the ones we're going to
  1405. * put on some particular functions using __attribute__((target)).
  1406. */
  1407. #define __ARM_NEON 1
  1408. #define __ARM_FEATURE_CRYPTO 1
  1409. #define __ARM_FEATURE_AES 1
  1410. #define FUNC_ISA __attribute__ ((target("neon,crypto")))
  1411. #endif /* USE_CLANG_ATTR_TARGET_AARCH64 */
  1412. #ifndef FUNC_ISA
  1413. #define FUNC_ISA
  1414. #endif
  1415. #ifdef USE_ARM64_NEON_H
  1416. #include <arm64_neon.h>
  1417. #else
  1418. #include <arm_neon.h>
  1419. #endif
  1420. static bool aes_hw_available(void)
  1421. {
  1422. /*
  1423. * For Arm, we delegate to a per-platform AES detection function,
  1424. * because it has to be implemented by asking the operating system
  1425. * rather than directly querying the CPU.
  1426. *
  1427. * That's because Arm systems commonly have multiple cores that
  1428. * are not all alike, so any method of querying whether NEON
  1429. * crypto instructions work on the _current_ CPU - even one as
  1430. * crude as just trying one and catching the SIGILL - wouldn't
  1431. * give an answer that you could still rely on the first time the
  1432. * OS migrated your process to another CPU.
  1433. */
  1434. return platform_aes_hw_available();
  1435. }
  1436. /*
  1437. * Core NEON encrypt/decrypt functions, one per length and direction.
  1438. */
  1439. #define NEON_CIPHER(len, repmacro) \
  1440. static FUNC_ISA inline uint8x16_t aes_neon_##len##_e( \
  1441. uint8x16_t v, const uint8x16_t *keysched) \
  1442. { \
  1443. repmacro(v = vaesmcq_u8(vaeseq_u8(v, *keysched++));); \
  1444. v = vaeseq_u8(v, *keysched++); \
  1445. return veorq_u8(v, *keysched); \
  1446. } \
  1447. static FUNC_ISA inline uint8x16_t aes_neon_##len##_d( \
  1448. uint8x16_t v, const uint8x16_t *keysched) \
  1449. { \
  1450. repmacro(v = vaesimcq_u8(vaesdq_u8(v, *keysched++));); \
  1451. v = vaesdq_u8(v, *keysched++); \
  1452. return veorq_u8(v, *keysched); \
  1453. }
  1454. NEON_CIPHER(128, REP9)
  1455. NEON_CIPHER(192, REP11)
  1456. NEON_CIPHER(256, REP13)
  1457. /*
  1458. * The main key expansion.
  1459. */
  1460. static FUNC_ISA void aes_neon_key_expand(
  1461. const unsigned char *key, size_t key_words,
  1462. uint8x16_t *keysched_e, uint8x16_t *keysched_d)
  1463. {
  1464. size_t rounds = key_words + 6;
  1465. size_t sched_words = (rounds + 1) * 4;
  1466. /*
  1467. * Store the key schedule as 32-bit integers during expansion, so
  1468. * that it's easy to refer back to individual previous words. We
  1469. * collect them into the final uint8x16_t form at the end.
  1470. */
  1471. uint32_t sched[MAXROUNDKEYS * 4];
  1472. unsigned rconpos = 0;
  1473. for (size_t i = 0; i < sched_words; i++) {
  1474. if (i < key_words) {
  1475. sched[i] = GET_32BIT_LSB_FIRST(key + 4 * i);
  1476. } else {
  1477. uint32_t temp = sched[i - 1];
  1478. bool rotate_and_round_constant = (i % key_words == 0);
  1479. bool sub = rotate_and_round_constant ||
  1480. (key_words == 8 && i % 8 == 4);
  1481. if (rotate_and_round_constant)
  1482. temp = (temp << 24) | (temp >> 8);
  1483. if (sub) {
  1484. uint32x4_t v32 = vdupq_n_u32(temp);
  1485. uint8x16_t v8 = vreinterpretq_u8_u32(v32);
  1486. v8 = vaeseq_u8(v8, vdupq_n_u8(0));
  1487. v32 = vreinterpretq_u32_u8(v8);
  1488. temp = vget_lane_u32(vget_low_u32(v32), 0);
  1489. }
  1490. if (rotate_and_round_constant) {
  1491. assert(rconpos < lenof(key_setup_round_constants));
  1492. temp ^= key_setup_round_constants[rconpos++];
  1493. }
  1494. sched[i] = sched[i - key_words] ^ temp;
  1495. }
  1496. }
  1497. /*
  1498. * Combine the key schedule words into uint8x16_t vectors and
  1499. * store them in the output context.
  1500. */
  1501. for (size_t round = 0; round <= rounds; round++)
  1502. keysched_e[round] = vreinterpretq_u8_u32(vld1q_u32(sched + 4*round));
  1503. smemclr(sched, sizeof(sched));
  1504. /*
  1505. * Now prepare the modified keys for the inverse cipher.
  1506. */
  1507. for (size_t eround = 0; eround <= rounds; eround++) {
  1508. size_t dround = rounds - eround;
  1509. uint8x16_t rkey = keysched_e[eround];
  1510. if (eround && dround) /* neither first nor last */
  1511. rkey = vaesimcq_u8(rkey);
  1512. keysched_d[dround] = rkey;
  1513. }
  1514. }
  1515. /*
  1516. * Auxiliary routine to reverse the byte order of a vector, so that
  1517. * the SDCTR IV can be made big-endian for feeding to the cipher.
  1518. *
  1519. * In fact we don't need to reverse the vector _all_ the way; we leave
  1520. * the two lanes in MSW,LSW order, because that makes no difference to
  1521. * the efficiency of the increment. That way we only have to reverse
  1522. * bytes within each lane in this function.
  1523. */
  1524. static FUNC_ISA inline uint8x16_t aes_neon_sdctr_reverse(uint8x16_t v)
  1525. {
  1526. return vrev64q_u8(v);
  1527. }
  1528. /*
  1529. * Auxiliary routine to increment the 128-bit counter used in SDCTR
  1530. * mode. There's no instruction to treat a 128-bit vector as a single
  1531. * long integer, so instead we have to increment the bottom half
  1532. * unconditionally, and the top half if the bottom half started off as
  1533. * all 1s (in which case there was about to be a carry).
  1534. */
  1535. static FUNC_ISA inline uint8x16_t aes_neon_sdctr_increment(uint8x16_t in)
  1536. {
  1537. #ifdef __aarch64__
  1538. /* There will be a carry if the low 64 bits are all 1s. */
  1539. uint64x1_t all1 = vcreate_u64(0xFFFFFFFFFFFFFFFF);
  1540. uint64x1_t carry = vceq_u64(vget_high_u64(vreinterpretq_u64_u8(in)), all1);
  1541. /* Make a word whose bottom half is unconditionally all 1s, and
  1542. * the top half is 'carry', i.e. all 0s most of the time but all
  1543. * 1s if we need to increment the top half. Then that word is what
  1544. * we need to _subtract_ from the input counter. */
  1545. uint64x2_t subtrahend = vcombine_u64(carry, all1);
  1546. #else
  1547. /* AArch32 doesn't have comparisons that operate on a 64-bit lane,
  1548. * so we start by comparing each 32-bit half of the low 64 bits
  1549. * _separately_ to all-1s. */
  1550. uint32x2_t all1 = vdup_n_u32(0xFFFFFFFF);
  1551. uint32x2_t carry = vceq_u32(
  1552. vget_high_u32(vreinterpretq_u32_u8(in)), all1);
  1553. /* Swap the 32-bit words of the compare output, and AND with the
  1554. * unswapped version. Now carry is all 1s iff the bottom half of
  1555. * the input counter was all 1s, and all 0s otherwise. */
  1556. carry = vand_u32(carry, vrev64_u32(carry));
  1557. /* Now make the vector to subtract in the same way as above. */
  1558. uint64x2_t subtrahend = vreinterpretq_u64_u32(vcombine_u32(carry, all1));
  1559. #endif
  1560. return vreinterpretq_u8_u64(
  1561. vsubq_u64(vreinterpretq_u64_u8(in), subtrahend));
  1562. }
  1563. /*
  1564. * The SSH interface and the cipher modes.
  1565. */
  1566. typedef struct aes_neon_context aes_neon_context;
  1567. struct aes_neon_context {
  1568. uint8x16_t keysched_e[MAXROUNDKEYS], keysched_d[MAXROUNDKEYS], iv;
  1569. ssh_cipher ciph;
  1570. };
  1571. static ssh_cipher *aes_hw_new(const ssh_cipheralg *alg)
  1572. {
  1573. if (!aes_hw_available_cached())
  1574. return NULL;
  1575. aes_neon_context *ctx = snew(aes_neon_context);
  1576. ctx->ciph.vt = alg;
  1577. return &ctx->ciph;
  1578. }
  1579. static void aes_hw_free(ssh_cipher *ciph)
  1580. {
  1581. aes_neon_context *ctx = container_of(ciph, aes_neon_context, ciph);
  1582. smemclr(ctx, sizeof(*ctx));
  1583. sfree(ctx);
  1584. }
  1585. static void aes_hw_setkey(ssh_cipher *ciph, const void *vkey)
  1586. {
  1587. aes_neon_context *ctx = container_of(ciph, aes_neon_context, ciph);
  1588. const unsigned char *key = (const unsigned char *)vkey;
  1589. aes_neon_key_expand(key, ctx->ciph.vt->real_keybits / 32,
  1590. ctx->keysched_e, ctx->keysched_d);
  1591. }
  1592. static FUNC_ISA void aes_hw_setiv_cbc(ssh_cipher *ciph, const void *iv)
  1593. {
  1594. aes_neon_context *ctx = container_of(ciph, aes_neon_context, ciph);
  1595. ctx->iv = vld1q_u8(iv);
  1596. }
  1597. static FUNC_ISA void aes_hw_setiv_sdctr(ssh_cipher *ciph, const void *iv)
  1598. {
  1599. aes_neon_context *ctx = container_of(ciph, aes_neon_context, ciph);
  1600. uint8x16_t counter = vld1q_u8(iv);
  1601. ctx->iv = aes_neon_sdctr_reverse(counter);
  1602. }
  1603. typedef uint8x16_t (*aes_neon_fn)(uint8x16_t v, const uint8x16_t *keysched);
  1604. static FUNC_ISA inline void aes_cbc_neon_encrypt(
  1605. ssh_cipher *ciph, void *vblk, int blklen, aes_neon_fn encrypt)
  1606. {
  1607. aes_neon_context *ctx = container_of(ciph, aes_neon_context, ciph);
  1608. for (uint8_t *blk = (uint8_t *)vblk, *finish = blk + blklen;
  1609. blk < finish; blk += 16) {
  1610. uint8x16_t plaintext = vld1q_u8(blk);
  1611. uint8x16_t cipher_input = veorq_u8(plaintext, ctx->iv);
  1612. uint8x16_t ciphertext = encrypt(cipher_input, ctx->keysched_e);
  1613. vst1q_u8(blk, ciphertext);
  1614. ctx->iv = ciphertext;
  1615. }
  1616. }
  1617. static FUNC_ISA inline void aes_cbc_neon_decrypt(
  1618. ssh_cipher *ciph, void *vblk, int blklen, aes_neon_fn decrypt)
  1619. {
  1620. aes_neon_context *ctx = container_of(ciph, aes_neon_context, ciph);
  1621. for (uint8_t *blk = (uint8_t *)vblk, *finish = blk + blklen;
  1622. blk < finish; blk += 16) {
  1623. uint8x16_t ciphertext = vld1q_u8(blk);
  1624. uint8x16_t decrypted = decrypt(ciphertext, ctx->keysched_d);
  1625. uint8x16_t plaintext = veorq_u8(decrypted, ctx->iv);
  1626. vst1q_u8(blk, plaintext);
  1627. ctx->iv = ciphertext;
  1628. }
  1629. }
  1630. static FUNC_ISA inline void aes_sdctr_neon(
  1631. ssh_cipher *ciph, void *vblk, int blklen, aes_neon_fn encrypt)
  1632. {
  1633. aes_neon_context *ctx = container_of(ciph, aes_neon_context, ciph);
  1634. for (uint8_t *blk = (uint8_t *)vblk, *finish = blk + blklen;
  1635. blk < finish; blk += 16) {
  1636. uint8x16_t counter = aes_neon_sdctr_reverse(ctx->iv);
  1637. uint8x16_t keystream = encrypt(counter, ctx->keysched_e);
  1638. uint8x16_t input = vld1q_u8(blk);
  1639. uint8x16_t output = veorq_u8(input, keystream);
  1640. vst1q_u8(blk, output);
  1641. ctx->iv = aes_neon_sdctr_increment(ctx->iv);
  1642. }
  1643. }
  1644. #define NEON_ENC_DEC(len) \
  1645. static FUNC_ISA void aes##len##_cbc_hw_encrypt( \
  1646. ssh_cipher *ciph, void *vblk, int blklen) \
  1647. { aes_cbc_neon_encrypt(ciph, vblk, blklen, aes_neon_##len##_e); } \
  1648. static FUNC_ISA void aes##len##_cbc_hw_decrypt( \
  1649. ssh_cipher *ciph, void *vblk, int blklen) \
  1650. { aes_cbc_neon_decrypt(ciph, vblk, blklen, aes_neon_##len##_d); } \
  1651. static FUNC_ISA void aes##len##_sdctr_hw( \
  1652. ssh_cipher *ciph, void *vblk, int blklen) \
  1653. { aes_sdctr_neon(ciph, vblk, blklen, aes_neon_##len##_e); } \
  1654. NEON_ENC_DEC(128)
  1655. NEON_ENC_DEC(192)
  1656. NEON_ENC_DEC(256)
  1657. /* ----------------------------------------------------------------------
  1658. * Stub functions if we have no hardware-accelerated AES. In this
  1659. * case, aes_hw_new returns NULL (though it should also never be
  1660. * selected by aes_select, so the only thing that should even be
  1661. * _able_ to call it is testcrypt). As a result, the remaining vtable
  1662. * functions should never be called at all.
  1663. */
  1664. #elif HW_AES == HW_AES_NONE
  1665. bool aes_hw_available(void)
  1666. {
  1667. return false;
  1668. }
  1669. static ssh_cipher *aes_hw_new(const ssh_cipheralg *alg)
  1670. {
  1671. return NULL;
  1672. }
  1673. #define STUB_BODY { unreachable("Should never be called"); }
  1674. static void aes_hw_free(ssh_cipher *ciph) STUB_BODY
  1675. static void aes_hw_setkey(ssh_cipher *ciph, const void *key) STUB_BODY
  1676. static void aes_hw_setiv_cbc(ssh_cipher *ciph, const void *iv) STUB_BODY
  1677. static void aes_hw_setiv_sdctr(ssh_cipher *ciph, const void *iv) STUB_BODY
  1678. #define STUB_ENC_DEC(len) \
  1679. static void aes##len##_cbc_hw_encrypt( \
  1680. ssh_cipher *ciph, void *vblk, int blklen) STUB_BODY \
  1681. static void aes##len##_cbc_hw_decrypt( \
  1682. ssh_cipher *ciph, void *vblk, int blklen) STUB_BODY \
  1683. static void aes##len##_sdctr_hw( \
  1684. ssh_cipher *ciph, void *vblk, int blklen) STUB_BODY
  1685. STUB_ENC_DEC(128)
  1686. STUB_ENC_DEC(192)
  1687. STUB_ENC_DEC(256)
  1688. #endif /* HW_AES */