summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGravatar wwylele2017-01-01 14:58:02 +0200
committerGravatar wwylele2017-02-21 23:57:31 +0200
commitea1ea0224c04753402e0b6472080f0c5d90a7a46 (patch)
treed6823e52d913418d63ec3f0b7ed12eb763a98899
parentMerge pull request #2562 from yuriks/pica-refactor3 (diff)
downloadyuzu-ea1ea0224c04753402e0b6472080f0c5d90a7a46.tar.gz
yuzu-ea1ea0224c04753402e0b6472080f0c5d90a7a46.tar.xz
yuzu-ea1ea0224c04753402e0b6472080f0c5d90a7a46.zip
HW: add AES engine & implement AES-CCM
m---------externals/dynarmic0
-rw-r--r--src/common/common_paths.h1
-rw-r--r--src/common/logging/backend.cpp1
-rw-r--r--src/common/logging/log.h1
-rw-r--r--src/core/CMakeLists.txt6
-rw-r--r--src/core/hw/aes/arithmetic128.cpp47
-rw-r--r--src/core/hw/aes/arithmetic128.h17
-rw-r--r--src/core/hw/aes/ccm.cpp95
-rw-r--r--src/core/hw/aes/ccm.h40
-rw-r--r--src/core/hw/aes/key.cpp173
-rw-r--r--src/core/hw/aes/key.h35
-rw-r--r--src/core/hw/hw.cpp2
12 files changed, 418 insertions, 0 deletions
diff --git a/externals/dynarmic b/externals/dynarmic
Subproject 459d7d1bafcf85677c989b7cb260d3789aa813e Subproject 358cf7c32205a5114964865c86a8455daf81073
diff --git a/src/common/common_paths.h b/src/common/common_paths.h
index b56105306..d5b510cdb 100644
--- a/src/common/common_paths.h
+++ b/src/common/common_paths.h
@@ -45,3 +45,4 @@
45 45
46// Sys files 46// Sys files
47#define SHARED_FONT "shared_font.bin" 47#define SHARED_FONT "shared_font.bin"
48#define AES_KEYS "aes_keys.txt"
diff --git a/src/common/logging/backend.cpp b/src/common/logging/backend.cpp
index 2ef3e6b05..0ea65e817 100644
--- a/src/common/logging/backend.cpp
+++ b/src/common/logging/backend.cpp
@@ -62,6 +62,7 @@ namespace Log {
62 SUB(HW, Memory) \ 62 SUB(HW, Memory) \
63 SUB(HW, LCD) \ 63 SUB(HW, LCD) \
64 SUB(HW, GPU) \ 64 SUB(HW, GPU) \
65 SUB(HW, AES) \
65 CLS(Frontend) \ 66 CLS(Frontend) \
66 CLS(Render) \ 67 CLS(Render) \
67 SUB(Render, Software) \ 68 SUB(Render, Software) \
diff --git a/src/common/logging/log.h b/src/common/logging/log.h
index 4330ef879..a590d39ff 100644
--- a/src/common/logging/log.h
+++ b/src/common/logging/log.h
@@ -79,6 +79,7 @@ enum class Class : ClassType {
79 HW_Memory, ///< Memory-map and address translation 79 HW_Memory, ///< Memory-map and address translation
80 HW_LCD, ///< LCD register emulation 80 HW_LCD, ///< LCD register emulation
81 HW_GPU, ///< GPU control emulation 81 HW_GPU, ///< GPU control emulation
82 HW_AES, ///< AES engine emulation
82 Frontend, ///< Emulator UI 83 Frontend, ///< Emulator UI
83 Render, ///< Emulator video output and hardware acceleration 84 Render, ///< Emulator video output and hardware acceleration
84 Render_Software, ///< Software renderer backend 85 Render_Software, ///< Software renderer backend
diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt
index 1da10afab..da3d024bb 100644
--- a/src/core/CMakeLists.txt
+++ b/src/core/CMakeLists.txt
@@ -159,6 +159,9 @@ set(SRCS
159 hle/service/y2r_u.cpp 159 hle/service/y2r_u.cpp
160 hle/shared_page.cpp 160 hle/shared_page.cpp
161 hle/svc.cpp 161 hle/svc.cpp
162 hw/aes/arithmetic128.cpp
163 hw/aes/ccm.cpp
164 hw/aes/key.cpp
162 hw/gpu.cpp 165 hw/gpu.cpp
163 hw/hw.cpp 166 hw/hw.cpp
164 hw/lcd.cpp 167 hw/lcd.cpp
@@ -342,6 +345,9 @@ set(HEADERS
342 hle/service/y2r_u.h 345 hle/service/y2r_u.h
343 hle/shared_page.h 346 hle/shared_page.h
344 hle/svc.h 347 hle/svc.h
348 hw/aes/arithmetic128.h
349 hw/aes/ccm.h
350 hw/aes/key.h
345 hw/gpu.h 351 hw/gpu.h
346 hw/hw.h 352 hw/hw.h
347 hw/lcd.h 353 hw/lcd.h
diff --git a/src/core/hw/aes/arithmetic128.cpp b/src/core/hw/aes/arithmetic128.cpp
new file mode 100644
index 000000000..55b954a52
--- /dev/null
+++ b/src/core/hw/aes/arithmetic128.cpp
@@ -0,0 +1,47 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include <algorithm>
6#include <functional>
7#include "core/hw/aes/arithmetic128.h"
8
9namespace HW {
10namespace AES {
11
12AESKey Lrot128(const AESKey& in, u32 rot) {
13 AESKey out;
14 rot %= 128;
15 const u32 byte_shift = rot / 8;
16 const u32 bit_shift = rot % 8;
17
18 for (u32 i = 0; i < 16; i++) {
19 const u32 wrap_index_a = (i + byte_shift) % 16;
20 const u32 wrap_index_b = (i + byte_shift + 1) % 16;
21 out[i] = ((in[wrap_index_a] << bit_shift) | (in[wrap_index_b] >> (8 - bit_shift))) & 0xFF;
22 }
23 return out;
24}
25
26AESKey Add128(const AESKey& a, const AESKey& b) {
27 AESKey out;
28 u32 carry = 0;
29 u32 sum = 0;
30
31 for (int i = 15; i >= 0; i--) {
32 sum = a[i] + b[i] + carry;
33 carry = sum >> 8;
34 out[i] = static_cast<u8>(sum & 0xff);
35 }
36
37 return out;
38}
39
40AESKey Xor128(const AESKey& a, const AESKey& b) {
41 AESKey out;
42 std::transform(a.cbegin(), a.cend(), b.cbegin(), out.begin(), std::bit_xor<>());
43 return out;
44}
45
46} // namespace AES
47} // namespace HW
diff --git a/src/core/hw/aes/arithmetic128.h b/src/core/hw/aes/arithmetic128.h
new file mode 100644
index 000000000..d670e2ce2
--- /dev/null
+++ b/src/core/hw/aes/arithmetic128.h
@@ -0,0 +1,17 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include "common/common_types.h"
8#include "core/hw/aes/key.h"
9
10namespace HW {
11namespace AES {
12AESKey Lrot128(const AESKey& in, u32 rot);
13AESKey Add128(const AESKey& a, const AESKey& b);
14AESKey Xor128(const AESKey& a, const AESKey& b);
15
16} // namspace AES
17} // namespace HW
diff --git a/src/core/hw/aes/ccm.cpp b/src/core/hw/aes/ccm.cpp
new file mode 100644
index 000000000..dc7035ab6
--- /dev/null
+++ b/src/core/hw/aes/ccm.cpp
@@ -0,0 +1,95 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include <algorithm>
6#include <cryptopp/aes.h>
7#include <cryptopp/ccm.h>
8#include <cryptopp/cryptlib.h>
9#include <cryptopp/filters.h>
10#include "common/alignment.h"
11#include "common/logging/log.h"
12#include "core/hw/aes/ccm.h"
13#include "core/hw/aes/key.h"
14
15namespace HW {
16namespace AES {
17
18namespace {
19
20// 3DS uses a non-standard AES-CCM algorithm, so we need to derive a sub class from the standard one
21// and override with the non-standard part.
22using CryptoPP::lword;
23using CryptoPP::AES;
24using CryptoPP::CCM_Final;
25using CryptoPP::CCM_Base;
26template <bool T_IsEncryption>
27class CCM_3DSVariant_Final : public CCM_Final<AES, CCM_MAC_SIZE, T_IsEncryption> {
28public:
29 void UncheckedSpecifyDataLengths(lword header_length, lword message_length,
30 lword footer_length) override {
31 // 3DS uses the aligned size to generate B0 for authentication, instead of the original size
32 lword aligned_message_length = Common::AlignUp(message_length, AES_BLOCK_SIZE);
33 CCM_Base::UncheckedSpecifyDataLengths(header_length, aligned_message_length, footer_length);
34 CCM_Base::m_messageLength = message_length; // restore the actual message size
35 }
36};
37
38class CCM_3DSVariant {
39public:
40 using Encryption = CCM_3DSVariant_Final<true>;
41 using Decryption = CCM_3DSVariant_Final<false>;
42};
43
44} // namespace
45
46std::vector<u8> EncryptSignCCM(const std::vector<u8>& pdata, const CCMNonce& nonce,
47 size_t slot_id) {
48 if (!IsNormalKeyAvailable(slot_id)) {
49 LOG_ERROR(HW_AES, "Key slot %d not available. Will use zero key.", slot_id);
50 }
51 const AESKey normal = GetNormalKey(slot_id);
52 std::vector<u8> cipher(pdata.size() + CCM_MAC_SIZE);
53
54 try {
55 CCM_3DSVariant::Encryption e;
56 e.SetKeyWithIV(normal.data(), AES_BLOCK_SIZE, nonce.data(), CCM_NONCE_SIZE);
57 e.SpecifyDataLengths(0, pdata.size(), 0);
58 CryptoPP::ArraySource as(pdata.data(), pdata.size(), true,
59 new CryptoPP::AuthenticatedEncryptionFilter(
60 e, new CryptoPP::ArraySink(cipher.data(), cipher.size())));
61 } catch (const CryptoPP::Exception& e) {
62 LOG_ERROR(HW_AES, "FAILED with: %s", e.what());
63 }
64 return cipher;
65}
66
67std::vector<u8> DecryptVerifyCCM(const std::vector<u8>& cipher, const CCMNonce& nonce,
68 size_t slot_id) {
69 if (!IsNormalKeyAvailable(slot_id)) {
70 LOG_ERROR(HW_AES, "Key slot %d not available. Will use zero key.", slot_id);
71 }
72 const AESKey normal = GetNormalKey(slot_id);
73 const std::size_t pdata_size = cipher.size() - CCM_MAC_SIZE;
74 std::vector<u8> pdata(pdata_size);
75
76 try {
77 CCM_3DSVariant::Decryption d;
78 d.SetKeyWithIV(normal.data(), AES_BLOCK_SIZE, nonce.data(), CCM_NONCE_SIZE);
79 d.SpecifyDataLengths(0, pdata_size, 0);
80 CryptoPP::AuthenticatedDecryptionFilter df(
81 d, new CryptoPP::ArraySink(pdata.data(), pdata_size));
82 CryptoPP::ArraySource as(cipher.data(), cipher.size(), true, new CryptoPP::Redirector(df));
83 if (!df.GetLastResult()) {
84 LOG_ERROR(HW_AES, "FAILED");
85 return {};
86 }
87 } catch (const CryptoPP::Exception& e) {
88 LOG_ERROR(HW_AES, "FAILED with: %s", e.what());
89 return {};
90 }
91 return pdata;
92}
93
94} // namespace AES
95} // namespace HW
diff --git a/src/core/hw/aes/ccm.h b/src/core/hw/aes/ccm.h
new file mode 100644
index 000000000..bf4146e80
--- /dev/null
+++ b/src/core/hw/aes/ccm.h
@@ -0,0 +1,40 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <array>
8#include <cstddef>
9#include <vector>
10#include "common/common_types.h"
11
12namespace HW {
13namespace AES {
14
15constexpr size_t CCM_NONCE_SIZE = 12;
16constexpr size_t CCM_MAC_SIZE = 16;
17
18using CCMNonce = std::array<u8, CCM_NONCE_SIZE>;
19
20/**
21 * Encrypts and adds a MAC to the given data using AES-CCM algorithm.
22 * @param pdata The plain text data to encrypt
23 * @param nonce The nonce data to use for encryption
24 * @param slot_id The slot ID of the key to use for encryption
25 * @returns a vector of u8 containing the encrypted data with MAC at the end
26 */
27std::vector<u8> EncryptSignCCM(const std::vector<u8>& pdata, const CCMNonce& nonce, size_t slot_id);
28
29/**
30 * Decrypts and verify the MAC of the given data using AES-CCM algorithm.
31 * @param cipher The cipher text data to decrypt, with MAC at the end to verify
32 * @param nonce The nonce data to use for decryption
33 * @param slot_id The slot ID of the key to use for decryption
34 * @returns a vector of u8 containing the decrypted data; an empty vector if the verification fails
35 */
36std::vector<u8> DecryptVerifyCCM(const std::vector<u8>& cipher, const CCMNonce& nonce,
37 size_t slot_id);
38
39} // namespace AES
40} // namespace HW
diff --git a/src/core/hw/aes/key.cpp b/src/core/hw/aes/key.cpp
new file mode 100644
index 000000000..4e8a8a59a
--- /dev/null
+++ b/src/core/hw/aes/key.cpp
@@ -0,0 +1,173 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include <algorithm>
6#include <exception>
7#include <sstream>
8#include <boost/optional.hpp>
9#include "common/common_paths.h"
10#include "common/file_util.h"
11#include "common/logging/log.h"
12#include "common/string_util.h"
13#include "core/hw/aes/arithmetic128.h"
14#include "core/hw/aes/key.h"
15
16namespace HW {
17namespace AES {
18
19namespace {
20
21boost::optional<AESKey> generator_constant;
22
23struct KeySlot {
24 boost::optional<AESKey> x;
25 boost::optional<AESKey> y;
26 boost::optional<AESKey> normal;
27
28 void SetKeyX(const AESKey& key) {
29 x = key;
30 if (y && generator_constant) {
31 GenerateNormalKey();
32 }
33 }
34
35 void SetKeyY(const AESKey& key) {
36 y = key;
37 if (x && generator_constant) {
38 GenerateNormalKey();
39 }
40 }
41
42 void SetNormalKey(const AESKey& key) {
43 normal = key;
44 }
45
46 void GenerateNormalKey() {
47 normal = Lrot128(Add128(Xor128(Lrot128(*x, 2), *y), *generator_constant), 87);
48 }
49
50 void Clear() {
51 x.reset();
52 y.reset();
53 normal.reset();
54 }
55};
56
57std::array<KeySlot, KeySlotID::MaxKeySlotID> key_slots;
58
59void ClearAllKeys() {
60 for (KeySlot& slot : key_slots) {
61 slot.Clear();
62 }
63 generator_constant.reset();
64}
65
66AESKey HexToKey(const std::string& hex) {
67 if (hex.size() < 32) {
68 throw std::invalid_argument("hex string is too short");
69 }
70
71 AESKey key;
72 for (size_t i = 0; i < key.size(); ++i) {
73 key[i] = static_cast<u8>(std::stoi(hex.substr(i * 2, 2), 0, 16));
74 }
75
76 return key;
77}
78
79void LoadPresetKeys() {
80 const std::string filepath = FileUtil::GetUserPath(D_SYSDATA_IDX) + AES_KEYS;
81 FileUtil::CreateFullPath(filepath); // Create path if not already created
82 std::ifstream file;
83 OpenFStream(file, filepath, std::ios_base::in);
84 if (!file) {
85 return;
86 }
87
88 while (!file.eof()) {
89 std::string line;
90 std::getline(file, line);
91 std::vector<std::string> parts;
92 Common::SplitString(line, '=', parts);
93 if (parts.size() != 2) {
94 LOG_ERROR(HW_AES, "Failed to parse %s", line.c_str());
95 continue;
96 }
97
98 const std::string& name = parts[0];
99 AESKey key;
100 try {
101 key = HexToKey(parts[1]);
102 } catch (const std::logic_error& e) {
103 LOG_ERROR(HW_AES, "Invalid key %s: %s", parts[1].c_str(), e.what());
104 continue;
105 }
106
107 if (name == "generator") {
108 generator_constant = key;
109 continue;
110 }
111
112 size_t slot_id;
113 char key_type;
114 if (std::sscanf(name.c_str(), "slot0x%zXKey%c", &slot_id, &key_type) != 2) {
115 LOG_ERROR(HW_AES, "Invalid key name %s", name.c_str());
116 continue;
117 }
118
119 if (slot_id >= MaxKeySlotID) {
120 LOG_ERROR(HW_AES, "Out of range slot ID 0x%zX", slot_id);
121 continue;
122 }
123
124 switch (key_type) {
125 case 'X':
126 key_slots.at(slot_id).SetKeyX(key);
127 break;
128 case 'Y':
129 key_slots.at(slot_id).SetKeyY(key);
130 break;
131 case 'N':
132 key_slots.at(slot_id).SetNormalKey(key);
133 break;
134 default:
135 LOG_ERROR(HW_AES, "Invalid key type %c", key_type);
136 break;
137 }
138 }
139}
140
141} // namespace
142
143void InitKeys() {
144 ClearAllKeys();
145 LoadPresetKeys();
146}
147
148void SetGeneratorConstant(const AESKey& key) {
149 generator_constant = key;
150}
151
152void SetKeyX(size_t slot_id, const AESKey& key) {
153 key_slots.at(slot_id).SetKeyX(key);
154}
155
156void SetKeyY(size_t slot_id, const AESKey& key) {
157 key_slots.at(slot_id).SetKeyY(key);
158}
159
160void SetNormalKey(size_t slot_id, const AESKey& key) {
161 key_slots.at(slot_id).SetNormalKey(key);
162}
163
164bool IsNormalKeyAvailable(size_t slot_id) {
165 return key_slots.at(slot_id).normal.is_initialized();
166}
167
168AESKey GetNormalKey(size_t slot_id) {
169 return key_slots.at(slot_id).normal.value_or(AESKey{});
170}
171
172} // namespace AES
173} // namespace HW
diff --git a/src/core/hw/aes/key.h b/src/core/hw/aes/key.h
new file mode 100644
index 000000000..b01d04f13
--- /dev/null
+++ b/src/core/hw/aes/key.h
@@ -0,0 +1,35 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <array>
8#include <cstddef>
9#include "common/common_types.h"
10
11namespace HW {
12namespace AES {
13
14enum KeySlotID : size_t {
15 APTWrap = 0x31,
16
17 MaxKeySlotID = 0x40,
18};
19
20constexpr size_t AES_BLOCK_SIZE = 16;
21
22using AESKey = std::array<u8, AES_BLOCK_SIZE>;
23
24void InitKeys();
25
26void SetGeneratorConstant(const AESKey& key);
27void SetKeyX(size_t slot_id, const AESKey& key);
28void SetKeyY(size_t slot_id, const AESKey& key);
29void SetNormalKey(size_t slot_id, const AESKey& key);
30
31bool IsNormalKeyAvailable(size_t slot_id);
32AESKey GetNormalKey(size_t slot_id);
33
34} // namspace AES
35} // namespace HW
diff --git a/src/core/hw/hw.cpp b/src/core/hw/hw.cpp
index 9ff8825b2..8499f2ce6 100644
--- a/src/core/hw/hw.cpp
+++ b/src/core/hw/hw.cpp
@@ -4,6 +4,7 @@
4 4
5#include "common/common_types.h" 5#include "common/common_types.h"
6#include "common/logging/log.h" 6#include "common/logging/log.h"
7#include "core/hw/aes/key.h"
7#include "core/hw/gpu.h" 8#include "core/hw/gpu.h"
8#include "core/hw/hw.h" 9#include "core/hw/hw.h"
9#include "core/hw/lcd.h" 10#include "core/hw/lcd.h"
@@ -85,6 +86,7 @@ void Update() {}
85 86
86/// Initialize hardware 87/// Initialize hardware
87void Init() { 88void Init() {
89 AES::InitKeys();
88 GPU::Init(); 90 GPU::Init();
89 LCD::Init(); 91 LCD::Init();
90 LOG_DEBUG(HW, "initialized OK"); 92 LOG_DEBUG(HW, "initialized OK");