aboutsummaryrefslogtreecommitdiff
path: root/src/core/crypto/partition_data_manager.cpp
blob: e185838e571dd5be9c2e30c54e8fd4cc784c0cb4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
// SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later

// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include <algorithm>
#include <array>
#include <cctype>
#include <cstring>
#include <mbedtls/sha256.h>
#include "common/common_funcs.h"
#include "common/common_types.h"
#include "common/hex_util.h"
#include "common/logging/log.h"
#include "common/string_util.h"
#include "common/swap.h"
#include "core/crypto/key_manager.h"
#include "core/crypto/partition_data_manager.h"
#include "core/crypto/xts_encryption_layer.h"
#include "core/file_sys/kernel_executable.h"
#include "core/file_sys/vfs/vfs.h"
#include "core/file_sys/vfs/vfs_offset.h"
#include "core/file_sys/vfs/vfs_vector.h"
#include "core/loader/loader.h"

using Common::AsArray;

namespace Core::Crypto {

struct Package2Header {
    std::array<u8, 0x100> signature;
    Key128 header_ctr;
    std::array<Key128, 4> section_ctr;
    u32_le magic;
    u32_le base_offset;
    INSERT_PADDING_BYTES(4);
    u8 version_max;
    u8 version_min;
    INSERT_PADDING_BYTES(2);
    std::array<u32_le, 4> section_size;
    std::array<u32_le, 4> section_offset;
    std::array<SHA256Hash, 4> section_hash;
};
static_assert(sizeof(Package2Header) == 0x200, "Package2Header has incorrect size.");

const u8 PartitionDataManager::MAX_KEYBLOB_SOURCE_HASH = 32;

static FileSys::VirtualFile FindFileInDirWithNames(const FileSys::VirtualDir& dir,
                                                   const std::string& name) {
    const auto upper = Common::ToUpper(name);

    for (const auto& fname : {name, name + ".bin", upper, upper + ".BIN"}) {
        if (dir->GetFile(fname) != nullptr) {
            return dir->GetFile(fname);
        }
    }

    return nullptr;
}

PartitionDataManager::PartitionDataManager(const FileSys::VirtualDir& sysdata_dir)
    : boot0(FindFileInDirWithNames(sysdata_dir, "BOOT0")),
      fuses(FindFileInDirWithNames(sysdata_dir, "fuses")),
      kfuses(FindFileInDirWithNames(sysdata_dir, "kfuses")),
      package2({
          FindFileInDirWithNames(sysdata_dir, "BCPKG2-1-Normal-Main"),
          FindFileInDirWithNames(sysdata_dir, "BCPKG2-2-Normal-Sub"),
          FindFileInDirWithNames(sysdata_dir, "BCPKG2-3-SafeMode-Main"),
          FindFileInDirWithNames(sysdata_dir, "BCPKG2-4-SafeMode-Sub"),
          FindFileInDirWithNames(sysdata_dir, "BCPKG2-5-Repair-Main"),
          FindFileInDirWithNames(sysdata_dir, "BCPKG2-6-Repair-Sub"),
      }),
      prodinfo(FindFileInDirWithNames(sysdata_dir, "PRODINFO")),
      secure_monitor(FindFileInDirWithNames(sysdata_dir, "secmon")),
      package1_decrypted(FindFileInDirWithNames(sysdata_dir, "pkg1_decr")),
      secure_monitor_bytes(secure_monitor == nullptr ? std::vector<u8>{}
                                                     : secure_monitor->ReadAllBytes()),
      package1_decrypted_bytes(package1_decrypted == nullptr ? std::vector<u8>{}
                                                             : package1_decrypted->ReadAllBytes()) {
}

PartitionDataManager::~PartitionDataManager() = default;

bool PartitionDataManager::HasBoot0() const {
    return boot0 != nullptr;
}

FileSys::VirtualFile PartitionDataManager::GetBoot0Raw() const {
    return boot0;
}

PartitionDataManager::EncryptedKeyBlob PartitionDataManager::GetEncryptedKeyblob(
    std::size_t index) const {
    if (HasBoot0() && index < NUM_ENCRYPTED_KEYBLOBS)
        return GetEncryptedKeyblobs()[index];
    return {};
}

PartitionDataManager::EncryptedKeyBlobs PartitionDataManager::GetEncryptedKeyblobs() const {
    if (!HasBoot0())
        return {};

    EncryptedKeyBlobs out{};
    for (size_t i = 0; i < out.size(); ++i)
        boot0->Read(out[i].data(), out[i].size(), 0x180000 + i * 0x200);
    return out;
}

std::vector<u8> PartitionDataManager::GetSecureMonitor() const {
    return secure_monitor_bytes;
}

std::vector<u8> PartitionDataManager::GetPackage1Decrypted() const {
    return package1_decrypted_bytes;
}

bool PartitionDataManager::HasFuses() const {
    return fuses != nullptr;
}

FileSys::VirtualFile PartitionDataManager::GetFusesRaw() const {
    return fuses;
}

std::array<u8, 16> PartitionDataManager::GetSecureBootKey() const {
    if (!HasFuses())
        return {};
    Key128 out{};
    fuses->Read(out.data(), out.size(), 0xA4);
    return out;
}

bool PartitionDataManager::HasKFuses() const {
    return kfuses != nullptr;
}

FileSys::VirtualFile PartitionDataManager::GetKFusesRaw() const {
    return kfuses;
}

bool PartitionDataManager::HasPackage2(Package2Type type) const {
    return package2.at(static_cast<size_t>(type)) != nullptr;
}

FileSys::VirtualFile PartitionDataManager::GetPackage2Raw(Package2Type type) const {
    return package2.at(static_cast<size_t>(type));
}

static bool AttemptDecrypt(const std::array<u8, 16>& key, Package2Header& header) {
    Package2Header temp = header;
    AESCipher<Key128> cipher(key, Mode::CTR);
    cipher.SetIV(header.header_ctr);
    cipher.Transcode(&temp.header_ctr, sizeof(Package2Header) - sizeof(Package2Header::signature),
                     &temp.header_ctr, Op::Decrypt);
    if (temp.magic == Common::MakeMagic('P', 'K', '2', '1')) {
        header = temp;
        return true;
    }

    return false;
}

void PartitionDataManager::DecryptPackage2(const std::array<Key128, 0x20>& package2_keys,
                                           Package2Type type) {
    FileSys::VirtualFile file = std::make_shared<FileSys::OffsetVfsFile>(
        package2[static_cast<size_t>(type)],
        package2[static_cast<size_t>(type)]->GetSize() - 0x4000, 0x4000);

    Package2Header header{};
    if (file->ReadObject(&header) != sizeof(Package2Header))
        return;

    std::size_t revision = 0xFF;
    if (header.magic != Common::MakeMagic('P', 'K', '2', '1')) {
        for (std::size_t i = 0; i < package2_keys.size(); ++i) {
            if (AttemptDecrypt(package2_keys[i], header)) {
                revision = i;
            }
        }
    }

    if (header.magic != Common::MakeMagic('P', 'K', '2', '1'))
        return;

    const auto a = std::make_shared<FileSys::OffsetVfsFile>(
        file, header.section_size[1], header.section_size[0] + sizeof(Package2Header));

    auto c = a->ReadAllBytes();

    AESCipher<Key128> cipher(package2_keys[revision], Mode::CTR);
    cipher.SetIV(header.section_ctr[1]);
    cipher.Transcode(c.data(), c.size(), c.data(), Op::Decrypt);

    const auto ini_file = std::make_shared<FileSys::VectorVfsFile>(c);
    const FileSys::INI ini{ini_file};
    if (ini.GetStatus() != Loader::ResultStatus::Success)
        return;

    for (const auto& kip : ini.GetKIPs()) {
        if (kip.GetStatus() != Loader::ResultStatus::Success)
            return;

        if (kip.GetName() != "FS" && kip.GetName() != "spl") {
            continue;
        }

        const auto& text = kip.GetTextSection();
        const auto& rodata = kip.GetRODataSection();
        const auto& data = kip.GetDataSection();

        std::vector<u8> out;
        out.reserve(text.size() + rodata.size() + data.size());
        out.insert(out.end(), text.begin(), text.end());
        out.insert(out.end(), rodata.begin(), rodata.end());
        out.insert(out.end(), data.begin(), data.end());

        if (kip.GetName() == "FS")
            package2_fs[static_cast<size_t>(type)] = std::move(out);
        else if (kip.GetName() == "spl")
            package2_spl[static_cast<size_t>(type)] = std::move(out);
    }
}

const std::vector<u8>& PartitionDataManager::GetPackage2FSDecompressed(Package2Type type) const {
    return package2_fs.at(static_cast<size_t>(type));
}

const std::vector<u8>& PartitionDataManager::GetPackage2SPLDecompressed(Package2Type type) const {
    return package2_spl.at(static_cast<size_t>(type));
}

bool PartitionDataManager::HasProdInfo() const {
    return prodinfo != nullptr;
}

FileSys::VirtualFile PartitionDataManager::GetProdInfoRaw() const {
    return prodinfo;
}

void PartitionDataManager::DecryptProdInfo(std::array<u8, 0x20> bis_key) {
    if (prodinfo == nullptr)
        return;

    prodinfo_decrypted = std::make_shared<XTSEncryptionLayer>(prodinfo, bis_key);
}

FileSys::VirtualFile PartitionDataManager::GetDecryptedProdInfo() const {
    return prodinfo_decrypted;
}

std::array<u8, 576> PartitionDataManager::GetETicketExtendedKek() const {
    std::array<u8, 0x240> out{};
    if (prodinfo_decrypted != nullptr)
        prodinfo_decrypted->Read(out.data(), out.size(), 0x3890);
    return out;
}
} // namespace Core::Crypto