This repository has been archived by the owner on Aug 18, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathWADGEN.py
1403 lines (1193 loc) · 50.2 KB
/
WADGEN.py
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import binascii
import os
import struct
from Crypto.PublicKey.RSA import construct
from Crypto.Signature import PKCS1_v1_5
from requests import get, HTTPError
import utils
from Struct import Struct
from utils import CachedProperty
DECRYPTION_KEYS = [
b"\xEB\xE4\x2A\x22\x5E\x85\x93\xE4\x48\xD9\xC5\x45\x73\x81\xAA\xF7", # Common Key
b"\x63\xB8\x2B\xB4\xF4\x61\x4E\x2E\x13\xF2\xFE\xFB\xBA\x4C\x9B\x7E", # Korean Key
b"\x30\xbf\xc7\x6e\x7c\x19\xaf\xbb\x23\x16\x33\x30\xce\xd7\xc2\x8d" # vWii Key
]
DSI_KEY = b"\xAF\x1B\xF5\x16\xA8\x07\xD2\x1A\xEA\x45\x98\x4F\x04\x74\x28\x61" # DSi Key
class Signature:
"""Represents the Signature
Reference: https://www.3dbrew.org/wiki/Title_metadata#Signature_Data
"""
class SignatureRSA2048(Struct):
__endian__ = Struct.BE
def __format__(self):
self.type = Struct.uint32
self.data = Struct.string(0x100)
self.padding = Struct.string(0x3C)
class SignatureRSA4096(Struct):
__endian__ = Struct.BE
def __format__(self):
self.type = Struct.uint32
self.data = Struct.string(0x200)
self.padding = Struct.string(0x3C)
class SignatureECC(Struct):
__endian__ = Struct.BE
def __format__(self):
self.type = Struct.uint32
self.data = Struct.string(0x3C)
self.padding = Struct.string(0x40)
def __init__(self, filebytes):
signature_type = filebytes[:4]
self.signature_length = utils.get_sig_size(signature_type)
if self.signature_length == 0x200 + 0x3C:
self.signature = self.SignatureRSA4096()
elif self.signature_length == 0x100 + 0x3C:
self.signature = self.SignatureRSA2048()
elif self.signature_length == 0x3C + 0x40:
self.signature = self.SignatureECC()
else:
raise Exception("Unknown signature type {0}".format(signature_type)) # Should never happen
self.signature = self.signature.unpack(filebytes[:0x04 + self.signature_length])
def __len__(self):
return 0x04 + self.signature_length
def __repr__(self):
return "{0} Signature Data".format(self.get_signature_type())
def pack(self):
return self.signature.pack()
def get_signature_type(self):
if self.signature_length == 0x200 + 0x3C:
return "RSA-4096 SHA1"
elif self.signature_length == 0x100 + 0x3C:
return "RSA-2048 SHA1"
elif self.signature_length == 0x3C + 0x40:
return "ECC"
else:
return "Unknown"
class Certificate:
"""Represents a Certificate
Reference: https://www.3dbrew.org/wiki/Certificates
"""
class CertificateStruct(Struct):
__endian__ = Struct.BE
def __format__(self):
self.issuer = Struct.string(0x40)
self.key_type = Struct.uint32
self.name = Struct.string(0x40)
self.unknown = Struct.uint32
class PubKeyRSA4096(Struct):
__endian__ = Struct.BE
def __format__(self):
self.modulus = Struct.string(0x200)
self.exponent = Struct.uint32
self.padding = Struct.string(0x34)
class PubKeyRSA2048(Struct):
__endian__ = Struct.BE
def __format__(self):
self.modulus = Struct.string(0x100)
self.exponent = Struct.uint32
self.padding = Struct.string(0x34)
class PubKeyECC(Struct):
__endian__ = Struct.BE
def __format__(self):
self.key = Struct.string(0x3C)
self.padding = Struct.string(0x3C)
def __init__(self, filebytes):
self.signature = Signature(filebytes)
self.certificate = self.CertificateStruct().unpack(
filebytes[len(self.signature):
len(self.signature) + len(self.CertificateStruct())]
)
pubkey_length = utils.get_key_length(self.certificate.key_type)
if pubkey_length == 0x200 + 0x4 + 0x34:
self.pubkey_struct = self.PubKeyRSA4096()
elif pubkey_length == 0x100 + 0x4 + 0x34:
self.pubkey_struct = self.PubKeyRSA2048()
elif pubkey_length == 0x3C + 0x3C:
self.pubkey_struct = self.PubKeyECC()
else:
raise Exception("Unknown Public Key type") # Should never happen
self.pubkey_struct = self.pubkey_struct.unpack(
filebytes[len(self.signature) + len(self.certificate):
len(self.signature) + len(self.certificate) + pubkey_length]
)
if pubkey_length != 0x3C + 0x3C:
self.pubkey = construct(
(int.from_bytes(self.pubkey_struct.modulus, byteorder="big"), self.pubkey_struct.exponent)
)
self.signer = PKCS1_v1_5.new(self.pubkey)
else:
self.pubkey = None
self.signer = None
def __len__(self):
return len(self.signature) + len(self.certificate) + len(self.pubkey_struct)
def __repr__(self):
return "{0} issued by {1}".format(self.get_name(), self.get_issuer())
def __str__(self):
output = "Certificate:\n"
output += " {0} ({1})\n".format(self.get_name(), self.get_key_type())
output += " Signed by {0} using {1}".format(self.get_issuer(), self.signature.get_signature_type())
return output
def pack(self):
return self.signature.pack() + self.signature_pack()
def signature_pack(self):
return self.certificate.pack() + self.pubkey_struct.pack()
def get_issuer(self):
return self.certificate.issuer.rstrip(b"\00").decode().split("-")[-1]
def get_name(self):
return self.certificate.name.rstrip(b"\00").decode()
def get_key_type(self):
# https://www.3dbrew.org/wiki/Certificates#Public_Key
key_types = [
"RSA-4096",
"RSA-2048",
"Elliptic Curve"
]
try:
return key_types[self.certificate.key_type]
except IndexError:
return "Invalid key type"
class RootCertificate:
"""Represents the Root Certificate
Reference: https://www.3dbrew.org/wiki/Certificates
"""
class PubKeyRSA4096(Struct):
__endian__ = Struct.BE
def __format__(self):
self.modulus = Struct.string(0x200)
self.exponent = Struct.uint32
def __init__(self, file):
if isinstance(file, str): # Load file
try:
file = open(file, 'rb').read()
except FileNotFoundError:
raise FileNotFoundError('File not found')
self.pubkey_struct = self.PubKeyRSA4096().unpack(file)
self.pubkey = construct(
(int.from_bytes(self.pubkey_struct.modulus, byteorder="big"), self.pubkey_struct.exponent)
)
self.signer = PKCS1_v1_5.new(self.pubkey)
def __len__(self):
return len(self.pubkey_struct)
def __repr__(self):
return "Wii Root Certificate"
def __str__(self):
output = "Certificate:\n"
output += " {0} ({1})\n".format(self.get_name(), self.get_key_type())
return output
def pack(self):
return self.pubkey_struct.pack()
@staticmethod
def get_name():
return "Root"
@staticmethod
def get_key_type():
return "RSA-4096"
if os.path.isfile("root-key"):
ROOT_KEY = RootCertificate("root-key") # https://static.hackmii.com/root-key
else:
ROOT_KEY = None
class TMD:
"""Represents the Title Metadata
Reference: https://wiibrew.org/wiki/Title_metadata
Args:
file (Union[str, bytes]): Path to TMD or a TMD bytes-object
"""
class TMDHeader(Struct):
__endian__ = Struct.BE
def __format__(self):
self.issuer = Struct.string(64)
self.version = Struct.uint8
self.ca_crl_version = Struct.uint8
self.signer_crl_version = Struct.uint8
self.padding1 = Struct.uint8
self.system_version = Struct.uint64
self.titleid = Struct.uint64
self.type = Struct.uint32
self.group_id = Struct.uint16
self.zero = Struct.uint16
self.region = Struct.uint16
self.ratings = Struct.string(16)
self.reserved2 = Struct.string(12)
self.ipc_mask = Struct.string(12)
self.reserved3 = Struct.string(18)
self.access_rights = Struct.uint32
self.titleversion = Struct.uint16
self.contentcount = Struct.uint16
self.bootindex = Struct.uint16
self.padding2 = Struct.uint16
class TMDContents(Struct):
__endian__ = Struct.BE
def __format__(self):
self.cid = Struct.uint32
self.index = Struct.uint16
self.type = Struct.uint16
self.size = Struct.uint64
self.sha1 = Struct.string(20)
def get_cid(self):
return ("%08X" % self.cid).lower()
def get_iv(self):
return struct.pack(">H", self.index) + b"\x00" * 14
def get_type(self):
# https://github.com/dnasdw/libwiisharp/blob/master/libWiiSharp/TMD.cs#L27-L29
types = {
0x0001: "Normal",
0x4001: "DLC",
0x8001: "Shared"
}
try:
return types[self.type]
except KeyError:
return "Unknown"
def get_sha1_hex(self):
return binascii.hexlify(self.sha1).decode()
def get_hash_type(self):
hashes = {
"0d946e47249b00f6ad6c0037413d645da1a59f22": "Tiny vWii NAND Loader r2",
"9d19271538fbbef920a566a855cac71aa3fa4992": "Custom NAND Loader v1.1 MOD",
"f6b96dbf81b34500e1f723cab7acf544a40779db": "Custom NAND Loader v1.1 MOD IOS53",
"25c8b3c3ba6b1f0a27db400a5705652afdc22748": "Custom NAND Loader v1.1 MOD IOS55",
"7973a2a2123e7e4d716bba4a19855691f5ff458c": "Custom NAND Loader v1.1 MOD IOS56",
}
try:
return hashes[self.get_sha1_hex()]
except KeyError:
return None
def __repr__(self):
output = "Content {0}".format(self.get_cid())
return output
def __str__(self):
output = "Content:\n"
output += " ID Index Type Size Hash\n"
output += " {:s} {:<7d} {:<8s} {:<11s}".format(
self.get_cid(),
self.index,
self.get_type(),
utils.convert_size(self.size)
)
output += self.get_sha1_hex()
if self.get_hash_type():
output += " ({0})".format(self.get_hash_type())
output += "\n"
return output
def __init__(self, file):
if isinstance(file, str): # Load file
try:
file = open(file, 'rb').read()
except FileNotFoundError:
raise FileNotFoundError('File not found')
# Signature
self.signature = Signature(file)
pos = len(self.signature)
# Header
self.hdr = self.TMDHeader().unpack(file[pos:pos + len(self.TMDHeader())])
pos += len(self.hdr)
# Content Records
self.contents = []
for i in range(self.hdr.contentcount):
self.contents.append(self.TMDContents().unpack(file[pos:pos + len(self.TMDContents())]))
pos += len(self.TMDContents())
# Certificates
self.certificates = []
if file[pos:]:
self.certificates.append(Certificate(file[pos:]))
pos += len(self.certificates[0])
self.certificates.append(Certificate(file[pos:]))
if self.certificates:
if len(self.certificates) != 2:
raise Exception("Could not locate all Certs!")
def get_titleid(self):
return "{:08X}".format(self.hdr.titleid).zfill(16).lower()
def get_required_title(self):
return "{:08X}".format(self.hdr.system_version).zfill(16).lower()
def get_boot_index(self):
return ("%08X" % self.hdr.bootindex).lower()
def get_issuer(self):
"""Returns list with the certificate chain issuers.
There should be exactly three: the last one (CP) signs the TMD,
the one before that (CA) signs the CP cert and
the first one (Root) signs the CA cert.
"""
return self.hdr.issuer.rstrip(b"\00").decode().split("-")
def get_content_size(self):
size = 0
for content in self.contents:
size += content.size
size += utils.align_pointer(content.size)
return size
def get_type(self):
# https://dsibrew.org/wiki/Title_list#System_Codes
if self.get_titleid().startswith("00030"): # DSi
types = {
"4B": "DSiWare",
"48": "DSi System / Channel"
}
try:
return types[self.get_titleid()[8:10].upper()]
except KeyError:
return "Unknown"
else:
# https://wiibrew.org/wiki/Title_metadata#Example_code_application
types = {
"00000001": "System",
"00010000": "Game",
"00010001": "Channel",
"00010002": "System Channel",
"00010004": "Game Channel",
"00010005": "Downloadable Content",
"00010008": "Hidden Channel"
}
try:
return types[self.get_titleid()[:8].upper()]
except KeyError:
return "Unknown"
def get_region(self):
if self.get_titleid().startswith("00030"): # DSi
# https://dsibrew.org/wiki/Title_list#Region_Codes
regions = {
"41": "Free",
"43": "China",
"45": "North America",
"48": "Belgium / Netherlands",
"4A": "Japan",
"4B": "Korea",
"50": "Europe",
"55": "Australia and New Zealand",
"56": "Europe"
}
try:
return regions[self.get_titleid()[-2:].upper()]
except KeyError:
return "Unknown"
else:
# https://github.com/dnasdw/libwiisharp/blob/master/libWiiSharp/TMD.cs#L34-L37
regions = [
"Japan",
"USA",
"Europe",
"Free",
"Korea"
]
try:
return regions[self.hdr.region]
except IndexError:
return "Unknown"
def get_cr_index_by_cid(self, cid):
"""Returns Content Record index by CID."""
for i, content in enumerate(self.contents):
if content.get_cid() == cid:
return i
raise ValueError("CID {0} not found.".format(cid))
def get_cr_by_cid(self, cid):
"""Returns Content Record by CID."""
return self.contents[self.get_cr_index_by_cid(cid)]
def get_cert_by_name(self, name):
"""Returns certificate by name."""
for i, cert in enumerate(self.certificates):
if cert.get_name() == name:
return i
if name == "Root":
if ROOT_KEY:
return ROOT_KEY
raise ValueError("Certificate '{0}' not found.".format(name))
def fakesign(self):
"""Fakesigns TMD.
https://github.com/FIX94/Some-YAWMM-Mod/blob/e2708863036066c2cc8bad1fc142e90fb8a0464d/source/title.c#L50-L76
"""
# Fill signature with zeroes
sigsize = len(self.signature.signature.data)
self.signature.signature.data = b"\x00" * sigsize
# Modify content until SHA1 hash starts with 00
for i in range(65535): # Max value for unsigned short integer (2 bytes)
# Modify tmd padding2
self.hdr.padding2 = i
# Calculate hash
sha1hash = utils.Crypto.create_sha1hash_hex(self.signature_pack())
# Found valid hash!
if sha1hash.startswith("00"):
return
raise Exception("Fakesigning failed.")
def pack(self):
"""Returns TMD WITHOUT certificates."""
return self.signature.pack() + self.signature_pack()
def signature_pack(self):
"""Returns TMD only with body (the part that is signed)."""
pack = self.hdr.pack()
for content in self.contents:
pack += content.pack()
return pack
def dump(self, output=None):
"""Dumps TMD to output WITH Certificates. Replaces {titleid} and {titleversion} if in filename.
Returns raw binary if no output is given, returns the file path else.
"""
if output:
output = output.format(titleid=self.get_titleid(), titleversion=self.hdr.titleversion)
pack = self.pack()
for cert in self.certificates:
pack += cert.pack()
if output:
with open(output, "wb") as tmd_file:
tmd_file.write(pack)
return output
else:
return pack
def __len__(self):
"""Returns length of TMD WITHOUT certificates."""
size = 0
for content in self.contents:
size += len(content)
return size + len(self.signature) + len(self.hdr)
def __repr__(self):
return 'Title {id} v{ver}'.format(
id=self.get_titleid(),
ver=self.hdr.titleversion,
)
def __str__(self):
output = "TMD:\n"
output += " Title ID: {0}\n".format(self.get_titleid())
output += " Title Version: {0}\n".format(self.hdr.titleversion)
output += " Title Type: {0}\n".format(self.get_type())
if self.get_type() != "System":
output += " Region: {0}\n".format(self.get_region())
if self.hdr.system_version:
output += " Requires: {0}\n".format(self.get_required_title())
if self.hdr.bootindex:
output += " Boot APP: {0}\n".format(self.get_boot_index())
output += "\n"
output += " Number of contents: {0}\n".format(self.hdr.contentcount)
output += " Contents:\n"
output += " ID Index Type Size Hash\n"
for content in self.contents:
output += " {:s} {:<7d} {:<8s} {:<11s}".format(
content.get_cid(),
content.index,
content.get_type(),
utils.convert_size(content.size)
)
output += content.get_sha1_hex()
if content.get_hash_type():
output += " ({0})".format(content.get_hash_type())
output += "\n"
# TODO: Improve this, is a bit complicated to understand and duplicated
if self.certificates:
output += "\n"
output += " Certificates:\n"
try:
signs_tmd = self.get_cert_by_name(self.get_issuer()[-1]) # CP
signs_cp = self.get_cert_by_name(self.get_issuer()[1]) # CA
except ValueError:
output += " Could not locate the needed certificates.\n"
return output
try:
signs_ca = self.get_cert_by_name(self.get_issuer()[0]) # Root
except ValueError:
signs_ca = None
# Check TMD signature
verified = utils.Crypto.verify_signature(
self.certificates[signs_tmd],
self.signature_pack(),
self.signature
)
sha1hash = utils.Crypto.create_sha1hash_hex(self.signature_pack())
output += " TMD signed by {0} using {1}: {2} ".format(
"-".join(self.get_issuer()),
self.certificates[signs_tmd].get_key_type(),
sha1hash
)
if verified:
output += "[OK]"
else:
if sha1hash.startswith("00") and int.from_bytes(self.signature.signature.data, byteorder="big") == 0:
output += "[FAKESIGNED]"
else:
output += "[FAIL]"
output += "\n"
# Check CP signature
verified = utils.Crypto.verify_signature(
self.certificates[signs_cp],
self.certificates[signs_tmd].signature_pack(),
self.certificates[signs_tmd].signature
)
sha1hash = utils.Crypto.create_sha1hash_hex(self.certificates[signs_tmd].signature_pack())
output += " {0} ({1}) signed by {2} ({3}): {4} ".format(
self.certificates[signs_tmd].get_name(),
self.certificates[signs_tmd].get_key_type(),
self.certificates[signs_tmd].get_issuer(),
self.certificates[signs_cp].get_key_type(),
sha1hash
)
if verified:
output += "[OK]"
else:
output += "[FAIL]"
output += "\n"
# Check Root signature
if signs_ca:
verified = utils.Crypto.verify_signature(
signs_ca,
self.certificates[signs_cp].signature_pack(),
self.certificates[signs_cp].signature
)
sha1hash = utils.Crypto.create_sha1hash_hex(self.certificates[signs_cp].signature_pack())
output += " {0} ({1}) signed by {2} ({3}): {4} ".format(
self.certificates[signs_cp].get_name(),
self.certificates[signs_cp].get_key_type(),
self.certificates[signs_cp].get_issuer(),
ROOT_KEY.get_key_type(),
sha1hash
)
if verified:
output += "[OK]"
else:
output += "[FAIL]"
else:
output += " {0} ({1}) signed by {2}: Please place root-key in the same directory".format(
self.certificates[signs_cp].get_name(),
self.certificates[signs_cp].get_key_type(),
self.certificates[signs_cp].get_issuer()
)
output += "\n"
return output
class Ticket:
"""Represents the Ticket
Reference: https://wiibrew.org/wiki/Ticket
Args:
file (Union[str, bytes]): Path to Ticket or a Ticket bytes-object
"""
class TicketHeader(Struct):
__endian__ = Struct.BE
def __format__(self):
self.issuer = Struct.string(0x40)
self.ecdhdata = Struct.string(0x3C)
self.unused1 = Struct.string(0x03)
self.titlekey = Struct.string(0x10)
self.unknown1 = Struct.uint8
self.ticketid = Struct.uint64
self.consoleid = Struct.uint32
self.titleid = Struct.uint64
self.unknown2 = Struct.uint16
self.titleversion = Struct.uint16
self.permitted_titles_mask = Struct.uint32
self.permit_mask = Struct.uint32
self.export_allowed = Struct.uint8
self.ckeyindex = Struct.uint8
self.unknown3 = Struct.string(0x30)
self.content_access_permissions = Struct.string(0x40)
self.padding = Struct.uint16
self.limits = Struct.string(0x40)
def __init__(self, file):
if isinstance(file, str):
try:
file = open(file, 'rb').read()
except FileNotFoundError:
raise FileNotFoundError('File not found')
# Signature
self.signature = Signature(file)
pos = len(self.signature)
# Header
self.hdr = self.TicketHeader().unpack(file[pos:pos + 0x210])
pos += len(self.hdr)
self.titleiv = struct.pack(">Q", self.hdr.titleid) + b"\x00" * 8
# Certificates
self.certificates = []
if file[pos:]:
self.certificates.append(Certificate(file[pos:]))
pos += len(self.certificates[0])
self.certificates.append(Certificate(file[pos:]))
if self.certificates:
if len(self.certificates) != 2:
raise Exception("Could not locate all Certs!")
# Decrypt title key
self.decrypted_titlekey = utils.Crypto.decrypt_titlekey(
commonkey=self.get_decryption_key(),
iv=self.titleiv,
titlekey=self.hdr.titlekey
)
def get_titleid(self):
return "{:08X}".format(self.hdr.titleid).zfill(16).lower()
def get_issuer(self):
"""Returns list with the certificate chain issuers.
There should be exactly three: the last one (XS) signs the Ticket,
the one before that (CA) signs the CP cert and
the first one (Root) signs the CA cert.
"""
return self.hdr.issuer.rstrip(b"\00").decode().split("-")
def get_decryption_key(self):
# TODO: Debug (RVT) Tickets
"""Returns the appropiate Common Key"""
if self.get_titleid().startswith("00030"):
return DSI_KEY
try:
return DECRYPTION_KEYS[self.hdr.ckeyindex]
except IndexError:
print("WARNING: Unknown Common Key, assuming normal key")
return DECRYPTION_KEYS[0]
def get_common_key_type(self):
if self.get_titleid().startswith("00030"):
return "DSi"
key_types = [
"Normal",
"Korean",
"Wii U Wii Mode"
]
try:
return key_types[self.hdr.ckeyindex]
except IndexError:
return "Unknown"
def get_cert_by_name(self, name):
"""Returns certificate by name."""
for i, cert in enumerate(self.certificates):
if cert.get_name() == name:
return i
if name == "Root":
if ROOT_KEY:
return ROOT_KEY
raise ValueError("Certificate '{0}' not found.".format(name))
def fakesign(self):
"""Fakesigns ticket.
https://github.com/FIX94/Some-YAWMM-Mod/blob/e2708863036066c2cc8bad1fc142e90fb8a0464d/source/title.c#L22-L48
"""
# Fill signature with zeroes
sigsize = len(self.signature.signature.data)
self.signature.signature.data = b"\x00" * sigsize
# Modify content until SHA1 hash starts with 00
for i in range(65535): # Max value for unsigned short integer (2 bytes)
# Modify ticket padding
self.hdr.padding = i
# Calculate hash
sha1hash = utils.Crypto.create_sha1hash_hex(self.signature_pack())
# Found valid hash!
if sha1hash.startswith("00"):
return
raise Exception("Fakesigning failed.")
def pack(self):
"""Returns ticket WITHOUT certificates"""
return self.signature.pack() + self.hdr.pack()
def signature_pack(self):
"""Returns Ticket only with body (the part that is signed)."""
return self.hdr.pack()
def dump(self, output=None):
"""Dumps ticket to output WITH Certificates. Replaces {titleid} and {titleversion} if in filename.
NOTE that the titleversion in the ticket is often wrong!
Returns raw binary if no output is given, returns the file path else.
"""
if output:
output = output.format(titleid=self.get_titleid(), titleversion=self.hdr.titleversion)
pack = self.pack()
for cert in self.certificates:
pack += cert.pack()
if output:
with open(output, "wb") as cetk_file:
cetk_file.write(pack)
return output
else:
return pack
def __len__(self):
"""Returns length of ticket WITHOUT certificates"""
return len(self.signature) + len(self.hdr)
def __repr__(self):
return 'Ticket for title {id} v{ver}'.format(id=self.get_titleid(), ver=self.hdr.titleversion)
def __str__(self):
output = "Ticket:\n"
output += " Title ID: {0}\n".format(self.get_titleid())
output += " Ticket Title Version: {0}\n".format(self.hdr.titleversion)
if self.hdr.consoleid:
output += " Console ID: {0}\n".format(self.hdr.consoleid)
output += "\n"
output += " Common Key: {0}\n".format(self.get_common_key_type())
output += " Initialization vector: {0}\n".format(binascii.hexlify(self.titleiv).decode())
output += " Title key (encrypted): {0}\n".format(binascii.hexlify(self.hdr.titlekey).decode())
output += " Title key (decrypted): {0}\n".format(binascii.hexlify(self.decrypted_titlekey).decode())
# TODO: Improve this, is a bit complicated to understand and duplicated
if self.certificates:
output += "\n"
output += " Certificates:\n"
try:
signs_ticket = self.get_cert_by_name(self.get_issuer()[-1]) # XS
signs_cp = self.get_cert_by_name(self.get_issuer()[1]) # CA
except ValueError:
output += " Could not locate the needed certificates.\n"
return output
try:
signs_ca = self.get_cert_by_name(self.get_issuer()[0]) # Root
except ValueError:
signs_ca = None
# Check Ticket signature
verified = utils.Crypto.verify_signature(
self.certificates[signs_ticket],
self.signature_pack(),
self.signature
)
sha1hash = utils.Crypto.create_sha1hash_hex(self.signature_pack())
output += " Ticket signed by {0} using {1}: {2} ".format(
"-".join(self.get_issuer()),
self.certificates[signs_ticket].get_key_type(),
sha1hash
)
if verified:
output += "[OK]"
else:
if sha1hash.startswith("00") and int.from_bytes(self.signature.signature.data, byteorder="big") == 0:
output += "[FAKESIGNED]"
else:
output += "[FAIL]"
output += "\n"
# Check XS signature
verified = utils.Crypto.verify_signature(
self.certificates[signs_cp],
self.certificates[signs_ticket].signature_pack(),
self.certificates[signs_ticket].signature
)
sha1hash = utils.Crypto.create_sha1hash_hex(self.certificates[signs_ticket].signature_pack())
output += " {0} ({1}) signed by {2} ({3}): {4} ".format(
self.certificates[signs_ticket].get_name(),
self.certificates[signs_ticket].get_key_type(),
self.certificates[signs_ticket].get_issuer(),
self.certificates[signs_cp].get_key_type(),
sha1hash
)
if verified:
output += "[OK]"
else:
output += "[FAIL]"
output += "\n"
# Check Root signature
if signs_ca:
verified = utils.Crypto.verify_signature(
signs_ca,
self.certificates[signs_cp].signature_pack(),
self.certificates[signs_cp].signature
)
sha1hash = utils.Crypto.create_sha1hash_hex(self.certificates[signs_cp].signature_pack())
output += " {0} ({1}) signed by {2} ({3}): {4} ".format(
self.certificates[signs_cp].get_name(),
self.certificates[signs_cp].get_key_type(),
self.certificates[signs_cp].get_issuer(),
ROOT_KEY.get_key_type(),
sha1hash
)
if verified:
output += "[OK]"
else:
output += "[FAIL]"
else:
output += " {0} ({1}) signed by {2}: Please place root-key in the same directory".format(
self.certificates[signs_cp].get_name(),
self.certificates[signs_cp].get_key_type(),
self.certificates[signs_cp].get_issuer()
)
output += "\n"
return output
class WAD:
"""Represents a WAD file.
Reference: https://wiibrew.org/wiki/WAD_files
Args:
file (Union[str, bytes]): Path to WAD or a WAD bytes-object
"""
class WADHeader(Struct):
__endian__ = Struct.BE
def __format__(self):
self.hdrsize = Struct.uint32
self.type = Struct.string(0x04)
self.certchainsize = Struct.uint32
self.reserved = Struct.uint32
self.ticketsize = Struct.uint32
self.tmdsize = Struct.uint32
self.datasize = Struct.uint32
self.footersize = Struct.uint32
def __init__(self, file):
if isinstance(file, str):
try:
file = open(file, 'rb').read()
except FileNotFoundError:
raise FileNotFoundError('File not found')
# Header
self.hdr = self.WADHeader().unpack(file[:len(self.WADHeader())])
pos = self.hdr.hdrsize
# Certificates (always 3)
# Order is: CA + CP + XS
# TODO: Check vailidity of certs (+ dev certs)
pos += utils.align_pointer(pos)
self.certificates = []
for i in range(3):
self.certificates.append(Certificate(file[pos:]))
pos += len(self.certificates[i])
# Ticket
pos += utils.align_pointer(pos)
self.ticket = Ticket(file[pos:pos + self.hdr.ticketsize])
self.ticket.certificates.append(self.certificates[2]) # XS
self.ticket.certificates.append(self.certificates[0]) # CA
pos += self.hdr.ticketsize
# TMD
pos += utils.align_pointer(pos)
self.tmd = TMD(file[pos:pos + self.hdr.tmdsize])
self.tmd.certificates.append(self.certificates[1]) # CP
self.tmd.certificates.append(self.certificates[0]) # CA
pos += self.hdr.tmdsize
# Contents
pos += utils.align_pointer(pos)
self.contents = []
for content in self.tmd.contents:
content_size = content.size
content_size += utils.align_pointer(content_size, 16)
self.contents.append(file[pos:pos + content_size])
pos += content_size
pos += utils.align_pointer(pos)
# Footer, if present
pos += utils.align_pointer(pos)
if file[pos:]:
self.footer = file[pos:]
self.footer = self.footer[:self.hdr.footersize]
else:
self.footer = None
def pack(self):
"""Returns WAD file in binary."""
# Header
wad = self.hdr.pack()
wad += utils.align(len(self.hdr))
# Certificate Chain
wad += b"".join([x.pack() for x in self.certificates])
wad += utils.align(self.hdr.certchainsize)
# Ticket
wad += self.ticket.pack()
wad += utils.align(self.hdr.ticketsize)
# TMD
wad += self.tmd.pack()
wad += utils.align(self.hdr.tmdsize)