AES.hpp 16 KB

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