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