Debian Codegraph @

Source/Core/DiscIO/NANDImporter.cpp

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