sceutils 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sceutils/sceutils.py ADDED
@@ -0,0 +1,94 @@
1
+ import binascii
2
+ import zlib
3
+ from binascii import b2a_hex
4
+ from typing import IO
5
+
6
+ from Cryptodome.Cipher import AES
7
+
8
+ from . import keys
9
+ from .scetypes import (AppInfoHeader, CompressionType, EncryptionType,
10
+ KeyType, MetadataHeader, MetadataInfo,
11
+ MetadataSection, SceHeader, SceSegment, SceType,
12
+ SelfHeader, SelfType, SpkgHeader, SrvkHeader)
13
+
14
+
15
+ def zrif_decode(data: str) -> bytes:
16
+ zrif_dict = list(zlib.decompress(binascii.a2b_base64(b"eNpjYBgFo2AU0AsYAIElGt8MRJiDCAsw3xhEmIAIU4N4AwNdRxcXZ3+/EJCAkW6Ac7C7ARwYgviuQAaIdoPSzlDaBUo7QmknIM3ACIZM78+u7kx3VWYEAGJ9HV0=")))
17
+ d = zlib.decompressobj(wbits=10, zdict=bytes(zrif_dict))
18
+ raw = binascii.a2b_base64(data)
19
+ out = d.decompress(raw)
20
+ out += d.flush()
21
+ return out
22
+
23
+
24
+ def print_metadata_keyvault(keys):
25
+ print(' Metadata Vault:')
26
+ for i, key in enumerate(keys):
27
+ print(f' {i:#0{4}x}: {b2a_hex(key)}')
28
+
29
+
30
+ def get_segments(inf: IO[bytes], sce_hdr: SceHeader, sysver=-1, self_type=SelfType.NONE, keytype=0, klictxt=b"\0"*16, silent=False, use_spkg2=False) -> dict[int, SceSegment]:
31
+ inf.seek(sce_hdr.metadata_offset + 48)
32
+ dat = inf.read(sce_hdr.header_length - sce_hdr.metadata_offset - 48)
33
+ sce_type = sce_hdr.sce_type if not use_spkg2 else (sce_hdr.sce_type, 2)
34
+ (key, iv) = keys.SCE_KEYS.get(KeyType.METADATA, sce_type, sysver, sce_hdr.key_revision, self_type)
35
+ hdr_dec = AES.new(key, AES.MODE_CBC, iv)
36
+ if self_type == SelfType.APP:
37
+ keytype = 0
38
+ if sce_hdr.key_revision >= 2:
39
+ keytype = 1
40
+ (np_key, np_iv) = keys.SCE_KEYS.get(KeyType.NPDRM, sce_type, sysver, keytype, self_type)
41
+ npdrm_dec = AES.new(np_key, AES.MODE_CBC, np_iv)
42
+ predec = npdrm_dec.decrypt(klictxt)
43
+ npdrm_dec2 = AES.new(predec, AES.MODE_CBC, np_iv)
44
+ dec_in = npdrm_dec2.decrypt(dat[0:MetadataInfo._size])
45
+ else:
46
+ dec_in = dat[0:MetadataInfo._size]
47
+
48
+ dec = hdr_dec.decrypt(dec_in)
49
+ metadata_info = MetadataInfo.unpack(dec)
50
+ if not silent:
51
+ print(metadata_info)
52
+ contents_dec = AES.new(metadata_info.key, AES.MODE_CBC, metadata_info.iv)
53
+ dec = contents_dec.decrypt(dat[MetadataInfo._size:])
54
+ metadata_hdr = MetadataHeader.unpack(dec[0:MetadataHeader._size])
55
+ if not silent:
56
+ print(metadata_hdr)
57
+ segs = {}
58
+ start = MetadataHeader._size + metadata_hdr.section_count * MetadataSection._size
59
+ vault = [dec[start + 16 * x:start + 16 * (x + 1)] for x in range(metadata_hdr.key_count)]
60
+ if not silent:
61
+ print_metadata_keyvault(vault)
62
+ for i in range(metadata_hdr.section_count):
63
+ dat = dec[MetadataHeader._size + i * MetadataSection._size:]
64
+ metsec = MetadataSection.unpack(dat[:MetadataSection._size])
65
+ if not silent:
66
+ print(metsec)
67
+ if metsec.encryption == EncryptionType.AES128CTR:
68
+ segs[i] = SceSegment(metsec.offset, metsec.seg_idx, metsec.size, metsec.compression == CompressionType.DEFLATE, vault[metsec.key_idx], vault[metsec.iv_idx])
69
+ return segs
70
+
71
+
72
+ def get_key_type(inf, sce_hdr, silent=False) -> tuple[tuple[int, SelfType], bool]:
73
+ if sce_hdr.sce_type == SceType.SELF:
74
+ inf.seek(32)
75
+ self_hdr = SelfHeader.unpack(inf)
76
+ inf.seek(self_hdr.appinfo_offset)
77
+ appinfo_hdr = AppInfoHeader.unpack(inf)
78
+ if not silent:
79
+ print(appinfo_hdr)
80
+ return (appinfo_hdr.sys_version, appinfo_hdr.self_type), False
81
+ elif sce_hdr.sce_type == SceType.SRVK:
82
+ inf.seek(sce_hdr.header_length)
83
+ srvk = SrvkHeader.unpack(inf)
84
+ if not silent:
85
+ print(srvk)
86
+ return (srvk.sys_version, SelfType.NONE), False
87
+ elif sce_hdr.sce_type == SceType.SPKG:
88
+ inf.seek(sce_hdr.header_length)
89
+ spkg = SpkgHeader.unpack(inf)
90
+ if not silent:
91
+ print(spkg)
92
+ return (spkg.update_version << 16, SelfType.NONE), False # spkg.field_48 == 0x40
93
+ else:
94
+ raise ValueError(f'Unknown system version for type {sce_hdr.sce_types}')
sceutils/self2elf.py ADDED
@@ -0,0 +1,242 @@
1
+ #!/usr/bin/python3
2
+
3
+ import argparse
4
+ import copy
5
+ import os
6
+ import sys
7
+ import zlib
8
+ from typing import IO
9
+
10
+ from Cryptodome.Cipher import AES
11
+ from Cryptodome.Util import Counter
12
+
13
+ from sceutils import sceutils
14
+ from sceutils import keys
15
+ from .scetypes import (AppInfoHeader, ControlType, ElfHeader, ElfPhdr,
16
+ ElfShdr, SceControlInfo,
17
+ SceControlInfoDigest256, SceControlInfoDRM,
18
+ SceHeader, SceRIF, SceVersionInfo, SecureBool,
19
+ SegmentInfo, SelfHeader)
20
+
21
+
22
+ def self2elf(inf: IO[bytes], outf: IO[bytes] | None = None, klictxt=b'\0'*16, silent=False, ignore_sysver=False):
23
+ if outf is None:
24
+ outf = open(os.devnull, "wb")
25
+
26
+ sce = SceHeader.unpack(inf)
27
+ if not silent:
28
+ print(sce)
29
+ self_hdr = SelfHeader.unpack(inf)
30
+
31
+ inf.seek(self_hdr.appinfo_offset)
32
+ appinfo_hdr = AppInfoHeader.unpack(inf)
33
+ if ignore_sysver:
34
+ appinfo_hdr.sys_version = -1
35
+ if not silent:
36
+ print(appinfo_hdr)
37
+
38
+ inf.seek(self_hdr.sceversion_offset)
39
+ verinfo_hdr = SceVersionInfo.unpack(inf)
40
+ if not silent:
41
+ print(verinfo_hdr)
42
+
43
+ npdrmtype = 0
44
+ inf.seek(self_hdr.controlinfo_offset)
45
+ controlinfo_hdr = None
46
+ while controlinfo_hdr is None or controlinfo_hdr.more:
47
+ controlinfo_hdr = SceControlInfo.unpack(inf)
48
+ if not silent:
49
+ print(controlinfo_hdr)
50
+
51
+ control_size = controlinfo_hdr.size - 0x10
52
+ if controlinfo_hdr.control_type == ControlType.CONTROL_FLAGS:
53
+ inf.read(control_size)
54
+
55
+ elif controlinfo_hdr.control_type == ControlType.DIGEST_SHA256:
56
+ controldigest256 = SceControlInfoDigest256.unpack(inf)
57
+ if not silent:
58
+ print(controldigest256)
59
+
60
+ elif controlinfo_hdr.control_type == ControlType.NPDRM_VITA:
61
+ controlnpdrm = SceControlInfoDRM.unpack(inf)
62
+ npdrmtype = controlnpdrm.npdrm_type
63
+ if not silent:
64
+ print(controlnpdrm)
65
+
66
+ elif controlinfo_hdr.control_type == ControlType.UNK_SIG1:
67
+ inf.read(control_size)
68
+
69
+ elif controlinfo_hdr.control_type == ControlType.UNK_HASH1:
70
+ inf.read(control_size)
71
+
72
+ else:
73
+ #print(f"WARN: Unhandled ControlInfo {controlinfo_hdr.type}")
74
+ inf.read(control_size)
75
+
76
+ # read ehdr
77
+ inf.seek(self_hdr.elf_offset)
78
+ elf_hdr = ElfHeader.unpack(inf)
79
+ if not silent:
80
+ print(elf_hdr)
81
+
82
+ # read phdr
83
+ elf_phdrs: list[ElfPhdr] = []
84
+ inf.seek(self_hdr.phdr_offset)
85
+ for i in range(elf_hdr.e_phnum):
86
+ phdr = ElfPhdr.unpack(inf)
87
+ if not silent:
88
+ print(phdr)
89
+ elf_phdrs.append(phdr)
90
+
91
+ # read shdr
92
+ elf_shdrs: list[ElfShdr] = []
93
+ inf.seek(self_hdr.shdr_offset)
94
+ for i in range(elf_hdr.e_shnum):
95
+ shdr = ElfShdr.unpack(inf)
96
+ if not silent:
97
+ print(shdr)
98
+ elf_shdrs.append(shdr)
99
+
100
+ # read segment infos
101
+ encrypted = False
102
+ segment_infos: list[SegmentInfo] = []
103
+ inf.seek(self_hdr.segment_info_offset)
104
+ for i in range(elf_hdr.e_phnum):
105
+ segment_info = SegmentInfo.unpack(inf)
106
+ if not silent:
107
+ print(segment_info)
108
+ segment_infos.append(segment_info)
109
+ if segment_info.plaintext == SecureBool.NO:
110
+ encrypted = True
111
+
112
+ # falsely has sections set to what it was before stripping
113
+ if elf_hdr.e_machine == 0xf00d:
114
+ elf_hdr.e_shoff = 0
115
+ elf_hdr.e_shnum = 0
116
+
117
+ # placeholder elf header
118
+ elf_header_offset = outf.tell()
119
+ outf.write(b"\0" * elf_hdr._size)
120
+
121
+ # get keys
122
+ scesegs = {}
123
+ if encrypted:
124
+ scesegs = sceutils.get_segments(inf, sce, appinfo_hdr.sys_version, appinfo_hdr.self_type, npdrmtype, klictxt, silent)
125
+
126
+ # placeholder phdrs
127
+ phdrs_offset = outf.tell()
128
+ phdrs_size = (ElfPhdr._size * len(elf_phdrs))
129
+ outf.write(b"\0" * phdrs_size)
130
+
131
+ padding = (16 - (outf.tell() % 16))
132
+ outf.write(b"\0" * padding)
133
+
134
+ phdr_offsets_out: list[int] = [0] * elf_hdr.e_phnum
135
+ # copy segments, decrypted and decompressed if needed
136
+ for i in range(elf_hdr.e_phnum):
137
+ idx = scesegs[i].idx if scesegs else i
138
+ phdr = elf_phdrs[idx]
139
+ segment_info = segment_infos[idx]
140
+
141
+ if phdr.p_filesz == 0:
142
+ continue
143
+
144
+ if not silent:
145
+ print(f'Dumping segment {idx}...')
146
+
147
+ # data
148
+ inf.seek(segment_info.offset)
149
+ dat = inf.read(segment_info.size)
150
+
151
+ # encryption
152
+ if segment_infos[idx].plaintext == SecureBool.NO:
153
+ ctr = Counter.new(128, initial_value=int.from_bytes(scesegs[i].iv, "big"))
154
+ section_aes = AES.new(scesegs[i].key, AES.MODE_CTR, counter=ctr)
155
+ dat = section_aes.decrypt(dat)
156
+
157
+ # compression
158
+ if segment_infos[idx].compressed == SecureBool.YES:
159
+ z = zlib.decompressobj()
160
+ dat = z.decompress(dat)
161
+
162
+ # write alignment
163
+ align_bytes = outf.tell() % phdr.p_align
164
+ outf.write(b"\0" * align_bytes)
165
+
166
+ # write back
167
+ phdr_offsets_out[idx] = outf.tell()
168
+ outf.write(dat)
169
+
170
+ # write phdrs
171
+ outf.seek(phdrs_offset)
172
+ for phdr, data_offset in zip(elf_phdrs, phdr_offsets_out):
173
+ phdr_out = copy.copy(phdr)
174
+ phdr_out.p_offset = data_offset
175
+ outf.write(phdr_out.pack())
176
+
177
+ # placeholder shdr
178
+ shdrs_offset = outf.seek(0, 2)
179
+ outf.write(b"0" * (ElfShdr._size * elf_hdr.e_shnum))
180
+
181
+ # write shdr data that isnt in any segments, ie things not loaded by the os
182
+ shdr_offsets_out: list[int] = [0] * elf_hdr.e_shnum
183
+ for i in range(elf_hdr.e_shnum):
184
+ shdr = elf_shdrs[i]
185
+ # sections that are inside of segments dont need to be copied again, need to adjust the sh_offset
186
+ overlaps = False
187
+ for phdr, phdr_offset in zip(elf_phdrs, phdr_offsets_out):
188
+ if shdr.sh_offset >= phdr.p_offset and shdr.sh_offset < phdr.p_offset + phdr.p_filesz:
189
+ shdr_offsets_out[i] = shdr.sh_offset + (phdr_offset - phdr.p_offset)
190
+ overlaps = True
191
+ break
192
+ if overlaps:
193
+ continue
194
+
195
+ inf.seek(shdr.sh_offset + sce.header_length)
196
+ dat = inf.read(shdr.sh_size)
197
+ shdr_offsets_out[i] = outf.tell()
198
+ outf.write(dat)
199
+
200
+ # write shdrs
201
+ if elf_hdr.e_shnum > 0:
202
+ outf.seek(shdrs_offset)
203
+ for shdr, data_offset in zip(elf_shdrs, shdr_offsets_out):
204
+ shdr_out = copy.copy(shdr)
205
+ shdr_out.sh_offset = data_offset
206
+ outf.write(shdr_out.pack())
207
+
208
+ # write ehdr
209
+ outf.seek(elf_header_offset)
210
+ elf_hdr.e_phoff = phdrs_offset
211
+ if elf_hdr.e_shnum > 0:
212
+ elf_hdr.e_shoff = shdrs_offset
213
+ outf.write(elf_hdr.pack())
214
+
215
+
216
+ def main(argv = sys.argv):
217
+ parser = argparse.ArgumentParser()
218
+ parser.add_argument("-i", "--inputfile", help="input file name", type=str, required=True)
219
+ parser.add_argument("-o", "--outputfile", help="output file name", type=str, required=True)
220
+ parser.add_argument("-k", "--keyriffile", help="NoNpdrm RIF file name", type=str)
221
+ parser.add_argument("-z", "--zrif", help="zrif string", type=str)
222
+ parser.add_argument("-K", "--keys", help="keys filename", type=str, default="keys_external.py")
223
+ args = parser.parse_args(argv[1:])
224
+
225
+ keys.use_keys(args.keys)
226
+
227
+ if args.outputfile == "null":
228
+ args.outputfile = os.devnull
229
+
230
+ with open(args.inputfile, "rb") as inf, open(args.outputfile, "wb") as outf:
231
+ lic = None
232
+ if args.keyriffile:
233
+ with open(args.keyriffile, "rb") as rif:
234
+ lic = SceRIF.unpack(rif)
235
+ elif args.zrif:
236
+ rif = sceutils.zrif_decode(args.zrif)[:SceRIF._size]
237
+ lic = SceRIF.unpack(rif)
238
+ self2elf(inf, outf, *((lic.klicense,) if lic else ()))
239
+
240
+
241
+ if __name__ == "__main__":
242
+ main()
sceutils/selfinfo.py ADDED
@@ -0,0 +1,249 @@
1
+ #!/usr/bin/env python3
2
+ """Print every header and metadata structure contained in a SELF file."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import io
8
+ import pathlib
9
+ import sys
10
+ from typing import IO, Any
11
+
12
+ from . import keys, module_info, sceutils
13
+ from .scetypes import (
14
+ AppInfoHeader,
15
+ ControlType,
16
+ ElfHeader,
17
+ ElfPhdr,
18
+ ElfShdr,
19
+ SCE_MAGIC,
20
+ SceControlInfo,
21
+ SceControlInfoDigest256,
22
+ SceControlInfoDRM,
23
+ SceHeader,
24
+ SceType,
25
+ SceVersionInfo,
26
+ SegmentInfo,
27
+ SelfHeader,
28
+ SpkgHeader,
29
+ SrvkHeader,
30
+ )
31
+ from .self2elf import self2elf
32
+
33
+
34
+ def _read_control_infos(inf: IO[bytes], self_hdr: SelfHeader,
35
+ silent: bool) -> tuple[list[Any], int]:
36
+ infos: list[Any] = []
37
+ npdrm_type = 0
38
+ if not self_hdr.controlinfo_offset:
39
+ return infos, npdrm_type
40
+
41
+ inf.seek(self_hdr.controlinfo_offset)
42
+ hdr = None
43
+ while hdr is None or hdr.more:
44
+ hdr = SceControlInfo.unpack(inf)
45
+ if not silent:
46
+ print(hdr)
47
+ infos.append(hdr)
48
+
49
+ payload_size = max(hdr.size - SceControlInfo._size, 0)
50
+ if hdr.control_type == ControlType.DIGEST_SHA256:
51
+ digest = SceControlInfoDigest256.unpack(inf)
52
+ infos.append(digest)
53
+ if not silent:
54
+ print(digest)
55
+ elif hdr.control_type == ControlType.NPDRM_VITA:
56
+ drm = SceControlInfoDRM.unpack(inf)
57
+ npdrm_type = drm.npdrm_type
58
+ infos.append(drm)
59
+ if not silent:
60
+ print(drm)
61
+ else:
62
+ if payload_size:
63
+ infos.append(inf.read(payload_size))
64
+
65
+ return infos, npdrm_type
66
+
67
+
68
+ def read_self_info(inf: IO[bytes], *, decrypt: bool = True,
69
+ klictxt: bytes = b"\0" * 16,
70
+ include_module_info: bool = True,
71
+ silent: bool = False) -> dict[str, Any]:
72
+ """Parse a SELF/SRVK/SPKG file and return all discovered information.
73
+
74
+ ``inf`` must be a seekable binary file object. When ``decrypt`` is true
75
+ the encrypted metadata is parsed as well (this requires keys to have been
76
+ loaded with :func:`sceutils.keys.use_keys`).
77
+ """
78
+ info: dict[str, Any] = {}
79
+
80
+ inf.seek(0)
81
+ magic = inf.read(4)
82
+ if int.from_bytes(magic, "little") != SCE_MAGIC:
83
+ raise ValueError("not a SCE file (invalid magic)")
84
+ inf.seek(0)
85
+ sce = SceHeader.unpack(inf)
86
+ info["sce"] = sce
87
+ if not silent:
88
+ print(sce)
89
+
90
+ if sce.sce_type == SceType.SELF:
91
+ inf.seek(sce._size)
92
+ self_hdr = SelfHeader.unpack(inf)
93
+ info["self"] = self_hdr
94
+ if not silent:
95
+ print(self_hdr)
96
+
97
+ inf.seek(self_hdr.appinfo_offset)
98
+ appinfo = AppInfoHeader.unpack(inf)
99
+ info["appinfo"] = appinfo
100
+ if not silent:
101
+ print(appinfo)
102
+
103
+ if self_hdr.sceversion_offset:
104
+ inf.seek(self_hdr.sceversion_offset)
105
+ verinfo = SceVersionInfo.unpack(inf)
106
+ info["version_info"] = verinfo
107
+ if not silent:
108
+ print(verinfo)
109
+
110
+ control_infos, npdrm_type = _read_control_infos(inf, self_hdr, silent)
111
+ info["control_infos"] = control_infos
112
+ info["npdrm_type"] = npdrm_type
113
+
114
+ inf.seek(self_hdr.elf_offset)
115
+ elf_hdr = ElfHeader.unpack(inf)
116
+ info["elf_header"] = elf_hdr
117
+ if not silent:
118
+ print(elf_hdr)
119
+
120
+ phdrs = []
121
+ inf.seek(self_hdr.phdr_offset)
122
+ for _ in range(elf_hdr.e_phnum):
123
+ phdr = ElfPhdr.unpack(inf)
124
+ phdrs.append(phdr)
125
+ if not silent:
126
+ print(phdr)
127
+ info["phdrs"] = phdrs
128
+
129
+ shdrs = []
130
+ inf.seek(self_hdr.shdr_offset)
131
+ for _ in range(elf_hdr.e_shnum):
132
+ shdr = ElfShdr.unpack(inf)
133
+ shdrs.append(shdr)
134
+ if not silent:
135
+ print(shdr)
136
+ info["shdrs"] = shdrs
137
+
138
+ segment_infos = []
139
+ inf.seek(self_hdr.segment_info_offset)
140
+ for _ in range(elf_hdr.e_phnum):
141
+ segment_info = SegmentInfo.unpack(inf)
142
+ segment_infos.append(segment_info)
143
+ if not silent:
144
+ print(segment_info)
145
+ info["segment_infos"] = segment_infos
146
+
147
+ if decrypt:
148
+ try:
149
+ segments = sceutils.get_segments(
150
+ inf, sce, appinfo.sys_version, appinfo.self_type,
151
+ npdrm_type, klictxt, silent)
152
+ info["segments"] = segments
153
+ except Exception as exc: # noqa: BLE001 - metadata may be unavailable
154
+ info["segments_error"] = exc
155
+ if not silent:
156
+ print(f"Could not read encrypted metadata: {exc}")
157
+
158
+ if include_module_info and decrypt:
159
+ try:
160
+ elf = io.BytesIO()
161
+ inf.seek(0)
162
+ self2elf(inf, elf, klictxt, silent=True)
163
+ elf.seek(0)
164
+ module = module_info.read_module_info(elf)
165
+ info["module"] = module
166
+ if module is not None and not silent:
167
+ _print_module_info(module)
168
+ except Exception as exc: # noqa: BLE001 - not all files are modules
169
+ info["module_error"] = exc
170
+ if not silent:
171
+ print(f"Module info unavailable: {exc}")
172
+
173
+ elif sce.sce_type == SceType.SRVK:
174
+ inf.seek(sce.header_length)
175
+ srvk = SrvkHeader.unpack(inf)
176
+ info["srvk"] = srvk
177
+ if not silent:
178
+ print(srvk)
179
+
180
+ elif sce.sce_type == SceType.SPKG:
181
+ inf.seek(sce.header_length)
182
+ spkg = SpkgHeader.unpack(inf)
183
+ info["spkg"] = spkg
184
+ if not silent:
185
+ print(spkg)
186
+
187
+ else:
188
+ if not silent:
189
+ print(f"Unknown SCE type: {sce.sce_type}")
190
+
191
+ return info
192
+
193
+
194
+ def _print_module_info(module) -> None:
195
+ module_info_hdr, imports, exports = module
196
+ print("Module Info:")
197
+ print(f" module_name: {module_info_hdr.module_name}")
198
+ print(f" module_nid: 0x{module_info_hdr.module_nid:08X}")
199
+ print(f" version: {module_info_hdr.version}")
200
+ print(f" attributes: 0x{module_info_hdr.attributes:04X}")
201
+ print(f" imports ({len(imports)}):")
202
+ for imp in imports:
203
+ print(f" {imp.name} (0x{imp.nid:08X}): "
204
+ f"{len(imp.functions)} functions, {len(imp.variables)} variables")
205
+ print(f" exports ({len(exports)}):")
206
+ for exp in exports:
207
+ print(f" {exp.name} (0x{exp.nid:08X}): "
208
+ f"{len(exp.functions)} functions, {len(exp.variables)} variables")
209
+
210
+
211
+ def main(argv: list[str] | None = None) -> int:
212
+ argv = list(sys.argv if argv is None else argv)
213
+ parser = argparse.ArgumentParser(
214
+ prog="sceutils selfinfo",
215
+ description="Print all information from a SELF/SRVK/SPKG file.",
216
+ )
217
+ parser.add_argument("filename", type=pathlib.Path)
218
+ parser.add_argument(
219
+ "-K", "--keys", type=str, default="keys_external.py",
220
+ help="keys module to load (default: keys_external.py)",
221
+ )
222
+ parser.add_argument(
223
+ "--no-decrypt", action="store_true",
224
+ help="do not decrypt/parse encrypted metadata",
225
+ )
226
+ parser.add_argument(
227
+ "--no-module-info", action="store_true",
228
+ help="do not reconstruct the ELF to print module imports/exports",
229
+ )
230
+ args = parser.parse_args(argv[1:])
231
+
232
+ keys.use_keys(args.keys)
233
+
234
+ try:
235
+ with open(args.filename, "rb") as inf:
236
+ read_self_info(
237
+ inf,
238
+ decrypt=not args.no_decrypt,
239
+ include_module_info=not args.no_module_info,
240
+ silent=False,
241
+ )
242
+ except (OSError, TypeError, ValueError) as exc:
243
+ print(f"error: {exc}", file=sys.stderr)
244
+ return 1
245
+ return 0
246
+
247
+
248
+ if __name__ == "__main__":
249
+ raise SystemExit(main())
@@ -0,0 +1,42 @@
1
+ import os
2
+ import sys
3
+
4
+ from sceutils import pup_info
5
+
6
+ BLOCKSIZE = int(10e6)
7
+
8
+ def main(argv = sys.argv):
9
+ filename = argv[1]
10
+ print(filename)
11
+
12
+ with open(filename, "rb") as f:
13
+ while True:
14
+ data = f.read(BLOCKSIZE)
15
+ if len(data) == 0 or data is None:
16
+ break
17
+
18
+ if data.count(b"SCEUF"):
19
+ print("Found a pup")
20
+ index = data.index(b"SCEUF")
21
+
22
+ before = f.tell()
23
+ real_index = before - BLOCKSIZE + index
24
+ print(f"at 0x{real_index:x}")
25
+
26
+ f.seek(real_index)
27
+ info = pup_info.SCEUF.read(f)
28
+ print(info)
29
+ info.print()
30
+ yn = input("extract? [y/n]")
31
+ if yn != "y":
32
+ f.seek(before)
33
+ continue
34
+ else:
35
+ f.seek(real_index)
36
+ pup = f.read(info.data_len+info.header_len)
37
+ with open(f"{os.path.basename(filename)}_PSP2_{info.version:x}_{info.build_no}_{real_index:x}.PUP", "wb") as fo:
38
+ fo.write(pup)
39
+ print("written pup")
40
+
41
+ if __name__ == "__main__":
42
+ main()
@@ -0,0 +1,19 @@
1
+ import os
2
+ import sys
3
+
4
+ from sceutils import pup_fiction
5
+
6
+
7
+ def main(argv = sys.argv):
8
+ if len(argv) != 3:
9
+ print(f"Usage: {argv[0]} bootimage.skprx output-dir/")
10
+ sys.exit(1)
11
+
12
+ filename = argv[1]
13
+ out_dir = argv[2]
14
+ os.makedirs(out_dir, exist_ok=True)
15
+ pup_fiction.extract_bootimage(filename, out_dir)
16
+
17
+
18
+ if __name__ == "__main__":
19
+ main()