| 1 | // Copyright 2017 Dolphin Emulator Project |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | |
| 4 | #include "Common/Crypto/AES.h" |
| 5 | |
| 6 | #include <array> |
| 7 | #include <cstring> |
| 8 | #include <memory> |
| 9 | |
| 10 | #include <mbedtls/aes.h> |
| 11 | |
| 12 | #include "Common/Assert.h" |
| 13 | #include "Common/CPUDetect.h" |
| 14 | |
| 15 | #ifdef _MSC_VER |
| 16 | #include <intrin.h> |
| 17 | #else |
| 18 | #if defined(_M_X86_64) |
| 19 | #include <x86intrin.h> |
| 20 | #elif defined(_M_ARM_64) |
| 21 | #include <arm_acle.h> |
| 22 | #include <arm_neon.h> |
| 23 | #endif |
| 24 | #endif |
| 25 | |
| 26 | #ifdef _MSC_VER |
| 27 | #define ATTRIBUTE_TARGET(x) |
| 28 | #else |
| 29 | #define ATTRIBUTE_TARGET(x) [[gnu::target(x)]] |
| 30 | #endif |
| 31 | |
| 32 | namespace Common::AES |
| 33 | { |
| 34 | // For x64 and arm64, it's very unlikely a user's cpu does not support the accelerated version, |
| 35 | // fallback is just in case. |
| 36 | template <Mode AesMode> |
| 37 | class ContextGeneric final : public Context |
| 38 | { |
| 39 | public: |
| 40 | ContextGeneric(const u8* key) |
| 41 | { |
| 42 | mbedtls_aes_init(&ctx); |
| 43 | if constexpr (AesMode == Mode::Encrypt) |
| 44 | ASSERT(!mbedtls_aes_setkey_enc(&ctx, key, 128)); |
| 45 | else |
| 46 | ASSERT(!mbedtls_aes_setkey_dec(&ctx, key, 128)); |
| 47 | } |
| 48 | |
| 49 | bool Crypt(const u8* iv, u8* iv_out, const u8* buf_in, u8* buf_out, size_t len) const override |
| 50 | { |
| 51 | std::array<u8, BLOCK_SIZE> iv_tmp{}; |
| 52 | if (iv) |
| 53 | std::memcpy(&iv_tmp[0], iv, BLOCK_SIZE); |
| 54 | |
| 55 | constexpr int mode = (AesMode == Mode::Encrypt) ? MBEDTLS_AES_ENCRYPT : MBEDTLS_AES_DECRYPT; |
| 56 | if (mbedtls_aes_crypt_cbc(const_cast<mbedtls_aes_context*>(&ctx), mode, len, &iv_tmp[0], buf_in, |
| 57 | buf_out)) |
| 58 | return false; |
| 59 | |
| 60 | if (iv_out) |
| 61 | std::memcpy(iv_out, &iv_tmp[0], BLOCK_SIZE); |
| 62 | return true; |
| 63 | } |
| 64 | |
| 65 | private: |
| 66 | mbedtls_aes_context ctx{}; |
| 67 | }; |
| 68 | |
| 69 | #if defined(_M_X86_64) |
| 70 | |
| 71 | // Note that (for instructions with same data width) the actual instructions emitted vary depending |
| 72 | // on compiler and flags. The naming is somewhat confusing, because VAES cpuid flag was added after |
| 73 | // VAES(VEX.128): |
| 74 | // clang-format off |
| 75 | // instructions | cpuid flag | #define |
| 76 | // AES(128) | AES | - |
| 77 | // VAES(VEX.128) | AES & AVX | __AVX__ |
| 78 | // VAES(VEX.256) | VAES | - |
| 79 | // VAES(EVEX.128) | VAES & AVX512VL | __AVX512VL__ |
| 80 | // VAES(EVEX.256) | VAES & AVX512VL | __AVX512VL__ |
| 81 | // VAES(EVEX.512) | VAES & AVX512F | __AVX512F__ |
| 82 | // clang-format on |
| 83 | template <Mode AesMode> |
| 84 | class ContextAESNI final : public Context |
| 85 | { |
| 86 | static inline __m128i Aes128KeygenAssistFinish(__m128i key, __m128i kga) |
| 87 | { |
| 88 | __m128i tmp = _mm_shuffle_epi32(kga, _MM_SHUFFLE(3, 3, 3, 3)); |
| 89 | tmp = _mm_xor_si128(tmp, key); |
| 90 | |
| 91 | key = _mm_slli_si128(key, 4); |
| 92 | tmp = _mm_xor_si128(tmp, key); |
| 93 | key = _mm_slli_si128(key, 4); |
| 94 | tmp = _mm_xor_si128(tmp, key); |
| 95 | key = _mm_slli_si128(key, 4); |
| 96 | tmp = _mm_xor_si128(tmp, key); |
| 97 | return tmp; |
| 98 | } |
| 99 | |
| 100 | template <size_t RoundIdx> |
| 101 | ATTRIBUTE_TARGET("aes") |
| 102 | inline constexpr void StoreRoundKey(__m128i rk) |
| 103 | { |
| 104 | if constexpr (AesMode == Mode::Encrypt) |
| 105 | round_keys[RoundIdx] = rk; |
| 106 | else |
| 107 | { |
| 108 | constexpr size_t idx = NUM_ROUND_KEYS - RoundIdx - 1; |
| 109 | if constexpr (idx == 0 || idx == NUM_ROUND_KEYS - 1) |
| 110 | round_keys[idx] = rk; |
| 111 | else |
| 112 | round_keys[idx] = _mm_aesimc_si128(rk); |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | template <size_t RoundIdx, int Rcon> |
| 117 | ATTRIBUTE_TARGET("aes") |
| 118 | inline constexpr __m128i Aes128Keygen(__m128i rk) |
| 119 | { |
| 120 | rk = Aes128KeygenAssistFinish(rk, _mm_aeskeygenassist_si128(rk, Rcon)); |
| 121 | StoreRoundKey<RoundIdx>(rk); |
| 122 | return rk; |
| 123 | } |
| 124 | |
| 125 | public: |
| 126 | ContextAESNI(const u8* key) |
| 127 | { |
| 128 | __m128i rk = _mm_loadu_si128((const __m128i*)key); |
| 129 | StoreRoundKey<0>(rk); |
| 130 | rk = Aes128Keygen<1, 0x01>(rk); |
| 131 | rk = Aes128Keygen<2, 0x02>(rk); |
| 132 | rk = Aes128Keygen<3, 0x04>(rk); |
| 133 | rk = Aes128Keygen<4, 0x08>(rk); |
| 134 | rk = Aes128Keygen<5, 0x10>(rk); |
| 135 | rk = Aes128Keygen<6, 0x20>(rk); |
| 136 | rk = Aes128Keygen<7, 0x40>(rk); |
| 137 | rk = Aes128Keygen<8, 0x80>(rk); |
| 138 | rk = Aes128Keygen<9, 0x1b>(rk); |
| 139 | Aes128Keygen<10, 0x36>(rk); |
| 140 | } |
| 141 | |
| 142 | ATTRIBUTE_TARGET("aes") |
| 143 | inline void CryptBlock(__m128i* iv, const u8* buf_in, u8* buf_out) const |
| 144 | { |
| 145 | __m128i block = _mm_loadu_si128((const __m128i*)buf_in); |
| 146 | |
| 147 | if constexpr (AesMode == Mode::Encrypt) |
| 148 | { |
| 149 | block = _mm_xor_si128(_mm_xor_si128(block, *iv), round_keys[0]); |
| 150 | |
| 151 | for (size_t i = 1; i < Nr; ++i) |
| 152 | block = _mm_aesenc_si128(block, round_keys[i]); |
| 153 | block = _mm_aesenclast_si128(block, round_keys[Nr]); |
| 154 | |
| 155 | *iv = block; |
| 156 | } |
| 157 | else |
| 158 | { |
| 159 | __m128i iv_next = block; |
| 160 | |
| 161 | block = _mm_xor_si128(block, round_keys[0]); |
| 162 | |
| 163 | for (size_t i = 1; i < Nr; ++i) |
| 164 | block = _mm_aesdec_si128(block, round_keys[i]); |
| 165 | block = _mm_aesdeclast_si128(block, round_keys[Nr]); |
| 166 | |
| 167 | block = _mm_xor_si128(block, *iv); |
| 168 | *iv = iv_next; |
| 169 | } |
| 170 | |
| 171 | _mm_storeu_si128((__m128i*)buf_out, block); |
| 172 | } |
| 173 | |
| 174 | // Takes advantage of instruction pipelining to parallelize. |
| 175 | template <size_t NumBlocks> |
| 176 | ATTRIBUTE_TARGET("aes") |
| 177 | inline void DecryptPipelined(__m128i* iv, const u8* buf_in, u8* buf_out) const |
| 178 | { |
| 179 | constexpr size_t Depth = NumBlocks; |
| 180 | |
| 181 | __m128i block[Depth]; |
| 182 | for (size_t d = 0; d < Depth; d++) |
| 183 | block[d] = _mm_loadu_si128(&((const __m128i*)buf_in)[d]); |
| 184 | |
| 185 | __m128i iv_next[1 + Depth]; |
| 186 | iv_next[0] = *iv; |
| 187 | for (size_t d = 0; d < Depth; d++) |
| 188 | iv_next[1 + d] = block[d]; |
| 189 | |
| 190 | for (size_t d = 0; d < Depth; d++) |
| 191 | block[d] = _mm_xor_si128(block[d], round_keys[0]); |
| 192 | |
| 193 | // The main speedup is here |
| 194 | for (size_t i = 1; i < Nr; ++i) |
| 195 | for (size_t d = 0; d < Depth; d++) |
| 196 | block[d] = _mm_aesdec_si128(block[d], round_keys[i]); |
| 197 | for (size_t d = 0; d < Depth; d++) |
| 198 | block[d] = _mm_aesdeclast_si128(block[d], round_keys[Nr]); |
| 199 | |
| 200 | for (size_t d = 0; d < Depth; d++) |
| 201 | block[d] = _mm_xor_si128(block[d], iv_next[d]); |
| 202 | *iv = iv_next[1 + Depth - 1]; |
| 203 | |
| 204 | for (size_t d = 0; d < Depth; d++) |
| 205 | _mm_storeu_si128(&((__m128i*)buf_out)[d], block[d]); |
| 206 | } |
| 207 | |
| 208 | bool Crypt(const u8* iv, u8* iv_out, const u8* buf_in, u8* buf_out, size_t len) const override |
| 209 | { |
| 210 | if (len % BLOCK_SIZE) |
| 211 | return false; |
| 212 | |
| 213 | __m128i iv_block = iv ? _mm_loadu_si128((const __m128i*)iv) : _mm_setzero_si128(); |
| 214 | |
| 215 | if constexpr (AesMode == Mode::Decrypt) |
| 216 | { |
| 217 | // On amd zen2...(benchmark, not real-world): |
| 218 | // With AES(128) instructions, BLOCK_DEPTH results in following speedup vs. non-pipelined: 4: |
| 219 | // 18%, 8: 22%, 9: 26%, 10-15: 31%. 16: 8% (register exhaustion). With VAES(VEX.128), 10 gives |
| 220 | // 36% speedup vs. its corresponding baseline. VAES(VEX.128) is ~4% faster than AES(128). The |
| 221 | // result is similar on zen3. |
| 222 | // Zen3 in general is 20% faster than zen2 in aes, and VAES(VEX.256) is 35% faster than |
| 223 | // zen3/VAES(VEX.128). |
| 224 | // It seems like VAES(VEX.256) should be faster? |
| 225 | // TODO Choose value at runtime based on some criteria? |
| 226 | constexpr size_t BLOCK_DEPTH = 10; |
| 227 | constexpr size_t CHUNK_LEN = BLOCK_DEPTH * BLOCK_SIZE; |
| 228 | while (len >= CHUNK_LEN) |
| 229 | { |
| 230 | DecryptPipelined<BLOCK_DEPTH>(&iv_block, buf_in, buf_out); |
| 231 | buf_in += CHUNK_LEN; |
| 232 | buf_out += CHUNK_LEN; |
| 233 | len -= CHUNK_LEN; |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | len /= BLOCK_SIZE; |
| 238 | while (len--) |
| 239 | { |
| 240 | CryptBlock(&iv_block, buf_in, buf_out); |
| 241 | buf_in += BLOCK_SIZE; |
| 242 | buf_out += BLOCK_SIZE; |
| 243 | } |
| 244 | |
| 245 | if (iv_out) |
| 246 | _mm_storeu_si128((__m128i*)iv_out, iv_block); |
| 247 | |
| 248 | return true; |
| 249 | } |
| 250 | |
| 251 | private: |
| 252 | // Ensures alignment specifiers are respected. |
| 253 | struct XmmReg |
| 254 | { |
| 255 | __m128i data; |
| 256 | |
| 257 | XmmReg& operator=(const __m128i& m) |
| 258 | { |
| 259 | data = m; |
| 260 | return *this; |
| 261 | } |
| 262 | operator __m128i() const { return data; } |
| 263 | }; |
| 264 | std::array<XmmReg, NUM_ROUND_KEYS> round_keys; |
| 265 | }; |
| 266 | |
| 267 | #endif |
| 268 | |
| 269 | #if defined(_M_ARM_64) |
| 270 | |
| 271 | template <Mode AesMode> |
| 272 | class ContextNeon final : public Context |
| 273 | { |
| 274 | public: |
| 275 | template <size_t RoundIdx> |
| 276 | inline constexpr void StoreRoundKey(const u32* rk) |
| 277 | { |
| 278 | const uint8x16_t rk_block = vreinterpretq_u8_u32(vld1q_u32(rk)); |
| 279 | if constexpr (AesMode == Mode::Encrypt) |
| 280 | round_keys[RoundIdx] = rk_block; |
| 281 | else |
| 282 | { |
| 283 | constexpr size_t idx = NUM_ROUND_KEYS - RoundIdx - 1; |
| 284 | if constexpr (idx == 0 || idx == NUM_ROUND_KEYS - 1) |
| 285 | round_keys[idx] = rk_block; |
| 286 | else |
| 287 | round_keys[idx] = vaesimcq_u8(rk_block); |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | ContextNeon(const u8* key) |
| 292 | { |
| 293 | constexpr u8 rcon[]{0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36}; |
| 294 | std::array<u32, Nb * NUM_ROUND_KEYS> rk{}; |
| 295 | |
| 296 | // This uses a nice trick I've seen in wolfssl (not sure original author), |
| 297 | // which uses vaeseq_u8 to assist keygen. |
| 298 | // vaeseq_u8: op1 = SubBytes(ShiftRows(AddRoundKey(op1, op2))) |
| 299 | // given RotWord == ShiftRows for row 1 (rol(x,8)) |
| 300 | // Probably not super fast (moves to/from vector regs constantly), but it is nice and simple. |
| 301 | |
| 302 | std::memcpy(&rk[0], key, KEY_SIZE); |
| 303 | StoreRoundKey<0>(&rk[0]); |
| 304 | for (size_t i = 0; i < rk.size() - Nk; i += Nk) |
| 305 | { |
| 306 | const uint8x16_t enc = vaeseq_u8(vreinterpretq_u8_u32(vmovq_n_u32(rk[i + 3])), vmovq_n_u8(0)); |
| 307 | const u32 temp = vgetq_lane_u32(vreinterpretq_u32_u8(enc), 0); |
| 308 | rk[i + 4] = rk[i + 0] ^ std::rotr(temp, 8) ^ rcon[i / Nk]; |
| 309 | rk[i + 5] = rk[i + 4] ^ rk[i + 1]; |
| 310 | rk[i + 6] = rk[i + 5] ^ rk[i + 2]; |
| 311 | rk[i + 7] = rk[i + 6] ^ rk[i + 3]; |
| 312 | // clang-format off |
| 313 | // Not great |
| 314 | const size_t rki = 1 + i / Nk; |
| 315 | switch (rki) |
| 316 | { |
| 317 | case 1: StoreRoundKey< 1>(&rk[Nk * rki]); break; |
| 318 | case 2: StoreRoundKey< 2>(&rk[Nk * rki]); break; |
| 319 | case 3: StoreRoundKey< 3>(&rk[Nk * rki]); break; |
| 320 | case 4: StoreRoundKey< 4>(&rk[Nk * rki]); break; |
| 321 | case 5: StoreRoundKey< 5>(&rk[Nk * rki]); break; |
| 322 | case 6: StoreRoundKey< 6>(&rk[Nk * rki]); break; |
| 323 | case 7: StoreRoundKey< 7>(&rk[Nk * rki]); break; |
| 324 | case 8: StoreRoundKey< 8>(&rk[Nk * rki]); break; |
| 325 | case 9: StoreRoundKey< 9>(&rk[Nk * rki]); break; |
| 326 | case 10: StoreRoundKey<10>(&rk[Nk * rki]); break; |
| 327 | } |
| 328 | // clang-format on |
| 329 | } |
| 330 | } |
| 331 | |
| 332 | inline void CryptBlock(uint8x16_t* iv, const u8* buf_in, u8* buf_out) const |
| 333 | { |
| 334 | uint8x16_t block = vld1q_u8(buf_in); |
| 335 | |
| 336 | if constexpr (AesMode == Mode::Encrypt) |
| 337 | { |
| 338 | block = veorq_u8(block, *iv); |
| 339 | |
| 340 | for (size_t i = 0; i < Nr - 1; ++i) |
| 341 | block = vaesmcq_u8(vaeseq_u8(block, round_keys[i])); |
| 342 | block = vaeseq_u8(block, round_keys[Nr - 1]); |
| 343 | block = veorq_u8(block, round_keys[Nr]); |
| 344 | |
| 345 | *iv = block; |
| 346 | } |
| 347 | else |
| 348 | { |
| 349 | uint8x16_t iv_next = block; |
| 350 | |
| 351 | for (size_t i = 0; i < Nr - 1; ++i) |
| 352 | block = vaesimcq_u8(vaesdq_u8(block, round_keys[i])); |
| 353 | block = vaesdq_u8(block, round_keys[Nr - 1]); |
| 354 | block = veorq_u8(block, round_keys[Nr]); |
| 355 | |
| 356 | block = veorq_u8(block, *iv); |
| 357 | *iv = iv_next; |
| 358 | } |
| 359 | |
| 360 | vst1q_u8(buf_out, block); |
| 361 | } |
| 362 | |
| 363 | virtual bool Crypt(const u8* iv, u8* iv_out, const u8* buf_in, u8* buf_out, |
| 364 | size_t len) const override |
| 365 | { |
| 366 | if (len % BLOCK_SIZE) |
| 367 | return false; |
| 368 | |
| 369 | uint8x16_t iv_block = iv ? vld1q_u8(iv) : vmovq_n_u8(0); |
| 370 | |
| 371 | len /= BLOCK_SIZE; |
| 372 | while (len--) |
| 373 | { |
| 374 | CryptBlock(&iv_block, buf_in, buf_out); |
| 375 | buf_in += BLOCK_SIZE; |
| 376 | buf_out += BLOCK_SIZE; |
| 377 | } |
| 378 | |
| 379 | if (iv_out) |
| 380 | vst1q_u8(iv_out, iv_block); |
| 381 | |
| 382 | return true; |
| 383 | } |
| 384 | |
| 385 | private: |
| 386 | std::array<uint8x16_t, NUM_ROUND_KEYS> round_keys; |
| 387 | }; |
| 388 | |
| 389 | #endif |
| 390 | |
| 391 | template <Mode AesMode> |
| 392 | std::unique_ptr<Context> CreateContext(const u8* key) |
| 393 | { |
| 394 | if (cpu_info.bAES) |
| 395 | { |
| 396 | #if defined(_M_X86_64) |
| 397 | #if defined(__AVX__) |
| 398 | // If compiler enables AVX, the intrinsics will generate VAES(VEX.128) instructions. |
| 399 | // In the future we may want to compile the code twice and explicitly override the compiler |
| 400 | // flags. There doesn't seem to be much performance difference between AES(128) and |
| 401 | // VAES(VEX.128) at the moment, though. |
| 402 | if (cpu_info.bAVX) |
| 403 | #endif |
| 404 | return std::make_unique<ContextAESNI<AesMode>>(key); |
| 405 | #elif defined(_M_ARM_64) |
| 406 | return std::make_unique<ContextNeon<AesMode>>(key); |
| 407 | #endif |
| 408 | } |
| 409 | return std::make_unique<ContextGeneric<AesMode>>(key); |
| 410 | } |
| 411 | |
| 412 | std::unique_ptr<Context> CreateContextEncrypt(const u8* key) |
| 413 | { |
| 414 | return CreateContext<Mode::Encrypt>(key); |
| 415 | } |
| 416 | |
| 417 | std::unique_ptr<Context> CreateContextDecrypt(const u8* key) |
| 418 | { |
| 419 | return CreateContext<Mode::Decrypt>(key); |
| 420 | } |
| 421 | |
| 422 | // OFB encryption and decryption are the exact same. We don't encrypt though. |
| 423 | void CryptOFB(const u8* key, const u8* iv, u8* iv_out, const u8* buf_in, u8* buf_out, size_t size) |
| 424 | { |
| 425 | mbedtls_aes_context aes_ctx; |
| 426 | size_t iv_offset = 0; |
| 427 | |
| 428 | std::array<u8, 16> iv_tmp{}; |
| 429 | if (iv) |
| 430 | std::memcpy(&iv_tmp[0], iv, 16); |
| 431 | |
| 432 | ASSERT(!mbedtls_aes_setkey_enc(&aes_ctx, key, 128)); |
| 433 | mbedtls_aes_crypt_ofb(&aes_ctx, size, &iv_offset, &iv_tmp[0], buf_in, buf_out); |
| 434 | |
| 435 | if (iv_out) |
| 436 | std::memcpy(iv_out, &iv_tmp[0], 16); |
| 437 | } |
| 438 | |
| 439 | } // namespace Common::AES |