-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathSundancer
More file actions
executable file
·801 lines (597 loc) · 24.9 KB
/
Sundancer
File metadata and controls
executable file
·801 lines (597 loc) · 24.9 KB
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
#!/usr/bin/env python3
import os
import time
import json
import shutil
import zipfile
import tarfile
import tempfile
import argparse
import plistlib
import subprocess
from pathlib import Path
from typing import List, Tuple
from dataclasses import dataclass, fields, is_dataclass
from yolosign import yolosign, off2page
# ===================== patch config =====================
def hexint(s: str):
return int(s, 16)
def BytesOrString(s: str):
try:
return bytes.fromhex(s)
except ValueError:
return s.encode("ascii") + b"\0"
@dataclass
class Patch:
name: str
offset: hexint
patch: BytesOrString
@dataclass
class FilePatch:
path: str
patches: List[Patch]
@dataclass
class CopyEmbeddedResource:
embedded: str
dest: str
@dataclass
class Bluetooth:
filename: str
offset: hexint
length: hexint
# XXX split this to `original` & `destination`?
@dataclass
class ManifestItem:
component: str
iv: str = None
key: str = None
patches: List[Patch] = None
copy_files: List[str] = None
launchdaemons_to_unlimit: List[str] = None
file_patches: List[FilePatch] = None
copy_embedded_files: List[CopyEmbeddedResource] = None
bluetooth: Bluetooth = None
@dataclass
class IPSWConfig:
device: str
build: str
manifest: List[ManifestItem]
def component(self, comp: str):
return next(
filter(lambda x: x.component == comp, self.manifest))
@dataclass
class Defaults:
kernel_cache: str
kernel_cache_jailbroken: str
device_tree: str
exploit: str
@dataclass
class Config:
original: IPSWConfig
destination: IPSWConfig
defaults: Defaults
def dataclass_from_dict(cls, d):
if isinstance(d, list):
(inner,) = cls.__args__
return [dataclass_from_dict(inner, i) for i in d]
if is_dataclass(cls):
fieldtypes = {f.name:f.type for f in fields(cls)}
return cls(**{f:dataclass_from_dict(fieldtypes[f],d[f]) for f in d})
else:
return cls(d)
DESTINATION_FW_RAMDISK_SIZE = 16 * 1024 * 1024
# ===================== debug logging =====================
NONE = ""
DIM = "\u001b[2m"
RESET = "\u001b[0m"
start_time = 0.0
_verbose = False
def _debug_init(verbose: bool):
global start_time, _verbose
start_time = time.time()
_verbose = verbose
def _log(color, args, kwargs):
print(color + "|%7.3f | " % (time.time() - start_time), end="")
print(*args, **kwargs, end=RESET+"\n")
def log(*args, **kwargs):
_log(NONE, args, kwargs)
def debug(*args, **kwargs):
if _verbose:
_log(DIM, args, kwargs)
# ================== subprocess wrappers ==================
def _run(exec: Path, args: List[str], env: dict = None):
subprocess.run([exec] + args, env=env, check=True, stdout=subprocess.DEVNULL)
def image3_decrypt(src: Path, dest: Path, iv: str, key: str, keep_cont: bool = False):
args = [str(src), str(dest), "-iv", str(iv), "-k", str(key)]
if keep_cont:
args += ["-decrypt"]
_run(
SCRIPT_ROOT / "executables" / "xpwntool",
args)
debug("decrypted Image3 at %s to %s" % (src.name, dest.name))
def image3_create(src: Path, dest: Path, template: Path):
_run(
SCRIPT_ROOT / "executables" / "xpwntool",
[str(src), str(dest), "-t", str(template)])
debug("created Image3 at %s from %s with template %s" % (dest.name, src.name, template.name))
def dmg_extract(src: Path, dest: Path, key: str):
_run(
SCRIPT_ROOT / "executables" / "dmg",
["extract", str(src), str(dest), "-k", key])
debug("decrypted DMG at %s to %s" % (src.name, dest.name))
def dmg_build(src: Path, dest: Path):
_run(
SCRIPT_ROOT / "executables" / "dmg",
["build", str(src), str(dest)])
debug("built DMG at %s to %s" % (src.name, dest.name))
def hfsplus_grow(dmg: Path, size: int):
_run(
SCRIPT_ROOT / "executables" / "hfsplus",
[str(dmg), "grow", str(size)])
debug("grown HFS+ image at %s to %d bytes" % (dmg.name, size))
def hfsplus_extract(dmg: Path, src: str, dest: Path):
_run(
SCRIPT_ROOT / "executables" / "hfsplus",
[str(dmg), "extract", src, str(dest)])
debug("extracted %s to %s from HFS+ image at %s" % (src, dest.name, dmg.name))
def hfsplus_replace(dmg: Path, src: Path, dest: str, uid: int = 0, gid: int = 0, mode: int = 0o644):
_run(
SCRIPT_ROOT / "executables" / "hfsplus",
[str(dmg), "rm", dest])
hfsplus_add(dmg, src, dest, uid, gid, mode)
def hfsplus_add(dmg: Path, src: Path, dest: str, uid: int = 0, gid: int = 0, mode: int = 0o644):
_run(
SCRIPT_ROOT / "executables" / "hfsplus",
[str(dmg), "add", str(src), dest])
_run(
SCRIPT_ROOT / "executables" / "hfsplus",
[str(dmg), "chown", "%d:%d" % (uid, gid), dest])
_run(
SCRIPT_ROOT / "executables" / "hfsplus",
[str(dmg), "chmod", "%o" % (mode), dest])
debug("added %s in HFS+ image at %s to %s" % (src.name, dmg.name, dest))
def hfsplus_rm(dmg: Path, path: str):
_run(
SCRIPT_ROOT / "executables" / "hfsplus",
[str(dmg), "rm", path])
debug("removed %s from HFS+ image at %s" % (path, dmg.name))
def hfsplus_rmdir(dmg: Path, dir: str):
_run(
SCRIPT_ROOT / "executables" / "hfsplus",
[str(dmg), "rmall", dir])
debug("removed %s folder from HFS+ image at %s" % (dir, dmg.name))
def hfsplus_mv(dmg: Path, src: str, dest: str):
_run(
SCRIPT_ROOT / "executables" / "hfsplus",
[str(dmg), "mv", src, dest])
debug("moved %s to %s in HFS+ image at %s" % (src, dest, dmg.name))
def hfsplus_untar(dmg: Path, tar: Path, dest: str):
_run(
SCRIPT_ROOT / "executables" / "hfsplus",
[str(dmg), "untar", str(tar), dest])
debug("untar'd %s to %s in HFS+ image at %s" % (tar.name, dest, dmg.name))
# ===================== IPSW parsing =====================
class BuildIdentity:
def __init__(self, raw: dict, manifest: "BuildManifest"):
self.raw = raw
self.manifest = manifest
self.chip_id = raw["ApChipID"]
self.board_id = raw["ApBoardID"]
self.device = raw["Info"]["DeviceClass"]
self.restore_behavior = raw["Info"]["RestoreBehavior"]
self.build_train = raw["Info"]["BuildTrain"]
self.minimum_system_partition = raw["Info"]["MinimumSystemPartition"]
self.components = { k:v["Info"]["Path"] for k,v in raw["Manifest"].items() }
debug("loaded build identity for %s (%s)" % (self.device, self.restore_behavior))
@property
def device_short(self):
if self.device.endswith("ap"):
return self.device[:-2]
# bold of me to assume this is ever going to be used for dev boards, but...
elif self.device.endswith("dev"):
return self.device[:-3]
raise RuntimeError("device class is neither AP nor DEV?!")
class BuildManifest:
def __init__(self, data: bytes):
self.raw = plistlib.loads(data)
self.version = self.raw["ProductVersion"]
self.build = self.raw["ProductBuildVersion"]
self.identities = list()
for i in self.raw["BuildIdentities"]:
self.identities.append(BuildIdentity(i, self))
debug("loaded build manifest for iOS %s (%s)" % (self.version, self.build))
def find_identity(self, device: str, behavior: str) -> BuildIdentity:
return next(filter(
lambda x: x.device == device and x.restore_behavior == behavior,
self.identities)
)
class IPSW:
def __init__(self, path: Path):
self.path = path
self._zip = zipfile.ZipFile(path)
raw_manifest = self.read_file("BuildManifest.plist")
self.manifest = BuildManifest(raw_manifest)
debug("loaded IPSW")
def read_file(self, path: str) -> bytes:
return self._zip.read(path)
def extract_file(self, src: str, dest: str):
with self._zip.open(src, "r") as zf:
with open(dest, "wb") as f:
shutil.copyfileobj(zf, f)
def extract_comp(comp: str, dest_dir: Path, ipsw: IPSW, build_identity: BuildIdentity) -> str:
path = build_identity.components[comp]
name = os.path.basename(path)
ipsw.extract_file(path, dest_dir / name)
debug("extracted component %s from IPSW at %s" % (comp, ipsw.path))
return name
# ====================== main logic ======================
@dataclass
class AddFile:
src: Path
dest: str
uid: int = 0
gid: int = 0
mode: int = 0o644
def original_fw_extract_firmwares(wd: Path, ipsw: IPSW, build_identity: BuildIdentity) -> List[AddFile]:
result = []
log("extracting iOS 5 root filesystem")
os_orig_path = wd / extract_comp("OS", wd, ipsw, build_identity)
os_raw_path = os_orig_path.with_name("OriginalOS.dmg")
os_cfg = gCfg.original.component("OS")
dmg_extract(os_orig_path, os_raw_path, os_cfg.key)
os_orig_path.unlink()
if os_cfg.copy_files:
log("extracting WLAN & multitouch firmwares")
for f in os_cfg.copy_files:
hfsplus_extract(os_raw_path, f, wd / os.path.basename(f))
result.append(AddFile(
wd / os.path.basename(f),
f
))
if os_cfg.bluetooth:
log("extracting Bluetooth firmware")
bluetool_path = wd / "BlueTool"
hfsplus_extract(os_raw_path, "/usr/sbin/BlueTool", bluetool_path)
with open(bluetool_path, "rb") as f:
f.seek(os_cfg.bluetooth.offset)
bluetooth_fw = f.read(os_cfg.bluetooth.length)
bluetool_path.unlink()
bluetooth_fw_path = wd / os_cfg.bluetooth.filename
with open(bluetooth_fw_path, "wb") as f:
f.write(bluetooth_fw)
result.append(AddFile(
bluetooth_fw_path,
"/private/etc/bluetool/" + os_cfg.bluetooth.filename
))
os_raw_path.unlink()
return result
def patch_binary(src: Path, dest: Path, patches: List[Patch], codesign: bool = False):
try:
shutil.copyfile(src, dest)
except shutil.SameFileError:
pass
pages = []
with open(dest, "r+b") as f:
for p in patches:
f.seek(p.offset)
f.write(p.patch)
if codesign:
pages.append(off2page(p.offset))
if codesign:
yolosign(dest, pages)
def original_fw_replace_comp(comp: str, iv: str, key: str, src: Path, wd: Path, ipsw: IPSW, build_identity: BuildIdentity) -> str:
path = wd / extract_comp(comp, wd, ipsw, build_identity)
decrypted_path = path.with_suffix(".decrypted")
image3_decrypt(path, decrypted_path, iv, key, keep_cont=True)
path.unlink()
image3_create(src, wd / comp, decrypted_path)
decrypted_path.unlink()
return comp
def original_fw_process_iboots(wd: Path, ipsw: IPSW, build_identity: BuildIdentity) -> List[str]:
result = {}
# LLB
result["LLB"] = extract_comp("LLB", wd, ipsw, build_identity)
# iBoot
result["iBoot"] = extract_comp("iBoot", wd, ipsw, build_identity)
def patch_image3(src: Path, dest: Path, iv: str, key: str, patches: List[Patch]):
raw_path = src.with_suffix(".raw")
image3_decrypt(src, raw_path, iv, key)
patched_path = src.with_suffix(".patched")
patch_binary(raw_path, patched_path, patches)
raw_path.unlink()
template_path = src.with_suffix(".template")
shutil.copyfile(src, template_path)
image3_create(patched_path, dest, template_path)
patched_path.unlink()
template_path.unlink()
# iBSS
ibss_name = extract_comp("iBSS", wd, ipsw, build_identity)
ibss_cfg = gCfg.original.component("iBSS")
ibss_orig_path = wd / ibss_name
patch_image3(ibss_orig_path, ibss_orig_path, ibss_cfg.iv, ibss_cfg.key, ibss_cfg.patches)
result["iBSS"] = ibss_name
# iBEC
ibec_name = extract_comp("iBEC", wd, ipsw, build_identity)
ibec_cfg = gCfg.original.component("iBEC")
ibec_orig_path = wd / ibec_name
patch_image3(ibec_orig_path, ibec_orig_path, ibec_cfg.iv, ibec_cfg.key, ibec_cfg.patches)
result["iBEC"] = ibec_name
return result
def _unlimit_launch_daemon(wd: Path, dmg_path: Path, launch_daemon: str):
log("unlimiting %s LaunchDaemon" % os.path.basename(launch_daemon))
plist_tmp_path = wd / "launch_daemon.plist"
hfsplus_extract(dmg_path, launch_daemon, plist_tmp_path)
with open(plist_tmp_path, "rb") as f:
plist = plistlib.load(f)
del plist["LimitLoadToHardware"]
with open(plist_tmp_path, "wb") as f:
plistlib.dump(plist, f, fmt=plistlib.FMT_XML)
hfsplus_replace(dmg_path, plist_tmp_path, launch_daemon)
plist_tmp_path.unlink()
JAILBREAK_ROOTFS_MIBS = 128
HACTIVATOR_DYLIB_DESTINATION = "/usr/lib/hactivator.dylib"
LOCKDOWND_DAEMON_PLIST = "/System/Library/LaunchDaemons/com.apple.mobile.lockdown.plist"
def destination_fw_process_root_filesystem(wd: Path, ipsw: IPSW, build_identity: BuildIdentity, to_add: List[AddFile], jailbreak: bool = False) -> str:
log("extracting iOS 6 root filesystem")
os_orig_path = wd / extract_comp("OS", wd, ipsw, build_identity)
os_raw_path = os_orig_path.with_name("DestinationOS.dmg")
os_cfg = gCfg.destination.component("OS")
dmg_extract(os_orig_path, os_raw_path, os_cfg.key)
os_orig_path.unlink()
log("removing OTA update files")
hfsplus_rmdir(os_raw_path, "/usr/standalone/update")
log("patching files")
if os_cfg.file_patches:
for p in os_cfg.file_patches:
file_tmp_path = wd / "f"
hfsplus_extract(os_raw_path, p.path, file_tmp_path)
patch_binary(file_tmp_path, file_tmp_path, p.patches, codesign=True)
hfsplus_replace(os_raw_path, file_tmp_path, p.path, mode=0o755)
file_tmp_path.unlink()
if os_cfg.launchdaemons_to_unlimit:
for ld in os_cfg.launchdaemons_to_unlimit:
_unlimit_launch_daemon(wd, os_raw_path, ld)
log("adding Hactivator")
to_add.append(AddFile(SCRIPT_ROOT / "hactivator" / "hactivator.dylib", HACTIVATOR_DYLIB_DESTINATION, mode=0o755))
lockdownd_plist_tmp_path = wd / "lockdownd.plist"
hfsplus_extract(os_raw_path, LOCKDOWND_DAEMON_PLIST, lockdownd_plist_tmp_path)
with open(lockdownd_plist_tmp_path, "rb") as f:
lockdownd_plist = plistlib.load(f)
lockdownd_plist["EnvironmentVariables"] = {
"DYLD_INSERT_LIBRARIES" : HACTIVATOR_DYLIB_DESTINATION
}
with open(lockdownd_plist_tmp_path, "wb") as f:
plistlib.dump(lockdownd_plist, f)
hfsplus_replace(os_raw_path, lockdownd_plist_tmp_path, LOCKDOWND_DAEMON_PLIST)
lockdownd_plist_tmp_path.unlink()
if os_cfg.copy_embedded_files:
for f in os_cfg.copy_embedded_files:
to_add.append(AddFile(RESOURCES_ROOT / f.embedded, f.dest))
# `hfsplus` messes up if we create already existing folders/files,
# `hfsplus` messes up if add files to non-existing folders,
# so we use tarball extraction capability that handles all that well
tar_path = wd / "files.tar"
tar = tarfile.open(tar_path, "x", format=tarfile.GNU_FORMAT)
already_there = set()
for a in to_add:
p = ""
# `hfsplus` needs explicit entries for directories
comps = str(Path(a.dest).parent).split("/")
for c in comps:
if not c:
continue
p += c + "/"
if p not in already_there:
inf = tarfile.TarInfo(p)
inf.type = tarfile.DIRTYPE
inf.uid = 0
inf.gid = 0
inf.mode = 0o755
tar.addfile(inf)
already_there.add(p)
inf = tarfile.TarInfo(a.dest[1:])
inf.type = tarfile.REGTYPE
inf.size = os.stat(a.src).st_size
inf.uid = a.uid
inf.gid = a.gid
inf.mode = a.mode
with open(a.src, "rb") as f:
tar.addfile(inf, f)
debug("added %s to temporary tarball" % a.dest)
tar.close()
hfsplus_untar(os_raw_path, tar_path, "/")
tar_path.unlink()
if jailbreak:
log("growing root filesystem")
hfsplus_grow(os_raw_path, (build_identity.minimum_system_partition + JAILBREAK_ROOTFS_MIBS) * 1024 * 1024)
log("unpacking Cydia tarball")
hfsplus_untar(os_raw_path, RESOURCES_ROOT / "Cydia.tar", "/")
with tempfile.NamedTemporaryFile() as f:
hfsplus_add(os_raw_path, Path(f.name), "/.cydia_no_stash")
log("replacing fstab")
hfsplus_replace(os_raw_path, RESOURCES_ROOT / "fstab", "/private/etc/fstab")
# breaks everything, unfortunately
# hfsplus_mv(os_raw_path, "/", "/%s%s.N18OS" % (build_identity.build_train, ipsw.manifest.build))
log("packaging iOS 6 root filesystem")
os_dest = "DestinationOS-packed.dmg"
dmg_build(os_raw_path, wd / os_dest)
os_raw_path.unlink()
return os_dest
OPTIONS_PLIST_DESTINATION = "/usr/local/share/restore/options.plist"
def destination_fw_process_ramdisk(wd: Path, ipsw: IPSW, build_identity: BuildIdentity) -> str:
log("extracting iOS 6 ramdisk")
rd_orig_path = wd / extract_comp("RestoreRamDisk", wd, ipsw, build_identity)
rd_raw_path = rd_orig_path.with_name("DestinationRamdisk.dmg")
rd_cfg = gCfg.destination.component("RestoreRamDisk")
image3_decrypt(rd_orig_path, rd_raw_path, rd_cfg.iv, rd_cfg.key)
log("growing ramdisk")
hfsplus_grow(rd_raw_path, DESTINATION_FW_RAMDISK_SIZE)
if rd_cfg.file_patches:
for p in rd_cfg.file_patches:
file_tmp_path = wd / "f"
hfsplus_extract(rd_raw_path, p.path, file_tmp_path)
patch_binary(file_tmp_path, file_tmp_path, p.patches, codesign=True)
hfsplus_replace(rd_raw_path, file_tmp_path, p.path, mode=0o755)
file_tmp_path.unlink()
log("replacing rc.boot")
hfsplus_replace(rd_raw_path, SCRIPT_ROOT / "rc_boot" / "rc.boot", "/etc/rc.boot", mode=0o755)
log("putting exploit.dmg")
hfsplus_add(rd_raw_path, SCRIPT_ROOT / "exploit" / gCfg.defaults.exploit, "/exploit.dmg")
log("patching options plist")
hfsplus_mv(
rd_raw_path, "/usr/local/share/restore/options.%s.plist" % build_identity.device_short, OPTIONS_PLIST_DESTINATION)
options_tmp_path = wd / "options.plist"
hfsplus_extract(rd_raw_path, OPTIONS_PLIST_DESTINATION, options_tmp_path)
with open(options_tmp_path, "rb") as f:
options = plistlib.load(f)
options["UpdateBaseband"] = False
with open(options_tmp_path, "wb") as f:
plistlib.dump(options, f)
hfsplus_replace(rd_raw_path, options_tmp_path, OPTIONS_PLIST_DESTINATION)
options_tmp_path.unlink()
log("packaging iOS 6 ramdisk")
rd_dest = "DestinationRamdiskPatched.img3"
image3_create(rd_raw_path, wd / rd_dest, rd_orig_path)
rd_orig_path.unlink()
rd_raw_path.unlink()
return rd_dest
def assemble_bundle(
wd: Path,
original_ipsw: IPSW,
original_identity: BuildIdentity,
destination_ipsw: IPSW,
destination_identity: BuildIdentity,
patched_comps: dict,
output: Path
):
log("assembling bundle")
output.mkdir()
raw_identity = original_identity.raw.copy()
raw_identity["Info"]["BuildNumber"] = destination_ipsw.manifest.build
raw_identity["Info"]["BuildTrain"] = destination_identity.build_train
for k,v in raw_identity["Manifest"].items():
comp_path = v["Info"]["Path"]
comp_parent = os.path.dirname(comp_path)
comp_parent_dest = output / comp_parent
comp_parent_dest.mkdir(exist_ok=True, parents=True)
comp_dest = comp_parent_dest / os.path.basename(comp_path)
if k in patched_comps:
if comp_dest.exists():
comp_dest.unlink()
shutil.copyfile(wd / patched_comps[k], comp_dest)
else:
original_ipsw.extract_file(comp_path, comp_dest)
raw_manifest = original_ipsw.manifest.raw.copy()
raw_manifest["ProductBuildVersion"] = destination_ipsw.manifest.build
raw_manifest["ProductVersion"] = destination_ipsw.manifest.version
raw_manifest["BuildIdentities"] = [raw_identity]
with open(output / "BuildManifest.plist", "wb") as f:
plistlib.dump(raw_manifest, f, fmt=plistlib.FMT_XML)
log("wrote BuildManifest")
def process(args):
global gCfg
original_ipsw = IPSW(args.original)
destination_ipsw = IPSW(args.destination)
gCfg, original_identity, destination_identity = _load_config(original_ipsw, destination_ipsw)
if not args.kernel:
if args.jailbreak:
kernel = ARTIFACTS_ROOT / gCfg.defaults.kernel_cache_jailbroken
else:
kernel = ARTIFACTS_ROOT / gCfg.defaults.kernel_cache
else:
kernel = args.kernel
if not kernel.exists():
print("kernelcache does NOT exist")
exit(-1)
devicetree = args.devicetree if args.devicetree else (ARTIFACTS_ROOT / gCfg.defaults.device_tree)
if not devicetree.exists():
print("DeviceTree does NOT exist")
exit(-1)
with tempfile.TemporaryDirectory() as wd:
wd = Path(wd)
patched_comps = {}
log("processing iOS 5 iBoots")
patched_comps.update(original_fw_process_iboots(wd, original_ipsw, original_identity))
log("packaging kernelcache")
kc_cfg = gCfg.original.component("KernelCache")
patched_comps["KernelCache"] = patched_comps["RestoreKernelCache"] = original_fw_replace_comp("KernelCache", kc_cfg.iv, kc_cfg.key, kernel, wd, original_ipsw, original_identity)
log("packaging DeviceTree")
dt_cfg = gCfg.original.component("DeviceTree")
patched_comps["DeviceTree"] = patched_comps["RestoreDeviceTree"] = original_fw_replace_comp("DeviceTree", dt_cfg.iv, dt_cfg.key, devicetree, wd, original_ipsw, original_identity)
add_files = []
add_files += original_fw_extract_firmwares(wd, original_ipsw, original_identity)
patched_comps["OS"] = destination_fw_process_root_filesystem(wd, destination_ipsw, destination_identity, add_files, args.jailbreak)
patched_comps["RestoreRamDisk"] = destination_fw_process_ramdisk(wd, destination_ipsw, destination_identity)
assemble_bundle(
wd,
original_ipsw,
original_identity,
destination_ipsw,
destination_identity,
patched_comps,
args.output
)
def _load_config(original_ipsw: IPSW, destination_ipsw: IPSW) -> Tuple[Config, BuildIdentity, BuildIdentity]:
# Big O is watching me!
matches = []
for root, _, files in os.walk(CONFIGS_ROOT):
for f in files:
full_path = Path(root) / f
if full_path.suffix != ".json":
continue
with open(full_path, "r") as f:
curr = json.load(f)
for original_identity in original_ipsw.manifest.identities:
if original_identity.restore_behavior != "Erase":
continue
for destination_identity in destination_ipsw.manifest.identities:
if destination_identity.restore_behavior != "Erase":
continue
if curr["original"]["device"] == original_identity.device and curr["original"]["build"] == original_identity.manifest.build \
and curr["destination"]["device"] == destination_identity.device and curr["destination"]["build"] == destination_identity.manifest.build:
matches.append(
(dataclass_from_dict(Config, curr), original_identity, destination_identity,))
if len(matches) == 0:
raise RuntimeError("no config available for such IPSWs combo")
if len(matches) > 1:
raise RuntimeError("BUG: multiple configs for this IPSWs combo")
return matches.pop()
SCRIPT_ROOT = Path(__file__).parent
RESOURCES_ROOT = SCRIPT_ROOT / "resources"
ARTIFACTS_ROOT = SCRIPT_ROOT / "artifacts"
CONFIGS_ROOT = SCRIPT_ROOT / "configs"
gCfg = None
def main():
parser = argparse.ArgumentParser(description="convert iPod touch 3 iOS 5.1.1 IPSW to iOS 6.x")
parser.add_argument("original", type=Path, help="path to original IPSW for target device")
parser.add_argument("destination", type=Path, help="path to destination IPSW")
parser.add_argument("output", type=Path, help="path to output restore bundle")
parser.add_argument("-v", "--verbose", action="store_true", help="verbose logging")
parser.add_argument("-j", "--jailbreak", action="store_true", help="apply jailbreak")
parser.add_argument(
"-k", "--kernel",
help="override kernelcache",
type=Path,
required=False
)
parser.add_argument(
"-d", "--devicetree",
help="override DeviceTree",
type=Path,
required=False
)
args = parser.parse_args()
_debug_init(args.verbose)
if args.output.exists():
print("output path already exists")
exit(-1)
if not args.original.exists():
print("original IPSW does NOT exist")
exit(-1)
if not args.destination.exists():
print("destination IPSW does NOT exist")
exit(-1)
process(args)
log("DONE!")
if __name__ == "__main__":
main()