AES.hpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  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 AES-GMAC-SIV.
  238. *
  239. * Encryption requires two passes. The first pass starts after init
  240. * with aad (if any) followed by update1() and finish1(). Then the
  241. * update2() and finish2() methods must be used over the same data
  242. * (but NOT AAD) again.
  243. *
  244. * This supports encryption of a maximum of 2^31 bytes of data per
  245. * call to init().
  246. */
  247. class GMACSIVEncryptor
  248. {
  249. public:
  250. /**
  251. * Create a new AES-GMAC-SIV encryptor keyed with the provided AES instances
  252. *
  253. * @param k0 First of two AES instances keyed with K0
  254. * @param k1 Second of two AES instances keyed with K1
  255. */
  256. ZT_INLINE GMACSIVEncryptor(const AES &k0,const AES &k1) noexcept :
  257. _gmac(k0),
  258. _ctr(k1) {}
  259. /**
  260. * Initialize AES-GMAC-SIV
  261. *
  262. * @param iv IV in network byte order (byte order in which it will appear on the wire)
  263. * @param output Pointer to buffer to receive ciphertext, must be large enough for all to-be-processed data!
  264. */
  265. ZT_INLINE void init(const uint64_t iv,void *const output) noexcept
  266. {
  267. // Output buffer to receive the result of AES-CTR encryption.
  268. _output = output;
  269. // Initialize GMAC with 64-bit IV (and remaining 32 bits padded to zero).
  270. _tag[0] = iv;
  271. _tag[1] = 0;
  272. _gmac.init(reinterpret_cast<const uint8_t *>(_tag));
  273. }
  274. /**
  275. * Process AAD (additional authenticated data) that is not being encrypted.
  276. *
  277. * If such data exists this must be called before update1() and finish1().
  278. *
  279. * Note: current code only supports one single chunk of AAD. Don't call this
  280. * multiple times per message.
  281. *
  282. * @param aad Additional authenticated data
  283. * @param len Length of AAD in bytes
  284. */
  285. ZT_INLINE void aad(const void *const aad,unsigned int len) noexcept
  286. {
  287. // Feed ADD into GMAC first
  288. _gmac.update(aad,len);
  289. // End of AAD is padded to a multiple of 16 bytes to ensure unique encoding.
  290. len &= 0xfU;
  291. if (len != 0)
  292. _gmac.update(Utils::ZERO256,16 - len);
  293. }
  294. /**
  295. * First pass plaintext input function
  296. *
  297. * @param input Plaintext chunk
  298. * @param len Length of plaintext chunk
  299. */
  300. ZT_INLINE void update1(const void *const input,const unsigned int len) noexcept
  301. {
  302. _gmac.update(input,len);
  303. }
  304. /**
  305. * Finish first pass, compute CTR IV, initialize second pass.
  306. */
  307. ZT_INLINE void finish1() noexcept
  308. {
  309. uint64_t tmp[2];
  310. // Compute 128-bit GMAC tag.
  311. _gmac.finish(reinterpret_cast<uint8_t *>(tmp));
  312. // Shorten to 64 bits, concatenate with message IV, and encrypt with AES to
  313. // yield the CTR IV and opaque IV/MAC blob. In ZeroTier's use of GMAC-SIV
  314. // this get split into the packet ID (64 bits) and the MAC (64 bits) in each
  315. // packet and then recombined on receipt for legacy reasons (but with no
  316. // cryptographic or performance impact).
  317. _tag[1] = tmp[0] ^ tmp[1];
  318. _ctr._aes.encrypt(_tag,_tag);
  319. // Initialize CTR with 96-bit CTR nonce and 32-bit counter. The counter
  320. // incorporates 31 more bits of entropy which should raise our security margin
  321. // a bit, but this is not included in the worst case analysis of GMAC-SIV.
  322. // The most significant bit of the counter is masked to zero to allow up to
  323. // 2^31 bytes to be encrypted before the counter loops. Some CTR implementations
  324. // increment the whole big-endian 128-bit integer in which case this could be
  325. // used for more than 2^31 bytes, but ours does not for performance reasons
  326. // and so 2^31 should be considered the input limit.
  327. tmp[0] = _tag[0];
  328. tmp[1] = _tag[1] & ZT_CONST_TO_BE_UINT64(0xffffffff7fffffffULL);
  329. _ctr.init(reinterpret_cast<const uint8_t *>(tmp),_output);
  330. }
  331. /**
  332. * Second pass plaintext input function
  333. *
  334. * The same plaintext must be fed in the second time in the same order,
  335. * though chunk boundaries do not have to be the same.
  336. *
  337. * @param input Plaintext chunk
  338. * @param len Length of plaintext chunk
  339. */
  340. ZT_INLINE void update2(const void *const input,const unsigned int len) noexcept
  341. {
  342. _ctr.crypt(input,len);
  343. }
  344. /**
  345. * Finish second pass and return a pointer to the opaque 128-bit IV+MAC block
  346. *
  347. * The returned pointer remains valid as long as this object exists and init()
  348. * is not called again.
  349. *
  350. * @return Pointer to 128-bit opaque IV+MAC (packed into two 64-bit integers)
  351. */
  352. ZT_INLINE const uint64_t *finish2()
  353. {
  354. _ctr.finish();
  355. return _tag;
  356. }
  357. private:
  358. void *_output;
  359. uint64_t _tag[2];
  360. AES::GMAC _gmac;
  361. AES::CTR _ctr;
  362. };
  363. /**
  364. * Decryptor for AES-GMAC-SIV.
  365. *
  366. * GMAC-SIV decryption is single-pass. AAD (if any) must be processed first.
  367. */
  368. class GMACSIVDecryptor
  369. {
  370. public:
  371. ZT_INLINE GMACSIVDecryptor(const AES &k0,const AES &k1) noexcept :
  372. _ctr(k1),
  373. _gmac(k0) {}
  374. /**
  375. * Initialize decryptor for a new message
  376. *
  377. * @param tag 128-bit combined IV/MAC originally created by GMAC-SIV encryption
  378. * @param output Buffer in which to write output plaintext (must be large enough!)
  379. */
  380. ZT_INLINE void init(const uint64_t tag[2],void *const output) noexcept
  381. {
  382. uint64_t tmp[2];
  383. tmp[0] = tag[0];
  384. tmp[1] = tag[1] & ZT_CONST_TO_BE_UINT64(0xffffffff7fffffffULL);
  385. _ctr.init(reinterpret_cast<const uint8_t *>(tmp),output);
  386. _ctr._aes.decrypt(tag,_ivMac);
  387. tmp[0] = _ivMac[0];
  388. tmp[1] = 0;
  389. _gmac.init(reinterpret_cast<const uint8_t *>(tmp));
  390. _output = output;
  391. _decryptedLen = 0;
  392. }
  393. /**
  394. * Process AAD (additional authenticated data) that wasn't encrypted
  395. *
  396. * @param aad Additional authenticated data
  397. * @param len Length of AAD in bytes
  398. */
  399. ZT_INLINE void aad(const void *const aad,unsigned int len) noexcept
  400. {
  401. _gmac.update(aad,len);
  402. len &= 0xfU;
  403. if (len != 0)
  404. _gmac.update(Utils::ZERO256,16 - len);
  405. }
  406. /**
  407. * Feed ciphertext into the decryptor
  408. *
  409. * Unlike encryption, GMAC-SIV decryption requires only one pass.
  410. *
  411. * @param input Input ciphertext
  412. * @param len Length of ciphertext
  413. */
  414. ZT_INLINE void update(const void *const input,const unsigned int len) noexcept
  415. {
  416. _ctr.crypt(input,len);
  417. _decryptedLen += len;
  418. }
  419. /**
  420. * Flush decryption, compute MAC, and verify
  421. *
  422. * @return True if resulting plaintext (and AAD) pass message authentication check
  423. */
  424. ZT_INLINE bool finish() noexcept
  425. {
  426. _ctr.finish();
  427. uint64_t gmacTag[2];
  428. _gmac.update(_output,_decryptedLen);
  429. _gmac.finish(reinterpret_cast<uint8_t *>(gmacTag));
  430. return (gmacTag[0] ^ gmacTag[1]) == _ivMac[1];
  431. }
  432. private:
  433. uint64_t _ivMac[2];
  434. AES::CTR _ctr;
  435. AES::GMAC _gmac;
  436. void *_output;
  437. unsigned int _decryptedLen;
  438. };
  439. private:
  440. static const uint32_t Te0[256];
  441. static const uint32_t Te1[256];
  442. static const uint32_t Te2[256];
  443. static const uint32_t Te3[256];
  444. static const uint32_t Te4[256];
  445. static const uint32_t Td0[256];
  446. static const uint32_t Td1[256];
  447. static const uint32_t Td2[256];
  448. static const uint32_t Td3[256];
  449. static const uint8_t Td4[256];
  450. static const uint32_t rcon[10];
  451. void _initSW(const uint8_t key[32]) noexcept;
  452. void _encryptSW(const uint8_t in[16],uint8_t out[16]) const noexcept;
  453. void _decryptSW(const uint8_t in[16],uint8_t out[16]) const noexcept;
  454. union {
  455. #ifdef ZT_AES_AESNI
  456. struct {
  457. __m128i k[28];
  458. __m128i h,hh,hhh,hhhh;
  459. } ni;
  460. #endif
  461. struct {
  462. uint64_t h[2];
  463. uint32_t ek[60];
  464. uint32_t dk[60];
  465. } sw;
  466. } _k;
  467. #ifdef ZT_AES_AESNI
  468. static const __m128i s_shuf;
  469. void _init_aesni(const uint8_t key[32]) noexcept;
  470. ZT_INLINE void _encrypt_aesni(const void *const in,void *const out) const noexcept
  471. {
  472. __m128i tmp = _mm_loadu_si128((const __m128i *)in);
  473. tmp = _mm_xor_si128(tmp,_k.ni.k[0]);
  474. tmp = _mm_aesenc_si128(tmp,_k.ni.k[1]);
  475. tmp = _mm_aesenc_si128(tmp,_k.ni.k[2]);
  476. tmp = _mm_aesenc_si128(tmp,_k.ni.k[3]);
  477. tmp = _mm_aesenc_si128(tmp,_k.ni.k[4]);
  478. tmp = _mm_aesenc_si128(tmp,_k.ni.k[5]);
  479. tmp = _mm_aesenc_si128(tmp,_k.ni.k[6]);
  480. tmp = _mm_aesenc_si128(tmp,_k.ni.k[7]);
  481. tmp = _mm_aesenc_si128(tmp,_k.ni.k[8]);
  482. tmp = _mm_aesenc_si128(tmp,_k.ni.k[9]);
  483. tmp = _mm_aesenc_si128(tmp,_k.ni.k[10]);
  484. tmp = _mm_aesenc_si128(tmp,_k.ni.k[11]);
  485. tmp = _mm_aesenc_si128(tmp,_k.ni.k[12]);
  486. tmp = _mm_aesenc_si128(tmp,_k.ni.k[13]);
  487. _mm_storeu_si128((__m128i *)out,_mm_aesenclast_si128(tmp,_k.ni.k[14]));
  488. }
  489. ZT_INLINE void _decrypt_aesni(const void *in,void *out) const noexcept
  490. {
  491. __m128i tmp = _mm_loadu_si128((const __m128i *)in);
  492. tmp = _mm_xor_si128(tmp,_k.ni.k[14]);
  493. tmp = _mm_aesdec_si128(tmp,_k.ni.k[15]);
  494. tmp = _mm_aesdec_si128(tmp,_k.ni.k[16]);
  495. tmp = _mm_aesdec_si128(tmp,_k.ni.k[17]);
  496. tmp = _mm_aesdec_si128(tmp,_k.ni.k[18]);
  497. tmp = _mm_aesdec_si128(tmp,_k.ni.k[19]);
  498. tmp = _mm_aesdec_si128(tmp,_k.ni.k[20]);
  499. tmp = _mm_aesdec_si128(tmp,_k.ni.k[21]);
  500. tmp = _mm_aesdec_si128(tmp,_k.ni.k[22]);
  501. tmp = _mm_aesdec_si128(tmp,_k.ni.k[23]);
  502. tmp = _mm_aesdec_si128(tmp,_k.ni.k[24]);
  503. tmp = _mm_aesdec_si128(tmp,_k.ni.k[25]);
  504. tmp = _mm_aesdec_si128(tmp,_k.ni.k[26]);
  505. tmp = _mm_aesdec_si128(tmp,_k.ni.k[27]);
  506. _mm_storeu_si128((__m128i *)out,_mm_aesdeclast_si128(tmp,_k.ni.k[0]));
  507. }
  508. static ZT_INLINE __m128i _mult_block_aesni(const __m128i shuf,const __m128i h,__m128i y) noexcept
  509. {
  510. y = _mm_shuffle_epi8(y,shuf);
  511. __m128i t1 = _mm_clmulepi64_si128(h,y,0x00);
  512. __m128i t2 = _mm_clmulepi64_si128(h,y,0x01);
  513. __m128i t3 = _mm_clmulepi64_si128(h,y,0x10);
  514. __m128i t4 = _mm_clmulepi64_si128(h,y,0x11);
  515. t2 = _mm_xor_si128(t2,t3);
  516. t3 = _mm_slli_si128(t2,8);
  517. t2 = _mm_srli_si128(t2,8);
  518. t1 = _mm_xor_si128(t1,t3);
  519. t4 = _mm_xor_si128(t4,t2);
  520. __m128i t5 = _mm_srli_epi32(t1,31);
  521. t1 = _mm_slli_epi32(t1,1);
  522. __m128i t6 = _mm_srli_epi32(t4,31);
  523. t4 = _mm_slli_epi32(t4,1);
  524. t3 = _mm_srli_si128(t5,12);
  525. t6 = _mm_slli_si128(t6,4);
  526. t5 = _mm_slli_si128(t5,4);
  527. t1 = _mm_or_si128(t1,t5);
  528. t4 = _mm_or_si128(t4,t6);
  529. t4 = _mm_or_si128(t4,t3);
  530. t5 = _mm_slli_epi32(t1,31);
  531. t6 = _mm_slli_epi32(t1,30);
  532. t3 = _mm_slli_epi32(t1,25);
  533. t5 = _mm_xor_si128(t5,t6);
  534. t5 = _mm_xor_si128(t5,t3);
  535. t6 = _mm_srli_si128(t5,4);
  536. t4 = _mm_xor_si128(t4,t6);
  537. t5 = _mm_slli_si128(t5,12);
  538. t1 = _mm_xor_si128(t1,t5);
  539. t4 = _mm_xor_si128(t4,t1);
  540. t5 = _mm_srli_epi32(t1,1);
  541. t2 = _mm_srli_epi32(t1,2);
  542. t3 = _mm_srli_epi32(t1,7);
  543. t4 = _mm_xor_si128(t4,t2);
  544. t4 = _mm_xor_si128(t4,t3);
  545. t4 = _mm_xor_si128(t4,t5);
  546. return _mm_shuffle_epi8(t4,shuf);
  547. }
  548. #endif
  549. };
  550. } // namespace ZeroTier
  551. #endif