sshaes.c 78 KB

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