Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
CTCaer
GitHub Repository: CTCaer/hekate
Path: blob/master/bootloader/hos/pkg2.c
1476 views
1
/*
2
* Copyright (c) 2018 naehrwert
3
* Copyright (c) 2018-2025 CTCaer
4
*
5
* This program is free software; you can redistribute it and/or modify it
6
* under the terms and conditions of the GNU General Public License,
7
* version 2, as published by the Free Software Foundation.
8
*
9
* This program is distributed in the hope it will be useful, but WITHOUT
10
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
12
* more details.
13
*
14
* You should have received a copy of the GNU General Public License
15
* along with this program. If not, see <http://www.gnu.org/licenses/>.
16
*/
17
18
#include <string.h>
19
20
#include <bdk.h>
21
22
#include "hos.h"
23
#include "pkg2.h"
24
#include "pkg2_ini_kippatch.h"
25
26
#include "../config.h"
27
#include <libs/compr/blz.h>
28
#include <libs/fatfs/ff.h>
29
#include "../storage/emummc.h"
30
31
//#define DPRINTF(...) gfx_printf(__VA_ARGS__)
32
#define DPRINTF(...)
33
34
extern hekate_config h_cfg;
35
extern const u8 package2_keyseed[];
36
37
u32 pkg2_newkern_ini1_info;
38
u32 pkg2_newkern_ini1_start;
39
u32 pkg2_newkern_ini1_end;
40
u32 pkg2_newkern_ini1_rela;
41
42
enum kip_offset_section
43
{
44
KIP_TEXT = 0,
45
KIP_RODATA = 1,
46
KIP_DATA = 2,
47
KIP_BSS = 3,
48
KIP_UNKSEC1 = 4,
49
KIP_UNKSEC2 = 5
50
};
51
52
#define KIP_PATCH_SECTION_SHIFT (29)
53
#define KIP_PATCH_SECTION_MASK (7 << KIP_PATCH_SECTION_SHIFT)
54
#define KIP_PATCH_OFFSET_MASK (~KIP_PATCH_SECTION_MASK)
55
#define GET_KIP_PATCH_SECTION(x) (((x) >> KIP_PATCH_SECTION_SHIFT) & 7)
56
#define GET_KIP_PATCH_OFFSET(x) ((x) & KIP_PATCH_OFFSET_MASK)
57
#define KPS(x) ((u32)(x) << KIP_PATCH_SECTION_SHIFT)
58
59
#include "pkg2_patches.inl"
60
61
static kip1_id_t *_kip_id_sets = (kip1_id_t *)_kip_ids;
62
static u32 _kip_id_sets_cnt = ARRAY_SIZE(_kip_ids);
63
64
void pkg2_get_ids(kip1_id_t **ids, u32 *entries)
65
{
66
*ids = _kip_id_sets;
67
*entries = _kip_id_sets_cnt;
68
}
69
70
static void parse_external_kip_patches()
71
{
72
static bool ext_patches_parsed = false;
73
74
if (ext_patches_parsed)
75
return;
76
77
LIST_INIT(ini_kip_sections);
78
if (ini_patch_parse(&ini_kip_sections, "bootloader/patches.ini"))
79
{
80
// Copy ids into a new patchset.
81
_kip_id_sets = zalloc(sizeof(kip1_id_t) * 256); // Max 256 kip ids.
82
memcpy(_kip_id_sets, _kip_ids, sizeof(_kip_ids));
83
84
// Parse patchsets and glue them together.
85
LIST_FOREACH_ENTRY(ini_kip_sec_t, ini_psec, &ini_kip_sections, link)
86
{
87
kip1_id_t *kip = NULL;
88
bool found = false;
89
for (u32 kip_idx = 0; kip_idx < _kip_id_sets_cnt + 1; kip_idx++)
90
{
91
kip = &_kip_id_sets[kip_idx];
92
93
// Check if reached the end of predefined list.
94
if (!kip->name)
95
break;
96
97
// Check if name and hash match.
98
if (!strcmp(kip->name, ini_psec->name) && !memcmp(kip->hash, ini_psec->hash, 8))
99
{
100
found = true;
101
break;
102
}
103
}
104
105
if (!kip)
106
continue;
107
108
// If not found, create a new empty entry.
109
if (!found)
110
{
111
kip->name = ini_psec->name;
112
memcpy(kip->hash, ini_psec->hash, 8);
113
kip->patchset = zalloc(sizeof(kip1_patchset_t));
114
115
_kip_id_sets_cnt++;
116
}
117
118
kip1_patchset_t *patchsets = (kip1_patchset_t *)zalloc(sizeof(kip1_patchset_t) * 16); // Max 16 patchsets per kip.
119
120
u32 patchset_idx;
121
for (patchset_idx = 0; kip->patchset[patchset_idx].name != NULL; patchset_idx++)
122
{
123
patchsets[patchset_idx].name = kip->patchset[patchset_idx].name;
124
patchsets[patchset_idx].patches = kip->patchset[patchset_idx].patches;
125
}
126
127
kip->patchset = patchsets;
128
bool first_ext_patch = true;
129
u32 patch_idx = 0;
130
131
// Parse patches and glue them together to a patchset.
132
kip1_patch_t *patches = zalloc(sizeof(kip1_patch_t) * 32); // Max 32 patches per set.
133
LIST_FOREACH_ENTRY(ini_patchset_t, pt, &ini_psec->pts, link)
134
{
135
if (first_ext_patch)
136
{
137
first_ext_patch = false;
138
patchsets[patchset_idx].name = pt->name;
139
patchsets[patchset_idx].patches = patches;
140
}
141
else if (strcmp(pt->name, patchsets[patchset_idx].name))
142
{
143
// New patchset name found, create a new set.
144
patchset_idx++;
145
patch_idx = 0;
146
patches = zalloc(sizeof(kip1_patch_t) * 32); // Max 32 patches per set.
147
148
patchsets[patchset_idx].name = pt->name;
149
patchsets[patchset_idx].patches = patches;
150
}
151
152
if (pt->length)
153
{
154
patches[patch_idx].offset = pt->offset;
155
patches[patch_idx].length = pt->length;
156
157
patches[patch_idx].src_data = (char *)pt->src_data;
158
patches[patch_idx].dst_data = (char *)pt->dst_data;
159
}
160
else
161
patches[patch_idx].src_data = malloc(1); // Empty patches check. Keep everything else as 0.
162
163
patch_idx++;
164
}
165
patchset_idx++;
166
patchsets[patchset_idx].name = NULL;
167
patchsets[patchset_idx].patches = NULL;
168
}
169
}
170
171
ext_patches_parsed = true;
172
}
173
174
const pkg2_kernel_id_t *pkg2_identify(const u8 *hash)
175
{
176
for (u32 i = 0; i < ARRAY_SIZE(_pkg2_kernel_ids); i++)
177
{
178
if (!memcmp(hash, _pkg2_kernel_ids[i].hash, sizeof(_pkg2_kernel_ids[0].hash)))
179
return &_pkg2_kernel_ids[i];
180
}
181
return NULL;
182
}
183
184
static u32 _pkg2_calc_kip1_size(pkg2_kip1_t *kip1)
185
{
186
u32 size = sizeof(pkg2_kip1_t);
187
for (u32 j = 0; j < KIP1_NUM_SECTIONS; j++)
188
size += kip1->sections[j].size_comp;
189
return size;
190
}
191
192
static void _pkg2_get_newkern_info(u8 *kern_data)
193
{
194
u32 crt_start = 0;
195
pkg2_newkern_ini1_info = 0;
196
pkg2_newkern_ini1_start = 0;
197
pkg2_newkern_ini1_rela = 0;
198
199
u32 first_op = *(u32 *)kern_data;
200
if ((first_op & 0xFE000000) == 0x14000000)
201
crt_start = (first_op & 0x1FFFFFF) << 2;
202
203
// Find static OP offset that is close to INI1 offset.
204
u32 counter_ops = 0x100;
205
while (counter_ops)
206
{
207
if (*(u32 *)(kern_data + crt_start + 0x100 - counter_ops) == PKG2_NEWKERN_GET_INI1_HEURISTIC)
208
{
209
// OP found. Add 12 for the INI1 info offset.
210
pkg2_newkern_ini1_info = crt_start + 0x100 - counter_ops + 12;
211
212
// On v2 kernel with dynamic crt there's a NOP after heuristic. Offset one op.
213
if (crt_start)
214
pkg2_newkern_ini1_info += 4;
215
break;
216
}
217
218
counter_ops -= 4;
219
}
220
221
// Offset not found?
222
if (!counter_ops)
223
return;
224
225
u32 info_op = *(u32 *)(kern_data + pkg2_newkern_ini1_info);
226
pkg2_newkern_ini1_info += ((info_op & 0xFFFF) >> 3); // Parse ADR and PC.
227
228
pkg2_newkern_ini1_start = *(u32 *)(kern_data + pkg2_newkern_ini1_info);
229
pkg2_newkern_ini1_end = *(u32 *)(kern_data + pkg2_newkern_ini1_info + 0x8);
230
231
// On v2 kernel with dynamic crt, values are relative to value address.
232
if (crt_start)
233
{
234
pkg2_newkern_ini1_rela = pkg2_newkern_ini1_info;
235
pkg2_newkern_ini1_start += pkg2_newkern_ini1_info;
236
pkg2_newkern_ini1_end += pkg2_newkern_ini1_info + 0x8;
237
}
238
}
239
240
bool pkg2_parse_kips(link_t *info, pkg2_hdr_t *pkg2, bool *new_pkg2)
241
{
242
u8 *ptr;
243
// Check for new pkg2 type.
244
if (!pkg2->sec_size[PKG2_SEC_INI1])
245
{
246
_pkg2_get_newkern_info(pkg2->data);
247
248
if (!pkg2_newkern_ini1_start)
249
return false;
250
251
ptr = pkg2->data + pkg2_newkern_ini1_start;
252
*new_pkg2 = true;
253
}
254
else
255
ptr = pkg2->data + pkg2->sec_size[PKG2_SEC_KERNEL];
256
257
pkg2_ini1_t *ini1 = (pkg2_ini1_t *)ptr;
258
ptr += sizeof(pkg2_ini1_t);
259
260
for (u32 i = 0; i < ini1->num_procs; i++)
261
{
262
pkg2_kip1_t *kip1 = (pkg2_kip1_t *)ptr;
263
pkg2_kip1_info_t *ki = (pkg2_kip1_info_t *)malloc(sizeof(pkg2_kip1_info_t));
264
ki->kip1 = kip1;
265
ki->size = _pkg2_calc_kip1_size(kip1);
266
list_append(info, &ki->link);
267
ptr += ki->size;
268
DPRINTF(" kip1 %d:%s @ %08X (%08X)\n", i, kip1->name, (u32)kip1, ki->size);
269
}
270
271
return true;
272
}
273
274
int pkg2_has_kip(link_t *info, u64 tid)
275
{
276
LIST_FOREACH_ENTRY(pkg2_kip1_info_t, ki, info, link)
277
if (ki->kip1->tid == tid)
278
return 1;
279
return 0;
280
}
281
282
void pkg2_replace_kip(link_t *info, u64 tid, pkg2_kip1_t *kip1)
283
{
284
LIST_FOREACH_ENTRY(pkg2_kip1_info_t, ki, info, link)
285
{
286
if (ki->kip1->tid == tid)
287
{
288
ki->kip1 = kip1;
289
ki->size = _pkg2_calc_kip1_size(kip1);
290
DPRINTF("replaced kip %s (new size %08X)\n", kip1->name, ki->size);
291
return;
292
}
293
}
294
}
295
296
void pkg2_add_kip(link_t *info, pkg2_kip1_t *kip1)
297
{
298
pkg2_kip1_info_t *ki = (pkg2_kip1_info_t *)malloc(sizeof(pkg2_kip1_info_t));
299
ki->kip1 = kip1;
300
ki->size = _pkg2_calc_kip1_size(kip1);
301
DPRINTF("added kip %s (size %08X)\n", kip1->name, ki->size);
302
list_append(info, &ki->link);
303
}
304
305
void pkg2_merge_kip(link_t *info, pkg2_kip1_t *kip1)
306
{
307
if (pkg2_has_kip(info, kip1->tid))
308
pkg2_replace_kip(info, kip1->tid, kip1);
309
else
310
pkg2_add_kip(info, kip1);
311
}
312
313
static int _decompress_kip(pkg2_kip1_info_t *ki, u32 sectsToDecomp)
314
{
315
u32 compClearMask = ~sectsToDecomp;
316
if ((ki->kip1->flags & compClearMask) == ki->kip1->flags)
317
return 0; // Already decompressed, nothing to do.
318
319
pkg2_kip1_t hdr;
320
memcpy(&hdr, ki->kip1, sizeof(hdr));
321
322
u32 new_kip_size = sizeof(hdr);
323
for (u32 sect_idx = 0; sect_idx < KIP1_NUM_SECTIONS; sect_idx++)
324
{
325
u32 comp_bit_mask = BIT(sect_idx);
326
// For compressed, cant get actual decompressed size without doing it, so use safe "output size".
327
if (sect_idx < 3 && (sectsToDecomp & comp_bit_mask) && (hdr.flags & comp_bit_mask))
328
new_kip_size += hdr.sections[sect_idx].size_decomp;
329
else
330
new_kip_size += hdr.sections[sect_idx].size_comp;
331
}
332
333
pkg2_kip1_t *new_kip = malloc(new_kip_size);
334
u8 *dst_data = new_kip->data;
335
const u8 *src_data = ki->kip1->data;
336
for (u32 sect_idx = 0; sect_idx < KIP1_NUM_SECTIONS; sect_idx++)
337
{
338
u32 comp_bit_mask = BIT(sect_idx);
339
// Easy copy path for uncompressed or ones we dont want to uncompress.
340
if (sect_idx >= 3 || !(sectsToDecomp & comp_bit_mask) || !(hdr.flags & comp_bit_mask))
341
{
342
u32 dataSize = hdr.sections[sect_idx].size_comp;
343
if (dataSize == 0)
344
continue;
345
346
memcpy(dst_data, src_data, dataSize);
347
src_data += dataSize;
348
dst_data += dataSize;
349
continue;
350
}
351
352
u32 comp_size = hdr.sections[sect_idx].size_comp;
353
u32 output_size = hdr.sections[sect_idx].size_decomp;
354
gfx_printf("Decomping '%s', sect %d, size %d..\n", (char *)hdr.name, sect_idx, comp_size);
355
if (blz_uncompress_srcdest(src_data, comp_size, dst_data, output_size) == 0)
356
{
357
gfx_con.mute = false;
358
gfx_printf("%kERROR decomping sect %d of '%s'!%k\n", TXT_CLR_ERROR, sect_idx, (char *)hdr.name, TXT_CLR_DEFAULT);
359
free(new_kip);
360
361
return 1;
362
}
363
else
364
{
365
DPRINTF("Done! Decompressed size is %d!\n", output_size);
366
}
367
hdr.sections[sect_idx].size_comp = output_size;
368
src_data += comp_size;
369
dst_data += output_size;
370
}
371
372
hdr.flags &= compClearMask;
373
memcpy(new_kip, &hdr, sizeof(hdr));
374
new_kip_size = dst_data - (u8 *)(new_kip);
375
376
free(ki->kip1);
377
ki->kip1 = new_kip;
378
ki->size = new_kip_size;
379
380
return 0;
381
}
382
383
static int _kipm_inject(const char *kipm_path, char *target_name, pkg2_kip1_info_t *ki)
384
{
385
if (!strcmp((char *)ki->kip1->name, target_name))
386
{
387
u32 size = 0;
388
u8 *kipm_data = (u8 *)sd_file_read(kipm_path, &size);
389
if (!kipm_data)
390
return 1;
391
392
u32 inject_size = size - sizeof(ki->kip1->caps);
393
u8 *kip_patched_data = (u8 *)malloc(ki->size + inject_size);
394
395
// Copy headers.
396
memcpy(kip_patched_data, ki->kip1, sizeof(pkg2_kip1_t));
397
398
pkg2_kip1_t *fs_kip = ki->kip1;
399
ki->kip1 = (pkg2_kip1_t *)kip_patched_data;
400
ki->size = ki->size + inject_size;
401
402
// Patch caps.
403
memcpy(&ki->kip1->caps, kipm_data, sizeof(ki->kip1->caps));
404
// Copy our .text data.
405
memcpy(&ki->kip1->data, kipm_data + sizeof(ki->kip1->caps), inject_size);
406
407
u32 new_offset = 0;
408
409
for (u32 section_idx = 0; section_idx < KIP1_NUM_SECTIONS - 2; section_idx++)
410
{
411
if (!section_idx) // .text.
412
{
413
memcpy(ki->kip1->data + inject_size, fs_kip->data, fs_kip->sections[0].size_comp);
414
ki->kip1->sections[0].size_decomp += inject_size;
415
ki->kip1->sections[0].size_comp += inject_size;
416
}
417
else // Others.
418
{
419
if (section_idx < 3)
420
memcpy(ki->kip1->data + new_offset + inject_size, fs_kip->data + new_offset, fs_kip->sections[section_idx].size_comp);
421
ki->kip1->sections[section_idx].offset += inject_size;
422
}
423
new_offset += fs_kip->sections[section_idx].size_comp;
424
}
425
426
// Patch PMC capabilities for 1.0.0.
427
if (!emu_cfg.fs_ver)
428
{
429
for (u32 i = 0; i < 0x20; i++)
430
{
431
if (ki->kip1->caps[i] == 0xFFFFFFFF)
432
{
433
ki->kip1->caps[i] = 0x07000E7F;
434
break;
435
}
436
}
437
}
438
439
free(kipm_data);
440
return 0;
441
}
442
443
return 1;
444
}
445
446
const char *pkg2_patch_kips(link_t *info, char *patch_names)
447
{
448
bool emummc_patch_selected = false;
449
450
if (patch_names == NULL || patch_names[0] == 0)
451
return NULL;
452
453
gfx_printf("%kPatching kips%k\n", TXT_CLR_ORANGE, TXT_CLR_DEFAULT);
454
455
static const u32 MAX_NUM_PATCHES_REQUESTED = sizeof(u32) * 8;
456
char *patches[MAX_NUM_PATCHES_REQUESTED];
457
458
u32 patches_num = 1;
459
patches[0] = patch_names;
460
{
461
for (char *p = patch_names; *p != 0; p++)
462
{
463
if (*p == ',')
464
{
465
*p = 0;
466
patches[patches_num++] = p + 1;
467
if (patches_num >= MAX_NUM_PATCHES_REQUESTED)
468
return "too_many_patches";
469
}
470
else if (*p >= 'A' && *p <= 'Z') // Convert to lowercase.
471
*p += 0x20;
472
}
473
}
474
475
u32 patches_applied = 0; // Bitset over patches.
476
for (u32 i = 0; i < patches_num; i++)
477
{
478
// Eliminate leading spaces.
479
for (const char *p = patches[i]; *p != 0; p++)
480
{
481
if (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n')
482
patches[i]++;
483
else
484
break;
485
}
486
487
int patch_len = strlen(patches[i]);
488
if (patch_len == 0)
489
continue;
490
491
// Eliminate trailing spaces.
492
for (int chIdx = patch_len - 1; chIdx >= 0; chIdx--)
493
{
494
const char *p = patches[i] + chIdx;
495
if (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n')
496
patch_len = chIdx;
497
else
498
break;
499
}
500
patches[i][patch_len] = 0;
501
502
DPRINTF("Requested patch: '%s'\n", patches[i]);
503
}
504
505
// Parse external patches if needed.
506
for (u32 i = 0; i < patches_num; i++)
507
{
508
if (!strcmp(patches[i], "emummc"))
509
{
510
// emuMMC patch is managed on its own.
511
emummc_patch_selected = true;
512
patches_applied |= BIT(i);
513
continue;
514
}
515
516
if (strcmp(patches[i], "nogc"))
517
parse_external_kip_patches();
518
}
519
520
u32 kip_hash[SE_SHA_256_SIZE / sizeof(u32)];
521
LIST_FOREACH_ENTRY(pkg2_kip1_info_t, ki, info, link)
522
{
523
// Reset hash so it can be calculated for the new kip.
524
kip_hash[0] = 0;
525
526
bool emummc_patch_apply = emummc_patch_selected && !strcmp((char *)ki->kip1->name, "FS");
527
528
// Check all SHA256 ID sets. (IDs are grouped per KIP. IDs are still unique.)
529
for (u32 kip_id_idx = 0; kip_id_idx < _kip_id_sets_cnt; kip_id_idx++)
530
{
531
// Check if KIP name macthes ID's KIP name.
532
if (strcmp((char *)ki->kip1->name, _kip_id_sets[kip_id_idx].name) != 0)
533
continue;
534
535
// Check if there are patches to apply.
536
bool patches_found = false;
537
const kip1_patchset_t *patchset = _kip_id_sets[kip_id_idx].patchset;
538
while (patchset != NULL && patchset->name != NULL && !patches_found)
539
{
540
for (u32 i = 0; i < patches_num; i++)
541
{
542
// Continue if patch name does not match.
543
if (strcmp(patchset->name, patches[i]) != 0)
544
continue;
545
546
patches_found = true;
547
break;
548
}
549
patchset++;
550
}
551
552
// Don't bother hashing this KIP if no patches are enabled for it.
553
if (!patches_found && !emummc_patch_apply)
554
continue;
555
556
// Check if current KIP not hashed and hash it.
557
if (kip_hash[0] == 0)
558
if (!se_calc_sha256_oneshot(kip_hash, ki->kip1, ki->size))
559
memset(kip_hash, 0, sizeof(kip_hash));
560
561
// Check if kip is the expected version.
562
if (memcmp(kip_hash, _kip_id_sets[kip_id_idx].hash, sizeof(_kip_id_sets[0].hash)) != 0)
563
continue;
564
565
// Find out which sections are affected by the enabled patches, in order to decompress them.
566
u32 sections_affected = 0;
567
patchset = _kip_id_sets[kip_id_idx].patchset;
568
while (patchset != NULL && patchset->name != NULL)
569
{
570
if (patchset->patches != NULL)
571
{
572
for (u32 patch_idx = 0; patch_idx < patches_num; patch_idx++)
573
{
574
if (strcmp(patchset->name, patches[patch_idx]))
575
continue;
576
577
for (const kip1_patch_t *patch = patchset->patches; patch != NULL && (patch->length != 0); patch++)
578
sections_affected |= BIT(GET_KIP_PATCH_SECTION(patch->offset));
579
}
580
}
581
patchset++;
582
}
583
584
// If emuMMC is enabled, set its affected section.
585
if (emummc_patch_apply)
586
sections_affected |= BIT(KIP_TEXT);
587
588
// Got patches to apply to this kip, have to decompress it.
589
if (_decompress_kip(ki, sections_affected))
590
return (char *)ki->kip1->name; // Failed to decompress.
591
592
// Apply all patches for matched ID.
593
patchset = _kip_id_sets[kip_id_idx].patchset;
594
while (patchset != NULL && patchset->name != NULL)
595
{
596
for (u32 patch_idx = 0; patch_idx < patches_num; patch_idx++)
597
{
598
// Check if patchset name matches requested patch.
599
if (strcmp(patchset->name, patches[patch_idx]))
600
continue;
601
602
u32 applied_mask = BIT(patch_idx);
603
604
// Check if patchset is empty.
605
if (patchset->patches == NULL)
606
{
607
DPRINTF("Patch '%s' not necessary for %s\n", patchset->name, (char *)ki->kip1->name);
608
patches_applied |= applied_mask;
609
610
continue; // Continue in case it's double defined.
611
}
612
613
// Apply patches per section.
614
u8 *kip_sect_data = ki->kip1->data;
615
for (u32 section_idx = 0; section_idx < KIP1_NUM_SECTIONS; section_idx++)
616
{
617
if (sections_affected & BIT(section_idx))
618
{
619
gfx_printf("Applying '%s' on %s, sect %d\n", patchset->name, (char *)ki->kip1->name, section_idx);
620
for (const kip1_patch_t *patch = patchset->patches; patch != NULL && patch->src_data != NULL; patch++)
621
{
622
// Check if patch is in current section.
623
if (GET_KIP_PATCH_SECTION(patch->offset) != section_idx)
624
continue;
625
626
// Check if patch is empty.
627
if (!patch->length)
628
{
629
gfx_con.mute = false;
630
gfx_printf("%kPatch empty!%k\n", TXT_CLR_ERROR, TXT_CLR_DEFAULT);
631
return patchset->name; // MUST stop here as it's not probably intended.
632
}
633
634
// If source does not match and is not already patched, throw an error.
635
u32 patch_offset = GET_KIP_PATCH_OFFSET(patch->offset);
636
if (patch->src_data != KIP1_PATCH_SRC_NO_CHECK &&
637
(memcmp(&kip_sect_data[patch_offset], patch->src_data, patch->length) != 0) &&
638
(memcmp(&kip_sect_data[patch_offset], patch->dst_data, patch->length) != 0))
639
{
640
gfx_con.mute = false;
641
gfx_printf("%kPatch mismatch at 0x%x!%k\n", TXT_CLR_ERROR, patch_offset, TXT_CLR_DEFAULT);
642
return patchset->name; // MUST stop here as kip is likely corrupt.
643
}
644
else
645
{
646
DPRINTF("Patching %d bytes at offset 0x%x\n", patch->length, patch_offset);
647
memcpy(&kip_sect_data[patch_offset], patch->dst_data, patch->length);
648
}
649
}
650
}
651
kip_sect_data += ki->kip1->sections[section_idx].size_comp;
652
}
653
654
patches_applied |= applied_mask;
655
}
656
657
patchset++;
658
}
659
660
// emuMMC must be applied after all other patches, since it affects TEXT offset.
661
if (emummc_patch_apply)
662
{
663
// Encode ID.
664
emu_cfg.fs_ver = kip_id_idx;
665
if (kip_id_idx)
666
emu_cfg.fs_ver--;
667
if (kip_id_idx > 17)
668
emu_cfg.fs_ver -= 2;
669
670
// Inject emuMMC code.
671
gfx_printf("Injecting emuMMC. FS ID: %d\n", emu_cfg.fs_ver);
672
if (_kipm_inject("bootloader/sys/emummc.kipm", "FS", ki))
673
return "emummc";
674
675
// Skip checking again.
676
emummc_patch_selected = false;
677
emummc_patch_apply = false;
678
}
679
}
680
}
681
682
// Check if all patches were applied.
683
for (u32 i = 0; i < patches_num; i++)
684
{
685
if ((patches_applied & BIT(i)) == 0)
686
return patches[i];
687
}
688
689
// Check if emuMMC was applied.
690
if (emummc_patch_selected)
691
return "emummc";
692
693
return NULL;
694
}
695
696
// Master key 7 encrypted with 8. (7.0.0 with 8.1.0). AES-ECB
697
static const u8 mkey_vector_7xx[SE_KEY_128_SIZE] =
698
{ 0xEA, 0x60, 0xB3, 0xEA, 0xCE, 0x8F, 0x24, 0x46, 0x7D, 0x33, 0x9C, 0xD1, 0xBC, 0x24, 0x98, 0x29 };
699
700
u8 pkg2_keyslot;
701
pkg2_hdr_t *pkg2_decrypt(void *data, u8 kb, bool is_exo)
702
{
703
u8 *pdata = (u8 *)data;
704
705
// Skip signature.
706
pdata += 0x100;
707
708
pkg2_hdr_t *hdr = (pkg2_hdr_t *)pdata;
709
710
// Skip header.
711
pdata += sizeof(pkg2_hdr_t);
712
713
// Set pkg2 key slot to default. If 7.0.0 it will change to 9.
714
pkg2_keyslot = 8;
715
716
// Decrypt 7.0.0 pkg2 via 8.1.0 mkey on Erista.
717
if (!h_cfg.t210b01 && kb == HOS_KB_VERSION_700)
718
{
719
u8 tmp_mkey[SE_KEY_128_SIZE];
720
721
// Decrypt 7.0.0 encrypted mkey.
722
se_aes_crypt_ecb(!is_exo ? 7 : 13, DECRYPT, tmp_mkey, SE_KEY_128_SIZE, mkey_vector_7xx, SE_KEY_128_SIZE);
723
724
// Set and unwrap pkg2 key.
725
se_aes_key_set(9, tmp_mkey, SE_KEY_128_SIZE);
726
se_aes_unwrap_key(9, 9, package2_keyseed);
727
728
pkg2_keyslot = 9;
729
}
730
731
// Decrypt header.
732
se_aes_crypt_ctr(pkg2_keyslot, hdr, sizeof(pkg2_hdr_t), hdr, sizeof(pkg2_hdr_t), hdr);
733
734
if (hdr->magic != PKG2_MAGIC)
735
return NULL;
736
737
// Decrypt sections.
738
for (u32 i = 0; i < 4; i++)
739
{
740
DPRINTF("sec %d has size %08X\n", i, hdr->sec_size[i]);
741
if (!hdr->sec_size[i])
742
continue;
743
744
se_aes_crypt_ctr(pkg2_keyslot, pdata, hdr->sec_size[i], pdata, hdr->sec_size[i], &hdr->sec_ctr[i * SE_AES_IV_SIZE]);
745
746
pdata += hdr->sec_size[i];
747
}
748
749
return hdr;
750
}
751
752
static u32 _pkg2_ini1_build(u8 *pdst, u8 *psec, pkg2_hdr_t *hdr, link_t *kips_info, bool new_pkg2)
753
{
754
// Calculate INI1 size.
755
u32 ini1_size = sizeof(pkg2_ini1_t);
756
LIST_FOREACH_ENTRY(pkg2_kip1_info_t, ki, kips_info, link)
757
{
758
ini1_size += ki->size;
759
}
760
761
// Align size and set it.
762
ini1_size = ALIGN(ini1_size, 4);
763
764
// For new kernel if INI1 fits in the old one, use it.
765
bool use_old_ini_region = psec && ini1_size <= (pkg2_newkern_ini1_end - pkg2_newkern_ini1_start);
766
if (use_old_ini_region)
767
pdst = psec + pkg2_newkern_ini1_start;
768
769
// Set initial header and magic.
770
pkg2_ini1_t *ini1 = (pkg2_ini1_t *)pdst;
771
memset(ini1, 0, sizeof(pkg2_ini1_t));
772
ini1->magic = INI1_MAGIC;
773
ini1->size = ini1_size;
774
pdst += sizeof(pkg2_ini1_t);
775
776
// Merge KIPs into INI1.
777
LIST_FOREACH_ENTRY(pkg2_kip1_info_t, ki, kips_info, link)
778
{
779
DPRINTF("adding kip1 '%s' @ %08X (%08X)\n", (char *)ki->kip1->name, (u32)ki->kip1, ki->size);
780
memcpy(pdst, ki->kip1, ki->size);
781
pdst += ki->size;
782
ini1->num_procs++;
783
}
784
785
// Encrypt INI1 in its own section if old pkg2. Otherwise it gets embedded into Kernel.
786
if (!new_pkg2)
787
{
788
hdr->sec_size[PKG2_SEC_INI1] = ini1_size;
789
hdr->sec_off[PKG2_SEC_INI1] = 0x14080000;
790
se_aes_crypt_ctr(8, ini1, ini1_size, ini1, ini1_size, &hdr->sec_ctr[PKG2_SEC_INI1 * SE_AES_IV_SIZE]);
791
}
792
else
793
{
794
hdr->sec_size[PKG2_SEC_INI1] = 0;
795
hdr->sec_off[PKG2_SEC_INI1] = 0;
796
}
797
798
return !use_old_ini_region ? ini1_size : 0;
799
}
800
801
void pkg2_build_encrypt(void *dst, void *hos_ctxt, link_t *kips_info, bool is_exo)
802
{
803
launch_ctxt_t *ctxt = (launch_ctxt_t *)hos_ctxt;
804
u32 meso_magic = *(u32 *)(ctxt->kernel + 4);
805
u32 kernel_size = ctxt->kernel_size;
806
u8 kb = ctxt->pkg1_id->kb;
807
u8 *pdst = (u8 *)dst;
808
809
// Force new Package2 if Mesosphere.
810
bool is_meso = (meso_magic & 0xF0FFFFFF) == ATM_MESOSPHERE;
811
if (is_meso)
812
ctxt->new_pkg2 = true;
813
814
// Set key version. For Erista 7.0.0, use 8.1.0 because of a bug in Exo2?
815
u8 key_ver = kb ? kb + 1 : 0;
816
if (pkg2_keyslot == 9)
817
{
818
key_ver = HOS_KB_VERSION_810 + 1;
819
pkg2_keyslot = 8;
820
}
821
822
// Signature.
823
memset(pdst, 0, 0x100);
824
pdst += 0x100;
825
826
// Header.
827
pkg2_hdr_t *hdr = (pkg2_hdr_t *)pdst;
828
memset(hdr, 0, sizeof(pkg2_hdr_t));
829
830
// Set initial header values.
831
hdr->magic = PKG2_MAGIC;
832
hdr->bl_ver = 0;
833
hdr->pkg2_ver = 0xFF;
834
835
if (!ctxt->new_pkg2)
836
hdr->base = 0x10000000;
837
else
838
hdr->base = 0x60000;
839
DPRINTF("%s @ %08X (%08X)\n", is_meso ? "Mesosphere": "kernel",(u32)ctxt->kernel, kernel_size);
840
841
pdst += sizeof(pkg2_hdr_t);
842
843
// Kernel.
844
memcpy(pdst, ctxt->kernel, kernel_size);
845
if (!ctxt->new_pkg2)
846
hdr->sec_off[PKG2_SEC_KERNEL] = 0x10000000;
847
else
848
{
849
// Build INI1 for new Package2.
850
u32 ini1_size = _pkg2_ini1_build(pdst + kernel_size, is_meso ? NULL : pdst, hdr, kips_info, true);
851
hdr->sec_off[PKG2_SEC_KERNEL] = 0x60000;
852
853
// Set new INI1 offset to kernel.
854
u32 meso_meta_offset = *(u32 *)(pdst + 8);
855
if (is_meso && (meso_magic & 0x0F000000)) // MSS1.
856
*(u32 *)(pdst + meso_meta_offset) = kernel_size - meso_meta_offset;
857
else if (ini1_size)
858
{
859
if (is_meso) // MSS0.
860
*(u32 *)(pdst + 8) = kernel_size;
861
else
862
*(u32 *)(pdst + pkg2_newkern_ini1_info) = kernel_size - pkg2_newkern_ini1_rela;
863
}
864
865
kernel_size += ini1_size;
866
}
867
hdr->sec_size[PKG2_SEC_KERNEL] = kernel_size;
868
se_aes_crypt_ctr(pkg2_keyslot, pdst, kernel_size, pdst, kernel_size, &hdr->sec_ctr[PKG2_SEC_KERNEL * SE_AES_IV_SIZE]);
869
pdst += kernel_size;
870
DPRINTF("kernel encrypted\n");
871
872
// Build INI1 for old Package2.
873
u32 ini1_size = 0;
874
if (!ctxt->new_pkg2)
875
ini1_size = _pkg2_ini1_build(pdst, NULL, hdr, kips_info, false);
876
DPRINTF("INI1 encrypted\n");
877
878
if (!is_exo) // Not needed on Exosphere 1.0.0 and up.
879
{
880
// Calculate SHA256 over encrypted sections. Only 3 have valid hashes.
881
u8 *pk2_hash_data = (u8 *)dst + 0x100 + sizeof(pkg2_hdr_t);
882
for (u32 i = PKG2_SEC_KERNEL; i <= PKG2_SEC_UNUSED; i++)
883
{
884
se_calc_sha256_oneshot(&hdr->sec_sha256[SE_SHA_256_SIZE * i], (void *)pk2_hash_data, hdr->sec_size[i]);
885
pk2_hash_data += hdr->sec_size[i];
886
}
887
}
888
889
// Encrypt header.
890
*(u32 *)hdr->ctr = 0x100 + sizeof(pkg2_hdr_t) + kernel_size + ini1_size;
891
hdr->ctr[4] = key_ver;
892
se_aes_crypt_ctr(pkg2_keyslot, hdr, sizeof(pkg2_hdr_t), hdr, sizeof(pkg2_hdr_t), hdr);
893
memset(hdr->ctr, 0 , SE_AES_IV_SIZE);
894
*(u32 *)hdr->ctr = 0x100 + sizeof(pkg2_hdr_t) + kernel_size + ini1_size;
895
hdr->ctr[4] = key_ver;
896
}
897
898