AES.hpp 14 KB

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