key_manager.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. // Copyright 2018 yuzu emulator team
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <array>
  6. #include <fstream>
  7. #include <locale>
  8. #include <sstream>
  9. #include <string_view>
  10. #include <tuple>
  11. #include <vector>
  12. #include "common/common_paths.h"
  13. #include "common/file_util.h"
  14. #include "common/hex_util.h"
  15. #include "common/logging/log.h"
  16. #include "core/crypto/aes_util.h"
  17. #include "core/crypto/key_manager.h"
  18. #include "core/loader/loader.h"
  19. #include "core/settings.h"
  20. namespace Core::Crypto {
  21. Key128 GenerateKeyEncryptionKey(Key128 source, Key128 master, Key128 kek_seed, Key128 key_seed) {
  22. Key128 out{};
  23. AESCipher<Key128> cipher1(master, Mode::ECB);
  24. cipher1.Transcode(kek_seed.data(), kek_seed.size(), out.data(), Op::Decrypt);
  25. AESCipher<Key128> cipher2(out, Mode::ECB);
  26. cipher2.Transcode(source.data(), source.size(), out.data(), Op::Decrypt);
  27. if (key_seed != Key128{}) {
  28. AESCipher<Key128> cipher3(out, Mode::ECB);
  29. cipher3.Transcode(key_seed.data(), key_seed.size(), out.data(), Op::Decrypt);
  30. }
  31. return out;
  32. }
  33. boost::optional<Key128> DeriveSDSeed() {
  34. const FileUtil::IOFile save_43(FileUtil::GetUserPath(FileUtil::UserPath::NANDDir) +
  35. "/system/save/8000000000000043",
  36. "rb+");
  37. if (!save_43.IsOpen())
  38. return boost::none;
  39. const FileUtil::IOFile sd_private(
  40. FileUtil::GetUserPath(FileUtil::UserPath::SDMCDir) + "/Nintendo/Contents/private", "rb+");
  41. if (!sd_private.IsOpen())
  42. return boost::none;
  43. sd_private.Seek(0, SEEK_SET);
  44. std::array<u8, 0x10> private_seed{};
  45. if (sd_private.ReadBytes(private_seed.data(), private_seed.size()) != 0x10)
  46. return boost::none;
  47. std::array<u8, 0x10> buffer{};
  48. std::size_t offset = 0;
  49. for (; offset + 0x10 < save_43.GetSize(); ++offset) {
  50. save_43.Seek(offset, SEEK_SET);
  51. save_43.ReadBytes(buffer.data(), buffer.size());
  52. if (buffer == private_seed)
  53. break;
  54. }
  55. if (offset + 0x10 >= save_43.GetSize())
  56. return boost::none;
  57. Key128 seed{};
  58. save_43.Seek(offset + 0x10, SEEK_SET);
  59. save_43.ReadBytes(seed.data(), seed.size());
  60. return seed;
  61. }
  62. Loader::ResultStatus DeriveSDKeys(std::array<Key256, 2>& sd_keys, KeyManager& keys) {
  63. if (!keys.HasKey(S128KeyType::Source, static_cast<u64>(SourceKeyType::SDKek)))
  64. return Loader::ResultStatus::ErrorMissingSDKEKSource;
  65. if (!keys.HasKey(S128KeyType::Source, static_cast<u64>(SourceKeyType::AESKekGeneration)))
  66. return Loader::ResultStatus::ErrorMissingAESKEKGenerationSource;
  67. if (!keys.HasKey(S128KeyType::Source, static_cast<u64>(SourceKeyType::AESKeyGeneration)))
  68. return Loader::ResultStatus::ErrorMissingAESKeyGenerationSource;
  69. const auto sd_kek_source =
  70. keys.GetKey(S128KeyType::Source, static_cast<u64>(SourceKeyType::SDKek));
  71. const auto aes_kek_gen =
  72. keys.GetKey(S128KeyType::Source, static_cast<u64>(SourceKeyType::AESKekGeneration));
  73. const auto aes_key_gen =
  74. keys.GetKey(S128KeyType::Source, static_cast<u64>(SourceKeyType::AESKeyGeneration));
  75. const auto master_00 = keys.GetKey(S128KeyType::Master);
  76. const auto sd_kek =
  77. GenerateKeyEncryptionKey(sd_kek_source, master_00, aes_kek_gen, aes_key_gen);
  78. keys.SetKey(S128KeyType::SDKek, sd_kek);
  79. if (!keys.HasKey(S128KeyType::SDSeed))
  80. return Loader::ResultStatus::ErrorMissingSDSeed;
  81. const auto sd_seed = keys.GetKey(S128KeyType::SDSeed);
  82. if (!keys.HasKey(S256KeyType::SDKeySource, static_cast<u64>(SDKeyType::Save)))
  83. return Loader::ResultStatus::ErrorMissingSDSaveKeySource;
  84. if (!keys.HasKey(S256KeyType::SDKeySource, static_cast<u64>(SDKeyType::NCA)))
  85. return Loader::ResultStatus::ErrorMissingSDNCAKeySource;
  86. std::array<Key256, 2> sd_key_sources{
  87. keys.GetKey(S256KeyType::SDKeySource, static_cast<u64>(SDKeyType::Save)),
  88. keys.GetKey(S256KeyType::SDKeySource, static_cast<u64>(SDKeyType::NCA)),
  89. };
  90. // Combine sources and seed
  91. for (auto& source : sd_key_sources) {
  92. for (std::size_t i = 0; i < source.size(); ++i)
  93. source[i] ^= sd_seed[i & 0xF];
  94. }
  95. AESCipher<Key128> cipher(sd_kek, Mode::ECB);
  96. // The transform manipulates sd_keys as part of the Transcode, so the return/output is
  97. // unnecessary. This does not alter sd_keys_sources.
  98. std::transform(sd_key_sources.begin(), sd_key_sources.end(), sd_keys.begin(),
  99. sd_key_sources.begin(), [&cipher](const Key256& source, Key256& out) {
  100. cipher.Transcode(source.data(), source.size(), out.data(), Op::Decrypt);
  101. return source; ///< Return unaltered source to satisfy output requirement.
  102. });
  103. return Loader::ResultStatus::Success;
  104. }
  105. KeyManager::KeyManager() {
  106. // Initialize keys
  107. const std::string hactool_keys_dir = FileUtil::GetHactoolConfigurationPath();
  108. const std::string yuzu_keys_dir = FileUtil::GetUserPath(FileUtil::UserPath::KeysDir);
  109. if (Settings::values.use_dev_keys) {
  110. dev_mode = true;
  111. AttemptLoadKeyFile(yuzu_keys_dir, hactool_keys_dir, "dev.keys", false);
  112. AttemptLoadKeyFile(yuzu_keys_dir, yuzu_keys_dir, "dev.keys_autogenerated", false);
  113. } else {
  114. dev_mode = false;
  115. AttemptLoadKeyFile(yuzu_keys_dir, hactool_keys_dir, "prod.keys", false);
  116. AttemptLoadKeyFile(yuzu_keys_dir, yuzu_keys_dir, "prod.keys_autogenerated", false);
  117. }
  118. AttemptLoadKeyFile(yuzu_keys_dir, hactool_keys_dir, "title.keys", true);
  119. AttemptLoadKeyFile(yuzu_keys_dir, yuzu_keys_dir, "title.keys_autogenerated", true);
  120. AttemptLoadKeyFile(yuzu_keys_dir, hactool_keys_dir, "console.keys", false);
  121. AttemptLoadKeyFile(yuzu_keys_dir, yuzu_keys_dir, "console.keys_autogenerated", false);
  122. }
  123. void KeyManager::LoadFromFile(const std::string& filename, bool is_title_keys) {
  124. std::ifstream file(filename);
  125. if (!file.is_open())
  126. return;
  127. std::string line;
  128. while (std::getline(file, line)) {
  129. std::vector<std::string> out;
  130. std::stringstream stream(line);
  131. std::string item;
  132. while (std::getline(stream, item, '='))
  133. out.push_back(std::move(item));
  134. if (out.size() != 2)
  135. continue;
  136. out[0].erase(std::remove(out[0].begin(), out[0].end(), ' '), out[0].end());
  137. out[1].erase(std::remove(out[1].begin(), out[1].end(), ' '), out[1].end());
  138. if (is_title_keys) {
  139. auto rights_id_raw = Common::HexStringToArray<16>(out[0]);
  140. u128 rights_id{};
  141. std::memcpy(rights_id.data(), rights_id_raw.data(), rights_id_raw.size());
  142. Key128 key = Common::HexStringToArray<16>(out[1]);
  143. s128_keys[{S128KeyType::Titlekey, rights_id[1], rights_id[0]}] = key;
  144. } else {
  145. std::transform(out[0].begin(), out[0].end(), out[0].begin(), ::tolower);
  146. if (s128_file_id.find(out[0]) != s128_file_id.end()) {
  147. const auto index = s128_file_id.at(out[0]);
  148. Key128 key = Common::HexStringToArray<16>(out[1]);
  149. s128_keys[{index.type, index.field1, index.field2}] = key;
  150. } else if (s256_file_id.find(out[0]) != s256_file_id.end()) {
  151. const auto index = s256_file_id.at(out[0]);
  152. Key256 key = Common::HexStringToArray<32>(out[1]);
  153. s256_keys[{index.type, index.field1, index.field2}] = key;
  154. }
  155. }
  156. }
  157. }
  158. void KeyManager::AttemptLoadKeyFile(const std::string& dir1, const std::string& dir2,
  159. const std::string& filename, bool title) {
  160. if (FileUtil::Exists(dir1 + DIR_SEP + filename))
  161. LoadFromFile(dir1 + DIR_SEP + filename, title);
  162. else if (FileUtil::Exists(dir2 + DIR_SEP + filename))
  163. LoadFromFile(dir2 + DIR_SEP + filename, title);
  164. }
  165. bool KeyManager::HasKey(S128KeyType id, u64 field1, u64 field2) const {
  166. return s128_keys.find({id, field1, field2}) != s128_keys.end();
  167. }
  168. bool KeyManager::HasKey(S256KeyType id, u64 field1, u64 field2) const {
  169. return s256_keys.find({id, field1, field2}) != s256_keys.end();
  170. }
  171. Key128 KeyManager::GetKey(S128KeyType id, u64 field1, u64 field2) const {
  172. if (!HasKey(id, field1, field2))
  173. return {};
  174. return s128_keys.at({id, field1, field2});
  175. }
  176. Key256 KeyManager::GetKey(S256KeyType id, u64 field1, u64 field2) const {
  177. if (!HasKey(id, field1, field2))
  178. return {};
  179. return s256_keys.at({id, field1, field2});
  180. }
  181. template <std::size_t Size>
  182. void KeyManager::WriteKeyToFile(bool title_key, std::string_view keyname,
  183. const std::array<u8, Size>& key) {
  184. const std::string yuzu_keys_dir = FileUtil::GetUserPath(FileUtil::UserPath::KeysDir);
  185. std::string filename = "title.keys_autogenerated";
  186. if (category == KeyCategory::Standard)
  187. filename = dev_mode ? "dev.keys_autogenerated" : "prod.keys_autogenerated";
  188. else if (category == KeyCategory::Console)
  189. filename = "console.keys_autogenerated";
  190. const auto add_info_text = !FileUtil::Exists(yuzu_keys_dir + DIR_SEP + filename);
  191. FileUtil::CreateFullPath(yuzu_keys_dir + DIR_SEP + filename);
  192. std::ofstream file(yuzu_keys_dir + DIR_SEP + filename, std::ios::app);
  193. if (!file.is_open())
  194. return;
  195. if (add_info_text) {
  196. file
  197. << "# This file is autogenerated by Yuzu\n"
  198. << "# It serves to store keys that were automatically generated from the normal keys\n"
  199. << "# If you are experiencing issues involving keys, it may help to delete this file\n";
  200. }
  201. file << fmt::format("\n{} = {}", keyname, Common::HexArrayToString(key));
  202. AttemptLoadKeyFile(yuzu_keys_dir, yuzu_keys_dir, filename, category == KeyCategory::Title);
  203. }
  204. void KeyManager::SetKey(S128KeyType id, Key128 key, u64 field1, u64 field2) {
  205. if (s128_keys.find({id, field1, field2}) != s128_keys.end())
  206. return;
  207. if (id == S128KeyType::Titlekey) {
  208. Key128 rights_id;
  209. std::memcpy(rights_id.data(), &field2, sizeof(u64));
  210. std::memcpy(rights_id.data() + sizeof(u64), &field1, sizeof(u64));
  211. WriteKeyToFile(true, Common::HexArrayToString(rights_id), key);
  212. }
  213. const auto iter2 = std::find_if(
  214. s128_file_id.begin(), s128_file_id.end(),
  215. [&id, &field1, &field2](const std::pair<std::string, KeyIndex<S128KeyType>> elem) {
  216. return std::tie(elem.second.type, elem.second.field1, elem.second.field2) ==
  217. std::tie(id, field1, field2);
  218. });
  219. if (iter2 != s128_file_id.end())
  220. WriteKeyToFile(false, iter2->first, key);
  221. s128_keys[{id, field1, field2}] = key;
  222. }
  223. void KeyManager::SetKey(S256KeyType id, Key256 key, u64 field1, u64 field2) {
  224. if (s256_keys.find({id, field1, field2}) != s256_keys.end())
  225. return;
  226. const auto iter = std::find_if(
  227. s256_file_id.begin(), s256_file_id.end(),
  228. [&id, &field1, &field2](const std::pair<std::string, KeyIndex<S256KeyType>> elem) {
  229. return std::tie(elem.second.type, elem.second.field1, elem.second.field2) ==
  230. std::tie(id, field1, field2);
  231. });
  232. if (iter != s256_file_id.end())
  233. WriteKeyToFile(KeyCategory::Standard, iter->first, key);
  234. s256_keys[{id, field1, field2}] = key;
  235. }
  236. bool KeyManager::KeyFileExists(bool title) {
  237. const std::string hactool_keys_dir = FileUtil::GetHactoolConfigurationPath();
  238. const std::string yuzu_keys_dir = FileUtil::GetUserPath(FileUtil::UserPath::KeysDir);
  239. if (title) {
  240. return FileUtil::Exists(hactool_keys_dir + DIR_SEP + "title.keys") ||
  241. FileUtil::Exists(yuzu_keys_dir + DIR_SEP + "title.keys");
  242. }
  243. if (Settings::values.use_dev_keys) {
  244. return FileUtil::Exists(hactool_keys_dir + DIR_SEP + "dev.keys") ||
  245. FileUtil::Exists(yuzu_keys_dir + DIR_SEP + "dev.keys");
  246. }
  247. return FileUtil::Exists(hactool_keys_dir + DIR_SEP + "prod.keys") ||
  248. FileUtil::Exists(yuzu_keys_dir + DIR_SEP + "prod.keys");
  249. }
  250. void KeyManager::DeriveSDSeedLazy() {
  251. if (HasKey(S128KeyType::SDSeed))
  252. return;
  253. const auto res = DeriveSDSeed();
  254. if (res != boost::none)
  255. SetKey(S128KeyType::SDSeed, res.get());
  256. }
  257. const boost::container::flat_map<std::string, KeyIndex<S128KeyType>> KeyManager::s128_file_id = {
  258. {"master_key_00", {S128KeyType::Master, 0, 0}},
  259. {"master_key_01", {S128KeyType::Master, 1, 0}},
  260. {"master_key_02", {S128KeyType::Master, 2, 0}},
  261. {"master_key_03", {S128KeyType::Master, 3, 0}},
  262. {"master_key_04", {S128KeyType::Master, 4, 0}},
  263. {"package1_key_00", {S128KeyType::Package1, 0, 0}},
  264. {"package1_key_01", {S128KeyType::Package1, 1, 0}},
  265. {"package1_key_02", {S128KeyType::Package1, 2, 0}},
  266. {"package1_key_03", {S128KeyType::Package1, 3, 0}},
  267. {"package1_key_04", {S128KeyType::Package1, 4, 0}},
  268. {"package2_key_00", {S128KeyType::Package2, 0, 0}},
  269. {"package2_key_01", {S128KeyType::Package2, 1, 0}},
  270. {"package2_key_02", {S128KeyType::Package2, 2, 0}},
  271. {"package2_key_03", {S128KeyType::Package2, 3, 0}},
  272. {"package2_key_04", {S128KeyType::Package2, 4, 0}},
  273. {"titlekek_00", {S128KeyType::Titlekek, 0, 0}},
  274. {"titlekek_01", {S128KeyType::Titlekek, 1, 0}},
  275. {"titlekek_02", {S128KeyType::Titlekek, 2, 0}},
  276. {"titlekek_03", {S128KeyType::Titlekek, 3, 0}},
  277. {"titlekek_04", {S128KeyType::Titlekek, 4, 0}},
  278. {"eticket_rsa_kek", {S128KeyType::ETicketRSAKek, 0, 0}},
  279. {"key_area_key_application_00",
  280. {S128KeyType::KeyArea, 0, static_cast<u64>(KeyAreaKeyType::Application)}},
  281. {"key_area_key_application_01",
  282. {S128KeyType::KeyArea, 1, static_cast<u64>(KeyAreaKeyType::Application)}},
  283. {"key_area_key_application_02",
  284. {S128KeyType::KeyArea, 2, static_cast<u64>(KeyAreaKeyType::Application)}},
  285. {"key_area_key_application_03",
  286. {S128KeyType::KeyArea, 3, static_cast<u64>(KeyAreaKeyType::Application)}},
  287. {"key_area_key_application_04",
  288. {S128KeyType::KeyArea, 4, static_cast<u64>(KeyAreaKeyType::Application)}},
  289. {"key_area_key_ocean_00", {S128KeyType::KeyArea, 0, static_cast<u64>(KeyAreaKeyType::Ocean)}},
  290. {"key_area_key_ocean_01", {S128KeyType::KeyArea, 1, static_cast<u64>(KeyAreaKeyType::Ocean)}},
  291. {"key_area_key_ocean_02", {S128KeyType::KeyArea, 2, static_cast<u64>(KeyAreaKeyType::Ocean)}},
  292. {"key_area_key_ocean_03", {S128KeyType::KeyArea, 3, static_cast<u64>(KeyAreaKeyType::Ocean)}},
  293. {"key_area_key_ocean_04", {S128KeyType::KeyArea, 4, static_cast<u64>(KeyAreaKeyType::Ocean)}},
  294. {"key_area_key_system_00", {S128KeyType::KeyArea, 0, static_cast<u64>(KeyAreaKeyType::System)}},
  295. {"key_area_key_system_01", {S128KeyType::KeyArea, 1, static_cast<u64>(KeyAreaKeyType::System)}},
  296. {"key_area_key_system_02", {S128KeyType::KeyArea, 2, static_cast<u64>(KeyAreaKeyType::System)}},
  297. {"key_area_key_system_03", {S128KeyType::KeyArea, 3, static_cast<u64>(KeyAreaKeyType::System)}},
  298. {"key_area_key_system_04", {S128KeyType::KeyArea, 4, static_cast<u64>(KeyAreaKeyType::System)}},
  299. {"sd_card_kek_source", {S128KeyType::Source, static_cast<u64>(SourceKeyType::SDKEK), 0}},
  300. {"aes_kek_generation_source",
  301. {S128KeyType::Source, static_cast<u64>(SourceKeyType::AESKEKGeneration), 0}},
  302. {"aes_key_generation_source",
  303. {S128KeyType::Source, static_cast<u64>(SourceKeyType::AESKeyGeneration), 0}},
  304. {"sd_seed", {S128KeyType::SDSeed, 0, 0}},
  305. };
  306. const boost::container::flat_map<std::string, KeyIndex<S256KeyType>> KeyManager::s256_file_id = {
  307. {"header_key", {S256KeyType::Header, 0, 0}},
  308. {"sd_card_save_key_source", {S256KeyType::SDKeySource, static_cast<u64>(SDKeyType::Save), 0}},
  309. {"sd_card_nca_key_source", {S256KeyType::SDKeySource, static_cast<u64>(SDKeyType::NCA), 0}},
  310. };
  311. } // namespace Core::Crypto