AES.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2024-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #ifndef ZT_AES_HPP
  14. #define ZT_AES_HPP
  15. #include "Constants.hpp"
  16. #include "Utils.hpp"
  17. #include "SHA512.hpp"
  18. #include <cstdint>
  19. #include <cstring>
  20. #ifndef ZT_AES_NO_ACCEL
  21. #ifdef ZT_ARCH_X64
  22. #include <wmmintrin.h>
  23. #include <emmintrin.h>
  24. #include <smmintrin.h>
  25. #include <immintrin.h>
  26. #define ZT_AES_AESNI 1
  27. #endif
  28. #endif
  29. namespace ZeroTier {
  30. /**
  31. * AES-256 and pals including GMAC, CTR, etc.
  32. *
  33. * This includes hardware acceleration for certain processors. The software
  34. * mode is fallback and is significantly slower.
  35. */
  36. class AES
  37. {
  38. public:
  39. /**
  40. * @return True if this system has hardware AES acceleration
  41. */
  42. static ZT_INLINE bool accelerated()
  43. {
  44. #ifdef ZT_AES_AESNI
  45. return Utils::CPUID.aes;
  46. #else
  47. return false;
  48. #endif
  49. }
  50. /**
  51. * Create an un-initialized AES instance (must call init() before use)
  52. */
  53. ZT_INLINE AES() noexcept
  54. {
  55. Utils::memoryLock(this,sizeof(AES));
  56. }
  57. /**
  58. * Create an AES instance with the given key
  59. *
  60. * @param key 256-bit key
  61. */
  62. explicit ZT_INLINE AES(const void *const key) noexcept
  63. {
  64. Utils::memoryLock(this,sizeof(AES));
  65. this->init(key);
  66. }
  67. ZT_INLINE ~AES()
  68. {
  69. Utils::burn(&_k,sizeof(_k));
  70. Utils::memoryUnlock(this,sizeof(AES));
  71. }
  72. /**
  73. * Set (or re-set) this AES256 cipher's key
  74. *
  75. * @param key 256-bit / 32-byte key
  76. */
  77. ZT_INLINE void init(const void *key) noexcept
  78. {
  79. #ifdef ZT_AES_AESNI
  80. if (likely(Utils::CPUID.aes)) {
  81. _init_aesni(reinterpret_cast<const uint8_t *>(key));
  82. return;
  83. }
  84. #endif
  85. _initSW(reinterpret_cast<const uint8_t *>(key));
  86. }
  87. /**
  88. * Encrypt a single AES block
  89. *
  90. * @param in Input block
  91. * @param out Output block (can be same as input)
  92. */
  93. ZT_INLINE void encrypt(const void *const in,void *const out) const noexcept
  94. {
  95. #ifdef ZT_AES_AESNI
  96. if (likely(Utils::CPUID.aes)) {
  97. _encrypt_aesni(in,out);
  98. return;
  99. }
  100. #endif
  101. _encryptSW(reinterpret_cast<const uint8_t *>(in),reinterpret_cast<uint8_t *>(out));
  102. }
  103. /**
  104. * Decrypt a single AES block
  105. *
  106. * @param in Input block
  107. * @param out Output block (can be same as input)
  108. */
  109. ZT_INLINE void decrypt(const void *const in,void *const out) const noexcept
  110. {
  111. #ifdef ZT_AES_AESNI
  112. if (likely(Utils::CPUID.aes)) {
  113. _decrypt_aesni(in,out);
  114. return;
  115. }
  116. #endif
  117. _decryptSW(reinterpret_cast<const uint8_t *>(in),reinterpret_cast<uint8_t *>(out));
  118. }
  119. class GMACSIVEncryptor;
  120. /**
  121. * Streaming GMAC calculator
  122. */
  123. class GMAC
  124. {
  125. friend class GMACSIVEncryptor;
  126. public:
  127. /**
  128. * Create a new instance of GMAC (must be initialized with init() before use)
  129. *
  130. * @param aes Keyed AES instance to use
  131. */
  132. ZT_INLINE GMAC(const AES &aes) : _aes(aes) {}
  133. /**
  134. * Reset and initialize for a new GMAC calculation
  135. *
  136. * @param iv 96-bit initialization vector (pad with zeroes if actual IV is shorter)
  137. */
  138. ZT_INLINE void init(const uint8_t iv[12]) noexcept
  139. {
  140. _rp = 0;
  141. _len = 0;
  142. // We fill the least significant 32 bits in the _iv field with 1 since in GCM mode
  143. // this would hold the counter, but we're not doing GCM. The counter is therefore
  144. // always 1.
  145. #ifdef ZT_AES_AESNI // also implies an x64 processor
  146. *reinterpret_cast<uint64_t *>(_iv) = *reinterpret_cast<const uint64_t *>(iv);
  147. *reinterpret_cast<uint32_t *>(_iv + 8) = *reinterpret_cast<const uint64_t *>(iv + 8);
  148. *reinterpret_cast<uint32_t *>(_iv + 12) = 0x01000000; // 0x00000001 in big-endian byte order
  149. #else
  150. for(int i=0;i<12;++i)
  151. _iv[i] = iv[i];
  152. _iv[12] = 0;
  153. _iv[13] = 0;
  154. _iv[14] = 0;
  155. _iv[15] = 1;
  156. #endif
  157. _y[0] = 0;
  158. _y[1] = 0;
  159. }
  160. /**
  161. * Process data through GMAC
  162. *
  163. * @param data Bytes to process
  164. * @param len Length of input
  165. */
  166. void update(const void *data,unsigned int len) noexcept;
  167. /**
  168. * Process any remaining cached bytes and generate tag
  169. *
  170. * Don't call finish() more than once or you'll get an invalid result.
  171. *
  172. * @param tag 128-bit GMAC tag (can be truncated)
  173. */
  174. void finish(uint8_t tag[16]) noexcept;
  175. private:
  176. const AES &_aes;
  177. unsigned int _rp;
  178. unsigned int _len;
  179. uint8_t _r[16]; // remainder
  180. uint8_t _iv[16];
  181. uint64_t _y[2];
  182. };
  183. /**
  184. * Streaming AES-CTR encrypt/decrypt
  185. *
  186. * NOTE: this doesn't support overflow of the counter in the least significant 32 bits.
  187. * AES-GMAC-CTR doesn't need this, so we don't support it as an optimization.
  188. */
  189. class CTR
  190. {
  191. friend class GMACSIVEncryptor;
  192. public:
  193. ZT_INLINE CTR(const AES &aes) noexcept : _aes(aes) {}
  194. /**
  195. * Initialize this CTR instance to encrypt a new stream
  196. *
  197. * @param iv Unique initialization vector and initial 32-bit counter (least significant 32 bits, big-endian)
  198. * @param output Buffer to which to store output (MUST be large enough for total bytes processed!)
  199. */
  200. ZT_INLINE void init(const uint8_t iv[16],void *const output) noexcept
  201. {
  202. _ctr[0] = Utils::loadAsIsEndian<uint64_t>(iv);
  203. _ctr[1] = Utils::loadAsIsEndian<uint64_t>(iv + 8);
  204. _out = reinterpret_cast<uint8_t *>(output);
  205. _len = 0;
  206. }
  207. /**
  208. * Encrypt or decrypt data, writing result to the output provided to init()
  209. *
  210. * @param input Input data
  211. * @param len Length of input
  212. */
  213. void crypt(const void *input,unsigned int len) noexcept;
  214. /**
  215. * Finish any remaining bytes if total bytes processed wasn't a multiple of 16
  216. *
  217. * Don't call more than once for a given stream or data may be corrupted.
  218. */
  219. void finish() noexcept;
  220. private:
  221. const AES &_aes;
  222. uint64_t _ctr[2];
  223. uint8_t *_out;
  224. unsigned int _len;
  225. };
  226. /**
  227. * Encrypt with AES-GMAC-SIV
  228. */
  229. class GMACSIVEncryptor
  230. {
  231. public:
  232. /**
  233. * Create a new AES-GMAC-SIV encryptor keyed with the provided AES instances
  234. *
  235. * @param k0 First of two AES instances keyed with K0
  236. * @param k1 Second of two AES instances keyed with K1
  237. */
  238. ZT_INLINE GMACSIVEncryptor(const AES &k0,const AES &k1) noexcept :
  239. _gmac(k0),
  240. _ctr(k1) {}
  241. /**
  242. * Initialize AES-GMAC-SIV
  243. *
  244. * @param iv IV in network byte order (byte order in which it will appear on the wire)
  245. * @param output Pointer to buffer to receive ciphertext, must be large enough for all to-be-processed data!
  246. */
  247. ZT_INLINE void init(const uint64_t iv,void *const output) noexcept
  248. {
  249. // Output buffer to receive the result of AES-CTR encryption.
  250. _output = output;
  251. // Initialize GMAC with 64-bit IV (and remaining 32 bits padded to zero).
  252. _tag[0] = iv;
  253. _tag[1] = 0;
  254. _gmac.init(reinterpret_cast<const uint8_t *>(_tag));
  255. }
  256. /**
  257. * Process AAD (additional authenticated data) that is not being encrypted
  258. *
  259. * This must be called prior to update1, finish1, etc. if there is AAD to include
  260. * in the MAC that is not included in the plaintext.
  261. *
  262. * This currently only supports one chunk of AAD. Don't call multiple times per message.
  263. *
  264. * @param aad Additional authenticated data
  265. * @param len Length of AAD in bytes
  266. */
  267. ZT_INLINE void aad(const void *const aad,unsigned int len) noexcept
  268. {
  269. // Feed ADD into GMAC first
  270. _gmac.update(aad,len);
  271. // End of AAD is padded to a multiple of 16 bytes to ensure unique encoding.
  272. len &= 0xfU;
  273. if (len != 0)
  274. _gmac.update(Utils::ZERO256,16 - len);
  275. }
  276. /**
  277. * First pass plaintext input function
  278. *
  279. * @param input Plaintext chunk
  280. * @param len Length of plaintext chunk
  281. */
  282. ZT_INLINE void update1(const void *const input,const unsigned int len) noexcept
  283. {
  284. _gmac.update(input,len);
  285. }
  286. /**
  287. * Finish first pass, compute CTR IV, initialize second pass.
  288. */
  289. ZT_INLINE void finish1() noexcept
  290. {
  291. uint64_t tmp[2];
  292. // Compute 128-bit GMAC tag.
  293. _gmac.finish(reinterpret_cast<uint8_t *>(tmp));
  294. // Truncate to 64 bits, concatenate after 64-bit message IV, and encrypt with AES.
  295. _tag[1] = tmp[0];
  296. _ctr._aes.encrypt(_tag,_tag);
  297. // Mask least significant 32 bits to get CTR IV and initialize CTR.
  298. tmp[0] = _tag[0];
  299. #if __BYTE_ORDER == __BIG_ENDIAN
  300. ctrIv[1] = _iv[1] & 0xffffffff00000000ULL;
  301. #else
  302. tmp[1] = _tag[1] & 0x00000000ffffffffULL;
  303. #endif
  304. _ctr.init(reinterpret_cast<const uint8_t *>(tmp),_output);
  305. }
  306. /**
  307. * Second pass plaintext input function
  308. *
  309. * The same plaintext must be fed in the second time in the same order,
  310. * though chunk boundaries do not have to be the same.
  311. *
  312. * @param input Plaintext chunk
  313. * @param len Length of plaintext chunk
  314. */
  315. ZT_INLINE void update2(const void *const input,const unsigned int len) noexcept
  316. {
  317. _ctr.crypt(input,len);
  318. }
  319. /**
  320. * Finish second pass and return a pointer to the opaque 128-bit IV+MAC block
  321. *
  322. * The returned pointer remains valid as long as this object exists and init()
  323. * is not called again.
  324. *
  325. * @return Pointer to 128-bit opaque IV+MAC (packed into two 64-bit integers)
  326. */
  327. ZT_INLINE const uint64_t *finish2()
  328. {
  329. _ctr.finish();
  330. return _tag;
  331. }
  332. private:
  333. void *_output;
  334. uint64_t _tag[2];
  335. AES::GMAC _gmac;
  336. AES::CTR _ctr;
  337. };
  338. private:
  339. static const uint32_t Te0[256];
  340. static const uint32_t Te1[256];
  341. static const uint32_t Te2[256];
  342. static const uint32_t Te3[256];
  343. static const uint32_t Te4[256];
  344. static const uint32_t Td0[256];
  345. static const uint32_t Td1[256];
  346. static const uint32_t Td2[256];
  347. static const uint32_t Td3[256];
  348. static const uint8_t Td4[256];
  349. static const uint32_t rcon[10];
  350. void _initSW(const uint8_t key[32]) noexcept;
  351. void _encryptSW(const uint8_t in[16],uint8_t out[16]) const noexcept;
  352. void _decryptSW(const uint8_t in[16],uint8_t out[16]) const noexcept;
  353. union {
  354. #ifdef ZT_AES_AESNI
  355. struct {
  356. __m128i k[28];
  357. __m128i h,hh,hhh,hhhh;
  358. } ni;
  359. #endif
  360. struct {
  361. uint64_t h[2];
  362. uint32_t ek[60];
  363. uint32_t dk[60];
  364. } sw;
  365. } _k;
  366. #ifdef ZT_AES_AESNI
  367. static const __m128i s_shuf;
  368. void _init_aesni(const uint8_t key[32]) noexcept;
  369. ZT_INLINE void _encrypt_aesni(const void *const in,void *const out) const noexcept
  370. {
  371. __m128i tmp = _mm_loadu_si128((const __m128i *)in);
  372. tmp = _mm_xor_si128(tmp,_k.ni.k[0]);
  373. tmp = _mm_aesenc_si128(tmp,_k.ni.k[1]);
  374. tmp = _mm_aesenc_si128(tmp,_k.ni.k[2]);
  375. tmp = _mm_aesenc_si128(tmp,_k.ni.k[3]);
  376. tmp = _mm_aesenc_si128(tmp,_k.ni.k[4]);
  377. tmp = _mm_aesenc_si128(tmp,_k.ni.k[5]);
  378. tmp = _mm_aesenc_si128(tmp,_k.ni.k[6]);
  379. tmp = _mm_aesenc_si128(tmp,_k.ni.k[7]);
  380. tmp = _mm_aesenc_si128(tmp,_k.ni.k[8]);
  381. tmp = _mm_aesenc_si128(tmp,_k.ni.k[9]);
  382. tmp = _mm_aesenc_si128(tmp,_k.ni.k[10]);
  383. tmp = _mm_aesenc_si128(tmp,_k.ni.k[11]);
  384. tmp = _mm_aesenc_si128(tmp,_k.ni.k[12]);
  385. tmp = _mm_aesenc_si128(tmp,_k.ni.k[13]);
  386. _mm_storeu_si128((__m128i *)out,_mm_aesenclast_si128(tmp,_k.ni.k[14]));
  387. }
  388. ZT_INLINE void _decrypt_aesni(const void *in,void *out) const noexcept
  389. {
  390. __m128i tmp = _mm_loadu_si128((const __m128i *)in);
  391. tmp = _mm_xor_si128(tmp,_k.ni.k[14]);
  392. tmp = _mm_aesdec_si128(tmp,_k.ni.k[15]);
  393. tmp = _mm_aesdec_si128(tmp,_k.ni.k[16]);
  394. tmp = _mm_aesdec_si128(tmp,_k.ni.k[17]);
  395. tmp = _mm_aesdec_si128(tmp,_k.ni.k[18]);
  396. tmp = _mm_aesdec_si128(tmp,_k.ni.k[19]);
  397. tmp = _mm_aesdec_si128(tmp,_k.ni.k[20]);
  398. tmp = _mm_aesdec_si128(tmp,_k.ni.k[21]);
  399. tmp = _mm_aesdec_si128(tmp,_k.ni.k[22]);
  400. tmp = _mm_aesdec_si128(tmp,_k.ni.k[23]);
  401. tmp = _mm_aesdec_si128(tmp,_k.ni.k[24]);
  402. tmp = _mm_aesdec_si128(tmp,_k.ni.k[25]);
  403. tmp = _mm_aesdec_si128(tmp,_k.ni.k[26]);
  404. tmp = _mm_aesdec_si128(tmp,_k.ni.k[27]);
  405. _mm_storeu_si128((__m128i *)out,_mm_aesdeclast_si128(tmp,_k.ni.k[0]));
  406. }
  407. static ZT_INLINE __m128i _mult_block_aesni(const __m128i shuf,const __m128i h,__m128i y) noexcept
  408. {
  409. y = _mm_shuffle_epi8(y,shuf);
  410. __m128i t1 = _mm_clmulepi64_si128(h,y,0x00);
  411. __m128i t2 = _mm_clmulepi64_si128(h,y,0x01);
  412. __m128i t3 = _mm_clmulepi64_si128(h,y,0x10);
  413. __m128i t4 = _mm_clmulepi64_si128(h,y,0x11);
  414. t2 = _mm_xor_si128(t2,t3);
  415. t3 = _mm_slli_si128(t2,8);
  416. t2 = _mm_srli_si128(t2,8);
  417. t1 = _mm_xor_si128(t1,t3);
  418. t4 = _mm_xor_si128(t4,t2);
  419. __m128i t5 = _mm_srli_epi32(t1,31);
  420. t1 = _mm_slli_epi32(t1,1);
  421. __m128i t6 = _mm_srli_epi32(t4,31);
  422. t4 = _mm_slli_epi32(t4,1);
  423. t3 = _mm_srli_si128(t5,12);
  424. t6 = _mm_slli_si128(t6,4);
  425. t5 = _mm_slli_si128(t5,4);
  426. t1 = _mm_or_si128(t1,t5);
  427. t4 = _mm_or_si128(t4,t6);
  428. t4 = _mm_or_si128(t4,t3);
  429. t5 = _mm_slli_epi32(t1,31);
  430. t6 = _mm_slli_epi32(t1,30);
  431. t3 = _mm_slli_epi32(t1,25);
  432. t5 = _mm_xor_si128(t5,t6);
  433. t5 = _mm_xor_si128(t5,t3);
  434. t6 = _mm_srli_si128(t5,4);
  435. t4 = _mm_xor_si128(t4,t6);
  436. t5 = _mm_slli_si128(t5,12);
  437. t1 = _mm_xor_si128(t1,t5);
  438. t4 = _mm_xor_si128(t4,t1);
  439. t5 = _mm_srli_epi32(t1,1);
  440. t2 = _mm_srli_epi32(t1,2);
  441. t3 = _mm_srli_epi32(t1,7);
  442. t4 = _mm_xor_si128(t4,t2);
  443. t4 = _mm_xor_si128(t4,t3);
  444. t4 = _mm_xor_si128(t4,t5);
  445. return _mm_shuffle_epi8(t4,shuf);
  446. }
  447. #endif
  448. };
  449. } // namespace ZeroTier
  450. #endif