AES.hpp 15 KB

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