AES.hpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  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 <emmintrin.h>
  23. #include <smmintrin.h>
  24. #include <immintrin.h>
  25. #include <wmmintrin.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 // NOLINT(cppcoreguidelines-pro-type-member-init,hicpp-member-init)
  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 // NOLINT(cppcoreguidelines-pro-type-member-init,hicpp-member-init)
  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 *const 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. class GMACSIVDecryptor;
  121. /**
  122. * Streaming GMAC calculator
  123. */
  124. class GMAC
  125. {
  126. friend class GMACSIVEncryptor;
  127. friend class GMACSIVDecryptor;
  128. public:
  129. /**
  130. * Create a new instance of GMAC (must be initialized with init() before use)
  131. *
  132. * @param aes Keyed AES instance to use
  133. */
  134. ZT_INLINE GMAC(const AES &aes) : _aes(aes) {}
  135. /**
  136. * Reset and initialize for a new GMAC calculation
  137. *
  138. * @param iv 96-bit initialization vector (pad with zeroes if actual IV is shorter)
  139. */
  140. ZT_INLINE void init(const uint8_t iv[12]) noexcept
  141. {
  142. _rp = 0;
  143. _len = 0;
  144. // We fill the least significant 32 bits in the _iv field with 1 since in GCM mode
  145. // this would hold the counter, but we're not doing GCM. The counter is therefore
  146. // always 1.
  147. #ifdef ZT_AES_AESNI // also implies an x64 processor
  148. *reinterpret_cast<uint64_t *>(_iv) = *reinterpret_cast<const uint64_t *>(iv);
  149. *reinterpret_cast<uint32_t *>(_iv + 8) = *reinterpret_cast<const uint64_t *>(iv + 8);
  150. *reinterpret_cast<uint32_t *>(_iv + 12) = 0x01000000; // 0x00000001 in big-endian byte order
  151. #else
  152. for(int i=0;i<12;++i)
  153. _iv[i] = iv[i];
  154. _iv[12] = 0;
  155. _iv[13] = 0;
  156. _iv[14] = 0;
  157. _iv[15] = 1;
  158. #endif
  159. _y[0] = 0;
  160. _y[1] = 0;
  161. }
  162. /**
  163. * Process data through GMAC
  164. *
  165. * @param data Bytes to process
  166. * @param len Length of input
  167. */
  168. void update(const void *data,unsigned int len) noexcept;
  169. /**
  170. * Process any remaining cached bytes and generate tag
  171. *
  172. * Don't call finish() more than once or you'll get an invalid result.
  173. *
  174. * @param tag 128-bit GMAC tag (can be truncated)
  175. */
  176. void finish(uint8_t tag[16]) noexcept;
  177. private:
  178. const AES &_aes;
  179. unsigned int _rp;
  180. unsigned int _len;
  181. uint8_t _r[16]; // remainder
  182. uint8_t _iv[16];
  183. uint64_t _y[2];
  184. };
  185. /**
  186. * Streaming AES-CTR encrypt/decrypt
  187. *
  188. * NOTE: this doesn't support overflow of the counter in the least significant 32 bits.
  189. * AES-GMAC-CTR doesn't need this, so we don't support it as an optimization.
  190. */
  191. class CTR
  192. {
  193. friend class GMACSIVEncryptor;
  194. friend class GMACSIVDecryptor;
  195. public:
  196. ZT_INLINE CTR(const AES &aes) noexcept : _aes(aes) {}
  197. /**
  198. * Initialize this CTR instance to encrypt a new stream
  199. *
  200. * @param iv Unique initialization vector and initial 32-bit counter (least significant 32 bits, big-endian)
  201. * @param output Buffer to which to store output (MUST be large enough for total bytes processed!)
  202. */
  203. ZT_INLINE void init(const uint8_t iv[16],void *const output) noexcept
  204. {
  205. _ctr[0] = Utils::loadAsIsEndian<uint64_t>(iv);
  206. _ctr[1] = Utils::loadAsIsEndian<uint64_t>(iv + 8);
  207. _out = reinterpret_cast<uint8_t *>(output);
  208. _len = 0;
  209. }
  210. /**
  211. * Encrypt or decrypt data, writing result to the output provided to init()
  212. *
  213. * @param input Input data
  214. * @param len Length of input
  215. */
  216. void crypt(const void *input,unsigned int len) noexcept;
  217. /**
  218. * Finish any remaining bytes if total bytes processed wasn't a multiple of 16
  219. *
  220. * Don't call more than once for a given stream or data may be corrupted.
  221. */
  222. void finish() noexcept;
  223. private:
  224. const AES &_aes;
  225. uint64_t _ctr[2];
  226. uint8_t *_out;
  227. unsigned int _len;
  228. };
  229. /**
  230. * Encryptor for GMAC-SIV
  231. */
  232. class GMACSIVEncryptor
  233. {
  234. public:
  235. /**
  236. * Create a new AES-GMAC-SIV encryptor keyed with the provided AES instances
  237. *
  238. * @param k0 First of two AES instances keyed with K0
  239. * @param k1 Second of two AES instances keyed with K1
  240. */
  241. ZT_INLINE GMACSIVEncryptor(const AES &k0,const AES &k1) noexcept : // NOLINT(cppcoreguidelines-pro-type-member-init,hicpp-member-init)
  242. _gmac(k0),
  243. _ctr(k1) {}
  244. /**
  245. * Initialize AES-GMAC-SIV
  246. *
  247. * @param iv IV in network byte order (byte order in which it will appear on the wire)
  248. * @param output Pointer to buffer to receive ciphertext, must be large enough for all to-be-processed data!
  249. */
  250. ZT_INLINE void init(const uint64_t iv,void *const output) noexcept
  251. {
  252. // Output buffer to receive the result of AES-CTR encryption.
  253. _output = output;
  254. // Initialize GMAC with 64-bit IV (and remaining 32 bits padded to zero).
  255. _tag[0] = iv;
  256. _tag[1] = 0;
  257. _gmac.init(reinterpret_cast<const uint8_t *>(_tag));
  258. }
  259. /**
  260. * Process AAD (additional authenticated data) that is not being encrypted
  261. *
  262. * This must be called prior to update1, finish1, etc. if there is AAD to include
  263. * in the MAC that is not included in the plaintext.
  264. *
  265. * This currently only supports one chunk of AAD. Don't call multiple times per message.
  266. *
  267. * @param aad Additional authenticated data
  268. * @param len Length of AAD in bytes
  269. */
  270. ZT_INLINE void aad(const void *const aad,unsigned int len) noexcept
  271. {
  272. // Feed ADD into GMAC first
  273. _gmac.update(aad,len);
  274. // End of AAD is padded to a multiple of 16 bytes to ensure unique encoding.
  275. len &= 0xfU;
  276. if (len != 0)
  277. _gmac.update(Utils::ZERO256,16 - len);
  278. }
  279. /**
  280. * First pass plaintext input function
  281. *
  282. * @param input Plaintext chunk
  283. * @param len Length of plaintext chunk
  284. */
  285. ZT_INLINE void update1(const void *const input,const unsigned int len) noexcept
  286. {
  287. _gmac.update(input,len);
  288. }
  289. /**
  290. * Finish first pass, compute CTR IV, initialize second pass.
  291. */
  292. ZT_INLINE void finish1() noexcept
  293. {
  294. uint64_t tmp[2];
  295. // Compute 128-bit GMAC tag.
  296. _gmac.finish(reinterpret_cast<uint8_t *>(tmp));
  297. // Truncate to 64 bits, concatenate after 64-bit message IV, and encrypt with AES.
  298. _tag[1] = tmp[0];
  299. _ctr._aes.encrypt(_tag,_tag);
  300. // Mask least significant 32 bits to get CTR IV and initialize CTR.
  301. tmp[0] = _tag[0];
  302. #if __BYTE_ORDER == __BIG_ENDIAN
  303. ctrIv[1] = _iv[1] & 0xffffffff00000000ULL;
  304. #else
  305. tmp[1] = _tag[1] & 0x00000000ffffffffULL;
  306. #endif
  307. _ctr.init(reinterpret_cast<const uint8_t *>(tmp),_output);
  308. }
  309. /**
  310. * Second pass plaintext input function
  311. *
  312. * The same plaintext must be fed in the second time in the same order,
  313. * though chunk boundaries do not have to be the same.
  314. *
  315. * @param input Plaintext chunk
  316. * @param len Length of plaintext chunk
  317. */
  318. ZT_INLINE void update2(const void *const input,const unsigned int len) noexcept
  319. {
  320. _ctr.crypt(input,len);
  321. }
  322. /**
  323. * Finish second pass and return a pointer to the opaque 128-bit IV+MAC block
  324. *
  325. * The returned pointer remains valid as long as this object exists and init()
  326. * is not called again.
  327. *
  328. * @return Pointer to 128-bit opaque IV+MAC (packed into two 64-bit integers)
  329. */
  330. ZT_INLINE const uint64_t *finish2()
  331. {
  332. _ctr.finish();
  333. return _tag;
  334. }
  335. private:
  336. void *_output;
  337. uint64_t _tag[2];
  338. AES::GMAC _gmac;
  339. AES::CTR _ctr;
  340. };
  341. /**
  342. * Decryptor for GMAC-SIV
  343. */
  344. class GMACSIVDecryptor
  345. {
  346. public:
  347. ZT_INLINE GMACSIVDecryptor(const AES &k0,const AES &k1) noexcept : // NOLINT(cppcoreguidelines-pro-type-member-init,hicpp-member-init)
  348. _ctr(k1),
  349. _gmac(k0) {}
  350. /**
  351. * Initialize decryptor for a new message
  352. *
  353. * @param tag 128-bit combined IV/MAC originally created by GMAC-SIV encryption
  354. * @param output Buffer in which to write output plaintext (must be large enough!)
  355. */
  356. ZT_INLINE void init(const uint64_t tag[2],void *const output) noexcept
  357. {
  358. // Init CTR with the most significant 96 bits of the tag (as in encryption).
  359. uint64_t tmp[2];
  360. tmp[0] = tag[0];
  361. #if __BYTE_ORDER == __BIG_ENDIAN
  362. tmp[1] = tag[1] & 0xffffffff00000000ULL;
  363. #else
  364. tmp[1] = tag[1] & 0x00000000ffffffffULL;
  365. #endif
  366. _ctr.init(reinterpret_cast<const uint8_t *>(tmp),output);
  367. // Decrypt the opaque tag to yield the original IV and 64-bit truncated MAC.
  368. _ctr._aes.decrypt(tag,_ivMac);
  369. // Initialize GMAC with the original IV.
  370. tmp[0] = _ivMac[0];
  371. tmp[1] = 0;
  372. _gmac.init(reinterpret_cast<const uint8_t *>(tmp));
  373. _output = output;
  374. _decryptedLen = 0;
  375. }
  376. /**
  377. * Process AAD (additional authenticated data) that wasn't encrypted
  378. *
  379. * @param aad Additional authenticated data
  380. * @param len Length of AAD in bytes
  381. */
  382. ZT_INLINE void aad(const void *const aad,unsigned int len) noexcept
  383. {
  384. _gmac.update(aad,len);
  385. len &= 0xfU;
  386. if (len != 0)
  387. _gmac.update(Utils::ZERO256,16 - len);
  388. }
  389. /**
  390. * Feed ciphertext into the decryptor
  391. *
  392. * Unlike encryption, GMAC-SIV decryption requires only one pass.
  393. *
  394. * @param input Input ciphertext
  395. * @param len Length of ciphertext
  396. */
  397. ZT_INLINE void update(const void *const input,const unsigned int len) noexcept
  398. {
  399. _ctr.crypt(input,len);
  400. _decryptedLen += len;
  401. }
  402. /**
  403. * Flush decryption, compute MAC, and verify
  404. *
  405. * @return True if resulting plaintext (and AAD) pass message authentication check
  406. */
  407. ZT_INLINE bool finish() noexcept
  408. {
  409. // Flush any remaining bytes from CTR.
  410. _ctr.finish();
  411. // Feed plaintext through GMAC.
  412. _gmac.update(_output,_decryptedLen);
  413. uint64_t gmacTag[2];
  414. _gmac.finish(reinterpret_cast<uint8_t *>(gmacTag));
  415. // MAC passes if its first 64 bits equals the MAC we got by decrypting the tag.
  416. return gmacTag[0] == _ivMac[1];
  417. }
  418. private:
  419. uint64_t _ivMac[2];
  420. AES::CTR _ctr;
  421. AES::GMAC _gmac;
  422. void *_output;
  423. unsigned int _decryptedLen;
  424. };
  425. private:
  426. static const uint32_t Te0[256];
  427. static const uint32_t Te1[256];
  428. static const uint32_t Te2[256];
  429. static const uint32_t Te3[256];
  430. static const uint32_t Te4[256];
  431. static const uint32_t Td0[256];
  432. static const uint32_t Td1[256];
  433. static const uint32_t Td2[256];
  434. static const uint32_t Td3[256];
  435. static const uint8_t Td4[256];
  436. static const uint32_t rcon[10];
  437. void _initSW(const uint8_t key[32]) noexcept;
  438. void _encryptSW(const uint8_t in[16],uint8_t out[16]) const noexcept;
  439. void _decryptSW(const uint8_t in[16],uint8_t out[16]) const noexcept;
  440. union {
  441. #ifdef ZT_AES_AESNI
  442. struct {
  443. __m128i k[28];
  444. __m128i h,hh,hhh,hhhh;
  445. } ni;
  446. #endif
  447. struct {
  448. uint64_t h[2];
  449. uint32_t ek[60];
  450. uint32_t dk[60];
  451. } sw;
  452. } _k;
  453. #ifdef ZT_AES_AESNI
  454. static const __m128i s_shuf;
  455. void _init_aesni(const uint8_t key[32]) noexcept;
  456. ZT_INLINE void _encrypt_aesni(const void *const in,void *const out) const noexcept
  457. {
  458. __m128i tmp = _mm_loadu_si128((const __m128i *)in);
  459. tmp = _mm_xor_si128(tmp,_k.ni.k[0]);
  460. tmp = _mm_aesenc_si128(tmp,_k.ni.k[1]);
  461. tmp = _mm_aesenc_si128(tmp,_k.ni.k[2]);
  462. tmp = _mm_aesenc_si128(tmp,_k.ni.k[3]);
  463. tmp = _mm_aesenc_si128(tmp,_k.ni.k[4]);
  464. tmp = _mm_aesenc_si128(tmp,_k.ni.k[5]);
  465. tmp = _mm_aesenc_si128(tmp,_k.ni.k[6]);
  466. tmp = _mm_aesenc_si128(tmp,_k.ni.k[7]);
  467. tmp = _mm_aesenc_si128(tmp,_k.ni.k[8]);
  468. tmp = _mm_aesenc_si128(tmp,_k.ni.k[9]);
  469. tmp = _mm_aesenc_si128(tmp,_k.ni.k[10]);
  470. tmp = _mm_aesenc_si128(tmp,_k.ni.k[11]);
  471. tmp = _mm_aesenc_si128(tmp,_k.ni.k[12]);
  472. tmp = _mm_aesenc_si128(tmp,_k.ni.k[13]);
  473. _mm_storeu_si128((__m128i *)out,_mm_aesenclast_si128(tmp,_k.ni.k[14]));
  474. }
  475. ZT_INLINE void _decrypt_aesni(const void *in,void *out) const noexcept
  476. {
  477. __m128i tmp = _mm_loadu_si128((const __m128i *)in);
  478. tmp = _mm_xor_si128(tmp,_k.ni.k[14]);
  479. tmp = _mm_aesdec_si128(tmp,_k.ni.k[15]);
  480. tmp = _mm_aesdec_si128(tmp,_k.ni.k[16]);
  481. tmp = _mm_aesdec_si128(tmp,_k.ni.k[17]);
  482. tmp = _mm_aesdec_si128(tmp,_k.ni.k[18]);
  483. tmp = _mm_aesdec_si128(tmp,_k.ni.k[19]);
  484. tmp = _mm_aesdec_si128(tmp,_k.ni.k[20]);
  485. tmp = _mm_aesdec_si128(tmp,_k.ni.k[21]);
  486. tmp = _mm_aesdec_si128(tmp,_k.ni.k[22]);
  487. tmp = _mm_aesdec_si128(tmp,_k.ni.k[23]);
  488. tmp = _mm_aesdec_si128(tmp,_k.ni.k[24]);
  489. tmp = _mm_aesdec_si128(tmp,_k.ni.k[25]);
  490. tmp = _mm_aesdec_si128(tmp,_k.ni.k[26]);
  491. tmp = _mm_aesdec_si128(tmp,_k.ni.k[27]);
  492. _mm_storeu_si128((__m128i *)out,_mm_aesdeclast_si128(tmp,_k.ni.k[0]));
  493. }
  494. static ZT_INLINE __m128i _mult_block_aesni(const __m128i shuf,const __m128i h,__m128i y) noexcept
  495. {
  496. y = _mm_shuffle_epi8(y,shuf);
  497. __m128i t1 = _mm_clmulepi64_si128(h,y,0x00);
  498. __m128i t2 = _mm_clmulepi64_si128(h,y,0x01);
  499. __m128i t3 = _mm_clmulepi64_si128(h,y,0x10);
  500. __m128i t4 = _mm_clmulepi64_si128(h,y,0x11);
  501. t2 = _mm_xor_si128(t2,t3);
  502. t3 = _mm_slli_si128(t2,8);
  503. t2 = _mm_srli_si128(t2,8);
  504. t1 = _mm_xor_si128(t1,t3);
  505. t4 = _mm_xor_si128(t4,t2);
  506. __m128i t5 = _mm_srli_epi32(t1,31);
  507. t1 = _mm_slli_epi32(t1,1);
  508. __m128i t6 = _mm_srli_epi32(t4,31);
  509. t4 = _mm_slli_epi32(t4,1);
  510. t3 = _mm_srli_si128(t5,12);
  511. t6 = _mm_slli_si128(t6,4);
  512. t5 = _mm_slli_si128(t5,4);
  513. t1 = _mm_or_si128(t1,t5);
  514. t4 = _mm_or_si128(t4,t6);
  515. t4 = _mm_or_si128(t4,t3);
  516. t5 = _mm_slli_epi32(t1,31);
  517. t6 = _mm_slli_epi32(t1,30);
  518. t3 = _mm_slli_epi32(t1,25);
  519. t5 = _mm_xor_si128(t5,t6);
  520. t5 = _mm_xor_si128(t5,t3);
  521. t6 = _mm_srli_si128(t5,4);
  522. t4 = _mm_xor_si128(t4,t6);
  523. t5 = _mm_slli_si128(t5,12);
  524. t1 = _mm_xor_si128(t1,t5);
  525. t4 = _mm_xor_si128(t4,t1);
  526. t5 = _mm_srli_epi32(t1,1);
  527. t2 = _mm_srli_epi32(t1,2);
  528. t3 = _mm_srli_epi32(t1,7);
  529. t4 = _mm_xor_si128(t4,t2);
  530. t4 = _mm_xor_si128(t4,t3);
  531. t4 = _mm_xor_si128(t4,t5);
  532. return _mm_shuffle_epi8(t4,shuf);
  533. }
  534. #endif
  535. };
  536. } // namespace ZeroTier
  537. #endif