AES.hpp 15 KB

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