content_archive.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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 <cstring>
  6. #include <utility>
  7. #include <boost/optional.hpp>
  8. #include "common/logging/log.h"
  9. #include "core/crypto/aes_util.h"
  10. #include "core/crypto/ctr_encryption_layer.h"
  11. #include "core/file_sys/content_archive.h"
  12. #include "core/file_sys/nca_patch.h"
  13. #include "core/file_sys/partition_filesystem.h"
  14. #include "core/file_sys/romfs.h"
  15. #include "core/file_sys/vfs_offset.h"
  16. #include "core/loader/loader.h"
  17. namespace FileSys {
  18. // Media offsets in headers are stored divided by 512. Mult. by this to get real offset.
  19. constexpr u64 MEDIA_OFFSET_MULTIPLIER = 0x200;
  20. constexpr u64 SECTION_HEADER_SIZE = 0x200;
  21. constexpr u64 SECTION_HEADER_OFFSET = 0x400;
  22. constexpr u32 IVFC_MAX_LEVEL = 6;
  23. enum class NCASectionFilesystemType : u8 {
  24. PFS0 = 0x2,
  25. ROMFS = 0x3,
  26. };
  27. struct NCASectionHeaderBlock {
  28. INSERT_PADDING_BYTES(3);
  29. NCASectionFilesystemType filesystem_type;
  30. NCASectionCryptoType crypto_type;
  31. INSERT_PADDING_BYTES(3);
  32. };
  33. static_assert(sizeof(NCASectionHeaderBlock) == 0x8, "NCASectionHeaderBlock has incorrect size.");
  34. struct NCASectionRaw {
  35. NCASectionHeaderBlock header;
  36. std::array<u8, 0x138> block_data;
  37. std::array<u8, 0x8> section_ctr;
  38. INSERT_PADDING_BYTES(0xB8);
  39. };
  40. static_assert(sizeof(NCASectionRaw) == 0x200, "NCASectionRaw has incorrect size.");
  41. struct PFS0Superblock {
  42. NCASectionHeaderBlock header_block;
  43. std::array<u8, 0x20> hash;
  44. u32_le size;
  45. INSERT_PADDING_BYTES(4);
  46. u64_le hash_table_offset;
  47. u64_le hash_table_size;
  48. u64_le pfs0_header_offset;
  49. u64_le pfs0_size;
  50. INSERT_PADDING_BYTES(0x1B0);
  51. };
  52. static_assert(sizeof(PFS0Superblock) == 0x200, "PFS0Superblock has incorrect size.");
  53. struct RomFSSuperblock {
  54. NCASectionHeaderBlock header_block;
  55. IVFCHeader ivfc;
  56. INSERT_PADDING_BYTES(0x118);
  57. };
  58. static_assert(sizeof(RomFSSuperblock) == 0x200, "RomFSSuperblock has incorrect size.");
  59. struct BKTRHeader {
  60. u64_le offset;
  61. u64_le size;
  62. u32_le magic;
  63. INSERT_PADDING_BYTES(0x4);
  64. u32_le number_entries;
  65. INSERT_PADDING_BYTES(0x4);
  66. };
  67. static_assert(sizeof(BKTRHeader) == 0x20, "BKTRHeader has incorrect size.");
  68. struct BKTRSuperblock {
  69. NCASectionHeaderBlock header_block;
  70. IVFCHeader ivfc;
  71. INSERT_PADDING_BYTES(0x18);
  72. BKTRHeader relocation;
  73. BKTRHeader subsection;
  74. INSERT_PADDING_BYTES(0xC0);
  75. };
  76. static_assert(sizeof(BKTRSuperblock) == 0x200, "BKTRSuperblock has incorrect size.");
  77. union NCASectionHeader {
  78. NCASectionRaw raw;
  79. PFS0Superblock pfs0;
  80. RomFSSuperblock romfs;
  81. BKTRSuperblock bktr;
  82. };
  83. static_assert(sizeof(NCASectionHeader) == 0x200, "NCASectionHeader has incorrect size.");
  84. bool IsValidNCA(const NCAHeader& header) {
  85. // TODO(DarkLordZach): Add NCA2/NCA0 support.
  86. return header.magic == Common::MakeMagic('N', 'C', 'A', '3');
  87. }
  88. u8 NCA::GetCryptoRevision() const {
  89. u8 master_key_id = header.crypto_type;
  90. if (header.crypto_type_2 > master_key_id)
  91. master_key_id = header.crypto_type_2;
  92. if (master_key_id > 0)
  93. --master_key_id;
  94. return master_key_id;
  95. }
  96. boost::optional<Core::Crypto::Key128> NCA::GetKeyAreaKey(NCASectionCryptoType type) const {
  97. const auto master_key_id = GetCryptoRevision();
  98. if (!keys.HasKey(Core::Crypto::S128KeyType::KeyArea, master_key_id, header.key_index))
  99. return boost::none;
  100. std::vector<u8> key_area(header.key_area.begin(), header.key_area.end());
  101. Core::Crypto::AESCipher<Core::Crypto::Key128> cipher(
  102. keys.GetKey(Core::Crypto::S128KeyType::KeyArea, master_key_id, header.key_index),
  103. Core::Crypto::Mode::ECB);
  104. cipher.Transcode(key_area.data(), key_area.size(), key_area.data(), Core::Crypto::Op::Decrypt);
  105. Core::Crypto::Key128 out;
  106. if (type == NCASectionCryptoType::XTS)
  107. std::copy(key_area.begin(), key_area.begin() + 0x10, out.begin());
  108. else if (type == NCASectionCryptoType::CTR || type == NCASectionCryptoType::BKTR)
  109. std::copy(key_area.begin() + 0x20, key_area.begin() + 0x30, out.begin());
  110. else
  111. LOG_CRITICAL(Crypto, "Called GetKeyAreaKey on invalid NCASectionCryptoType type={:02X}",
  112. static_cast<u8>(type));
  113. u128 out_128{};
  114. memcpy(out_128.data(), out.data(), 16);
  115. LOG_DEBUG(Crypto, "called with crypto_rev={:02X}, kak_index={:02X}, key={:016X}{:016X}",
  116. master_key_id, header.key_index, out_128[1], out_128[0]);
  117. return out;
  118. }
  119. boost::optional<Core::Crypto::Key128> NCA::GetTitlekey() {
  120. const auto master_key_id = GetCryptoRevision();
  121. u128 rights_id{};
  122. memcpy(rights_id.data(), header.rights_id.data(), 16);
  123. if (rights_id == u128{}) {
  124. status = Loader::ResultStatus::ErrorInvalidRightsID;
  125. return boost::none;
  126. }
  127. auto titlekey = keys.GetKey(Core::Crypto::S128KeyType::Titlekey, rights_id[1], rights_id[0]);
  128. if (titlekey == Core::Crypto::Key128{}) {
  129. status = Loader::ResultStatus::ErrorMissingTitlekey;
  130. return boost::none;
  131. }
  132. if (!keys.HasKey(Core::Crypto::S128KeyType::Titlekek, master_key_id)) {
  133. status = Loader::ResultStatus::ErrorMissingTitlekek;
  134. return boost::none;
  135. }
  136. Core::Crypto::AESCipher<Core::Crypto::Key128> cipher(
  137. keys.GetKey(Core::Crypto::S128KeyType::Titlekek, master_key_id), Core::Crypto::Mode::ECB);
  138. cipher.Transcode(titlekey.data(), titlekey.size(), titlekey.data(), Core::Crypto::Op::Decrypt);
  139. return titlekey;
  140. }
  141. VirtualFile NCA::Decrypt(NCASectionHeader s_header, VirtualFile in, u64 starting_offset) {
  142. if (!encrypted)
  143. return in;
  144. switch (s_header.raw.header.crypto_type) {
  145. case NCASectionCryptoType::NONE:
  146. LOG_DEBUG(Crypto, "called with mode=NONE");
  147. return in;
  148. case NCASectionCryptoType::CTR:
  149. // During normal BKTR decryption, this entire function is skipped. This is for the metadata,
  150. // which uses the same CTR as usual.
  151. case NCASectionCryptoType::BKTR:
  152. LOG_DEBUG(Crypto, "called with mode=CTR, starting_offset={:016X}", starting_offset);
  153. {
  154. boost::optional<Core::Crypto::Key128> key = boost::none;
  155. if (has_rights_id) {
  156. status = Loader::ResultStatus::Success;
  157. key = GetTitlekey();
  158. if (key == boost::none) {
  159. if (status == Loader::ResultStatus::Success)
  160. status = Loader::ResultStatus::ErrorMissingTitlekey;
  161. return nullptr;
  162. }
  163. } else {
  164. key = GetKeyAreaKey(NCASectionCryptoType::CTR);
  165. if (key == boost::none) {
  166. status = Loader::ResultStatus::ErrorMissingKeyAreaKey;
  167. return nullptr;
  168. }
  169. }
  170. auto out = std::make_shared<Core::Crypto::CTREncryptionLayer>(
  171. std::move(in), key.value(), starting_offset);
  172. std::vector<u8> iv(16);
  173. for (u8 i = 0; i < 8; ++i)
  174. iv[i] = s_header.raw.section_ctr[0x8 - i - 1];
  175. out->SetIV(iv);
  176. return std::static_pointer_cast<VfsFile>(out);
  177. }
  178. case NCASectionCryptoType::XTS:
  179. // TODO(DarkLordZach): Find a test case for XTS-encrypted NCAs
  180. default:
  181. LOG_ERROR(Crypto, "called with unhandled crypto type={:02X}",
  182. static_cast<u8>(s_header.raw.header.crypto_type));
  183. return nullptr;
  184. }
  185. }
  186. NCA::NCA(VirtualFile file_, VirtualFile bktr_base_romfs_, u64 bktr_base_ivfc_offset)
  187. : file(std::move(file_)),
  188. bktr_base_romfs(bktr_base_romfs_ ? std::move(bktr_base_romfs_) : nullptr) {
  189. status = Loader::ResultStatus::Success;
  190. if (file == nullptr) {
  191. status = Loader::ResultStatus::ErrorNullFile;
  192. return;
  193. }
  194. if (sizeof(NCAHeader) != file->ReadObject(&header)) {
  195. LOG_ERROR(Loader, "File reader errored out during header read.");
  196. status = Loader::ResultStatus::ErrorBadNCAHeader;
  197. return;
  198. }
  199. encrypted = false;
  200. if (!IsValidNCA(header)) {
  201. if (header.magic == Common::MakeMagic('N', 'C', 'A', '2')) {
  202. status = Loader::ResultStatus::ErrorNCA2;
  203. return;
  204. }
  205. if (header.magic == Common::MakeMagic('N', 'C', 'A', '0')) {
  206. status = Loader::ResultStatus::ErrorNCA0;
  207. return;
  208. }
  209. NCAHeader dec_header{};
  210. Core::Crypto::AESCipher<Core::Crypto::Key256> cipher(
  211. keys.GetKey(Core::Crypto::S256KeyType::Header), Core::Crypto::Mode::XTS);
  212. cipher.XTSTranscode(&header, sizeof(NCAHeader), &dec_header, 0, 0x200,
  213. Core::Crypto::Op::Decrypt);
  214. if (IsValidNCA(dec_header)) {
  215. header = dec_header;
  216. encrypted = true;
  217. } else {
  218. if (dec_header.magic == Common::MakeMagic('N', 'C', 'A', '2')) {
  219. status = Loader::ResultStatus::ErrorNCA2;
  220. return;
  221. }
  222. if (dec_header.magic == Common::MakeMagic('N', 'C', 'A', '0')) {
  223. status = Loader::ResultStatus::ErrorNCA0;
  224. return;
  225. }
  226. if (!keys.HasKey(Core::Crypto::S256KeyType::Header))
  227. status = Loader::ResultStatus::ErrorMissingHeaderKey;
  228. else
  229. status = Loader::ResultStatus::ErrorIncorrectHeaderKey;
  230. return;
  231. }
  232. }
  233. has_rights_id = std::find_if_not(header.rights_id.begin(), header.rights_id.end(),
  234. [](char c) { return c == '\0'; }) != header.rights_id.end();
  235. const std::ptrdiff_t number_sections =
  236. std::count_if(std::begin(header.section_tables), std::end(header.section_tables),
  237. [](NCASectionTableEntry entry) { return entry.media_offset > 0; });
  238. std::vector<NCASectionHeader> sections(number_sections);
  239. const auto length_sections = SECTION_HEADER_SIZE * number_sections;
  240. if (encrypted) {
  241. auto raw = file->ReadBytes(length_sections, SECTION_HEADER_OFFSET);
  242. Core::Crypto::AESCipher<Core::Crypto::Key256> cipher(
  243. keys.GetKey(Core::Crypto::S256KeyType::Header), Core::Crypto::Mode::XTS);
  244. cipher.XTSTranscode(raw.data(), length_sections, sections.data(), 2, SECTION_HEADER_SIZE,
  245. Core::Crypto::Op::Decrypt);
  246. } else {
  247. file->ReadBytes(sections.data(), length_sections, SECTION_HEADER_OFFSET);
  248. }
  249. is_update = std::find_if(sections.begin(), sections.end(), [](const NCASectionHeader& header) {
  250. return header.raw.header.crypto_type == NCASectionCryptoType::BKTR;
  251. }) != sections.end();
  252. ivfc_offset = 0;
  253. for (std::ptrdiff_t i = 0; i < number_sections; ++i) {
  254. auto section = sections[i];
  255. if (section.raw.header.filesystem_type == NCASectionFilesystemType::ROMFS) {
  256. const std::size_t base_offset =
  257. header.section_tables[i].media_offset * MEDIA_OFFSET_MULTIPLIER;
  258. ivfc_offset = section.romfs.ivfc.levels[IVFC_MAX_LEVEL - 1].offset;
  259. const std::size_t romfs_offset = base_offset + ivfc_offset;
  260. const std::size_t romfs_size = section.romfs.ivfc.levels[IVFC_MAX_LEVEL - 1].size;
  261. auto raw = std::make_shared<OffsetVfsFile>(file, romfs_size, romfs_offset);
  262. auto dec = Decrypt(section, raw, romfs_offset);
  263. if (dec == nullptr) {
  264. if (status != Loader::ResultStatus::Success)
  265. return;
  266. if (has_rights_id)
  267. status = Loader::ResultStatus::ErrorIncorrectTitlekeyOrTitlekek;
  268. else
  269. status = Loader::ResultStatus::ErrorIncorrectKeyAreaKey;
  270. return;
  271. }
  272. if (section.raw.header.crypto_type == NCASectionCryptoType::BKTR) {
  273. if (section.bktr.relocation.magic != Common::MakeMagic('B', 'K', 'T', 'R') ||
  274. section.bktr.subsection.magic != Common::MakeMagic('B', 'K', 'T', 'R')) {
  275. status = Loader::ResultStatus::ErrorBadBKTRHeader;
  276. return;
  277. }
  278. if (section.bktr.relocation.offset + section.bktr.relocation.size !=
  279. section.bktr.subsection.offset) {
  280. status = Loader::ResultStatus::ErrorBKTRSubsectionNotAfterRelocation;
  281. return;
  282. }
  283. const u64 size =
  284. MEDIA_OFFSET_MULTIPLIER * (header.section_tables[i].media_end_offset -
  285. header.section_tables[i].media_offset);
  286. if (section.bktr.subsection.offset + section.bktr.subsection.size != size) {
  287. status = Loader::ResultStatus::ErrorBKTRSubsectionNotAtEnd;
  288. return;
  289. }
  290. const u64 offset = section.romfs.ivfc.levels[IVFC_MAX_LEVEL - 1].offset;
  291. RelocationBlock relocation_block{};
  292. if (dec->ReadObject(&relocation_block, section.bktr.relocation.offset - offset) !=
  293. sizeof(RelocationBlock)) {
  294. status = Loader::ResultStatus::ErrorBadRelocationBlock;
  295. return;
  296. }
  297. SubsectionBlock subsection_block{};
  298. if (dec->ReadObject(&subsection_block, section.bktr.subsection.offset - offset) !=
  299. sizeof(RelocationBlock)) {
  300. status = Loader::ResultStatus::ErrorBadSubsectionBlock;
  301. return;
  302. }
  303. std::vector<RelocationBucketRaw> relocation_buckets_raw(
  304. (section.bktr.relocation.size - sizeof(RelocationBlock)) /
  305. sizeof(RelocationBucketRaw));
  306. if (dec->ReadBytes(relocation_buckets_raw.data(),
  307. section.bktr.relocation.size - sizeof(RelocationBlock),
  308. section.bktr.relocation.offset + sizeof(RelocationBlock) -
  309. offset) !=
  310. section.bktr.relocation.size - sizeof(RelocationBlock)) {
  311. status = Loader::ResultStatus::ErrorBadRelocationBuckets;
  312. return;
  313. }
  314. std::vector<SubsectionBucketRaw> subsection_buckets_raw(
  315. (section.bktr.subsection.size - sizeof(SubsectionBlock)) /
  316. sizeof(SubsectionBucketRaw));
  317. if (dec->ReadBytes(subsection_buckets_raw.data(),
  318. section.bktr.subsection.size - sizeof(SubsectionBlock),
  319. section.bktr.subsection.offset + sizeof(SubsectionBlock) -
  320. offset) !=
  321. section.bktr.subsection.size - sizeof(SubsectionBlock)) {
  322. status = Loader::ResultStatus::ErrorBadSubsectionBuckets;
  323. return;
  324. }
  325. std::vector<RelocationBucket> relocation_buckets(relocation_buckets_raw.size());
  326. std::transform(relocation_buckets_raw.begin(), relocation_buckets_raw.end(),
  327. relocation_buckets.begin(), &ConvertRelocationBucketRaw);
  328. std::vector<SubsectionBucket> subsection_buckets(subsection_buckets_raw.size());
  329. std::transform(subsection_buckets_raw.begin(), subsection_buckets_raw.end(),
  330. subsection_buckets.begin(), &ConvertSubsectionBucketRaw);
  331. u32 ctr_low;
  332. std::memcpy(&ctr_low, section.raw.section_ctr.data(), sizeof(ctr_low));
  333. subsection_buckets.back().entries.push_back(
  334. {section.bktr.relocation.offset, {0}, ctr_low});
  335. subsection_buckets.back().entries.push_back({size, {0}, 0});
  336. boost::optional<Core::Crypto::Key128> key = boost::none;
  337. if (encrypted) {
  338. if (has_rights_id) {
  339. status = Loader::ResultStatus::Success;
  340. key = GetTitlekey();
  341. if (key == boost::none) {
  342. status = Loader::ResultStatus::ErrorMissingTitlekey;
  343. return;
  344. }
  345. } else {
  346. key = GetKeyAreaKey(NCASectionCryptoType::BKTR);
  347. if (key == boost::none) {
  348. status = Loader::ResultStatus::ErrorMissingKeyAreaKey;
  349. return;
  350. }
  351. }
  352. }
  353. if (bktr_base_romfs == nullptr) {
  354. status = Loader::ResultStatus::ErrorMissingBKTRBaseRomFS;
  355. return;
  356. }
  357. auto bktr = std::make_shared<BKTR>(
  358. bktr_base_romfs, std::make_shared<OffsetVfsFile>(file, romfs_size, base_offset),
  359. relocation_block, relocation_buckets, subsection_block, subsection_buckets,
  360. encrypted, encrypted ? key.get() : Core::Crypto::Key128{}, base_offset,
  361. bktr_base_ivfc_offset, section.raw.section_ctr);
  362. // BKTR applies to entire IVFC, so make an offset version to level 6
  363. files.push_back(std::make_shared<OffsetVfsFile>(
  364. bktr, romfs_size, section.romfs.ivfc.levels[IVFC_MAX_LEVEL - 1].offset));
  365. romfs = files.back();
  366. } else {
  367. files.push_back(std::move(dec));
  368. romfs = files.back();
  369. }
  370. } else if (section.raw.header.filesystem_type == NCASectionFilesystemType::PFS0) {
  371. u64 offset = (static_cast<u64>(header.section_tables[i].media_offset) *
  372. MEDIA_OFFSET_MULTIPLIER) +
  373. section.pfs0.pfs0_header_offset;
  374. u64 size = MEDIA_OFFSET_MULTIPLIER * (header.section_tables[i].media_end_offset -
  375. header.section_tables[i].media_offset);
  376. auto dec =
  377. Decrypt(section, std::make_shared<OffsetVfsFile>(file, size, offset), offset);
  378. if (dec != nullptr) {
  379. auto npfs = std::make_shared<PartitionFilesystem>(std::move(dec));
  380. if (npfs->GetStatus() == Loader::ResultStatus::Success) {
  381. dirs.push_back(std::move(npfs));
  382. if (IsDirectoryExeFS(dirs.back()))
  383. exefs = dirs.back();
  384. } else {
  385. if (has_rights_id)
  386. status = Loader::ResultStatus::ErrorIncorrectTitlekeyOrTitlekek;
  387. else
  388. status = Loader::ResultStatus::ErrorIncorrectKeyAreaKey;
  389. return;
  390. }
  391. } else {
  392. if (status != Loader::ResultStatus::Success)
  393. return;
  394. if (has_rights_id)
  395. status = Loader::ResultStatus::ErrorIncorrectTitlekeyOrTitlekek;
  396. else
  397. status = Loader::ResultStatus::ErrorIncorrectKeyAreaKey;
  398. return;
  399. }
  400. }
  401. }
  402. status = Loader::ResultStatus::Success;
  403. }
  404. Loader::ResultStatus NCA::GetStatus() const {
  405. return status;
  406. }
  407. std::vector<std::shared_ptr<VfsFile>> NCA::GetFiles() const {
  408. if (status != Loader::ResultStatus::Success)
  409. return {};
  410. return files;
  411. }
  412. std::vector<std::shared_ptr<VfsDirectory>> NCA::GetSubdirectories() const {
  413. if (status != Loader::ResultStatus::Success)
  414. return {};
  415. return dirs;
  416. }
  417. std::string NCA::GetName() const {
  418. return file->GetName();
  419. }
  420. std::shared_ptr<VfsDirectory> NCA::GetParentDirectory() const {
  421. return file->GetContainingDirectory();
  422. }
  423. NCAContentType NCA::GetType() const {
  424. return header.content_type;
  425. }
  426. u64 NCA::GetTitleId() const {
  427. if (is_update || status == Loader::ResultStatus::ErrorMissingBKTRBaseRomFS)
  428. return header.title_id | 0x800;
  429. return header.title_id;
  430. }
  431. bool NCA::IsUpdate() const {
  432. return is_update;
  433. }
  434. VirtualFile NCA::GetRomFS() const {
  435. return romfs;
  436. }
  437. VirtualDir NCA::GetExeFS() const {
  438. return exefs;
  439. }
  440. VirtualFile NCA::GetBaseFile() const {
  441. return file;
  442. }
  443. u64 NCA::GetBaseIVFCOffset() const {
  444. return ivfc_offset;
  445. }
  446. bool NCA::ReplaceFileWithSubdirectory(VirtualFile file, VirtualDir dir) {
  447. return false;
  448. }
  449. } // namespace FileSys