xts_archive.cpp 5.8 KB

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