summaryrefslogtreecommitdiff
path: root/src/core/crypto
diff options
context:
space:
mode:
authorGravatar Mat M2018-08-24 23:47:46 -0400
committerGravatar GitHub2018-08-24 23:47:46 -0400
commit6426b0f5514d6a7c5cc369368947eceb380bfc85 (patch)
treeb7acdc39a4344570a6f2c098c30ad20114bf84db /src/core/crypto
parentMerge pull request #1065 from DarkLordZach/window-title (diff)
parentfile_sys/crypto: Fix missing/unnecessary includes (diff)
downloadyuzu-6426b0f5514d6a7c5cc369368947eceb380bfc85.tar.gz
yuzu-6426b0f5514d6a7c5cc369368947eceb380bfc85.tar.xz
yuzu-6426b0f5514d6a7c5cc369368947eceb380bfc85.zip
Merge pull request #1094 from DarkLordZach/nax0
file_sys: Add support for NAX archives
Diffstat (limited to 'src/core/crypto')
-rw-r--r--src/core/crypto/aes_util.cpp7
-rw-r--r--src/core/crypto/ctr_encryption_layer.cpp8
-rw-r--r--src/core/crypto/key_manager.cpp172
-rw-r--r--src/core/crypto/key_manager.h68
-rw-r--r--src/core/crypto/xts_encryption_layer.cpp58
-rw-r--r--src/core/crypto/xts_encryption_layer.h25
6 files changed, 288 insertions, 50 deletions
diff --git a/src/core/crypto/aes_util.cpp b/src/core/crypto/aes_util.cpp
index a9876c83e..72e4bed67 100644
--- a/src/core/crypto/aes_util.cpp
+++ b/src/core/crypto/aes_util.cpp
@@ -99,10 +99,7 @@ void AESCipher<Key, KeySize>::Transcode(const u8* src, size_t size, u8* dest, Op
99template <typename Key, size_t KeySize> 99template <typename Key, size_t KeySize>
100void AESCipher<Key, KeySize>::XTSTranscode(const u8* src, size_t size, u8* dest, size_t sector_id, 100void AESCipher<Key, KeySize>::XTSTranscode(const u8* src, size_t size, u8* dest, size_t sector_id,
101 size_t sector_size, Op op) { 101 size_t sector_size, Op op) {
102 if (size % sector_size > 0) { 102 ASSERT_MSG(size % sector_size == 0, "XTS decryption size must be a multiple of sector size.");
103 LOG_CRITICAL(Crypto, "Data size must be a multiple of sector size.");
104 return;
105 }
106 103
107 for (size_t i = 0; i < size; i += sector_size) { 104 for (size_t i = 0; i < size; i += sector_size) {
108 SetIV(CalculateNintendoTweak(sector_id++)); 105 SetIV(CalculateNintendoTweak(sector_id++));
@@ -112,4 +109,4 @@ void AESCipher<Key, KeySize>::XTSTranscode(const u8* src, size_t size, u8* dest,
112 109
113template class AESCipher<Key128>; 110template class AESCipher<Key128>;
114template class AESCipher<Key256>; 111template class AESCipher<Key256>;
115} // namespace Core::Crypto \ No newline at end of file 112} // namespace Core::Crypto
diff --git a/src/core/crypto/ctr_encryption_layer.cpp b/src/core/crypto/ctr_encryption_layer.cpp
index 106db02b3..3ea60dbd0 100644
--- a/src/core/crypto/ctr_encryption_layer.cpp
+++ b/src/core/crypto/ctr_encryption_layer.cpp
@@ -20,10 +20,8 @@ size_t CTREncryptionLayer::Read(u8* data, size_t length, size_t offset) const {
20 if (sector_offset == 0) { 20 if (sector_offset == 0) {
21 UpdateIV(base_offset + offset); 21 UpdateIV(base_offset + offset);
22 std::vector<u8> raw = base->ReadBytes(length, offset); 22 std::vector<u8> raw = base->ReadBytes(length, offset);
23 if (raw.size() != length) 23 cipher.Transcode(raw.data(), raw.size(), data, Op::Decrypt);
24 return Read(data, raw.size(), offset); 24 return raw.size();
25 cipher.Transcode(raw.data(), length, data, Op::Decrypt);
26 return length;
27 } 25 }
28 26
29 // offset does not fall on block boundary (0x10) 27 // offset does not fall on block boundary (0x10)
@@ -34,7 +32,7 @@ size_t CTREncryptionLayer::Read(u8* data, size_t length, size_t offset) const {
34 32
35 if (length + sector_offset < 0x10) { 33 if (length + sector_offset < 0x10) {
36 std::memcpy(data, block.data() + sector_offset, std::min<u64>(length, read)); 34 std::memcpy(data, block.data() + sector_offset, std::min<u64>(length, read));
37 return read; 35 return std::min<u64>(length, read);
38 } 36 }
39 std::memcpy(data, block.data() + sector_offset, read); 37 std::memcpy(data, block.data() + sector_offset, read);
40 return read + Read(data + read, length - read, offset + read); 38 return read + Read(data + read, length - read, offset + read);
diff --git a/src/core/crypto/key_manager.cpp b/src/core/crypto/key_manager.cpp
index db8b22c85..0b6c07de8 100644
--- a/src/core/crypto/key_manager.cpp
+++ b/src/core/crypto/key_manager.cpp
@@ -12,11 +12,112 @@
12#include "common/file_util.h" 12#include "common/file_util.h"
13#include "common/hex_util.h" 13#include "common/hex_util.h"
14#include "common/logging/log.h" 14#include "common/logging/log.h"
15#include "core/crypto/aes_util.h"
15#include "core/crypto/key_manager.h" 16#include "core/crypto/key_manager.h"
16#include "core/settings.h" 17#include "core/settings.h"
17 18
18namespace Core::Crypto { 19namespace Core::Crypto {
19 20
21Key128 GenerateKeyEncryptionKey(Key128 source, Key128 master, Key128 kek_seed, Key128 key_seed) {
22 Key128 out{};
23
24 AESCipher<Key128> cipher1(master, Mode::ECB);
25 cipher1.Transcode(kek_seed.data(), kek_seed.size(), out.data(), Op::Decrypt);
26 AESCipher<Key128> cipher2(out, Mode::ECB);
27 cipher2.Transcode(source.data(), source.size(), out.data(), Op::Decrypt);
28
29 if (key_seed != Key128{}) {
30 AESCipher<Key128> cipher3(out, Mode::ECB);
31 cipher3.Transcode(key_seed.data(), key_seed.size(), out.data(), Op::Decrypt);
32 }
33
34 return out;
35}
36
37boost::optional<Key128> DeriveSDSeed() {
38 const FileUtil::IOFile save_43(FileUtil::GetUserPath(FileUtil::UserPath::NANDDir) +
39 "/system/save/8000000000000043",
40 "rb+");
41 if (!save_43.IsOpen())
42 return boost::none;
43 const FileUtil::IOFile sd_private(
44 FileUtil::GetUserPath(FileUtil::UserPath::SDMCDir) + "/Nintendo/Contents/private", "rb+");
45 if (!sd_private.IsOpen())
46 return boost::none;
47
48 sd_private.Seek(0, SEEK_SET);
49 std::array<u8, 0x10> private_seed{};
50 if (sd_private.ReadBytes(private_seed.data(), private_seed.size()) != 0x10)
51 return boost::none;
52
53 std::array<u8, 0x10> buffer{};
54 size_t offset = 0;
55 for (; offset + 0x10 < save_43.GetSize(); ++offset) {
56 save_43.Seek(offset, SEEK_SET);
57 save_43.ReadBytes(buffer.data(), buffer.size());
58 if (buffer == private_seed)
59 break;
60 }
61
62 if (offset + 0x10 >= save_43.GetSize())
63 return boost::none;
64
65 Key128 seed{};
66 save_43.Seek(offset + 0x10, SEEK_SET);
67 save_43.ReadBytes(seed.data(), seed.size());
68 return seed;
69}
70
71Loader::ResultStatus DeriveSDKeys(std::array<Key256, 2>& sd_keys, const KeyManager& keys) {
72 if (!keys.HasKey(S128KeyType::Source, static_cast<u64>(SourceKeyType::SDKEK)))
73 return Loader::ResultStatus::ErrorMissingSDKEKSource;
74 if (!keys.HasKey(S128KeyType::Source, static_cast<u64>(SourceKeyType::AESKEKGeneration)))
75 return Loader::ResultStatus::ErrorMissingAESKEKGenerationSource;
76 if (!keys.HasKey(S128KeyType::Source, static_cast<u64>(SourceKeyType::AESKeyGeneration)))
77 return Loader::ResultStatus::ErrorMissingAESKeyGenerationSource;
78
79 const auto sd_kek_source =
80 keys.GetKey(S128KeyType::Source, static_cast<u64>(SourceKeyType::SDKEK));
81 const auto aes_kek_gen =
82 keys.GetKey(S128KeyType::Source, static_cast<u64>(SourceKeyType::AESKEKGeneration));
83 const auto aes_key_gen =
84 keys.GetKey(S128KeyType::Source, static_cast<u64>(SourceKeyType::AESKeyGeneration));
85 const auto master_00 = keys.GetKey(S128KeyType::Master);
86 const auto sd_kek =
87 GenerateKeyEncryptionKey(sd_kek_source, master_00, aes_kek_gen, aes_key_gen);
88
89 if (!keys.HasKey(S128KeyType::SDSeed))
90 return Loader::ResultStatus::ErrorMissingSDSeed;
91 const auto sd_seed = keys.GetKey(S128KeyType::SDSeed);
92
93 if (!keys.HasKey(S256KeyType::SDKeySource, static_cast<u64>(SDKeyType::Save)))
94 return Loader::ResultStatus::ErrorMissingSDSaveKeySource;
95 if (!keys.HasKey(S256KeyType::SDKeySource, static_cast<u64>(SDKeyType::NCA)))
96 return Loader::ResultStatus::ErrorMissingSDNCAKeySource;
97
98 std::array<Key256, 2> sd_key_sources{
99 keys.GetKey(S256KeyType::SDKeySource, static_cast<u64>(SDKeyType::Save)),
100 keys.GetKey(S256KeyType::SDKeySource, static_cast<u64>(SDKeyType::NCA)),
101 };
102
103 // Combine sources and seed
104 for (auto& source : sd_key_sources) {
105 for (size_t i = 0; i < source.size(); ++i)
106 source[i] ^= sd_seed[i & 0xF];
107 }
108
109 AESCipher<Key128> cipher(sd_kek, Mode::ECB);
110 // The transform manipulates sd_keys as part of the Transcode, so the return/output is
111 // unnecessary. This does not alter sd_keys_sources.
112 std::transform(sd_key_sources.begin(), sd_key_sources.end(), sd_keys.begin(),
113 sd_key_sources.begin(), [&cipher](const Key256& source, Key256& out) {
114 cipher.Transcode(source.data(), source.size(), out.data(), Op::Decrypt);
115 return source; ///< Return unaltered source to satisfy output requirement.
116 });
117
118 return Loader::ResultStatus::Success;
119}
120
20KeyManager::KeyManager() { 121KeyManager::KeyManager() {
21 // Initialize keys 122 // Initialize keys
22 const std::string hactool_keys_dir = FileUtil::GetHactoolConfigurationPath(); 123 const std::string hactool_keys_dir = FileUtil::GetHactoolConfigurationPath();
@@ -24,12 +125,15 @@ KeyManager::KeyManager() {
24 if (Settings::values.use_dev_keys) { 125 if (Settings::values.use_dev_keys) {
25 dev_mode = true; 126 dev_mode = true;
26 AttemptLoadKeyFile(yuzu_keys_dir, hactool_keys_dir, "dev.keys", false); 127 AttemptLoadKeyFile(yuzu_keys_dir, hactool_keys_dir, "dev.keys", false);
128 AttemptLoadKeyFile(yuzu_keys_dir, yuzu_keys_dir, "dev.keys_autogenerated", false);
27 } else { 129 } else {
28 dev_mode = false; 130 dev_mode = false;
29 AttemptLoadKeyFile(yuzu_keys_dir, hactool_keys_dir, "prod.keys", false); 131 AttemptLoadKeyFile(yuzu_keys_dir, hactool_keys_dir, "prod.keys", false);
132 AttemptLoadKeyFile(yuzu_keys_dir, yuzu_keys_dir, "prod.keys_autogenerated", false);
30 } 133 }
31 134
32 AttemptLoadKeyFile(yuzu_keys_dir, hactool_keys_dir, "title.keys", true); 135 AttemptLoadKeyFile(yuzu_keys_dir, hactool_keys_dir, "title.keys", true);
136 AttemptLoadKeyFile(yuzu_keys_dir, yuzu_keys_dir, "title.keys_autogenerated", true);
33} 137}
34 138
35void KeyManager::LoadFromFile(const std::string& filename, bool is_title_keys) { 139void KeyManager::LoadFromFile(const std::string& filename, bool is_title_keys) {
@@ -56,17 +160,17 @@ void KeyManager::LoadFromFile(const std::string& filename, bool is_title_keys) {
56 u128 rights_id{}; 160 u128 rights_id{};
57 std::memcpy(rights_id.data(), rights_id_raw.data(), rights_id_raw.size()); 161 std::memcpy(rights_id.data(), rights_id_raw.data(), rights_id_raw.size());
58 Key128 key = Common::HexStringToArray<16>(out[1]); 162 Key128 key = Common::HexStringToArray<16>(out[1]);
59 SetKey(S128KeyType::Titlekey, key, rights_id[1], rights_id[0]); 163 s128_keys[{S128KeyType::Titlekey, rights_id[1], rights_id[0]}] = key;
60 } else { 164 } else {
61 std::transform(out[0].begin(), out[0].end(), out[0].begin(), ::tolower); 165 std::transform(out[0].begin(), out[0].end(), out[0].begin(), ::tolower);
62 if (s128_file_id.find(out[0]) != s128_file_id.end()) { 166 if (s128_file_id.find(out[0]) != s128_file_id.end()) {
63 const auto index = s128_file_id.at(out[0]); 167 const auto index = s128_file_id.at(out[0]);
64 Key128 key = Common::HexStringToArray<16>(out[1]); 168 Key128 key = Common::HexStringToArray<16>(out[1]);
65 SetKey(index.type, key, index.field1, index.field2); 169 s128_keys[{index.type, index.field1, index.field2}] = key;
66 } else if (s256_file_id.find(out[0]) != s256_file_id.end()) { 170 } else if (s256_file_id.find(out[0]) != s256_file_id.end()) {
67 const auto index = s256_file_id.at(out[0]); 171 const auto index = s256_file_id.at(out[0]);
68 Key256 key = Common::HexStringToArray<32>(out[1]); 172 Key256 key = Common::HexStringToArray<32>(out[1]);
69 SetKey(index.type, key, index.field1, index.field2); 173 s256_keys[{index.type, index.field1, index.field2}] = key;
70 } 174 }
71 } 175 }
72 } 176 }
@@ -100,11 +204,50 @@ Key256 KeyManager::GetKey(S256KeyType id, u64 field1, u64 field2) const {
100 return s256_keys.at({id, field1, field2}); 204 return s256_keys.at({id, field1, field2});
101} 205}
102 206
207template <size_t Size>
208void KeyManager::WriteKeyToFile(bool title_key, std::string_view keyname,
209 const std::array<u8, Size>& key) {
210 const std::string yuzu_keys_dir = FileUtil::GetUserPath(FileUtil::UserPath::KeysDir);
211 std::string filename = "title.keys_autogenerated";
212 if (!title_key)
213 filename = dev_mode ? "dev.keys_autogenerated" : "prod.keys_autogenerated";
214 const auto add_info_text = !FileUtil::Exists(yuzu_keys_dir + DIR_SEP + filename);
215 FileUtil::CreateFullPath(yuzu_keys_dir + DIR_SEP + filename);
216 std::ofstream file(yuzu_keys_dir + DIR_SEP + filename, std::ios::app);
217 if (!file.is_open())
218 return;
219 if (add_info_text) {
220 file
221 << "# This file is autogenerated by Yuzu\n"
222 << "# It serves to store keys that were automatically generated from the normal keys\n"
223 << "# If you are experiencing issues involving keys, it may help to delete this file\n";
224 }
225
226 file << fmt::format("\n{} = {}", keyname, Common::HexArrayToString(key));
227 AttemptLoadKeyFile(yuzu_keys_dir, yuzu_keys_dir, filename, title_key);
228}
229
103void KeyManager::SetKey(S128KeyType id, Key128 key, u64 field1, u64 field2) { 230void KeyManager::SetKey(S128KeyType id, Key128 key, u64 field1, u64 field2) {
231 const auto iter = std::find_if(
232 s128_file_id.begin(), s128_file_id.end(),
233 [&id, &field1, &field2](const std::pair<std::string, KeyIndex<S128KeyType>> elem) {
234 return std::tie(elem.second.type, elem.second.field1, elem.second.field2) ==
235 std::tie(id, field1, field2);
236 });
237 if (iter != s128_file_id.end())
238 WriteKeyToFile(id == S128KeyType::Titlekey, iter->first, key);
104 s128_keys[{id, field1, field2}] = key; 239 s128_keys[{id, field1, field2}] = key;
105} 240}
106 241
107void KeyManager::SetKey(S256KeyType id, Key256 key, u64 field1, u64 field2) { 242void KeyManager::SetKey(S256KeyType id, Key256 key, u64 field1, u64 field2) {
243 const auto iter = std::find_if(
244 s256_file_id.begin(), s256_file_id.end(),
245 [&id, &field1, &field2](const std::pair<std::string, KeyIndex<S256KeyType>> elem) {
246 return std::tie(elem.second.type, elem.second.field1, elem.second.field2) ==
247 std::tie(id, field1, field2);
248 });
249 if (iter != s256_file_id.end())
250 WriteKeyToFile(false, iter->first, key);
108 s256_keys[{id, field1, field2}] = key; 251 s256_keys[{id, field1, field2}] = key;
109} 252}
110 253
@@ -125,7 +268,16 @@ bool KeyManager::KeyFileExists(bool title) {
125 FileUtil::Exists(yuzu_keys_dir + DIR_SEP + "prod.keys"); 268 FileUtil::Exists(yuzu_keys_dir + DIR_SEP + "prod.keys");
126} 269}
127 270
128const std::unordered_map<std::string, KeyIndex<S128KeyType>> KeyManager::s128_file_id = { 271void KeyManager::DeriveSDSeedLazy() {
272 if (HasKey(S128KeyType::SDSeed))
273 return;
274
275 const auto res = DeriveSDSeed();
276 if (res != boost::none)
277 SetKey(S128KeyType::SDSeed, res.get());
278}
279
280const boost::container::flat_map<std::string, KeyIndex<S128KeyType>> KeyManager::s128_file_id = {
129 {"master_key_00", {S128KeyType::Master, 0, 0}}, 281 {"master_key_00", {S128KeyType::Master, 0, 0}},
130 {"master_key_01", {S128KeyType::Master, 1, 0}}, 282 {"master_key_01", {S128KeyType::Master, 1, 0}},
131 {"master_key_02", {S128KeyType::Master, 2, 0}}, 283 {"master_key_02", {S128KeyType::Master, 2, 0}},
@@ -167,11 +319,17 @@ const std::unordered_map<std::string, KeyIndex<S128KeyType>> KeyManager::s128_fi
167 {"key_area_key_system_02", {S128KeyType::KeyArea, 2, static_cast<u64>(KeyAreaKeyType::System)}}, 319 {"key_area_key_system_02", {S128KeyType::KeyArea, 2, static_cast<u64>(KeyAreaKeyType::System)}},
168 {"key_area_key_system_03", {S128KeyType::KeyArea, 3, static_cast<u64>(KeyAreaKeyType::System)}}, 320 {"key_area_key_system_03", {S128KeyType::KeyArea, 3, static_cast<u64>(KeyAreaKeyType::System)}},
169 {"key_area_key_system_04", {S128KeyType::KeyArea, 4, static_cast<u64>(KeyAreaKeyType::System)}}, 321 {"key_area_key_system_04", {S128KeyType::KeyArea, 4, static_cast<u64>(KeyAreaKeyType::System)}},
322 {"sd_card_kek_source", {S128KeyType::Source, static_cast<u64>(SourceKeyType::SDKEK), 0}},
323 {"aes_kek_generation_source",
324 {S128KeyType::Source, static_cast<u64>(SourceKeyType::AESKEKGeneration), 0}},
325 {"aes_key_generation_source",
326 {S128KeyType::Source, static_cast<u64>(SourceKeyType::AESKeyGeneration), 0}},
327 {"sd_seed", {S128KeyType::SDSeed, 0, 0}},
170}; 328};
171 329
172const std::unordered_map<std::string, KeyIndex<S256KeyType>> KeyManager::s256_file_id = { 330const boost::container::flat_map<std::string, KeyIndex<S256KeyType>> KeyManager::s256_file_id = {
173 {"header_key", {S256KeyType::Header, 0, 0}}, 331 {"header_key", {S256KeyType::Header, 0, 0}},
174 {"sd_card_save_key", {S256KeyType::SDSave, 0, 0}}, 332 {"sd_card_save_key_source", {S256KeyType::SDKeySource, static_cast<u64>(SDKeyType::Save), 0}},
175 {"sd_card_nca_key", {S256KeyType::SDNCA, 0, 0}}, 333 {"sd_card_nca_key_source", {S256KeyType::SDKeySource, static_cast<u64>(SDKeyType::NCA), 0}},
176}; 334};
177} // namespace Core::Crypto 335} // namespace Core::Crypto
diff --git a/src/core/crypto/key_manager.h b/src/core/crypto/key_manager.h
index 0c62d4421..7ca3e6cbc 100644
--- a/src/core/crypto/key_manager.h
+++ b/src/core/crypto/key_manager.h
@@ -6,11 +6,13 @@
6 6
7#include <array> 7#include <array>
8#include <string> 8#include <string>
9#include <string_view>
9#include <type_traits> 10#include <type_traits>
10#include <unordered_map>
11#include <vector> 11#include <vector>
12#include <boost/container/flat_map.hpp>
12#include <fmt/format.h> 13#include <fmt/format.h>
13#include "common/common_types.h" 14#include "common/common_types.h"
15#include "core/loader/loader.h"
14 16
15namespace Core::Crypto { 17namespace Core::Crypto {
16 18
@@ -22,9 +24,8 @@ static_assert(sizeof(Key128) == 16, "Key128 must be 128 bytes big.");
22static_assert(sizeof(Key256) == 32, "Key128 must be 128 bytes big."); 24static_assert(sizeof(Key256) == 32, "Key128 must be 128 bytes big.");
23 25
24enum class S256KeyType : u64 { 26enum class S256KeyType : u64 {
25 Header, // 27 Header, //
26 SDSave, // 28 SDKeySource, // f1=SDKeyType
27 SDNCA, //
28}; 29};
29 30
30enum class S128KeyType : u64 { 31enum class S128KeyType : u64 {
@@ -36,6 +37,7 @@ enum class S128KeyType : u64 {
36 KeyArea, // f1=crypto revision f2=type {app, ocean, system} 37 KeyArea, // f1=crypto revision f2=type {app, ocean, system}
37 SDSeed, // 38 SDSeed, //
38 Titlekey, // f1=rights id LSB f2=rights id MSB 39 Titlekey, // f1=rights id LSB f2=rights id MSB
40 Source, // f1=source type, f2= sub id
39}; 41};
40 42
41enum class KeyAreaKeyType : u8 { 43enum class KeyAreaKeyType : u8 {
@@ -44,6 +46,17 @@ enum class KeyAreaKeyType : u8 {
44 System, 46 System,
45}; 47};
46 48
49enum class SourceKeyType : u8 {
50 SDKEK,
51 AESKEKGeneration,
52 AESKeyGeneration,
53};
54
55enum class SDKeyType : u8 {
56 Save,
57 NCA,
58};
59
47template <typename KeyType> 60template <typename KeyType>
48struct KeyIndex { 61struct KeyIndex {
49 KeyType type; 62 KeyType type;
@@ -59,34 +72,12 @@ struct KeyIndex {
59 } 72 }
60}; 73};
61 74
62// The following two (== and hash) are so KeyIndex can be a key in unordered_map 75// boost flat_map requires operator< for O(log(n)) lookups.
63
64template <typename KeyType> 76template <typename KeyType>
65bool operator==(const KeyIndex<KeyType>& lhs, const KeyIndex<KeyType>& rhs) { 77bool operator<(const KeyIndex<KeyType>& lhs, const KeyIndex<KeyType>& rhs) {
66 return std::tie(lhs.type, lhs.field1, lhs.field2) == std::tie(rhs.type, rhs.field1, rhs.field2); 78 return std::tie(lhs.type, lhs.field1, lhs.field2) < std::tie(rhs.type, rhs.field1, rhs.field2);
67} 79}
68 80
69template <typename KeyType>
70bool operator!=(const KeyIndex<KeyType>& lhs, const KeyIndex<KeyType>& rhs) {
71 return !operator==(lhs, rhs);
72}
73
74} // namespace Core::Crypto
75
76namespace std {
77template <typename KeyType>
78struct hash<Core::Crypto::KeyIndex<KeyType>> {
79 size_t operator()(const Core::Crypto::KeyIndex<KeyType>& k) const {
80 using std::hash;
81
82 return ((hash<u64>()(static_cast<u64>(k.type)) ^ (hash<u64>()(k.field1) << 1)) >> 1) ^
83 (hash<u64>()(k.field2) << 1);
84 }
85};
86} // namespace std
87
88namespace Core::Crypto {
89
90class KeyManager { 81class KeyManager {
91public: 82public:
92 KeyManager(); 83 KeyManager();
@@ -102,16 +93,27 @@ public:
102 93
103 static bool KeyFileExists(bool title); 94 static bool KeyFileExists(bool title);
104 95
96 // Call before using the sd seed to attempt to derive it if it dosen't exist. Needs system save
97 // 8*43 and the private file to exist.
98 void DeriveSDSeedLazy();
99
105private: 100private:
106 std::unordered_map<KeyIndex<S128KeyType>, Key128> s128_keys; 101 boost::container::flat_map<KeyIndex<S128KeyType>, Key128> s128_keys;
107 std::unordered_map<KeyIndex<S256KeyType>, Key256> s256_keys; 102 boost::container::flat_map<KeyIndex<S256KeyType>, Key256> s256_keys;
108 103
109 bool dev_mode; 104 bool dev_mode;
110 void LoadFromFile(const std::string& filename, bool is_title_keys); 105 void LoadFromFile(const std::string& filename, bool is_title_keys);
111 void AttemptLoadKeyFile(const std::string& dir1, const std::string& dir2, 106 void AttemptLoadKeyFile(const std::string& dir1, const std::string& dir2,
112 const std::string& filename, bool title); 107 const std::string& filename, bool title);
108 template <size_t Size>
109 void WriteKeyToFile(bool title_key, std::string_view keyname, const std::array<u8, Size>& key);
113 110
114 static const std::unordered_map<std::string, KeyIndex<S128KeyType>> s128_file_id; 111 static const boost::container::flat_map<std::string, KeyIndex<S128KeyType>> s128_file_id;
115 static const std::unordered_map<std::string, KeyIndex<S256KeyType>> s256_file_id; 112 static const boost::container::flat_map<std::string, KeyIndex<S256KeyType>> s256_file_id;
116}; 113};
114
115Key128 GenerateKeyEncryptionKey(Key128 source, Key128 master, Key128 kek_seed, Key128 key_seed);
116boost::optional<Key128> DeriveSDSeed();
117Loader::ResultStatus DeriveSDKeys(std::array<Key256, 2>& sd_keys, const KeyManager& keys);
118
117} // namespace Core::Crypto 119} // namespace Core::Crypto
diff --git a/src/core/crypto/xts_encryption_layer.cpp b/src/core/crypto/xts_encryption_layer.cpp
new file mode 100644
index 000000000..c10832cfe
--- /dev/null
+++ b/src/core/crypto/xts_encryption_layer.cpp
@@ -0,0 +1,58 @@
1// Copyright 2018 yuzu emulator team
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include <algorithm>
6#include <cstring>
7#include "common/assert.h"
8#include "core/crypto/xts_encryption_layer.h"
9
10namespace Core::Crypto {
11
12constexpr u64 XTS_SECTOR_SIZE = 0x4000;
13
14XTSEncryptionLayer::XTSEncryptionLayer(FileSys::VirtualFile base_, Key256 key_)
15 : EncryptionLayer(std::move(base_)), cipher(key_, Mode::XTS) {}
16
17size_t XTSEncryptionLayer::Read(u8* data, size_t length, size_t offset) const {
18 if (length == 0)
19 return 0;
20
21 const auto sector_offset = offset & 0x3FFF;
22 if (sector_offset == 0) {
23 if (length % XTS_SECTOR_SIZE == 0) {
24 std::vector<u8> raw = base->ReadBytes(length, offset);
25 cipher.XTSTranscode(raw.data(), raw.size(), data, offset / XTS_SECTOR_SIZE,
26 XTS_SECTOR_SIZE, Op::Decrypt);
27 return raw.size();
28 }
29 if (length > XTS_SECTOR_SIZE) {
30 const auto rem = length % XTS_SECTOR_SIZE;
31 const auto read = length - rem;
32 return Read(data, read, offset) + Read(data + read, rem, offset + read);
33 }
34 std::vector<u8> buffer = base->ReadBytes(XTS_SECTOR_SIZE, offset);
35 if (buffer.size() < XTS_SECTOR_SIZE)
36 buffer.resize(XTS_SECTOR_SIZE);
37 cipher.XTSTranscode(buffer.data(), buffer.size(), buffer.data(), offset / XTS_SECTOR_SIZE,
38 XTS_SECTOR_SIZE, Op::Decrypt);
39 std::memcpy(data, buffer.data(), std::min(buffer.size(), length));
40 return std::min(buffer.size(), length);
41 }
42
43 // offset does not fall on block boundary (0x4000)
44 std::vector<u8> block = base->ReadBytes(0x4000, offset - sector_offset);
45 if (block.size() < XTS_SECTOR_SIZE)
46 block.resize(XTS_SECTOR_SIZE);
47 cipher.XTSTranscode(block.data(), block.size(), block.data(),
48 (offset - sector_offset) / XTS_SECTOR_SIZE, XTS_SECTOR_SIZE, Op::Decrypt);
49 const size_t read = XTS_SECTOR_SIZE - sector_offset;
50
51 if (length + sector_offset < XTS_SECTOR_SIZE) {
52 std::memcpy(data, block.data() + sector_offset, std::min<u64>(length, read));
53 return std::min<u64>(length, read);
54 }
55 std::memcpy(data, block.data() + sector_offset, read);
56 return read + Read(data + read, length - read, offset + read);
57}
58} // namespace Core::Crypto
diff --git a/src/core/crypto/xts_encryption_layer.h b/src/core/crypto/xts_encryption_layer.h
new file mode 100644
index 000000000..7a1f1dc64
--- /dev/null
+++ b/src/core/crypto/xts_encryption_layer.h
@@ -0,0 +1,25 @@
1// Copyright 2018 yuzu emulator team
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include "core/crypto/aes_util.h"
8#include "core/crypto/encryption_layer.h"
9#include "core/crypto/key_manager.h"
10
11namespace Core::Crypto {
12
13// Sits on top of a VirtualFile and provides XTS-mode AES decription.
14class XTSEncryptionLayer : public EncryptionLayer {
15public:
16 XTSEncryptionLayer(FileSys::VirtualFile base, Key256 key);
17
18 size_t Read(u8* data, size_t length, size_t offset) const override;
19
20private:
21 // Must be mutable as operations modify cipher contexts.
22 mutable AESCipher<Key256> cipher;
23};
24
25} // namespace Core::Crypto