AES.hpp 14 KB

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