AES.hpp 14 KB

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