xts_archive.cpp 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. // SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <algorithm>
  4. #include <array>
  5. #include <cstring>
  6. #include <regex>
  7. #include <string>
  8. #include <mbedtls/md.h>
  9. #include <mbedtls/sha256.h>
  10. #include "common/fs/path_util.h"
  11. #include "common/hex_util.h"
  12. #include "common/string_util.h"
  13. #include "core/crypto/aes_util.h"
  14. #include "core/crypto/key_manager.h"
  15. #include "core/crypto/xts_encryption_layer.h"
  16. #include "core/file_sys/content_archive.h"
  17. #include "core/file_sys/vfs_offset.h"
  18. #include "core/file_sys/xts_archive.h"
  19. #include "core/loader/loader.h"
  20. namespace FileSys {
  21. constexpr u64 NAX_HEADER_PADDING_SIZE = 0x4000;
  22. template <typename SourceData, typename SourceKey, typename Destination>
  23. static bool CalculateHMAC256(Destination* out, const SourceKey* key, std::size_t key_length,
  24. const SourceData* data, std::size_t data_length) {
  25. mbedtls_md_context_t context;
  26. mbedtls_md_init(&context);
  27. if (mbedtls_md_setup(&context, mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), 1) ||
  28. mbedtls_md_hmac_starts(&context, reinterpret_cast<const u8*>(key), key_length) ||
  29. mbedtls_md_hmac_update(&context, reinterpret_cast<const u8*>(data), data_length) ||
  30. mbedtls_md_hmac_finish(&context, reinterpret_cast<u8*>(out))) {
  31. mbedtls_md_free(&context);
  32. return false;
  33. }
  34. mbedtls_md_free(&context);
  35. return true;
  36. }
  37. NAX::NAX(VirtualFile file_)
  38. : header(std::make_unique<NAXHeader>()),
  39. file(std::move(file_)), keys{Core::Crypto::KeyManager::Instance()} {
  40. std::string path = Common::FS::SanitizePath(file->GetFullPath());
  41. static const std::regex nax_path_regex("/registered/(000000[0-9A-F]{2})/([0-9A-F]{32})\\.nca",
  42. std::regex_constants::ECMAScript |
  43. std::regex_constants::icase);
  44. std::smatch match;
  45. if (!std::regex_search(path, match, nax_path_regex)) {
  46. status = Loader::ResultStatus::ErrorBadNAXFilePath;
  47. return;
  48. }
  49. const std::string two_dir = Common::ToUpper(match[1]);
  50. const std::string nca_id = Common::ToLower(match[2]);
  51. status = Parse(fmt::format("/registered/{}/{}.nca", two_dir, nca_id));
  52. }
  53. NAX::NAX(VirtualFile file_, std::array<u8, 0x10> nca_id)
  54. : header(std::make_unique<NAXHeader>()),
  55. file(std::move(file_)), keys{Core::Crypto::KeyManager::Instance()} {
  56. Core::Crypto::SHA256Hash hash{};
  57. mbedtls_sha256_ret(nca_id.data(), nca_id.size(), hash.data(), 0);
  58. status = Parse(fmt::format("/registered/000000{:02X}/{}.nca", hash[0],
  59. Common::HexToString(nca_id, false)));
  60. }
  61. NAX::~NAX() = default;
  62. Loader::ResultStatus NAX::Parse(std::string_view path) {
  63. if (file == nullptr) {
  64. return Loader::ResultStatus::ErrorNullFile;
  65. }
  66. if (file->ReadObject(header.get()) != sizeof(NAXHeader)) {
  67. return Loader::ResultStatus::ErrorBadNAXHeader;
  68. }
  69. if (header->magic != Common::MakeMagic('N', 'A', 'X', '0')) {
  70. return Loader::ResultStatus::ErrorBadNAXHeader;
  71. }
  72. if (file->GetSize() < NAX_HEADER_PADDING_SIZE + header->file_size) {
  73. return Loader::ResultStatus::ErrorIncorrectNAXFileSize;
  74. }
  75. keys.DeriveSDSeedLazy();
  76. std::array<Core::Crypto::Key256, 2> sd_keys{};
  77. const auto sd_keys_res = Core::Crypto::DeriveSDKeys(sd_keys, keys);
  78. if (sd_keys_res != Loader::ResultStatus::Success) {
  79. return sd_keys_res;
  80. }
  81. const auto enc_keys = header->key_area;
  82. std::size_t i = 0;
  83. for (; i < sd_keys.size(); ++i) {
  84. std::array<Core::Crypto::Key128, 2> nax_keys{};
  85. if (!CalculateHMAC256(nax_keys.data(), sd_keys[i].data(), 0x10, path.data(), path.size())) {
  86. return Loader::ResultStatus::ErrorNAXKeyHMACFailed;
  87. }
  88. for (std::size_t j = 0; j < nax_keys.size(); ++j) {
  89. Core::Crypto::AESCipher<Core::Crypto::Key128> cipher(nax_keys[j],
  90. Core::Crypto::Mode::ECB);
  91. cipher.Transcode(enc_keys[j].data(), 0x10, header->key_area[j].data(),
  92. Core::Crypto::Op::Decrypt);
  93. }
  94. Core::Crypto::SHA256Hash validation{};
  95. if (!CalculateHMAC256(validation.data(), &header->magic, 0x60, sd_keys[i].data() + 0x10,
  96. 0x10)) {
  97. return Loader::ResultStatus::ErrorNAXValidationHMACFailed;
  98. }
  99. if (header->hmac == validation)
  100. break;
  101. }
  102. if (i == 2) {
  103. return Loader::ResultStatus::ErrorNAXKeyDerivationFailed;
  104. }
  105. type = static_cast<NAXContentType>(i);
  106. Core::Crypto::Key256 final_key{};
  107. std::memcpy(final_key.data(), &header->key_area, final_key.size());
  108. const auto enc_file =
  109. std::make_shared<OffsetVfsFile>(file, header->file_size, NAX_HEADER_PADDING_SIZE);
  110. dec_file = std::make_shared<Core::Crypto::XTSEncryptionLayer>(enc_file, final_key);
  111. return Loader::ResultStatus::Success;
  112. }
  113. Loader::ResultStatus NAX::GetStatus() const {
  114. return status;
  115. }
  116. VirtualFile NAX::GetDecrypted() const {
  117. return dec_file;
  118. }
  119. std::unique_ptr<NCA> NAX::AsNCA() const {
  120. if (type == NAXContentType::NCA)
  121. return std::make_unique<NCA>(GetDecrypted());
  122. return nullptr;
  123. }
  124. NAXContentType NAX::GetContentType() const {
  125. return type;
  126. }
  127. std::vector<VirtualFile> NAX::GetFiles() const {
  128. return {dec_file};
  129. }
  130. std::vector<VirtualDir> NAX::GetSubdirectories() const {
  131. return {};
  132. }
  133. std::string NAX::GetName() const {
  134. return file->GetName();
  135. }
  136. VirtualDir NAX::GetParentDirectory() const {
  137. return file->GetContainingDirectory();
  138. }
  139. } // namespace FileSys