NANDImporter.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. // Copyright 2017 Dolphin Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include "DiscIO/NANDImporter.h"
  4. #include <algorithm>
  5. #include <cstring>
  6. #include "Common/Crypto/AES.h"
  7. #include "Common/FileUtil.h"
  8. #include "Common/IOFile.h"
  9. #include "Common/Logging/Log.h"
  10. #include "Common/MsgHandler.h"
  11. #include "Core/IOS/ES/Formats.h"
  12. namespace DiscIO
  13. {
  14. constexpr size_t NAND_SIZE = 0x20000000;
  15. constexpr size_t NAND_KEYS_SIZE = 0x400;
  16. NANDImporter::NANDImporter() : m_nand_root(File::GetUserPath(D_WIIROOT_IDX))
  17. {
  18. }
  19. NANDImporter::~NANDImporter() = default;
  20. void NANDImporter::ImportNANDBin(const std::string& path_to_bin,
  21. std::function<void()> update_callback,
  22. std::function<std::string()> get_otp_dump_path)
  23. {
  24. m_update_callback = std::move(update_callback);
  25. if (!ReadNANDBin(path_to_bin, get_otp_dump_path))
  26. return;
  27. if (!FindSuperblock())
  28. return;
  29. ExportKeys();
  30. ProcessEntry(0, "");
  31. ExtractCertificates();
  32. }
  33. bool NANDImporter::ReadNANDBin(const std::string& path_to_bin,
  34. std::function<std::string()> get_otp_dump_path)
  35. {
  36. constexpr size_t NAND_TOTAL_BLOCKS = 0x40000;
  37. constexpr size_t NAND_BLOCK_SIZE = 0x800;
  38. constexpr size_t NAND_ECC_BLOCK_SIZE = 0x40;
  39. constexpr size_t NAND_BIN_SIZE =
  40. (NAND_BLOCK_SIZE + NAND_ECC_BLOCK_SIZE) * NAND_TOTAL_BLOCKS; // 0x21000000
  41. File::IOFile file(path_to_bin, "rb");
  42. const u64 image_size = file.GetSize();
  43. if (image_size != NAND_BIN_SIZE + NAND_KEYS_SIZE && image_size != NAND_BIN_SIZE)
  44. {
  45. PanicAlertFmtT("This file does not look like a BootMii NAND backup.");
  46. return false;
  47. }
  48. m_nand.resize(NAND_SIZE);
  49. for (size_t i = 0; i < NAND_TOTAL_BLOCKS; i++)
  50. {
  51. // Instead of updating on every cycle, we only update every 1000 cycles for a balance between
  52. // not updating fast enough vs updating too fast
  53. if (i % 1000 == 0)
  54. m_update_callback();
  55. file.ReadBytes(&m_nand[i * NAND_BLOCK_SIZE], NAND_BLOCK_SIZE);
  56. // We don't care about the ECC blocks
  57. file.Seek(NAND_ECC_BLOCK_SIZE, File::SeekOrigin::Current);
  58. }
  59. m_nand_keys.resize(NAND_KEYS_SIZE);
  60. // Read the OTP/SEEPROM dump.
  61. // If it is not included in the NAND image, get a path to the dump and read key data from it.
  62. if (image_size == NAND_BIN_SIZE)
  63. {
  64. const std::string otp_dump_path = get_otp_dump_path();
  65. if (otp_dump_path.empty())
  66. return false;
  67. File::IOFile keys_file{otp_dump_path, "rb"};
  68. return keys_file.ReadBytes(m_nand_keys.data(), NAND_KEYS_SIZE);
  69. }
  70. // Otherwise, just read the key data from the NAND image.
  71. return file.ReadBytes(m_nand_keys.data(), NAND_KEYS_SIZE);
  72. }
  73. bool NANDImporter::FindSuperblock()
  74. {
  75. constexpr size_t NAND_SUPERBLOCK_START = 0x1fc00000;
  76. // There are 16 superblocks, choose the highest/newest version
  77. for (int i = 0; i < 16; i++)
  78. {
  79. auto superblock = std::make_unique<NANDSuperblock>();
  80. std::memcpy(superblock.get(), &m_nand[NAND_SUPERBLOCK_START + i * sizeof(NANDSuperblock)],
  81. sizeof(NANDSuperblock));
  82. if (std::memcmp(superblock->magic.data(), "SFFS", 4) != 0)
  83. {
  84. ERROR_LOG_FMT(DISCIO, "Superblock #{} does not exist", i);
  85. continue;
  86. }
  87. INFO_LOG_FMT(DISCIO, "Superblock #{} has version {:#x}", i, superblock->version);
  88. if (!m_superblock || superblock->version > m_superblock->version)
  89. m_superblock = std::move(superblock);
  90. }
  91. if (!m_superblock)
  92. {
  93. PanicAlertFmtT("This file does not contain a valid Wii filesystem.");
  94. return false;
  95. }
  96. INFO_LOG_FMT(DISCIO, "Using superblock version {:#x}", m_superblock->version);
  97. return true;
  98. }
  99. std::string NANDImporter::GetPath(const NANDFSTEntry& entry, const std::string& parent_path)
  100. {
  101. std::string name(entry.name, strnlen(entry.name, sizeof(NANDFSTEntry::name)));
  102. if (name.front() == '/' || parent_path.back() == '/')
  103. return parent_path + name;
  104. return parent_path + '/' + name;
  105. }
  106. void NANDImporter::ProcessEntry(u16 entry_number, const std::string& parent_path)
  107. {
  108. while (entry_number != 0xffff)
  109. {
  110. if (entry_number >= m_superblock->fst.size())
  111. {
  112. ERROR_LOG_FMT(DISCIO, "FST entry number {} out of range", entry_number);
  113. return;
  114. }
  115. const NANDFSTEntry entry = m_superblock->fst[entry_number];
  116. const std::string path = GetPath(entry, parent_path);
  117. INFO_LOG_FMT(DISCIO, "Entry: {} Path: {}", entry, path);
  118. m_update_callback();
  119. Type type = static_cast<Type>(entry.mode & 3);
  120. if (type == Type::File)
  121. {
  122. std::vector<u8> data = GetEntryData(entry);
  123. File::IOFile file(m_nand_root + path, "wb");
  124. file.WriteBytes(data.data(), data.size());
  125. }
  126. else if (type == Type::Directory)
  127. {
  128. File::CreateDir(m_nand_root + path);
  129. ProcessEntry(entry.sub, path);
  130. }
  131. else
  132. {
  133. ERROR_LOG_FMT(DISCIO, "Ignoring unknown entry type for {}", entry);
  134. }
  135. entry_number = entry.sib;
  136. }
  137. }
  138. std::vector<u8> NANDImporter::GetEntryData(const NANDFSTEntry& entry)
  139. {
  140. constexpr size_t NAND_FAT_BLOCK_SIZE = 0x4000;
  141. u16 sub = entry.sub;
  142. size_t remaining_bytes = entry.size;
  143. std::vector<u8> data{};
  144. data.reserve(remaining_bytes);
  145. auto block = std::make_unique<u8[]>(NAND_FAT_BLOCK_SIZE);
  146. while (remaining_bytes > 0)
  147. {
  148. if (sub >= m_superblock->fat.size())
  149. {
  150. ERROR_LOG_FMT(DISCIO, "FAT block index {} out of range", sub);
  151. return {};
  152. }
  153. m_aes_ctx->CryptIvZero(&m_nand[NAND_FAT_BLOCK_SIZE * sub], block.get(), NAND_FAT_BLOCK_SIZE);
  154. size_t size = std::min(remaining_bytes, NAND_FAT_BLOCK_SIZE);
  155. data.insert(data.end(), block.get(), block.get() + size);
  156. remaining_bytes -= size;
  157. sub = m_superblock->fat[sub];
  158. }
  159. return data;
  160. }
  161. bool NANDImporter::ExtractCertificates()
  162. {
  163. const std::string content_dir = m_nand_root + "/title/00000001/0000000d/content/";
  164. File::IOFile tmd_file(content_dir + "title.tmd", "rb");
  165. std::vector<u8> tmd_bytes(tmd_file.GetSize());
  166. if (!tmd_file.ReadBytes(tmd_bytes.data(), tmd_bytes.size()))
  167. {
  168. ERROR_LOG_FMT(DISCIO, "ExtractCertificates: Could not read IOS13 TMD");
  169. return false;
  170. }
  171. IOS::ES::TMDReader tmd(std::move(tmd_bytes));
  172. IOS::ES::Content content_metadata;
  173. if (!tmd.GetContent(tmd.GetBootIndex(), &content_metadata))
  174. {
  175. ERROR_LOG_FMT(DISCIO, "ExtractCertificates: Could not get content ID from TMD");
  176. return false;
  177. }
  178. File::IOFile content_file(content_dir + fmt::format("{:08x}.app", content_metadata.id), "rb");
  179. std::vector<u8> content_bytes(content_file.GetSize());
  180. if (!content_file.ReadBytes(content_bytes.data(), content_bytes.size()))
  181. {
  182. ERROR_LOG_FMT(DISCIO, "ExtractCertificates: Could not read IOS13 contents");
  183. return false;
  184. }
  185. struct PEMCertificate
  186. {
  187. std::string_view filename;
  188. std::array<u8, 4> search_bytes;
  189. };
  190. static constexpr std::array<PEMCertificate, 3> certificates{{
  191. {"/clientca.pem", {{0x30, 0x82, 0x03, 0xE9}}},
  192. {"/clientcakey.pem", {{0x30, 0x82, 0x02, 0x5D}}},
  193. {"/rootca.pem", {{0x30, 0x82, 0x03, 0x7D}}},
  194. }};
  195. for (const PEMCertificate& certificate : certificates)
  196. {
  197. const auto search_result =
  198. std::search(content_bytes.begin(), content_bytes.end(), certificate.search_bytes.begin(),
  199. certificate.search_bytes.end());
  200. if (search_result == content_bytes.end())
  201. {
  202. ERROR_LOG_FMT(DISCIO, "ExtractCertificates: Could not find offset for certficate '{}'",
  203. certificate.filename);
  204. return false;
  205. }
  206. const std::string pem_file_path = m_nand_root + std::string(certificate.filename);
  207. const ptrdiff_t certificate_offset = std::distance(content_bytes.begin(), search_result);
  208. constexpr int min_offset = 2;
  209. if (certificate_offset < min_offset)
  210. {
  211. ERROR_LOG_FMT(
  212. DISCIO,
  213. "ExtractCertificates: Invalid certificate offset {:#x}, must be between {:#x} and {:#x}",
  214. certificate_offset, min_offset, content_bytes.size());
  215. return false;
  216. }
  217. const u16 certificate_size = Common::swap16(&content_bytes[certificate_offset - min_offset]);
  218. const size_t available_size = content_bytes.size() - static_cast<size_t>(certificate_offset);
  219. if (certificate_size > available_size)
  220. {
  221. ERROR_LOG_FMT(
  222. DISCIO,
  223. "ExtractCertificates: Invalid certificate size {:#x}, must be {:#x} bytes or smaller",
  224. certificate_size, available_size);
  225. return false;
  226. }
  227. INFO_LOG_FMT(DISCIO, "ExtractCertificates: '{}' offset: {:#x} size: {:#x}",
  228. certificate.filename, certificate_offset, certificate_size);
  229. File::IOFile pem_file(pem_file_path, "wb");
  230. if (!pem_file.WriteBytes(&content_bytes[certificate_offset], certificate_size))
  231. {
  232. ERROR_LOG_FMT(DISCIO, "ExtractCertificates: Unable to write to file {}", pem_file_path);
  233. return false;
  234. }
  235. }
  236. return true;
  237. }
  238. void NANDImporter::ExportKeys()
  239. {
  240. constexpr size_t NAND_AES_KEY_OFFSET = 0x158;
  241. m_aes_ctx = Common::AES::CreateContextDecrypt(&m_nand_keys[NAND_AES_KEY_OFFSET]);
  242. const std::string file_path = m_nand_root + "/keys.bin";
  243. File::IOFile file(file_path, "wb");
  244. if (!file.WriteBytes(m_nand_keys.data(), NAND_KEYS_SIZE))
  245. PanicAlertFmtT("Unable to write to file {0}", file_path);
  246. }
  247. } // namespace DiscIO