Debian Codegraph @

Source/Core/DiscIO/VolumeWii.cpp

raw symbols SCIP
1 // Copyright 2008 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "DiscIO/VolumeWii.h"
5
6 #include <algorithm>
7 #include <array>
8 #include <cstddef>
9 #include <cstring>
10 #include <future>
11 #include <map>
12 #include <memory>
13 #include <optional>
14 #include <string>
15 #include <thread>
16 #include <utility>
17 #include <vector>
18
19 #include "Common/Align.h"
20 #include "Common/Assert.h"
21 #include "Common/CommonTypes.h"
22 #include "Common/Crypto/AES.h"
23 #include "Common/Crypto/SHA1.h"
24 #include "Common/Logging/Log.h"
25
26 #include "DiscIO/Blob.h"
27 #include "DiscIO/DiscExtractor.h"
28 #include "DiscIO/DiscUtils.h"
29 #include "DiscIO/Enums.h"
30 #include "DiscIO/FileSystemGCWii.h"
31 #include "DiscIO/Filesystem.h"
32 #include "DiscIO/Volume.h"
33 #include "DiscIO/WiiSaveBanner.h"
34
35 namespace DiscIO
36 {
37 VolumeWii::VolumeWii(std::unique_ptr<BlobReader> reader)
38 : m_reader(std::move(reader)), m_game_partition(PARTITION_NONE),
39 m_last_decrypted_block(UINT64_MAX)
40 {
41 ASSERT(m_reader);
42
43 m_has_hashes = m_reader->ReadSwapped<u8>(0x60) == u8(0);
44 m_has_encryption = m_reader->ReadSwapped<u8>(0x61) == u8(0);
45
46 if (m_has_encryption && !m_has_hashes)
47 ERROR_LOG_FMT(DISCIO, "Wii disc has encryption but no hashes! This probably won't work well");
48
49 for (u32 partition_group = 0; partition_group < 4; ++partition_group)
50 {
51 const std::optional<u32> number_of_partitions =
52 m_reader->ReadSwapped<u32>(0x40000 + (partition_group * 8));
53 if (!number_of_partitions)
54 continue;
55
56 const std::optional<u64> partition_table_offset =
57 ReadSwappedAndShifted(0x40000 + (partition_group * 8) + 4, PARTITION_NONE);
58 if (!partition_table_offset)
59 continue;
60
61 for (u32 i = 0; i < number_of_partitions; i++)
62 {
63 const std::optional<u64> partition_offset =
64 ReadSwappedAndShifted(*partition_table_offset + (i * 8), PARTITION_NONE);
65 if (!partition_offset)
66 continue;
67
68 const Partition partition(*partition_offset);
69
70 const std::optional<u32> partition_type =
71 m_reader->ReadSwapped<u32>(*partition_table_offset + (i * 8) + 4);
72 if (!partition_type)
73 continue;
74
75 // If this is the game partition, set m_game_partition
76 if (m_game_partition == PARTITION_NONE && *partition_type == 0)
77 m_game_partition = partition;
78
79 auto get_ticket = [this, partition]() -> IOS::ES::TicketReader {
80 std::vector<u8> ticket_buffer(sizeof(IOS::ES::Ticket));
81 if (!m_reader->Read(partition.offset, ticket_buffer.size(), ticket_buffer.data()))
82 return INVALID_TICKET;
83 return IOS::ES::TicketReader{std::move(ticket_buffer)};
84 };
85
86 auto get_tmd = [this, partition]() -> IOS::ES::TMDReader {
87 const std::optional<u32> tmd_size =
88 m_reader->ReadSwapped<u32>(partition.offset + WII_PARTITION_TMD_SIZE_ADDRESS);
89 const std::optional<u64> tmd_address = ReadSwappedAndShifted(
90 partition.offset + WII_PARTITION_TMD_OFFSET_ADDRESS, PARTITION_NONE);
91 if (!tmd_size || !tmd_address)
92 return INVALID_TMD;
93 if (!IOS::ES::IsValidTMDSize(*tmd_size))
94 {
95 // This check is normally done by ES in ES_DiVerify, but that would happen too late
96 // (after allocating the buffer), so we do the check here.
97 ERROR_LOG_FMT(DISCIO, "Invalid TMD size");
98 return INVALID_TMD;
99 }
100 std::vector<u8> tmd_buffer(*tmd_size);
101 if (!m_reader->Read(partition.offset + *tmd_address, *tmd_size, tmd_buffer.data()))
102 return INVALID_TMD;
103 return IOS::ES::TMDReader{std::move(tmd_buffer)};
104 };
105
106 auto get_cert_chain = [this, partition]() -> std::vector<u8> {
107 const std::optional<u32> size =
108 m_reader->ReadSwapped<u32>(partition.offset + WII_PARTITION_CERT_CHAIN_SIZE_ADDRESS);
109 const std::optional<u64> address = ReadSwappedAndShifted(
110 partition.offset + WII_PARTITION_CERT_CHAIN_OFFSET_ADDRESS, PARTITION_NONE);
111 if (!size || !address)
112 return {};
113 std::vector<u8> cert_chain(*size);
114 if (!m_reader->Read(partition.offset + *address, *size, cert_chain.data()))
115 return {};
116 return cert_chain;
117 };
118
119 auto get_h3_table = [this, partition]() -> std::vector<u8> {
120 if (!m_has_hashes)
121 return {};
122 const std::optional<u64> h3_table_offset = ReadSwappedAndShifted(
123 partition.offset + WII_PARTITION_H3_OFFSET_ADDRESS, PARTITION_NONE);
124 if (!h3_table_offset)
125 return {};
126 std::vector<u8> h3_table(WII_PARTITION_H3_SIZE);
127 if (!m_reader->Read(partition.offset + *h3_table_offset, WII_PARTITION_H3_SIZE,
128 h3_table.data()))
129 return {};
130 return h3_table;
131 };
132
133 auto get_key = [this, partition]() -> std::unique_ptr<Common::AES::Context> {
134 const IOS::ES::TicketReader& ticket = *m_partitions[partition].ticket;
135 if (!ticket.IsValid())
136 return nullptr;
137 return Common::AES::CreateContextDecrypt(ticket.GetTitleKey().data());
138 };
139
140 auto get_file_system = [this, partition]() -> std::unique_ptr<FileSystem> {
141 auto file_system = std::make_unique<FileSystemGCWii>(this, partition);
142 return file_system->IsValid() ? std::move(file_system) : nullptr;
143 };
144
145 auto get_data_offset = [this, partition]() -> u64 {
146 return ReadSwappedAndShifted(partition.offset + 0x2b8, PARTITION_NONE).value_or(0);
147 };
148
149 m_partitions.emplace(
150 partition, PartitionDetails{Common::Lazy<std::unique_ptr<Common::AES::Context>>(get_key),
151 Common::Lazy<IOS::ES::TicketReader>(get_ticket),
152 Common::Lazy<IOS::ES::TMDReader>(get_tmd),
153 Common::Lazy<std::vector<u8>>(get_cert_chain),
154 Common::Lazy<std::vector<u8>>(get_h3_table),
155 Common::Lazy<std::unique_ptr<FileSystem>>(get_file_system),
156 Common::Lazy<u64>(get_data_offset), *partition_type});
157 }
158 }
159 }
160
161 VolumeWii::~VolumeWii() = default;
162
163 bool VolumeWii::Read(u64 offset, u64 length, u8* buffer, const Partition& partition) const
164 {
165 if (partition == PARTITION_NONE)
166 return m_reader->Read(offset, length, buffer);
167
168 auto it = m_partitions.find(partition);
169 if (it == m_partitions.end())
170 return false;
171 const PartitionDetails& partition_details = it->second;
172
173 const u64 partition_data_offset = partition.offset + *partition_details.data_offset;
174 if (m_has_hashes && m_has_encryption &&
175 m_reader->SupportsReadWiiDecrypted(offset, length, partition_data_offset))
176 {
177 return m_reader->ReadWiiDecrypted(offset, length, buffer, partition_data_offset);
178 }
179
180 if (!m_has_hashes)
181 {
182 return m_reader->Read(partition_data_offset + offset, length, buffer);
183 }
184
185 Common::AES::Context* aes_context = nullptr;
186 std::unique_ptr<u8[]> read_buffer = nullptr;
187 if (m_has_encryption)
188 {
189 aes_context = partition_details.key->get();
190 if (!aes_context)
191 return false;
192
193 read_buffer = std::make_unique<u8[]>(BLOCK_TOTAL_SIZE);
194 }
195
196 while (length > 0)
197 {
198 // Calculate offsets
199 u64 block_offset_on_disc = partition_data_offset + offset / BLOCK_DATA_SIZE * BLOCK_TOTAL_SIZE;
200 u64 data_offset_in_block = offset % BLOCK_DATA_SIZE;
201
202 if (m_last_decrypted_block != block_offset_on_disc)
203 {
204 if (m_has_encryption)
205 {
206 // Read the current block
207 if (!m_reader->Read(block_offset_on_disc, BLOCK_TOTAL_SIZE, read_buffer.get()))
208 return false;
209
210 // Decrypt the block's data
211 DecryptBlockData(read_buffer.get(), m_last_decrypted_block_data, aes_context);
212 }
213 else
214 {
215 // Read the current block
216 if (!m_reader->Read(block_offset_on_disc + BLOCK_HEADER_SIZE, BLOCK_DATA_SIZE,
217 m_last_decrypted_block_data))
218 {
219 return false;
220 }
221 }
222
223 m_last_decrypted_block = block_offset_on_disc;
224 }
225
226 // Copy the decrypted data
227 u64 copy_size = std::min(length, BLOCK_DATA_SIZE - data_offset_in_block);
228 memcpy(buffer, &m_last_decrypted_block_data[data_offset_in_block],
229 static_cast<size_t>(copy_size));
230
231 // Update offsets
232 length -= copy_size;
233 buffer += copy_size;
234 offset += copy_size;
235 }
236
237 return true;
238 }
239
240 bool VolumeWii::HasWiiHashes() const
241 {
242 return m_has_hashes;
243 }
244
245 bool VolumeWii::HasWiiEncryption() const
246 {
247 return m_has_encryption;
248 }
249
250 std::vector<Partition> VolumeWii::GetPartitions() const
251 {
252 std::vector<Partition> partitions;
253 for (const auto& pair : m_partitions)
254 partitions.push_back(pair.first);
255 return partitions;
256 }
257
258 Partition VolumeWii::GetGamePartition() const
259 {
260 return m_game_partition;
261 }
262
263 std::optional<u32> VolumeWii::GetPartitionType(const Partition& partition) const
264 {
265 auto it = m_partitions.find(partition);
266 return it != m_partitions.end() ? it->second.type : std::optional<u32>();
267 }
268
269 std::optional<u64> VolumeWii::GetTitleID(const Partition& partition) const
270 {
271 const IOS::ES::TicketReader& ticket = GetTicket(partition);
272 if (!ticket.IsValid())
273 return {};
274 return ticket.GetTitleId();
275 }
276
277 const IOS::ES::TicketReader& VolumeWii::GetTicket(const Partition& partition) const
278 {
279 auto it = m_partitions.find(partition);
280 return it != m_partitions.end() ? *it->second.ticket : INVALID_TICKET;
281 }
282
283 const IOS::ES::TMDReader& VolumeWii::GetTMD(const Partition& partition) const
284 {
285 auto it = m_partitions.find(partition);
286 return it != m_partitions.end() ? *it->second.tmd : INVALID_TMD;
287 }
288
289 const std::vector<u8>& VolumeWii::GetCertificateChain(const Partition& partition) const
290 {
291 auto it = m_partitions.find(partition);
292 return it != m_partitions.end() ? *it->second.cert_chain : INVALID_CERT_CHAIN;
293 }
294
295 const FileSystem* VolumeWii::GetFileSystem(const Partition& partition) const
296 {
297 auto it = m_partitions.find(partition);
298 return it != m_partitions.end() ? it->second.file_system->get() : nullptr;
299 }
300
301 u64 VolumeWii::OffsetInHashedPartitionToRawOffset(u64 offset, const Partition& partition,
302 u64 partition_data_offset)
303 {
304 if (partition == PARTITION_NONE)
305 return offset;
306
307 return partition.offset + partition_data_offset + (offset / BLOCK_DATA_SIZE * BLOCK_TOTAL_SIZE) +
308 (offset % BLOCK_DATA_SIZE);
309 }
310
311 u64 VolumeWii::PartitionOffsetToRawOffset(u64 offset, const Partition& partition) const
312 {
313 auto it = m_partitions.find(partition);
314 if (it == m_partitions.end())
315 return offset;
316 const u64 data_offset = *it->second.data_offset;
317
318 if (!m_has_hashes)
319 return partition.offset + data_offset + offset;
320
321 return OffsetInHashedPartitionToRawOffset(offset, partition, data_offset);
322 }
323
324 std::string VolumeWii::GetGameTDBID(const Partition& partition) const
325 {
326 return GetGameID(partition);
327 }
328
329 Region VolumeWii::GetRegion() const
330 {
331 return RegionCodeToRegion(m_reader->ReadSwapped<u32>(0x4E000));
332 }
333
334 std::map<Language, std::string> VolumeWii::GetLongNames() const
335 {
336 std::vector<char16_t> names(NAMES_TOTAL_CHARS);
337 names.resize(ReadFile(*this, GetGamePartition(), "opening.bnr",
338 reinterpret_cast<u8*>(names.data()), NAMES_TOTAL_BYTES, 0x5C));
339 return ReadWiiNames(names);
340 }
341
342 std::vector<u32> VolumeWii::GetBanner(u32* width, u32* height) const
343 {
344 *width = 0;
345 *height = 0;
346
347 const std::optional<u64> title_id = GetTitleID(GetGamePartition());
348 if (!title_id)
349 return std::vector<u32>();
350
351 return WiiSaveBanner(*title_id).GetBanner(width, height);
352 }
353
354 Platform VolumeWii::GetVolumeType() const
355 {
356 return Platform::WiiDisc;
357 }
358
359 bool VolumeWii::IsDatelDisc() const
360 {
361 return m_game_partition == PARTITION_NONE;
362 }
363
364 BlobType VolumeWii::GetBlobType() const
365 {
366 return m_reader->GetBlobType();
367 }
368
369 u64 VolumeWii::GetDataSize() const
370 {
371 return m_reader->GetDataSize();
372 }
373
374 DataSizeType VolumeWii::GetDataSizeType() const
375 {
376 return m_reader->GetDataSizeType();
377 }
378
379 u64 VolumeWii::GetRawSize() const
380 {
381 return m_reader->GetRawSize();
382 }
383
384 const BlobReader& VolumeWii::GetBlobReader() const
385 {
386 return *m_reader;
387 }
388
389 std::array<u8, 20> VolumeWii::GetSyncHash() const
390 {
391 auto context = Common::SHA1::CreateContext();
392
393 // Disc header
394 ReadAndAddToSyncHash(context.get(), 0, 0x80, PARTITION_NONE);
395
396 // Region code
397 ReadAndAddToSyncHash(context.get(), 0x4E000, 4, PARTITION_NONE);
398
399 // The data offset of the game partition - an important factor for disc drive timings
400 const u64 data_offset = PartitionOffsetToRawOffset(0, GetGamePartition());
401 context->Update(reinterpret_cast<const u8*>(&data_offset), sizeof(data_offset));
402
403 // TMD
404 AddTMDToSyncHash(context.get(), GetGamePartition());
405
406 // Game partition contents
407 AddGamePartitionToSyncHash(context.get());
408
409 return context->Finish();
410 }
411
412 bool VolumeWii::CheckH3TableIntegrity(const Partition& partition) const
413 {
414 auto it = m_partitions.find(partition);
415 if (it == m_partitions.end())
416 return false;
417 const PartitionDetails& partition_details = it->second;
418
419 const std::vector<u8>& h3_table = *partition_details.h3_table;
420 if (h3_table.size() != WII_PARTITION_H3_SIZE)
421 return false;
422
423 const IOS::ES::TMDReader& tmd = *partition_details.tmd;
424 if (!tmd.IsValid())
425 return false;
426
427 const std::vector<IOS::ES::Content> contents = tmd.GetContents();
428 if (contents.size() != 1)
429 return false;
430
431 return Common::SHA1::CalculateDigest(h3_table) == contents[0].sha1;
432 }
433
434 bool VolumeWii::CheckBlockIntegrity(u64 block_index, const u8* encrypted_data,
435 const Partition& partition) const
436 {
437 auto it = m_partitions.find(partition);
438 if (it == m_partitions.end())
439 return false;
440 const PartitionDetails& partition_details = it->second;
441
442 if (block_index / BLOCKS_PER_GROUP * Common::SHA1::DIGEST_LEN >=
443 partition_details.h3_table->size())
444 {
445 return false;
446 }
447
448 HashBlock hashes;
449 u8 cluster_data_buffer[BLOCK_DATA_SIZE];
450 const u8* cluster_data;
451
452 if (m_has_encryption)
453 {
454 Common::AES::Context* aes_context = partition_details.key->get();
455 if (!aes_context)
456 return false;
457
458 DecryptBlockHashes(encrypted_data, &hashes, aes_context);
459 DecryptBlockData(encrypted_data, cluster_data_buffer, aes_context);
460 cluster_data = cluster_data_buffer;
461 }
462 else
463 {
464 std::memcpy(&hashes, encrypted_data, BLOCK_HEADER_SIZE);
465 cluster_data = encrypted_data + BLOCK_HEADER_SIZE;
466 }
467
468 for (u32 hash_index = 0; hash_index < 31; ++hash_index)
469 {
470 if (Common::SHA1::CalculateDigest(&cluster_data[hash_index * 0x400], 0x400) !=
471 hashes.h0[hash_index])
472 {
473 return false;
474 }
475 }
476
477 if (Common::SHA1::CalculateDigest(hashes.h0) != hashes.h1[block_index % 8])
478 return false;
479
480 if (Common::SHA1::CalculateDigest(hashes.h1) != hashes.h2[block_index / 8 % 8])
481 return false;
482
483 Common::SHA1::Digest h3_digest;
484 auto h3_digest_ptr =
485 partition_details.h3_table->data() + block_index / 64 * Common::SHA1::DIGEST_LEN;
486 memcpy(h3_digest.data(), h3_digest_ptr, sizeof(h3_digest));
487 if (Common::SHA1::CalculateDigest(hashes.h2) != h3_digest)
488 return false;
489
490 return true;
491 }
492
493 bool VolumeWii::CheckBlockIntegrity(u64 block_index, const Partition& partition) const
494 {
495 auto it = m_partitions.find(partition);
496 if (it == m_partitions.end())
497 return false;
498 const PartitionDetails& partition_details = it->second;
499 const u64 cluster_offset =
500 partition.offset + *partition_details.data_offset + block_index * BLOCK_TOTAL_SIZE;
501
502 std::vector<u8> cluster(BLOCK_TOTAL_SIZE);
503 if (!m_reader->Read(cluster_offset, cluster.size(), cluster.data()))
504 return false;
505 return CheckBlockIntegrity(block_index, cluster.data(), partition);
506 }
507
508 bool VolumeWii::HashGroup(const std::array<u8, BLOCK_DATA_SIZE> in[BLOCKS_PER_GROUP],
509 HashBlock out[BLOCKS_PER_GROUP],
510 const std::function<bool(size_t block)>& read_function)
511 {
512 std::array<std::future<void>, BLOCKS_PER_GROUP> hash_futures;
513 bool success = true;
514
515 for (size_t i = 0; i < BLOCKS_PER_GROUP; ++i)
516 {
517 if (read_function && success)
518 success = read_function(i);
519
520 hash_futures[i] = std::async(std::launch::async, [&in, &out, &hash_futures, success, i] {
521 const size_t h1_base = Common::AlignDown(i, 8);
522
523 if (success)
524 {
525 // H0 hashes
526 for (size_t j = 0; j < 31; ++j)
527 out[i].h0[j] = Common::SHA1::CalculateDigest(in[i].data() + j * 0x400, 0x400);
528
529 // H0 padding
530 out[i].padding_0 = {};
531
532 // H1 hash
533 out[h1_base].h1[i - h1_base] = Common::SHA1::CalculateDigest(out[i].h0);
534 }
535
536 if (i % 8 == 7)
537 {
538 for (size_t j = 0; j < 7; ++j)
539 hash_futures[h1_base + j].get();
540
541 if (success)
542 {
543 // H1 padding
544 out[h1_base].padding_1 = {};
545
546 // H1 copies
547 for (size_t j = 1; j < 8; ++j)
548 out[h1_base + j].h1 = out[h1_base].h1;
549
550 // H2 hash
551 out[0].h2[h1_base / 8] = Common::SHA1::CalculateDigest(out[i].h1);
552 }
553
554 if (i == BLOCKS_PER_GROUP - 1)
555 {
556 for (size_t j = 0; j < 7; ++j)
557 hash_futures[j * 8 + 7].get();
558
559 if (success)
560 {
561 // H2 padding
562 out[0].padding_2 = {};
563
564 // H2 copies
565 for (size_t j = 1; j < BLOCKS_PER_GROUP; ++j)
566 out[j].h2 = out[0].h2;
567 }
568 }
569 }
570 });
571 }
572
573 // Wait for all the async tasks to finish
574 hash_futures.back().get();
575
576 return success;
577 }
578
579 bool VolumeWii::EncryptGroup(
580 u64 offset, u64 partition_data_offset, u64 partition_data_decrypted_size,
581 const std::array<u8, AES_KEY_SIZE>& key, BlobReader* blob,
582 std::array<u8, GROUP_TOTAL_SIZE>* out,
583 const std::function<void(HashBlock hash_blocks[BLOCKS_PER_GROUP])>& hash_exception_callback)
584 {
585 std::vector<std::array<u8, BLOCK_DATA_SIZE>> unencrypted_data(BLOCKS_PER_GROUP);
586 std::vector<HashBlock> unencrypted_hashes(BLOCKS_PER_GROUP);
587
588 const bool success =
589 HashGroup(unencrypted_data.data(), unencrypted_hashes.data(), [&](size_t block) {
590 if (offset + (block + 1) * BLOCK_DATA_SIZE <= partition_data_decrypted_size)
591 {
592 if (!blob->ReadWiiDecrypted(offset + block * BLOCK_DATA_SIZE, BLOCK_DATA_SIZE,
593 unencrypted_data[block].data(), partition_data_offset))
594 {
595 return false;
596 }
597 }
598 else
599 {
600 unencrypted_data[block].fill(0);
601 }
602 return true;
603 });
604
605 if (!success)
606 return false;
607
608 if (hash_exception_callback)
609 hash_exception_callback(unencrypted_hashes.data());
610
611 const unsigned int threads =
612 std::min(BLOCKS_PER_GROUP, std::max<unsigned int>(1, std::thread::hardware_concurrency()));
613
614 std::vector<std::future<void>> encryption_futures(threads);
615
616 auto aes_context = Common::AES::CreateContextEncrypt(key.data());
617
618 for (size_t i = 0; i < threads; ++i)
619 {
620 encryption_futures[i] = std::async(
621 std::launch::async,
622 [&unencrypted_data, &unencrypted_hashes, &aes_context, &out](size_t start, size_t end) {
623 for (size_t j = start; j < end; ++j)
624 {
625 u8* out_ptr = out->data() + j * BLOCK_TOTAL_SIZE;
626
627 aes_context->CryptIvZero(reinterpret_cast<u8*>(&unencrypted_hashes[j]), out_ptr,
628 BLOCK_HEADER_SIZE);
629
630 aes_context->Crypt(out_ptr + 0x3D0, unencrypted_data[j].data(),
631 out_ptr + BLOCK_HEADER_SIZE, BLOCK_DATA_SIZE);
632 }
633 },
634 i * BLOCKS_PER_GROUP / threads, (i + 1) * BLOCKS_PER_GROUP / threads);
635 }
636
637 for (std::future<void>& future : encryption_futures)
638 future.get();
639
640 return true;
641 }
642
643 void VolumeWii::DecryptBlockHashes(const u8* in, HashBlock* out, Common::AES::Context* aes_context)
644 {
645 aes_context->CryptIvZero(in, reinterpret_cast<u8*>(out), sizeof(HashBlock));
646 }
647
648 void VolumeWii::DecryptBlockData(const u8* in, u8* out, Common::AES::Context* aes_context)
649 {
650 aes_context->Crypt(&in[0x3d0], &in[sizeof(HashBlock)], out, BLOCK_DATA_SIZE);
651 }
652
653 } // namespace DiscIO