AES.hpp 15 KB

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