sshaes.c 80 KB

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