Compare commits

...
Author SHA1 Message Date
yuzubot f7dbd26d72 "Merge Tagged PR 10048" 2023-09-02 12:03:40 +00:00
yuzubot 12853b37f7 "Merge Tagged PR 11381" 2023-09-02 12:03:38 +00:00
yuzubot 8babcd8003 "Merge Tagged PR 11384" 2023-09-02 12:03:37 +00:00
yuzubot 8644d98436 "Merge Tagged PR 11385" 2023-09-02 12:03:36 +00:00
yuzubot 78e33341b9 "Merge Tagged PR 11412" 2023-09-02 12:03:35 +00:00
13 changed files with 396 additions and 212 deletions

No files matched your search

+20 -7
View File
@@ -273,7 +273,8 @@ struct System::Impl {
time_manager.Initialize();
is_powered_on = true;
exit_lock = false;
exit_locked = false;
exit_requested = false;
microprofile_cpu[0] = MICROPROFILE_TOKEN(ARM_CPU0);
microprofile_cpu[1] = MICROPROFILE_TOKEN(ARM_CPU1);
@@ -398,12 +399,14 @@ struct System::Impl {
}
is_powered_on = false;
exit_lock = false;
exit_locked = false;
exit_requested = false;
if (gpu_core != nullptr) {
gpu_core->NotifyShutdown();
}
Network::CancelPendingSocketOperations();
kernel.SuspendApplication(true);
if (services) {
services->KillNVNFlinger();
@@ -425,6 +428,7 @@ struct System::Impl {
debugger.reset();
kernel.Shutdown();
memory.Reset();
Network::RestartSocketOperations();
if (auto room_member = room_network.GetRoomMember().lock()) {
Network::GameInfo game_info{};
@@ -507,7 +511,8 @@ struct System::Impl {
CpuManager cpu_manager;
std::atomic_bool is_powered_on{};
bool exit_lock = false;
bool exit_locked = false;
bool exit_requested = false;
bool nvdec_active{};
@@ -943,12 +948,20 @@ const Service::Time::TimeManager& System::GetTimeManager() const {
return impl->time_manager;
}
void System::SetExitLock(bool locked) {
impl->exit_lock = locked;
void System::SetExitLocked(bool locked) {
impl->exit_locked = locked;
}
bool System::GetExitLock() const {
return impl->exit_lock;
bool System::GetExitLocked() const {
return impl->exit_locked;
}
void System::SetExitRequested(bool requested) {
impl->exit_requested = requested;
}
bool System::GetExitRequested() const {
return impl->exit_requested;
}
void System::SetApplicationProcessBuildID(const CurrentBuildProcessID& id) {
+5 -2
View File
@@ -412,8 +412,11 @@ public:
/// Gets an immutable reference to the Room Network.
[[nodiscard]] const Network::RoomNetwork& GetRoomNetwork() const;
void SetExitLock(bool locked);
[[nodiscard]] bool GetExitLock() const;
void SetExitLocked(bool locked);
bool GetExitLocked() const;
void SetExitRequested(bool requested);
bool GetExitRequested() const;
void SetApplicationProcessBuildID(const CurrentBuildProcessID& id);
[[nodiscard]] const CurrentBuildProcessID& GetApplicationProcessBuildID() const;
+138 -90
View File
@@ -35,7 +35,6 @@ namespace Core::Crypto {
namespace {
constexpr u64 CURRENT_CRYPTO_REVISION = 0x5;
constexpr u64 FULL_TICKET_SIZE = 0x400;
using Common::AsArray;
@@ -156,6 +155,10 @@ u64 GetSignatureTypePaddingSize(SignatureType type) {
UNREACHABLE();
}
bool Ticket::IsValid() const {
return !std::holds_alternative<std::monostate>(data);
}
SignatureType Ticket::GetSignatureType() const {
if (const auto* ticket = std::get_if<RSA4096Ticket>(&data)) {
return ticket->sig_type;
@@ -210,6 +213,54 @@ Ticket Ticket::SynthesizeCommon(Key128 title_key, const std::array<u8, 16>& righ
return Ticket{out};
}
Ticket Ticket::Read(const FileSys::VirtualFile& file) {
// Attempt to read up to the largest ticket size, and make sure we read at least a signature
// type.
std::array<u8, sizeof(RSA4096Ticket)> raw_data{};
auto read_size = file->Read(raw_data.data(), raw_data.size(), 0);
if (read_size < sizeof(SignatureType)) {
LOG_WARNING(Crypto, "Attempted to read ticket file with invalid size {}.", read_size);
return Ticket{std::monostate()};
}
return Read(std::span{raw_data});
}
Ticket Ticket::Read(std::span<const u8> raw_data) {
// Some tools read only 0x180 bytes of ticket data instead of 0x2C0, so
// just make sure we have at least the bare minimum of data to work with.
SignatureType sig_type;
if (raw_data.size() < sizeof(SignatureType)) {
LOG_WARNING(Crypto, "Attempted to parse ticket buffer with invalid size {}.",
raw_data.size());
return Ticket{std::monostate()};
}
std::memcpy(&sig_type, raw_data.data(), sizeof(sig_type));
switch (sig_type) {
case SignatureType::RSA_4096_SHA1:
case SignatureType::RSA_4096_SHA256: {
RSA4096Ticket ticket{};
std::memcpy(&ticket, raw_data.data(), sizeof(ticket));
return Ticket{ticket};
}
case SignatureType::RSA_2048_SHA1:
case SignatureType::RSA_2048_SHA256: {
RSA2048Ticket ticket{};
std::memcpy(&ticket, raw_data.data(), sizeof(ticket));
return Ticket{ticket};
}
case SignatureType::ECDSA_SHA1:
case SignatureType::ECDSA_SHA256: {
ECDSATicket ticket{};
std::memcpy(&ticket, raw_data.data(), sizeof(ticket));
return Ticket{ticket};
}
default:
LOG_WARNING(Crypto, "Attempted to parse ticket buffer with invalid type {}.", sig_type);
return Ticket{std::monostate()};
}
}
Key128 GenerateKeyEncryptionKey(Key128 source, Key128 master, Key128 kek_seed, Key128 key_seed) {
Key128 out{};
@@ -290,9 +341,9 @@ void KeyManager::DeriveGeneralPurposeKeys(std::size_t crypto_revision) {
}
}
RSAKeyPair<2048> KeyManager::GetETicketRSAKey() const {
void KeyManager::DeriveETicketRSAKey() {
if (IsAllZeroArray(eticket_extended_kek) || !HasKey(S128KeyType::ETicketRSAKek)) {
return {};
return;
}
const auto eticket_final = GetKey(S128KeyType::ETicketRSAKek);
@@ -304,12 +355,12 @@ RSAKeyPair<2048> KeyManager::GetETicketRSAKey() const {
rsa_1.Transcode(eticket_extended_kek.data() + 0x10, eticket_extended_kek.size() - 0x10,
extended_dec.data(), Op::Decrypt);
RSAKeyPair<2048> rsa_key{};
std::memcpy(rsa_key.decryption_key.data(), extended_dec.data(), rsa_key.decryption_key.size());
std::memcpy(rsa_key.modulus.data(), extended_dec.data() + 0x100, rsa_key.modulus.size());
std::memcpy(rsa_key.exponent.data(), extended_dec.data() + 0x200, rsa_key.exponent.size());
return rsa_key;
std::memcpy(eticket_rsa_keypair.decryption_key.data(), extended_dec.data(),
eticket_rsa_keypair.decryption_key.size());
std::memcpy(eticket_rsa_keypair.modulus.data(), extended_dec.data() + 0x100,
eticket_rsa_keypair.modulus.size());
std::memcpy(eticket_rsa_keypair.exponent.data(), extended_dec.data() + 0x200,
eticket_rsa_keypair.exponent.size());
}
Key128 DeriveKeyblobMACKey(const Key128& keyblob_key, const Key128& mac_source) {
@@ -447,10 +498,12 @@ std::vector<Ticket> GetTicketblob(const Common::FS::IOFile& ticket_save) {
for (std::size_t offset = 0; offset + 0x4 < buffer.size(); ++offset) {
if (buffer[offset] == 0x4 && buffer[offset + 1] == 0x0 && buffer[offset + 2] == 0x1 &&
buffer[offset + 3] == 0x0) {
out.emplace_back();
auto& next = out.back();
std::memcpy(&next, buffer.data() + offset, sizeof(Ticket));
offset += FULL_TICKET_SIZE;
// NOTE: Assumes ticket blob will only contain RSA-2048 tickets.
auto ticket = Ticket::Read(std::span{buffer.data() + offset, sizeof(RSA2048Ticket)});
offset += sizeof(RSA2048Ticket);
if (ticket.IsValid()) {
out.push_back(ticket);
}
}
}
@@ -503,27 +556,38 @@ static std::optional<u64> FindTicketOffset(const std::array<u8, size>& data) {
return offset;
}
std::optional<std::pair<Key128, Key128>> ParseTicket(const Ticket& ticket,
const RSAKeyPair<2048>& key) {
std::optional<Key128> KeyManager::ParseTicketTitleKey(const Ticket& ticket) {
if (!ticket.IsValid()) {
LOG_WARNING(Crypto, "Attempted to parse title key of invalid ticket.");
return std::nullopt;
}
if (ticket.GetData().rights_id == Key128{}) {
LOG_WARNING(Crypto, "Attempted to parse title key of ticket with no rights ID.");
return std::nullopt;
}
const auto issuer = ticket.GetData().issuer;
if (IsAllZeroArray(issuer)) {
LOG_WARNING(Crypto, "Attempted to parse title key of ticket with invalid issuer.");
return std::nullopt;
}
if (issuer[0] != 'R' || issuer[1] != 'o' || issuer[2] != 'o' || issuer[3] != 't') {
LOG_INFO(Crypto, "Attempting to parse ticket with non-standard certificate authority.");
LOG_WARNING(Crypto, "Parsing ticket with non-standard certificate authority.");
}
Key128 rights_id = ticket.GetData().rights_id;
if (ticket.GetData().type == TitleKeyType::Common) {
return ticket.GetData().title_key_common;
}
if (rights_id == Key128{}) {
if (eticket_rsa_keypair == RSAKeyPair<2048>{}) {
LOG_WARNING(
Crypto,
"Skipping personalized ticket title key parsing due to missing ETicket RSA key-pair.");
return std::nullopt;
}
if (!std::any_of(ticket.GetData().title_key_common_pad.begin(),
ticket.GetData().title_key_common_pad.end(), [](u8 b) { return b != 0; })) {
return std::make_pair(rights_id, ticket.GetData().title_key_common);
}
mbedtls_mpi D; // RSA Private Exponent
mbedtls_mpi N; // RSA Modulus
mbedtls_mpi S; // Input
@@ -534,9 +598,12 @@ std::optional<std::pair<Key128, Key128>> ParseTicket(const Ticket& ticket,
mbedtls_mpi_init(&S);
mbedtls_mpi_init(&M);
mbedtls_mpi_read_binary(&D, key.decryption_key.data(), key.decryption_key.size());
mbedtls_mpi_read_binary(&N, key.modulus.data(), key.modulus.size());
mbedtls_mpi_read_binary(&S, ticket.GetData().title_key_block.data(), 0x100);
const auto& title_key_block = ticket.GetData().title_key_block;
mbedtls_mpi_read_binary(&D, eticket_rsa_keypair.decryption_key.data(),
eticket_rsa_keypair.decryption_key.size());
mbedtls_mpi_read_binary(&N, eticket_rsa_keypair.modulus.data(),
eticket_rsa_keypair.modulus.size());
mbedtls_mpi_read_binary(&S, title_key_block.data(), title_key_block.size());
mbedtls_mpi_exp_mod(&M, &S, &D, &N, nullptr);
@@ -564,8 +631,7 @@ std::optional<std::pair<Key128, Key128>> ParseTicket(const Ticket& ticket,
Key128 key_temp{};
std::memcpy(key_temp.data(), m_2.data() + *offset, key_temp.size());
return std::make_pair(rights_id, key_temp);
return key_temp;
}
KeyManager::KeyManager() {
@@ -669,6 +735,14 @@ void KeyManager::LoadFromFile(const std::filesystem::path& file_path, bool is_ti
encrypted_keyblobs[index] = Common::HexStringToArray<0xB0>(out[1]);
} else if (out[0].compare(0, 20, "eticket_extended_kek") == 0) {
eticket_extended_kek = Common::HexStringToArray<576>(out[1]);
} else if (out[0].compare(0, 19, "eticket_rsa_keypair") == 0) {
const auto key_data = Common::HexStringToArray<528>(out[1]);
std::memcpy(eticket_rsa_keypair.decryption_key.data(), key_data.data(),
eticket_rsa_keypair.decryption_key.size());
std::memcpy(eticket_rsa_keypair.modulus.data(), key_data.data() + 0x100,
eticket_rsa_keypair.modulus.size());
std::memcpy(eticket_rsa_keypair.exponent.data(), key_data.data() + 0x200,
eticket_rsa_keypair.exponent.size());
} else {
for (const auto& kv : KEYS_VARIABLE_LENGTH) {
if (!ValidCryptoRevisionString(out[0], kv.second.size(), 2)) {
@@ -1110,56 +1184,38 @@ void KeyManager::DeriveETicket(PartitionDataManager& data,
eticket_extended_kek = data.GetETicketExtendedKek();
WriteKeyToFile(KeyCategory::Console, "eticket_extended_kek", eticket_extended_kek);
DeriveETicketRSAKey();
PopulateTickets();
}
void KeyManager::PopulateTickets() {
const auto rsa_key = GetETicketRSAKey();
if (rsa_key == RSAKeyPair<2048>{}) {
if (ticket_databases_loaded) {
return;
}
ticket_databases_loaded = true;
if (!common_tickets.empty() && !personal_tickets.empty()) {
return;
}
std::vector<Ticket> tickets;
const auto system_save_e1_path =
Common::FS::GetYuzuPath(Common::FS::YuzuPath::NANDDir) / "system/save/80000000000000e1";
const Common::FS::IOFile save_e1{system_save_e1_path, Common::FS::FileAccessMode::Read,
Common::FS::FileType::BinaryFile};
if (Common::FS::Exists(system_save_e1_path)) {
const Common::FS::IOFile save_e1{system_save_e1_path, Common::FS::FileAccessMode::Read,
Common::FS::FileType::BinaryFile};
const auto blob1 = GetTicketblob(save_e1);
tickets.insert(tickets.end(), blob1.begin(), blob1.end());
}
const auto system_save_e2_path =
Common::FS::GetYuzuPath(Common::FS::YuzuPath::NANDDir) / "system/save/80000000000000e2";
if (Common::FS::Exists(system_save_e2_path)) {
const Common::FS::IOFile save_e2{system_save_e2_path, Common::FS::FileAccessMode::Read,
Common::FS::FileType::BinaryFile};
const auto blob2 = GetTicketblob(save_e2);
tickets.insert(tickets.end(), blob2.begin(), blob2.end());
}
const Common::FS::IOFile save_e2{system_save_e2_path, Common::FS::FileAccessMode::Read,
Common::FS::FileType::BinaryFile};
const auto blob2 = GetTicketblob(save_e2);
auto res = GetTicketblob(save_e1);
const auto idx = res.size();
res.insert(res.end(), blob2.begin(), blob2.end());
for (std::size_t i = 0; i < res.size(); ++i) {
const auto common = i < idx;
const auto pair = ParseTicket(res[i], rsa_key);
if (!pair) {
continue;
}
const auto& [rid, key] = *pair;
u128 rights_id;
std::memcpy(rights_id.data(), rid.data(), rid.size());
if (common) {
common_tickets[rights_id] = res[i];
} else {
personal_tickets[rights_id] = res[i];
}
SetKey(S128KeyType::Titlekey, key, rights_id[1], rights_id[0]);
for (const auto& ticket : tickets) {
AddTicket(ticket);
}
}
@@ -1291,41 +1347,33 @@ const std::map<u128, Ticket>& KeyManager::GetPersonalizedTickets() const {
return personal_tickets;
}
bool KeyManager::AddTicketCommon(Ticket raw) {
const auto rsa_key = GetETicketRSAKey();
if (rsa_key == RSAKeyPair<2048>{}) {
bool KeyManager::AddTicket(const Ticket& ticket) {
if (!ticket.IsValid()) {
LOG_WARNING(Crypto, "Attempted to add invalid ticket.");
return false;
}
const auto pair = ParseTicket(raw, rsa_key);
if (!pair) {
return false;
}
const auto& [rid, key] = *pair;
const auto& rid = ticket.GetData().rights_id;
u128 rights_id;
std::memcpy(rights_id.data(), rid.data(), rid.size());
common_tickets[rights_id] = raw;
SetKey(S128KeyType::Titlekey, key, rights_id[1], rights_id[0]);
return true;
}
bool KeyManager::AddTicketPersonalized(Ticket raw) {
const auto rsa_key = GetETicketRSAKey();
if (rsa_key == RSAKeyPair<2048>{}) {
return false;
if (ticket.GetData().type == Core::Crypto::TitleKeyType::Common) {
common_tickets[rights_id] = ticket;
} else {
personal_tickets[rights_id] = ticket;
}
const auto pair = ParseTicket(raw, rsa_key);
if (!pair) {
return false;
if (HasKey(S128KeyType::Titlekey, rights_id[1], rights_id[0])) {
LOG_DEBUG(Crypto,
"Skipping parsing title key from ticket for known rights ID {:016X}{:016X}.",
rights_id[1], rights_id[0]);
return true;
}
const auto& [rid, key] = *pair;
u128 rights_id;
std::memcpy(rights_id.data(), rid.data(), rid.size());
common_tickets[rights_id] = raw;
SetKey(S128KeyType::Titlekey, key, rights_id[1], rights_id[0]);
const auto key = ParseTicketTitleKey(ticket);
if (!key) {
return false;
}
SetKey(S128KeyType::Titlekey, key.value(), rights_id[1], rights_id[0]);
return true;
}
} // namespace Core::Crypto
+40 -15
View File
@@ -7,6 +7,7 @@
#include <filesystem>
#include <map>
#include <optional>
#include <span>
#include <string>
#include <variant>
@@ -29,8 +30,6 @@ enum class ResultStatus : u16;
namespace Core::Crypto {
constexpr u64 TICKET_FILE_TITLEKEY_OFFSET = 0x180;
using Key128 = std::array<u8, 0x10>;
using Key256 = std::array<u8, 0x20>;
using SHA256Hash = std::array<u8, 0x20>;
@@ -82,6 +81,7 @@ struct RSA4096Ticket {
INSERT_PADDING_BYTES(0x3C);
TicketData data;
};
static_assert(sizeof(RSA4096Ticket) == 0x500, "RSA4096Ticket has incorrect size.");
struct RSA2048Ticket {
SignatureType sig_type;
@@ -89,6 +89,7 @@ struct RSA2048Ticket {
INSERT_PADDING_BYTES(0x3C);
TicketData data;
};
static_assert(sizeof(RSA2048Ticket) == 0x400, "RSA2048Ticket has incorrect size.");
struct ECDSATicket {
SignatureType sig_type;
@@ -96,16 +97,41 @@ struct ECDSATicket {
INSERT_PADDING_BYTES(0x40);
TicketData data;
};
static_assert(sizeof(ECDSATicket) == 0x340, "ECDSATicket has incorrect size.");
struct Ticket {
std::variant<RSA4096Ticket, RSA2048Ticket, ECDSATicket> data;
std::variant<std::monostate, RSA4096Ticket, RSA2048Ticket, ECDSATicket> data;
SignatureType GetSignatureType() const;
TicketData& GetData();
const TicketData& GetData() const;
u64 GetSize() const;
[[nodiscard]] bool IsValid() const;
[[nodiscard]] SignatureType GetSignatureType() const;
[[nodiscard]] TicketData& GetData();
[[nodiscard]] const TicketData& GetData() const;
[[nodiscard]] u64 GetSize() const;
/**
* Synthesizes a common ticket given a title key and rights ID.
*
* @param title_key Title key to store in the ticket.
* @param rights_id Rights ID the ticket is for.
* @return The synthesized common ticket.
*/
static Ticket SynthesizeCommon(Key128 title_key, const std::array<u8, 0x10>& rights_id);
/**
* Reads a ticket from a file.
*
* @param file File to read the ticket from.
* @return The read ticket. If the ticket data is invalid, Ticket::IsValid() will be false.
*/
static Ticket Read(const FileSys::VirtualFile& file);
/**
* Reads a ticket from a memory buffer.
*
* @param raw_data Buffer to read the ticket from.
* @return The read ticket. If the ticket data is invalid, Ticket::IsValid() will be false.
*/
static Ticket Read(std::span<const u8> raw_data);
};
static_assert(sizeof(Key128) == 16, "Key128 must be 128 bytes big.");
@@ -264,8 +290,7 @@ public:
const std::map<u128, Ticket>& GetCommonTickets() const;
const std::map<u128, Ticket>& GetPersonalizedTickets() const;
bool AddTicketCommon(Ticket raw);
bool AddTicketPersonalized(Ticket raw);
bool AddTicket(const Ticket& ticket);
void ReloadKeys();
bool AreKeysLoaded() const;
@@ -279,10 +304,12 @@ private:
// Map from rights ID to ticket
std::map<u128, Ticket> common_tickets;
std::map<u128, Ticket> personal_tickets;
bool ticket_databases_loaded = false;
std::array<std::array<u8, 0xB0>, 0x20> encrypted_keyblobs{};
std::array<std::array<u8, 0x90>, 0x20> keyblobs{};
std::array<u8, 576> eticket_extended_kek{};
RSAKeyPair<2048> eticket_rsa_keypair{};
bool dev_mode;
void LoadFromFile(const std::filesystem::path& file_path, bool is_title_keys);
@@ -293,10 +320,13 @@ private:
void DeriveGeneralPurposeKeys(std::size_t crypto_revision);
RSAKeyPair<2048> GetETicketRSAKey() const;
void DeriveETicketRSAKey();
void SetKeyWrapped(S128KeyType id, Key128 key, u64 field1 = 0, u64 field2 = 0);
void SetKeyWrapped(S256KeyType id, Key256 key, u64 field1 = 0, u64 field2 = 0);
/// Parses the title key section of a ticket.
std::optional<Key128> ParseTicketTitleKey(const Ticket& ticket);
};
Key128 GenerateKeyEncryptionKey(Key128 source, Key128 master, Key128 kek_seed, Key128 key_seed);
@@ -311,9 +341,4 @@ Loader::ResultStatus DeriveSDKeys(std::array<Key256, 2>& sd_keys, KeyManager& ke
std::vector<Ticket> GetTicketblob(const Common::FS::IOFile& ticket_save);
// Returns a pair of {rights_id, titlekey}. Fails if the ticket has no certificate authority
// (offset 0x140-0x144 is zero)
std::optional<std::pair<Key128, Key128>> ParseTicket(const Ticket& ticket,
const RSAKeyPair<2048>& eticket_extended_key);
} // namespace Core::Crypto
+13 -4
View File
@@ -22,6 +22,10 @@
namespace FileSys {
static u8 MasterKeyIdForKeyGeneration(u8 key_generation) {
return std::max<u8>(key_generation, 1) - 1;
}
NCA::NCA(VirtualFile file_, const NCA* base_nca)
: file(std::move(file_)), keys{Core::Crypto::KeyManager::Instance()} {
if (file == nullptr) {
@@ -41,12 +45,17 @@ NCA::NCA(VirtualFile file_, const NCA* base_nca)
return;
}
// Ensure we have the proper key area keys to continue.
const u8 master_key_id = MasterKeyIdForKeyGeneration(reader->GetKeyGeneration());
if (!keys.HasKey(Core::Crypto::S128KeyType::KeyArea, master_key_id, reader->GetKeyIndex())) {
status = Loader::ResultStatus::ErrorMissingKeyAreaKey;
return;
}
RightsId rights_id{};
reader->GetRightsId(rights_id.data(), rights_id.size());
if (rights_id != RightsId{}) {
// External decryption key required; provide it here.
const auto key_generation = std::max<s32>(reader->GetKeyGeneration(), 1) - 1;
u128 rights_id_u128;
std::memcpy(rights_id_u128.data(), rights_id.data(), sizeof(rights_id));
@@ -57,12 +66,12 @@ NCA::NCA(VirtualFile file_, const NCA* base_nca)
return;
}
if (!keys.HasKey(Core::Crypto::S128KeyType::Titlekek, key_generation)) {
if (!keys.HasKey(Core::Crypto::S128KeyType::Titlekek, master_key_id)) {
status = Loader::ResultStatus::ErrorMissingTitlekek;
return;
}
auto titlekek = keys.GetKey(Core::Crypto::S128KeyType::Titlekek, key_generation);
auto titlekek = keys.GetKey(Core::Crypto::S128KeyType::Titlekek, master_key_id);
Core::Crypto::AESCipher<Core::Crypto::Key128> cipher(titlekek, Core::Crypto::Mode::ECB);
cipher.Transcode(titlekey.data(), titlekey.size(), titlekey.data(),
Core::Crypto::Op::Decrypt);
+3 -32
View File
@@ -164,24 +164,6 @@ VirtualFile NSP::GetNCAFile(u64 title_id, ContentRecordType type, TitleType titl
return nullptr;
}
std::vector<Core::Crypto::Key128> NSP::GetTitlekey() const {
if (extracted)
LOG_WARNING(Service_FS, "called on an NSP that is of type extracted.");
std::vector<Core::Crypto::Key128> out;
for (const auto& ticket_file : ticket_files) {
if (ticket_file == nullptr ||
ticket_file->GetSize() <
Core::Crypto::TICKET_FILE_TITLEKEY_OFFSET + sizeof(Core::Crypto::Key128)) {
continue;
}
out.emplace_back();
ticket_file->Read(out.back().data(), out.back().size(),
Core::Crypto::TICKET_FILE_TITLEKEY_OFFSET);
}
return out;
}
std::vector<VirtualFile> NSP::GetFiles() const {
return pfs->GetFiles();
}
@@ -208,22 +190,11 @@ void NSP::SetTicketKeys(const std::vector<VirtualFile>& files) {
continue;
}
if (ticket_file->GetSize() <
Core::Crypto::TICKET_FILE_TITLEKEY_OFFSET + sizeof(Core::Crypto::Key128)) {
auto ticket = Core::Crypto::Ticket::Read(ticket_file);
if (!keys.AddTicket(ticket)) {
LOG_WARNING(Common_Filesystem, "Could not load NSP ticket {}", ticket_file->GetName());
continue;
}
Core::Crypto::Key128 key{};
ticket_file->Read(key.data(), key.size(), Core::Crypto::TICKET_FILE_TITLEKEY_OFFSET);
// We get the name without the extension in order to create the rights ID.
std::string name_only(ticket_file->GetName());
name_only.erase(name_only.size() - 4);
const auto rights_id_raw = Common::HexStringToArray<16>(name_only);
u128 rights_id;
std::memcpy(rights_id.data(), rights_id_raw.data(), sizeof(u128));
keys.SetKey(Core::Crypto::S128KeyType::Titlekey, key, rights_id[1], rights_id[0]);
}
}
-1
View File
@@ -53,7 +53,6 @@ public:
TitleType title_type = TitleType::Application) const;
VirtualFile GetNCAFile(u64 title_id, ContentRecordType type,
TitleType title_type = TitleType::Application) const;
std::vector<Core::Crypto::Key128> GetTitlekey() const;
std::vector<VirtualFile> GetFiles() const override;
+6 -2
View File
@@ -341,7 +341,7 @@ void ISelfController::Exit(HLERequestContext& ctx) {
void ISelfController::LockExit(HLERequestContext& ctx) {
LOG_DEBUG(Service_AM, "called");
system.SetExitLock(true);
system.SetExitLocked(true);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ResultSuccess);
@@ -350,10 +350,14 @@ void ISelfController::LockExit(HLERequestContext& ctx) {
void ISelfController::UnlockExit(HLERequestContext& ctx) {
LOG_DEBUG(Service_AM, "called");
system.SetExitLock(false);
system.SetExitLocked(false);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ResultSuccess);
if (system.GetExitRequested()) {
system.Exit();
}
}
void ISelfController::EnterFatalSection(HLERequestContext& ctx) {
+4 -6
View File
@@ -122,20 +122,18 @@ private:
}
void ImportTicket(HLERequestContext& ctx) {
const auto ticket = ctx.ReadBuffer();
const auto raw_ticket = ctx.ReadBuffer();
[[maybe_unused]] const auto cert = ctx.ReadBuffer(1);
if (ticket.size() < sizeof(Core::Crypto::Ticket)) {
if (raw_ticket.size() < sizeof(Core::Crypto::Ticket)) {
LOG_ERROR(Service_ETicket, "The input buffer is not large enough!");
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ERROR_INVALID_ARGUMENT);
return;
}
Core::Crypto::Ticket raw{};
std::memcpy(&raw, ticket.data(), sizeof(Core::Crypto::Ticket));
if (!keys.AddTicketPersonalized(raw)) {
Core::Crypto::Ticket ticket = Core::Crypto::Ticket::Read(raw_ticket);
if (!keys.AddTicket(ticket)) {
LOG_ERROR(Service_ETicket, "The ticket could not be imported!");
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ERROR_INVALID_ARGUMENT);
+83 -3
View File
@@ -48,15 +48,32 @@ enum class CallType {
using socklen_t = int;
SOCKET interrupt_socket = static_cast<SOCKET>(-1);
void InterruptSocketOperations() {
closesocket(interrupt_socket);
}
void AcknowledgeInterrupt() {
interrupt_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
}
void Initialize() {
WSADATA wsa_data;
(void)WSAStartup(MAKEWORD(2, 2), &wsa_data);
AcknowledgeInterrupt();
}
void Finalize() {
InterruptSocketOperations();
WSACleanup();
}
SOCKET GetInterruptSocket() {
return interrupt_socket;
}
sockaddr TranslateFromSockAddrIn(SockAddrIn input) {
sockaddr_in result;
@@ -157,9 +174,39 @@ constexpr int SD_RECEIVE = SHUT_RD;
constexpr int SD_SEND = SHUT_WR;
constexpr int SD_BOTH = SHUT_RDWR;
void Initialize() {}
int interrupt_pipe_fd[2] = {-1, -1};
void Finalize() {}
void Initialize() {
if (pipe(interrupt_pipe_fd) != 0) {
LOG_ERROR(Network, "Failed to create interrupt pipe!");
}
int flags = fcntl(interrupt_pipe_fd[0], F_GETFL);
ASSERT_MSG(fcntl(interrupt_pipe_fd[0], F_SETFL, flags | O_NONBLOCK) == 0,
"Failed to set nonblocking state for interrupt pipe");
}
void Finalize() {
if (interrupt_pipe_fd[0] >= 0) {
close(interrupt_pipe_fd[0]);
}
if (interrupt_pipe_fd[1] >= 0) {
close(interrupt_pipe_fd[1]);
}
}
void InterruptSocketOperations() {
u8 value = 0;
ASSERT(write(interrupt_pipe_fd[1], &value, sizeof(value)) == 1);
}
void AcknowledgeInterrupt() {
u8 value = 0;
read(interrupt_pipe_fd[0], &value, sizeof(value));
}
SOCKET GetInterruptSocket() {
return interrupt_pipe_fd[0];
}
sockaddr TranslateFromSockAddrIn(SockAddrIn input) {
sockaddr_in result;
@@ -490,6 +537,14 @@ NetworkInstance::~NetworkInstance() {
Finalize();
}
void CancelPendingSocketOperations() {
InterruptSocketOperations();
}
void RestartSocketOperations() {
AcknowledgeInterrupt();
}
std::optional<IPv4Address> GetHostIPv4Address() {
const auto network_interface = Network::GetSelectedNetworkInterface();
if (!network_interface.has_value()) {
@@ -560,7 +615,14 @@ std::pair<s32, Errno> Poll(std::vector<PollFD>& pollfds, s32 timeout) {
return result;
});
const int result = WSAPoll(host_pollfds.data(), static_cast<ULONG>(num), timeout);
host_pollfds.push_back(WSAPOLLFD{
.fd = GetInterruptSocket(),
.events = POLLIN,
.revents = 0,
});
const int result =
WSAPoll(host_pollfds.data(), static_cast<ULONG>(host_pollfds.size()), timeout);
if (result == 0) {
ASSERT(std::all_of(host_pollfds.begin(), host_pollfds.end(),
[](WSAPOLLFD fd) { return fd.revents == 0; }));
@@ -627,6 +689,24 @@ Errno Socket::Initialize(Domain domain, Type type, Protocol protocol) {
std::pair<SocketBase::AcceptResult, Errno> Socket::Accept() {
sockaddr_in addr;
socklen_t addrlen = sizeof(addr);
std::vector<WSAPOLLFD> host_pollfds{
WSAPOLLFD{fd, POLLIN, 0},
WSAPOLLFD{GetInterruptSocket(), POLLIN, 0},
};
while (true) {
const int pollres =
WSAPoll(host_pollfds.data(), static_cast<ULONG>(host_pollfds.size()), -1);
if (host_pollfds[1].revents != 0) {
// Interrupt signaled before a client could be accepted, break
return {AcceptResult{}, Errno::AGAIN};
}
if (pollres > 0) {
break;
}
}
const SOCKET new_socket = accept(fd, reinterpret_cast<sockaddr*>(&addr), &addrlen);
if (new_socket == INVALID_SOCKET) {
+3
View File
@@ -96,6 +96,9 @@ public:
~NetworkInstance();
};
void CancelPendingSocketOperations();
void RestartSocketOperations();
#ifdef _WIN32
constexpr IPv4Address TranslateIPv4(in_addr addr) {
auto& bytes = addr.S_un.S_un_b;
+79 -49
View File
@@ -2010,8 +2010,16 @@ bool GMainWindow::OnShutdownBegin() {
emit EmulationStopping();
int shutdown_time = 1000;
if (system->DebuggerEnabled()) {
shutdown_time = 0;
} else if (system->GetExitLocked()) {
shutdown_time = 5000;
}
shutdown_timer.setSingleShot(true);
shutdown_timer.start(system->DebuggerEnabled() ? 0 : 5000);
shutdown_timer.start(shutdown_time);
connect(&shutdown_timer, &QTimer::timeout, this, &GMainWindow::OnEmulationStopTimeExpired);
connect(emu_thread.get(), &QThread::finished, this, &GMainWindow::OnEmulationStopped);
@@ -2573,50 +2581,48 @@ void GMainWindow::OnGameListDumpRomFS(u64 program_id, const std::string& game_pa
return;
}
FileSys::VirtualFile base_romfs;
if (loader->ReadRomFS(base_romfs) != Loader::ResultStatus::Success) {
failed();
return;
}
FileSys::VirtualFile packed_update_raw{};
loader->ReadUpdateRaw(packed_update_raw);
const auto& installed = system->GetContentProvider();
const auto romfs_title_id = SelectRomFSDumpTarget(installed, program_id);
if (!romfs_title_id) {
u64 title_id{};
u8 raw_type{};
if (!SelectRomFSDumpTarget(installed, program_id, &title_id, &raw_type)) {
failed();
return;
}
const auto type = *romfs_title_id == program_id ? FileSys::ContentRecordType::Program
: FileSys::ContentRecordType::Data;
const auto base_nca = installed.GetEntry(*romfs_title_id, type);
const auto type = static_cast<FileSys::ContentRecordType>(raw_type);
const auto base_nca = installed.GetEntry(title_id, type);
if (!base_nca) {
failed();
return;
}
const FileSys::NCA update_nca{packed_update_raw, nullptr};
if (type != FileSys::ContentRecordType::Program ||
update_nca.GetStatus() != Loader::ResultStatus::ErrorMissingBKTRBaseRomFS ||
update_nca.GetTitleId() != FileSys::GetUpdateTitleID(title_id)) {
packed_update_raw = {};
}
const auto base_romfs = base_nca->GetRomFS();
if (!base_romfs) {
failed();
return;
}
const auto dump_dir =
target == DumpRomFSTarget::Normal
? Common::FS::GetYuzuPath(Common::FS::YuzuPath::DumpDir)
: Common::FS::GetYuzuPath(Common::FS::YuzuPath::SDMCDir) / "atmosphere" / "contents";
const auto romfs_dir = fmt::format("{:016X}/romfs", *romfs_title_id);
const auto romfs_dir = fmt::format("{:016X}/romfs", title_id);
const auto path = Common::FS::PathToUTF8String(dump_dir / romfs_dir);
FileSys::VirtualFile romfs;
if (*romfs_title_id == program_id) {
const FileSys::PatchManager pm{program_id, system->GetFileSystemController(), installed};
romfs = pm.PatchRomFS(base_nca.get(), base_romfs, type, nullptr, false);
} else {
romfs = installed.GetEntry(*romfs_title_id, type)->GetRomFS();
}
const auto extracted = FileSys::ExtractRomFS(romfs, FileSys::RomFSExtractionType::Full);
if (extracted == nullptr) {
failed();
return;
}
const FileSys::PatchManager pm{title_id, system->GetFileSystemController(), installed};
auto romfs = pm.PatchRomFS(base_nca.get(), base_romfs, type, packed_update_raw, false);
const auto out = VfsFilesystemCreateDirectoryWrapper(vfs, path, FileSys::Mode::ReadWrite);
@@ -2640,6 +2646,12 @@ void GMainWindow::OnGameListDumpRomFS(u64 program_id, const std::string& game_pa
return;
}
const auto extracted = FileSys::ExtractRomFS(romfs, FileSys::RomFSExtractionType::Full);
if (extracted == nullptr) {
failed();
return;
}
const auto full = res == selections.constFirst();
const auto entry_size = CalculateRomFSEntrySize(extracted, full);
@@ -3261,7 +3273,7 @@ void GMainWindow::OnPauseContinueGame() {
}
void GMainWindow::OnStopGame() {
if (system->GetExitLock() && !ConfirmForceLockedExit()) {
if (system->GetExitLocked() && !ConfirmForceLockedExit()) {
return;
}
@@ -4350,28 +4362,41 @@ bool GMainWindow::CheckSystemArchiveDecryption() {
return mii_nca->GetRomFS().get() != nullptr;
}
std::optional<u64> GMainWindow::SelectRomFSDumpTarget(const FileSys::ContentProvider& installed,
u64 program_id) {
const auto dlc_entries =
installed.ListEntriesFilter(FileSys::TitleType::AOC, FileSys::ContentRecordType::Data);
std::vector<FileSys::ContentProviderEntry> dlc_match;
dlc_match.reserve(dlc_entries.size());
std::copy_if(dlc_entries.begin(), dlc_entries.end(), std::back_inserter(dlc_match),
[&program_id, &installed](const FileSys::ContentProviderEntry& entry) {
return FileSys::GetBaseTitleID(entry.title_id) == program_id &&
installed.GetEntry(entry)->GetStatus() == Loader::ResultStatus::Success;
});
bool GMainWindow::SelectRomFSDumpTarget(const FileSys::ContentProvider& installed, u64 program_id,
u64* selected_title_id, u8* selected_content_record_type) {
using ContentInfo = std::pair<FileSys::TitleType, FileSys::ContentRecordType>;
boost::container::flat_map<u64, ContentInfo> available_title_ids;
std::vector<u64> romfs_tids;
romfs_tids.push_back(program_id);
for (const auto& entry : dlc_match) {
romfs_tids.push_back(entry.title_id);
const auto RetrieveEntries = [&](FileSys::TitleType title_type,
FileSys::ContentRecordType record_type) {
const auto entries = installed.ListEntriesFilter(title_type, record_type);
for (const auto& entry : entries) {
if (FileSys::GetBaseTitleID(entry.title_id) == program_id &&
installed.GetEntry(entry)->GetStatus() == Loader::ResultStatus::Success) {
available_title_ids[entry.title_id] = {title_type, record_type};
}
}
};
RetrieveEntries(FileSys::TitleType::Application, FileSys::ContentRecordType::Program);
RetrieveEntries(FileSys::TitleType::AOC, FileSys::ContentRecordType::Data);
if (available_title_ids.empty()) {
return false;
}
if (romfs_tids.size() > 1) {
QStringList list{QStringLiteral("Base")};
for (std::size_t i = 1; i < romfs_tids.size(); ++i) {
list.push_back(QStringLiteral("DLC %1").arg(romfs_tids[i] & 0x7FF));
size_t title_index = 0;
if (available_title_ids.size() > 1) {
QStringList list;
for (auto& [title_id, content_info] : available_title_ids) {
const auto hex_title_id = QString::fromStdString(fmt::format("{:X}", title_id));
if (content_info.first == FileSys::TitleType::Application) {
list.push_back(QStringLiteral("Application [%1]").arg(hex_title_id));
} else {
list.push_back(
QStringLiteral("DLC %1 [%2]").arg(title_id & 0x7FF).arg(hex_title_id));
}
}
bool ok;
@@ -4379,13 +4404,16 @@ std::optional<u64> GMainWindow::SelectRomFSDumpTarget(const FileSys::ContentProv
this, tr("Select RomFS Dump Target"),
tr("Please select which RomFS you would like to dump."), list, 0, false, &ok);
if (!ok) {
return {};
return false;
}
return romfs_tids[list.indexOf(res)];
title_index = list.indexOf(res);
}
return program_id;
const auto selected_info = available_title_ids.nth(title_index);
*selected_title_id = selected_info->first;
*selected_content_record_type = static_cast<u8>(selected_info->second.second);
return true;
}
bool GMainWindow::ConfirmClose() {
@@ -4515,6 +4543,8 @@ void GMainWindow::RequestGameExit() {
auto applet_ae = sm.GetService<Service::AM::AppletAE>("appletAE");
bool has_signalled = false;
system->SetExitRequested(true);
if (applet_oe != nullptr) {
applet_oe->GetMessageQueue()->RequestExit();
has_signalled = true;
+2 -1
View File
@@ -375,7 +375,8 @@ private:
void RemoveAllTransferableShaderCaches(u64 program_id);
void RemoveCustomConfiguration(u64 program_id, const std::string& game_path);
void RemoveCacheStorage(u64 program_id);
std::optional<u64> SelectRomFSDumpTarget(const FileSys::ContentProvider&, u64 program_id);
bool SelectRomFSDumpTarget(const FileSys::ContentProvider&, u64 program_id,
u64* selected_title_id, u8* selected_content_record_type);
InstallResult InstallNSPXCI(const QString& filename);
InstallResult InstallNCA(const QString& filename);
void MigrateConfigFiles();