xts_archive.cpp 5.7 KB

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