AES.hpp 15 KB

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