AES.hpp 15 KB

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