ipsw-parser 1.9.2__tar.gz → 1.10.0__tar.gz
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.
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/PKG-INFO +2 -1
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/ipsw_parser/__main__.py +12 -1
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/ipsw_parser/_version.py +3 -3
- ipsw_parser-1.10.0/ipsw_parser/build_identity.py +387 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/ipsw_parser/dsc.py +14 -5
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/ipsw_parser.egg-info/PKG-INFO +2 -1
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/ipsw_parser.egg-info/SOURCES.txt +2 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/ipsw_parser.egg-info/requires.txt +1 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/ipsw_parser.egg-info/scm_file_list.json +2 -0
- ipsw_parser-1.10.0/ipsw_parser.egg-info/scm_version.json +8 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/requirements.txt +1 -0
- ipsw_parser-1.10.0/tests/test_copy_tree.py +24 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/tests/test_dsc.py +9 -0
- ipsw_parser-1.10.0/tests/test_extract.py +132 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/tests/test_sandbox_profiles.py +23 -2
- ipsw_parser-1.9.2/ipsw_parser/build_identity.py +0 -270
- ipsw_parser-1.9.2/ipsw_parser.egg-info/scm_version.json +0 -8
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/.gitattributes +0 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/.github/ISSUE_TEMPLATE/bug_report.md +0 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/.github/ISSUE_TEMPLATE/feature_request.md +0 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/.github/workflows/codeql.yml +0 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/.github/workflows/python-app.yml +0 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/.github/workflows/python-publish.yml +0 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/.gitignore +0 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/.pre-commit-config.yaml +0 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/CODE_OF_CONDUCT.md +0 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/LICENSE +0 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/README.md +0 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/ipsw_parser/__init__.py +0 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/ipsw_parser/archive.py +0 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/ipsw_parser/build_manifest.py +0 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/ipsw_parser/component.py +0 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/ipsw_parser/exceptions.py +0 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/ipsw_parser/firmware.py +0 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/ipsw_parser/ipsw.py +0 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/ipsw_parser/process.py +0 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/ipsw_parser/py.typed +0 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/ipsw_parser.egg-info/dependency_links.txt +0 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/ipsw_parser.egg-info/entry_points.txt +0 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/ipsw_parser.egg-info/top_level.txt +0 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/pyproject.toml +0 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/pytest.ini +0 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/setup.cfg +0 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/tests/test_archive_backends.py +0 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/tests/test_firmware.py +0 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/tests/test_kernelcache.py +0 -0
- {ipsw_parser-1.9.2 → ipsw_parser-1.10.0}/tests/test_process.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: ipsw-parser
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.10.0
|
|
4
4
|
Summary: python3 utility for parsing and extracting data from IPSW
|
|
5
5
|
Author-email: doronz88 <doron88@gmail.com>
|
|
6
6
|
Maintainer-email: doronz88 <doron88@gmail.com>
|
|
@@ -699,6 +699,7 @@ Requires-Dist: ansilogs>=1.1.0
|
|
|
699
699
|
Requires-Dist: bytestruct>=0.1.0
|
|
700
700
|
Requires-Dist: pyimg4>=0.8.8
|
|
701
701
|
Requires-Dist: requests
|
|
702
|
+
Requires-Dist: rich
|
|
702
703
|
Requires-Dist: remotezip2
|
|
703
704
|
Requires-Dist: typer
|
|
704
705
|
Provides-Extra: test
|
|
@@ -5,6 +5,8 @@ from typing import Annotated, Optional
|
|
|
5
5
|
|
|
6
6
|
import ansilogs
|
|
7
7
|
import typer
|
|
8
|
+
from rich.console import Console
|
|
9
|
+
from rich.progress import BarColumn, Progress, SpinnerColumn, TaskProgressColumn, TextColumn, TimeElapsedColumn
|
|
8
10
|
|
|
9
11
|
from ipsw_parser.ipsw import IPSW
|
|
10
12
|
|
|
@@ -62,7 +64,16 @@ def extract(ipsw: IpswArgument, output: OutputArgument, pem_db: PemDbOption = No
|
|
|
62
64
|
if not output.exists():
|
|
63
65
|
output.mkdir(parents=True, exist_ok=True)
|
|
64
66
|
|
|
65
|
-
|
|
67
|
+
# Log records keep being printed, above the progress display (which is not drawn unless on a terminal)
|
|
68
|
+
with Progress(
|
|
69
|
+
SpinnerColumn(finished_text="[green]✓"),
|
|
70
|
+
TextColumn("[bold]{task.description}[/] [dim]{task.fields[phase]}"),
|
|
71
|
+
BarColumn(),
|
|
72
|
+
TaskProgressColumn(text_format_no_percentage=""),
|
|
73
|
+
TimeElapsedColumn(),
|
|
74
|
+
console=Console(stderr=True),
|
|
75
|
+
) as progress:
|
|
76
|
+
parsed_ipsw.build_manifest.build_identities[0].extract(output, pem_db=pem_db, progress=progress)
|
|
66
77
|
parsed_ipsw.archive.extractall(
|
|
67
78
|
path=output, members=[f for f in parsed_ipsw.archive.filelist if f.filename.startswith("Firmware")]
|
|
68
79
|
)
|
|
@@ -18,7 +18,7 @@ version_tuple: tuple[int | str, ...]
|
|
|
18
18
|
commit_id: str | None
|
|
19
19
|
__commit_id__: str | None
|
|
20
20
|
|
|
21
|
-
__version__ = version = '1.
|
|
22
|
-
__version_tuple__ = version_tuple = (1,
|
|
21
|
+
__version__ = version = '1.10.0'
|
|
22
|
+
__version_tuple__ = version_tuple = (1, 10, 0)
|
|
23
23
|
|
|
24
|
-
__commit_id__ = commit_id = '
|
|
24
|
+
__commit_id__ = commit_id = 'g567d6858b'
|
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import logging
|
|
3
|
+
import os
|
|
4
|
+
import shutil
|
|
5
|
+
from collections import UserDict
|
|
6
|
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
7
|
+
from functools import cached_property
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from tempfile import TemporaryDirectory
|
|
10
|
+
from typing import TYPE_CHECKING, Any, Callable, Optional, Union
|
|
11
|
+
|
|
12
|
+
import requests
|
|
13
|
+
from pyimg4 import IM4P # pyright: ignore[reportMissingTypeStubs]
|
|
14
|
+
from rich.progress import Progress, TaskID
|
|
15
|
+
|
|
16
|
+
from ipsw_parser.archive import Archive
|
|
17
|
+
from ipsw_parser.component import Component, SupportsPathByEntry
|
|
18
|
+
from ipsw_parser.dsc import DSC_DIRECTORIES, find_dsc, split_dsc
|
|
19
|
+
from ipsw_parser.process import ProcessExecutionError, run
|
|
20
|
+
|
|
21
|
+
if TYPE_CHECKING:
|
|
22
|
+
from ipsw_parser.build_manifest import BuildManifest
|
|
23
|
+
|
|
24
|
+
logger = logging.getLogger(__name__)
|
|
25
|
+
|
|
26
|
+
AEA_MAGIC = b"AEA1"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _start(progress: Progress, name: str, phase: str) -> TaskID:
|
|
30
|
+
return progress.add_task(name, total=None, phase=phase)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _done(progress: Progress, task: TaskID) -> None:
|
|
34
|
+
progress.update(task, phase="done", total=1, completed=1)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def extract_as(
|
|
38
|
+
archive: Archive, member_name: str, output_path: Union[str, "os.PathLike[str]"], chunk_size: int = 64 * 1024
|
|
39
|
+
) -> None:
|
|
40
|
+
"""Extract one archive member into a caller-provided path."""
|
|
41
|
+
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
|
42
|
+
with archive.open(member_name) as source, open(output_path, "wb") as target:
|
|
43
|
+
shutil.copyfileobj(source, target, length=chunk_size)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _copy_tree(
|
|
47
|
+
src: Path, output: Path, max_reported: int = 20, copied: Optional[Callable[[int], object]] = None
|
|
48
|
+
) -> None:
|
|
49
|
+
"""
|
|
50
|
+
Copy ``src`` into ``output``, reporting the entries which could not be copied.
|
|
51
|
+
|
|
52
|
+
``copied`` is called with the size on disk of each file which is copied.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
def copy(source: str, target: str) -> None:
|
|
56
|
+
shutil.copy2(source, target)
|
|
57
|
+
if copied is not None:
|
|
58
|
+
# st_blocks does not exist on Windows (where no image gets mounted anyway)
|
|
59
|
+
copied(getattr(os.lstat(source), "st_blocks", 0) * 512)
|
|
60
|
+
|
|
61
|
+
try:
|
|
62
|
+
shutil.copytree(src, output, symlinks=True, dirs_exist_ok=True, copy_function=copy)
|
|
63
|
+
except shutil.Error as e:
|
|
64
|
+
# An incomplete copy would otherwise go unnoticed. When overwriting a previous extraction,
|
|
65
|
+
# its symlinks and its files without write permissions are expected here.
|
|
66
|
+
# The reason ends with the absolute paths, e.g. "[Errno 13] Permission denied: '/path'"
|
|
67
|
+
failures = [
|
|
68
|
+
os.path.relpath(source, src) + ": " + str(reason).split(": '")[0] for source, _, reason in e.args[0]
|
|
69
|
+
]
|
|
70
|
+
if len(failures) > max_reported:
|
|
71
|
+
failures[max_reported:] = [f"... and {len(failures) - max_reported} more"]
|
|
72
|
+
logger.warning("\n ".join([f"{len(e.args[0])} entries were not copied into {output}:", *failures]))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _move_tree(src: Path, dst: Path) -> None:
|
|
76
|
+
"""Move the files of ``src`` into ``dst``, through the symlinks to directories ``dst`` already has."""
|
|
77
|
+
for directory, directories, files in os.walk(src):
|
|
78
|
+
target = dst / os.path.relpath(directory, src)
|
|
79
|
+
target.mkdir(parents=True, exist_ok=True)
|
|
80
|
+
# walk() does not go into a symlink to a directory: it is moved like a file
|
|
81
|
+
for name in files + [name for name in directories if os.path.islink(os.path.join(directory, name))]:
|
|
82
|
+
os.replace(os.path.join(directory, name), target / name)
|
|
83
|
+
shutil.rmtree(src)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _extract_dmg(
|
|
87
|
+
dmg: Path,
|
|
88
|
+
output: Path,
|
|
89
|
+
sub_path: Optional[Path] = None,
|
|
90
|
+
pem_db: Optional[str] = None,
|
|
91
|
+
progress: Optional[Progress] = None,
|
|
92
|
+
task: Optional[TaskID] = None,
|
|
93
|
+
) -> None:
|
|
94
|
+
if progress is None or task is None:
|
|
95
|
+
progress = Progress(disable=True)
|
|
96
|
+
task = _start(progress, dmg.name, "")
|
|
97
|
+
# darwin system statistically have problems cleaning up after detaching the mountpoint
|
|
98
|
+
with TemporaryDirectory() as temp_dir_name:
|
|
99
|
+
temp_dir = Path(temp_dir_name)
|
|
100
|
+
mnt = temp_dir / "mnt"
|
|
101
|
+
mnt.mkdir()
|
|
102
|
+
|
|
103
|
+
with dmg.open("rb") as f:
|
|
104
|
+
magic = f.read(len(AEA_MAGIC))
|
|
105
|
+
if magic == AEA_MAGIC:
|
|
106
|
+
logger.debug("Found Apple Encrypted Archive. Decrypting...")
|
|
107
|
+
progress.update(task, phase="decrypting")
|
|
108
|
+
aea_dmg = str(dmg.absolute()) + ".aea"
|
|
109
|
+
dmg.rename(aea_dmg)
|
|
110
|
+
dmg = temp_dir / Path(aea_dmg).name.rsplit(".", 1)[0]
|
|
111
|
+
args: list[Union[str, Path]] = ["fw", "aea", aea_dmg, "-o", temp_dir]
|
|
112
|
+
if pem_db is not None:
|
|
113
|
+
pem_db_path: Union[str, Path] = pem_db
|
|
114
|
+
if "://" in pem_db:
|
|
115
|
+
# create a local file containing it
|
|
116
|
+
pem_db_path = temp_dir / "pem-db.json"
|
|
117
|
+
pem_db_path.write_text(requests.get(pem_db, verify=False).text)
|
|
118
|
+
args += ["--pem-db", pem_db_path]
|
|
119
|
+
run("ipsw", *args)
|
|
120
|
+
|
|
121
|
+
progress.update(task, phase="mounting")
|
|
122
|
+
run("hdiutil", "attach", "-mountpoint", mnt, dmg)
|
|
123
|
+
|
|
124
|
+
# The files are counted by their size on disk, to add up to the used space of the volume
|
|
125
|
+
progress.update(task, phase="copying", total=shutil.disk_usage(mnt).used)
|
|
126
|
+
_copy_tree(
|
|
127
|
+
mnt if sub_path is None else mnt / sub_path,
|
|
128
|
+
output,
|
|
129
|
+
copied=lambda size: progress.update(task, advance=size),
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
run("hdiutil", "detach", "-force", mnt)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _decode_sandbox_profiles(kernel_output: Path, output: Path, profile_type: Optional[str] = None) -> None:
|
|
136
|
+
args: list[Union[str, Path]] = ["sb", "list", kernel_output]
|
|
137
|
+
if profile_type is not None:
|
|
138
|
+
args += ["--type", profile_type]
|
|
139
|
+
|
|
140
|
+
output.mkdir(exist_ok=True, parents=True)
|
|
141
|
+
|
|
142
|
+
# One process decoding every profile parses the kernelcache once, instead of once per profile
|
|
143
|
+
batch_args: list[Union[str, Path]] = ["sb", "dec", kernel_output, "--format", "json"]
|
|
144
|
+
if profile_type is not None:
|
|
145
|
+
batch_args += ["--type", profile_type]
|
|
146
|
+
try:
|
|
147
|
+
profiles = json.loads(run("ipsw", *batch_args))
|
|
148
|
+
except (ProcessExecutionError, ValueError) as e:
|
|
149
|
+
logger.warning(f"failed to decode the sandbox profiles at once, decoding them one by one: {e}")
|
|
150
|
+
else:
|
|
151
|
+
for profile in profiles:
|
|
152
|
+
# Not with_suffix(): see decode_worker
|
|
153
|
+
(output / f"{profile['name']}.sb").write_text(profile["sbpl"])
|
|
154
|
+
return
|
|
155
|
+
|
|
156
|
+
profile_names = run("ipsw", *args).splitlines()
|
|
157
|
+
|
|
158
|
+
def decode_worker(profile_name: str) -> None:
|
|
159
|
+
# Not with_suffix(): it would cut a dotted name short, and com.apple.cloudd would share
|
|
160
|
+
# com.apple.sb with every other com.apple.* profile
|
|
161
|
+
profile_path = output / f"{profile_name}.sb"
|
|
162
|
+
decode_args: list[Union[str, Path]] = ["sb", "dec", kernel_output, profile_name]
|
|
163
|
+
if profile_type is not None:
|
|
164
|
+
decode_args += ["--type", profile_type]
|
|
165
|
+
try:
|
|
166
|
+
profile = run("ipsw", *decode_args)
|
|
167
|
+
except ProcessExecutionError as e:
|
|
168
|
+
logger.warning(f"failed to decode sandbox profile {profile_name}: {e}")
|
|
169
|
+
return
|
|
170
|
+
profile_path.write_text(profile)
|
|
171
|
+
|
|
172
|
+
with ThreadPoolExecutor(max_workers=os.cpu_count()) as executor:
|
|
173
|
+
futures = [
|
|
174
|
+
executor.submit(
|
|
175
|
+
decode_worker,
|
|
176
|
+
profile_name,
|
|
177
|
+
)
|
|
178
|
+
for profile_name in profile_names
|
|
179
|
+
]
|
|
180
|
+
for future in as_completed(futures):
|
|
181
|
+
future.result()
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _extract_kernelcache(build_identity: "BuildIdentity", output: Path) -> Path:
|
|
185
|
+
kernel_component = build_identity.get_component("KernelCache")
|
|
186
|
+
kernel_path = Path(kernel_component.path)
|
|
187
|
+
kernel_output = output / kernel_path.parts[-1]
|
|
188
|
+
output.mkdir(parents=True, exist_ok=True)
|
|
189
|
+
|
|
190
|
+
logger.info(f"extracting kernel into: {kernel_output}")
|
|
191
|
+
kernel_output.write_bytes(_im4p_payload(kernel_component.data))
|
|
192
|
+
try:
|
|
193
|
+
# In case the kernel is a FAT image, extract the arm64 macho
|
|
194
|
+
run("ipsw", "macho", "lipo", "-a", "arm64", kernel_output)
|
|
195
|
+
next(iter(kernel_output.parent.glob("*.arm64"))).rename(kernel_output)
|
|
196
|
+
except ProcessExecutionError:
|
|
197
|
+
pass
|
|
198
|
+
|
|
199
|
+
return kernel_output
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _kernel_identities(build_identity: "BuildIdentity") -> list["BuildIdentity"]:
|
|
203
|
+
"""
|
|
204
|
+
Return a build identity for each kernelcache of the IPSW.
|
|
205
|
+
|
|
206
|
+
An IPSW of several devices has a kernelcache for each of them, shared by its build identities.
|
|
207
|
+
"""
|
|
208
|
+
kernels: dict[str, BuildIdentity] = {}
|
|
209
|
+
for identity in build_identity.build_manifest.build_identities:
|
|
210
|
+
if identity.has_component("KernelCache"):
|
|
211
|
+
kernels.setdefault(identity.get_component_path("KernelCache"), identity)
|
|
212
|
+
return list(kernels.values())
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _im4p_payload(data: bytes) -> bytes:
|
|
216
|
+
"""Return the decompressed payload of an IM4P."""
|
|
217
|
+
payload = IM4P(data).payload
|
|
218
|
+
if payload is None:
|
|
219
|
+
raise ValueError("The IM4P carries no payload.")
|
|
220
|
+
payload.decompress()
|
|
221
|
+
return payload.output().data
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
class BuildIdentity(UserDict[str, Any]):
|
|
225
|
+
"""Dictionary-backed wrapper for a single build identity."""
|
|
226
|
+
|
|
227
|
+
def __init__(self, build_manifest: "BuildManifest", data: dict[str, Any]):
|
|
228
|
+
"""Wrap a single BuildIdentity entry from the manifest."""
|
|
229
|
+
super().__init__(data)
|
|
230
|
+
self.build_manifest = build_manifest
|
|
231
|
+
|
|
232
|
+
@cached_property
|
|
233
|
+
def device_class(self) -> str:
|
|
234
|
+
"""Return the normalized device class for this build identity."""
|
|
235
|
+
return self["Info"]["DeviceClass"].lower()
|
|
236
|
+
|
|
237
|
+
@cached_property
|
|
238
|
+
def restore_behavior(self) -> Optional[str]:
|
|
239
|
+
"""Return the restore behavior declared by the build identity."""
|
|
240
|
+
return self["Info"].get("RestoreBehavior")
|
|
241
|
+
|
|
242
|
+
@cached_property
|
|
243
|
+
def variant(self) -> Optional[str]:
|
|
244
|
+
"""Return the variant string for this build identity."""
|
|
245
|
+
return self["Info"].get("Variant")
|
|
246
|
+
|
|
247
|
+
@cached_property
|
|
248
|
+
def macos_variant(self) -> Optional[str]:
|
|
249
|
+
"""Return the macOS restore variant, if present."""
|
|
250
|
+
return self["Info"].get("MacOSVariant")
|
|
251
|
+
|
|
252
|
+
@cached_property
|
|
253
|
+
def manifest(self) -> dict[str, Any]:
|
|
254
|
+
"""Return the component manifest dictionary."""
|
|
255
|
+
return self["Manifest"]
|
|
256
|
+
|
|
257
|
+
@cached_property
|
|
258
|
+
def minimum_system_partition(self) -> Optional[int]:
|
|
259
|
+
"""Return the minimum system partition requirement, if present."""
|
|
260
|
+
return self["Info"].get("MinimumSystemPartition")
|
|
261
|
+
|
|
262
|
+
def get_component_path(self, component: str) -> str:
|
|
263
|
+
"""Return the archive path for a named component."""
|
|
264
|
+
return self.manifest[component]["Info"]["Path"]
|
|
265
|
+
|
|
266
|
+
def has_component(self, name: str) -> bool:
|
|
267
|
+
"""Return whether the build identity contains a named component."""
|
|
268
|
+
return name in self.manifest
|
|
269
|
+
|
|
270
|
+
def get_component(
|
|
271
|
+
self,
|
|
272
|
+
name: str,
|
|
273
|
+
tss: Optional[SupportsPathByEntry] = None,
|
|
274
|
+
data: Optional[bytes] = None,
|
|
275
|
+
path: Optional[str] = None,
|
|
276
|
+
) -> Component:
|
|
277
|
+
"""Return a component wrapper for a named manifest entry."""
|
|
278
|
+
return Component(self, name, tss=tss, data=data, path=path)
|
|
279
|
+
|
|
280
|
+
def extract_dsc(self, output: Path, pem_db: Optional[str] = None, split: bool = True) -> None:
|
|
281
|
+
"""Extract the system cryptex DSC payloads into ``output``."""
|
|
282
|
+
build_identity = self.build_manifest.build_identities[0]
|
|
283
|
+
if not build_identity.has_component("Cryptex1,SystemOS"):
|
|
284
|
+
return
|
|
285
|
+
|
|
286
|
+
device_support_symbols_path = output / "private/preboot/Cryptexes/OS/System"
|
|
287
|
+
device_support_symbols_path.mkdir(parents=True, exist_ok=True)
|
|
288
|
+
|
|
289
|
+
with TemporaryDirectory() as temp_dir:
|
|
290
|
+
system_os = Path(temp_dir) / "system_os.dmg"
|
|
291
|
+
system_os_component_path = build_identity.get_component_path("Cryptex1,SystemOS")
|
|
292
|
+
extract_as(self.build_manifest.ipsw.archive, system_os_component_path, system_os)
|
|
293
|
+
_extract_dmg(system_os, device_support_symbols_path, sub_path=Path("System"), pem_db=pem_db)
|
|
294
|
+
if split:
|
|
295
|
+
split_dsc(output)
|
|
296
|
+
|
|
297
|
+
def get_kernelcache_payload(self, arch: Optional[str] = None) -> bytes:
|
|
298
|
+
"""Return the decompressed kernelcache payload, optionally sliced by arch."""
|
|
299
|
+
payload = _im4p_payload(self.build_manifest.build_identities[0].get_component("KernelCache").data)
|
|
300
|
+
if arch is None:
|
|
301
|
+
return payload
|
|
302
|
+
|
|
303
|
+
with TemporaryDirectory() as temp_dir:
|
|
304
|
+
kernel_output = Path(temp_dir) / "kernel"
|
|
305
|
+
kernel_output.write_bytes(payload)
|
|
306
|
+
run("ipsw", "macho", "lipo", "-a", arch, kernel_output)
|
|
307
|
+
return Path(next(kernel_output.parent.glob(f"*.{arch}"))).read_bytes()
|
|
308
|
+
|
|
309
|
+
def extract_sandbox_profiles(self, output: Path) -> None:
|
|
310
|
+
"""Decode the normal and protobox sandbox profiles of every kernelcache into a directory of its own."""
|
|
311
|
+
|
|
312
|
+
def decode(kernel_identity: "BuildIdentity") -> None:
|
|
313
|
+
profiles = output / Path(kernel_identity.get_component_path("KernelCache")).name
|
|
314
|
+
with TemporaryDirectory() as temp_dir:
|
|
315
|
+
kernel_output = _extract_kernelcache(kernel_identity, Path(temp_dir))
|
|
316
|
+
_decode_sandbox_profiles(kernel_output, profiles)
|
|
317
|
+
_decode_sandbox_profiles(kernel_output, profiles / "protobox", profile_type="protobox")
|
|
318
|
+
|
|
319
|
+
with ThreadPoolExecutor() as executor:
|
|
320
|
+
list(executor.map(decode, _kernel_identities(self)))
|
|
321
|
+
|
|
322
|
+
def extract(self, output: Path, pem_db: Optional[str] = None, progress: Optional[Progress] = None) -> None:
|
|
323
|
+
"""
|
|
324
|
+
Extract the build identity contents into a filesystem layout.
|
|
325
|
+
|
|
326
|
+
``progress`` gets a task for each part of the extraction, whose ``phase`` field names its current step.
|
|
327
|
+
"""
|
|
328
|
+
logger.info(f"extracting into: {output}")
|
|
329
|
+
progress = progress or Progress(disable=True)
|
|
330
|
+
|
|
331
|
+
build_identity = self.build_manifest.build_identities[0]
|
|
332
|
+
archive = self.build_manifest.ipsw.archive
|
|
333
|
+
|
|
334
|
+
def extract_image(name: str, image_output: Path, dsc_directory: Optional[str]) -> None:
|
|
335
|
+
image_output.mkdir(parents=True, exist_ok=True)
|
|
336
|
+
logger.info(f"extracting {name} into: {image_output}")
|
|
337
|
+
task = _start(progress, name, "unpacking")
|
|
338
|
+
with TemporaryDirectory() as temp_dir:
|
|
339
|
+
dmg = Path(temp_dir) / f"{name}.dmg"
|
|
340
|
+
extract_as(archive, build_identity.get_component_path(name), dmg)
|
|
341
|
+
_extract_dmg(dmg, image_output, pem_db=pem_db, progress=progress, task=task)
|
|
342
|
+
_done(progress, task)
|
|
343
|
+
# The shared cache of an image is split as soon as it is there, whatever the other images are
|
|
344
|
+
# doing. Not into the output yet: its libraries go through symlinks of the OS image (those of
|
|
345
|
+
# WebKit lead to the cryptex, for instance), which have to be there first.
|
|
346
|
+
if dsc_directory is not None and find_dsc(output / dsc_directory):
|
|
347
|
+
task = _start(progress, f"{name} shared cache", "splitting")
|
|
348
|
+
split_dsc(output, [dsc_directory], output=split_output)
|
|
349
|
+
_done(progress, task)
|
|
350
|
+
|
|
351
|
+
def extract_kernel(kernel_identity: "BuildIdentity") -> None:
|
|
352
|
+
name = Path(kernel_identity.get_component_path("KernelCache")).name
|
|
353
|
+
task = _start(progress, name, "decoding sandbox profiles")
|
|
354
|
+
# Kernelcaches have sandbox profiles of the same names, so each one keeps its own next to it
|
|
355
|
+
kernel_output = _extract_kernelcache(kernel_identity, output / "Kernels" / name)
|
|
356
|
+
sandbox_profiles = output / "Kernels" / name / "sandbox/profiles"
|
|
357
|
+
logger.info(f"decoding sandbox profiles into: {sandbox_profiles}")
|
|
358
|
+
try:
|
|
359
|
+
_decode_sandbox_profiles(kernel_output, sandbox_profiles)
|
|
360
|
+
except ProcessExecutionError as e:
|
|
361
|
+
logger.error("Failed to extract sandbox profiles: %s", e)
|
|
362
|
+
try:
|
|
363
|
+
_decode_sandbox_profiles(kernel_output, sandbox_profiles / "protobox", profile_type="protobox")
|
|
364
|
+
except (ProcessExecutionError, FileNotFoundError, OSError) as e:
|
|
365
|
+
logger.error("Failed to extract sandbox profiles: %s", e)
|
|
366
|
+
_done(progress, task)
|
|
367
|
+
|
|
368
|
+
# On the volume of the output, for its files to be moved rather than copied
|
|
369
|
+
split_output = output / ".shared-cache"
|
|
370
|
+
|
|
371
|
+
# Each image, with the directory of its shared cache (the System/Cryptexes/OS symlink of the OS
|
|
372
|
+
# image leads to the one of the cryptex)
|
|
373
|
+
system_dsc, cryptex_dsc = DSC_DIRECTORIES[:2]
|
|
374
|
+
images: dict[str, tuple[Path, Optional[str]]] = {"OS": (output, system_dsc)}
|
|
375
|
+
for cryptex, name, dsc_directory in (("App", "Cryptex1,AppOS", None), ("OS", "Cryptex1,SystemOS", cryptex_dsc)):
|
|
376
|
+
if build_identity.has_component(name):
|
|
377
|
+
images[name] = (output / "private/preboot/Cryptexes" / cryptex, dsc_directory)
|
|
378
|
+
|
|
379
|
+
# The images and the kernelcaches don't depend on each other, and each of them is mostly
|
|
380
|
+
# waiting for an external tool
|
|
381
|
+
with ThreadPoolExecutor() as executor:
|
|
382
|
+
jobs = [executor.submit(extract_kernel, identity) for identity in _kernel_identities(self)]
|
|
383
|
+
jobs += [executor.submit(extract_image, name, *image) for name, image in images.items()]
|
|
384
|
+
for job in jobs:
|
|
385
|
+
job.result()
|
|
386
|
+
if split_output.exists():
|
|
387
|
+
_move_tree(split_output, output)
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import logging
|
|
2
2
|
import plistlib
|
|
3
|
+
from collections.abc import Sequence
|
|
3
4
|
from datetime import datetime
|
|
4
5
|
from pathlib import Path
|
|
6
|
+
from typing import Optional
|
|
5
7
|
|
|
6
8
|
from ipsw_parser.process import ProcessExecutionError, run
|
|
7
9
|
|
|
@@ -25,9 +27,10 @@ def find_dsc(directory: Path) -> list[Path]:
|
|
|
25
27
|
return sorted(file for file in directory.glob(DSC_NAME_PATTERN) if "." not in file.name and file.is_file())
|
|
26
28
|
|
|
27
29
|
|
|
28
|
-
def split_dsc(root: Path) -> list[Path]:
|
|
30
|
+
def split_dsc(root: Path, directories: Sequence[str] = DSC_DIRECTORIES, output: Optional[Path] = None) -> list[Path]:
|
|
29
31
|
"""
|
|
30
|
-
Split dyld shared caches found
|
|
32
|
+
Split dyld shared caches found in ``directories`` of ``root`` into their images, under ``output``
|
|
33
|
+
(``root`` by default).
|
|
31
34
|
|
|
32
35
|
``ipsw dyld split`` does it using Xcode's own extractor, which refuses a cache whose code
|
|
33
36
|
signature does not match (a patched one, for instance). Such a cache is extracted using
|
|
@@ -35,15 +38,21 @@ def split_dsc(root: Path) -> list[Path]:
|
|
|
35
38
|
|
|
36
39
|
:returns: The shared caches which were split.
|
|
37
40
|
"""
|
|
41
|
+
output = root if output is None else output
|
|
38
42
|
split: list[Path] = []
|
|
39
|
-
|
|
43
|
+
seen: set[Path] = set()
|
|
44
|
+
for directory in directories:
|
|
40
45
|
for dsc in find_dsc(root / directory):
|
|
46
|
+
# /System/Cryptexes/OS is a symlink to the cryptex: the same cache is not split twice
|
|
47
|
+
if dsc.resolve() in seen:
|
|
48
|
+
continue
|
|
49
|
+
seen.add(dsc.resolve())
|
|
41
50
|
logger.info(f"splitting DSC: {dsc}")
|
|
42
51
|
try:
|
|
43
|
-
run("ipsw", "dyld", "split", dsc, "-o",
|
|
52
|
+
run("ipsw", "dyld", "split", dsc, "-o", output)
|
|
44
53
|
except ProcessExecutionError as e:
|
|
45
54
|
logger.warning(f"`ipsw dyld split` failed, extracting the images of {dsc} instead: {e}")
|
|
46
|
-
run("ipsw", "dyld", "extract", dsc, "--all", "--output",
|
|
55
|
+
run("ipsw", "dyld", "extract", dsc, "--all", "--output", output)
|
|
47
56
|
split.append(dsc)
|
|
48
57
|
return split
|
|
49
58
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: ipsw-parser
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.10.0
|
|
4
4
|
Summary: python3 utility for parsing and extracting data from IPSW
|
|
5
5
|
Author-email: doronz88 <doron88@gmail.com>
|
|
6
6
|
Maintainer-email: doronz88 <doron88@gmail.com>
|
|
@@ -699,6 +699,7 @@ Requires-Dist: ansilogs>=1.1.0
|
|
|
699
699
|
Requires-Dist: bytestruct>=0.1.0
|
|
700
700
|
Requires-Dist: pyimg4>=0.8.8
|
|
701
701
|
Requires-Dist: requests
|
|
702
|
+
Requires-Dist: rich
|
|
702
703
|
Requires-Dist: remotezip2
|
|
703
704
|
Requires-Dist: typer
|
|
704
705
|
Provides-Extra: test
|
|
@@ -34,7 +34,9 @@ ipsw_parser.egg-info/scm_file_list.json
|
|
|
34
34
|
ipsw_parser.egg-info/scm_version.json
|
|
35
35
|
ipsw_parser.egg-info/top_level.txt
|
|
36
36
|
tests/test_archive_backends.py
|
|
37
|
+
tests/test_copy_tree.py
|
|
37
38
|
tests/test_dsc.py
|
|
39
|
+
tests/test_extract.py
|
|
38
40
|
tests/test_firmware.py
|
|
39
41
|
tests/test_kernelcache.py
|
|
40
42
|
tests/test_process.py
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
import pytest
|
|
5
|
+
|
|
6
|
+
from ipsw_parser import build_identity
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def test_entries_which_are_not_copied_are_named(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
|
|
10
|
+
src, output = tmp_path / "src", tmp_path / "output"
|
|
11
|
+
(src / "usr/lib").mkdir(parents=True)
|
|
12
|
+
(src / "usr/lib/libfoo.dylib").write_bytes(b"foo")
|
|
13
|
+
(src / "usr/lib/libbar.dylib").symlink_to("libfoo.dylib")
|
|
14
|
+
|
|
15
|
+
with caplog.at_level(logging.WARNING):
|
|
16
|
+
build_identity._copy_tree(src, output)
|
|
17
|
+
assert not caplog.records
|
|
18
|
+
# Extracting over a previous extraction: the symlink is already there
|
|
19
|
+
build_identity._copy_tree(src, output)
|
|
20
|
+
|
|
21
|
+
assert (output / "usr/lib/libfoo.dylib").read_bytes() == b"foo"
|
|
22
|
+
# The wording of the reason is up to the OS
|
|
23
|
+
(message,) = caplog.messages
|
|
24
|
+
assert message.startswith(f"1 entries were not copied into {output}:\n {Path('usr/lib/libbar.dylib')}: [")
|
|
@@ -111,3 +111,12 @@ def test_device_support_layout_is_not_finalized_without_a_cache(
|
|
|
111
111
|
|
|
112
112
|
assert commands == []
|
|
113
113
|
assert not (device_support / ".finalized").exists()
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def test_split_dsc_splits_a_symlinked_cryptex_once(tmp_path: Path, commands: list[tuple[str, ...]]) -> None:
|
|
117
|
+
cache = _create(tmp_path, CRYPTEX_DSC)
|
|
118
|
+
(tmp_path / "System/Cryptexes").mkdir(parents=True)
|
|
119
|
+
(tmp_path / "System/Cryptexes/OS").symlink_to("../../private/preboot/Cryptexes/OS")
|
|
120
|
+
|
|
121
|
+
assert dsc.split_dsc(tmp_path) == [cache]
|
|
122
|
+
assert len(commands) == 1
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
import threading
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from types import SimpleNamespace
|
|
5
|
+
from typing import TYPE_CHECKING, cast
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
|
|
9
|
+
from ipsw_parser import build_identity
|
|
10
|
+
from ipsw_parser.build_identity import BuildIdentity
|
|
11
|
+
|
|
12
|
+
CRYPTEX_DSC = "private/preboot/Cryptexes/OS/System/Library/Caches/com.apple.dyld"
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from ipsw_parser.build_manifest import BuildManifest
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def test_extract(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
19
|
+
events: list = []
|
|
20
|
+
cryptex_dsc_is_split = threading.Event()
|
|
21
|
+
manifest = {name: {"Info": {"Path": f"{name}.dmg"}} for name in ("OS", "Cryptex1,AppOS", "Cryptex1,SystemOS")}
|
|
22
|
+
build_manifest = cast("BuildManifest", SimpleNamespace(ipsw=SimpleNamespace(archive=None)))
|
|
23
|
+
# Two devices, the first of them having two build identities (erase and upgrade)
|
|
24
|
+
kernels = ("kernelcache.release.iphone16", "kernelcache.release.iphone16", "kernelcache.release.iphone17")
|
|
25
|
+
identities = [
|
|
26
|
+
BuildIdentity(build_manifest, {"Manifest": {**manifest, "KernelCache": {"Info": {"Path": kernel}}}})
|
|
27
|
+
for kernel in kernels
|
|
28
|
+
]
|
|
29
|
+
identity = identities[0]
|
|
30
|
+
identity.build_manifest.build_identities = identities
|
|
31
|
+
|
|
32
|
+
def extract_dmg(dmg: Path, output: Path, **kwargs: object) -> None:
|
|
33
|
+
if dmg.name == "OS.dmg":
|
|
34
|
+
# The OS image is the last one to be done
|
|
35
|
+
events.append(("split before the OS is done", cryptex_dsc_is_split.wait(timeout=10)))
|
|
36
|
+
events.append((dmg.name, output))
|
|
37
|
+
|
|
38
|
+
def split_dsc(root: Path, directories: list, output: Path) -> None:
|
|
39
|
+
assert output != root
|
|
40
|
+
events.append(("split", root, *directories))
|
|
41
|
+
if directories == [CRYPTEX_DSC]:
|
|
42
|
+
cryptex_dsc_is_split.set()
|
|
43
|
+
|
|
44
|
+
monkeypatch.setattr(build_identity, "extract_as", lambda archive, member, path: None)
|
|
45
|
+
monkeypatch.setattr(build_identity, "_extract_dmg", extract_dmg)
|
|
46
|
+
monkeypatch.setattr(
|
|
47
|
+
build_identity,
|
|
48
|
+
"_extract_kernelcache",
|
|
49
|
+
lambda identity, output: events.append(("kernel", output / identity.get_component_path("KernelCache"))),
|
|
50
|
+
)
|
|
51
|
+
monkeypatch.setattr(
|
|
52
|
+
build_identity,
|
|
53
|
+
"_decode_sandbox_profiles",
|
|
54
|
+
lambda kernel, output, profile_type=None: events.append(("sandbox", output)),
|
|
55
|
+
)
|
|
56
|
+
# Only the cryptex has a shared cache
|
|
57
|
+
monkeypatch.setattr(
|
|
58
|
+
build_identity, "find_dsc", lambda directory: [directory] if "Cryptexes" in str(directory) else []
|
|
59
|
+
)
|
|
60
|
+
monkeypatch.setattr(build_identity, "split_dsc", split_dsc)
|
|
61
|
+
|
|
62
|
+
identity.extract(tmp_path)
|
|
63
|
+
|
|
64
|
+
cryptexes = tmp_path / "private/preboot/Cryptexes"
|
|
65
|
+
# The shared cache of the cryptex is split once the cryptex is extracted, without waiting for the OS
|
|
66
|
+
assert sorted(events, key=str) == sorted(
|
|
67
|
+
[
|
|
68
|
+
("OS.dmg", tmp_path),
|
|
69
|
+
("Cryptex1,AppOS.dmg", cryptexes / "App"),
|
|
70
|
+
("Cryptex1,SystemOS.dmg", cryptexes / "OS"),
|
|
71
|
+
("split", tmp_path, CRYPTEX_DSC),
|
|
72
|
+
("split before the OS is done", True),
|
|
73
|
+
# Every kernelcache is extracted once, and has sandbox profiles of its own
|
|
74
|
+
*(
|
|
75
|
+
event
|
|
76
|
+
for kernel in set(kernels)
|
|
77
|
+
for event in (
|
|
78
|
+
("kernel", tmp_path / "Kernels" / kernel / kernel),
|
|
79
|
+
("sandbox", tmp_path / "Kernels" / kernel / "sandbox/profiles"),
|
|
80
|
+
("sandbox", tmp_path / "Kernels" / kernel / "sandbox/profiles/protobox"),
|
|
81
|
+
)
|
|
82
|
+
),
|
|
83
|
+
],
|
|
84
|
+
key=str,
|
|
85
|
+
)
|
|
86
|
+
assert events.index(("Cryptex1,SystemOS.dmg", cryptexes / "OS")) < events.index(("split", tmp_path, CRYPTEX_DSC))
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def test_sandbox_profiles_of_every_kernelcache_get_a_directory(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
90
|
+
decoded: list = []
|
|
91
|
+
build_manifest = cast("BuildManifest", SimpleNamespace())
|
|
92
|
+
kernels = ("kernelcache.release.iphone16", "kernelcache.release.iphone16", "kernelcache.release.iphone17")
|
|
93
|
+
identities = [
|
|
94
|
+
BuildIdentity(build_manifest, {"Manifest": {"KernelCache": {"Info": {"Path": kernel}}}}) for kernel in kernels
|
|
95
|
+
]
|
|
96
|
+
build_manifest.build_identities = identities
|
|
97
|
+
|
|
98
|
+
monkeypatch.setattr(
|
|
99
|
+
build_identity, "_extract_kernelcache", lambda identity, output: identity.get_component_path("KernelCache")
|
|
100
|
+
)
|
|
101
|
+
monkeypatch.setattr(
|
|
102
|
+
build_identity,
|
|
103
|
+
"_decode_sandbox_profiles",
|
|
104
|
+
lambda kernel, output, profile_type=None: decoded.append((kernel, output)),
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
identities[0].extract_sandbox_profiles(tmp_path)
|
|
108
|
+
|
|
109
|
+
assert sorted(decoded) == sorted(
|
|
110
|
+
(kernel, directory)
|
|
111
|
+
for kernel in set(kernels)
|
|
112
|
+
for directory in (tmp_path / kernel, tmp_path / kernel / "protobox")
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@pytest.mark.skipif(sys.platform == "win32", reason="images are only extracted on macOS")
|
|
117
|
+
def test_move_tree_goes_through_the_symlinks_of_the_destination(tmp_path: Path) -> None:
|
|
118
|
+
src, dst = tmp_path / "src", tmp_path / "dst"
|
|
119
|
+
(src / "Frameworks/WebKit.framework").mkdir(parents=True)
|
|
120
|
+
(src / "Frameworks/WebKit.framework/WebKit").write_bytes(b"webkit")
|
|
121
|
+
(src / "Frameworks/Foundation.framework").mkdir()
|
|
122
|
+
(src / "Frameworks/Foundation.framework/Foundation").write_bytes(b"foundation")
|
|
123
|
+
(dst / "Cryptex/WebKit.framework").mkdir(parents=True)
|
|
124
|
+
(dst / "Frameworks").mkdir()
|
|
125
|
+
(dst / "Frameworks/WebKit.framework").symlink_to("../Cryptex/WebKit.framework")
|
|
126
|
+
|
|
127
|
+
build_identity._move_tree(src, dst)
|
|
128
|
+
|
|
129
|
+
assert not src.exists()
|
|
130
|
+
assert (dst / "Frameworks/WebKit.framework").is_symlink()
|
|
131
|
+
assert (dst / "Cryptex/WebKit.framework/WebKit").read_bytes() == b"webkit"
|
|
132
|
+
assert (dst / "Frameworks/Foundation.framework/Foundation").read_bytes() == b"foundation"
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
+
import json
|
|
1
2
|
from pathlib import Path
|
|
3
|
+
from typing import Optional
|
|
2
4
|
|
|
3
5
|
import pytest
|
|
4
6
|
|
|
@@ -8,12 +10,16 @@ from ipsw_parser.process import ProcessExecutionError
|
|
|
8
10
|
PROFILES = ["baseline", "com.apple.cloudd", "com.apple.homed", "spotlightknowledged", "spotlightknowledged.updater"]
|
|
9
11
|
|
|
10
12
|
|
|
11
|
-
def _fake_ipsw(calls: list) -> object:
|
|
13
|
+
def _fake_ipsw(calls: list, batch: Optional[str] = None) -> object:
|
|
12
14
|
def run(tool: str, *args: object) -> str:
|
|
13
15
|
calls.append((tool, *map(str, args)))
|
|
14
16
|
assert tool == "ipsw"
|
|
15
17
|
if args[1] == "list":
|
|
16
18
|
return "\n".join(PROFILES) + "\n"
|
|
19
|
+
if "json" in args:
|
|
20
|
+
if batch is None:
|
|
21
|
+
raise ProcessExecutionError(["ipsw", "sb", "dec"], 1, "", "unknown flag: --format")
|
|
22
|
+
return batch
|
|
17
23
|
name = str(args[3])
|
|
18
24
|
if name == "com.apple.homed":
|
|
19
25
|
raise ProcessExecutionError(["ipsw", "sb", "dec"], 1, "", "cannot decode")
|
|
@@ -45,5 +51,20 @@ def test_profile_type_is_passed_to_list_and_decode(tmp_path: Path, monkeypatch:
|
|
|
45
51
|
|
|
46
52
|
build_identity._decode_sandbox_profiles(kernel, tmp_path / "protobox", profile_type="protobox")
|
|
47
53
|
|
|
48
|
-
assert calls[
|
|
54
|
+
assert calls[1] == ("ipsw", "sb", "list", str(kernel), "--type", "protobox")
|
|
49
55
|
assert ("ipsw", "sb", "dec", str(kernel), "spotlightknowledged.updater", "--type", "protobox") in calls
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def test_profiles_are_decoded_by_a_single_process(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
59
|
+
calls: list = []
|
|
60
|
+
batch = json.dumps([{"name": name, "sbpl": f"(profile {name})\n"} for name in PROFILES])
|
|
61
|
+
monkeypatch.setattr(build_identity, "run", _fake_ipsw(calls, batch))
|
|
62
|
+
kernel = tmp_path / "kernelcache"
|
|
63
|
+
output = tmp_path / "protobox"
|
|
64
|
+
|
|
65
|
+
build_identity._decode_sandbox_profiles(kernel, output, profile_type="protobox")
|
|
66
|
+
|
|
67
|
+
assert calls == [("ipsw", "sb", "dec", str(kernel), "--format", "json", "--type", "protobox")]
|
|
68
|
+
assert {path.name: path.read_text() for path in output.iterdir()} == {
|
|
69
|
+
f"{name}.sb": f"(profile {name})\n" for name in PROFILES
|
|
70
|
+
}
|
|
@@ -1,270 +0,0 @@
|
|
|
1
|
-
import logging
|
|
2
|
-
import os
|
|
3
|
-
import shutil
|
|
4
|
-
from collections import UserDict
|
|
5
|
-
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
6
|
-
from functools import cached_property
|
|
7
|
-
from pathlib import Path
|
|
8
|
-
from tempfile import TemporaryDirectory
|
|
9
|
-
from typing import TYPE_CHECKING, Any, Optional, Union
|
|
10
|
-
|
|
11
|
-
import requests
|
|
12
|
-
from pyimg4 import IM4P # pyright: ignore[reportMissingTypeStubs]
|
|
13
|
-
|
|
14
|
-
from ipsw_parser.archive import Archive
|
|
15
|
-
from ipsw_parser.component import Component, SupportsPathByEntry
|
|
16
|
-
from ipsw_parser.dsc import split_dsc
|
|
17
|
-
from ipsw_parser.process import ProcessExecutionError, run
|
|
18
|
-
|
|
19
|
-
if TYPE_CHECKING:
|
|
20
|
-
from ipsw_parser.build_manifest import BuildManifest
|
|
21
|
-
|
|
22
|
-
logger = logging.getLogger(__name__)
|
|
23
|
-
|
|
24
|
-
AEA_MAGIC = b"AEA1"
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
def extract_as(
|
|
28
|
-
archive: Archive, member_name: str, output_path: Union[str, "os.PathLike[str]"], chunk_size: int = 64 * 1024
|
|
29
|
-
) -> None:
|
|
30
|
-
"""Extract one archive member into a caller-provided path."""
|
|
31
|
-
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
|
32
|
-
with archive.open(member_name) as source, open(output_path, "wb") as target:
|
|
33
|
-
shutil.copyfileobj(source, target, length=chunk_size)
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
def _extract_dmg(dmg: Path, output: Path, sub_path: Optional[Path] = None, pem_db: Optional[str] = None) -> None:
|
|
37
|
-
# darwin system statistically have problems cleaning up after detaching the mountpoint
|
|
38
|
-
with TemporaryDirectory() as temp_dir_name:
|
|
39
|
-
temp_dir = Path(temp_dir_name)
|
|
40
|
-
mnt = temp_dir / "mnt"
|
|
41
|
-
mnt.mkdir()
|
|
42
|
-
|
|
43
|
-
with dmg.open("rb") as f:
|
|
44
|
-
magic = f.read(len(AEA_MAGIC))
|
|
45
|
-
if magic == AEA_MAGIC:
|
|
46
|
-
logger.debug("Found Apple Encrypted Archive. Decrypting...")
|
|
47
|
-
aea_dmg = str(dmg.absolute()) + ".aea"
|
|
48
|
-
dmg.rename(aea_dmg)
|
|
49
|
-
dmg = temp_dir / Path(aea_dmg).name.rsplit(".", 1)[0]
|
|
50
|
-
args: list[Union[str, Path]] = ["fw", "aea", aea_dmg, "-o", temp_dir]
|
|
51
|
-
if pem_db is not None:
|
|
52
|
-
pem_db_path: Union[str, Path] = pem_db
|
|
53
|
-
if "://" in pem_db:
|
|
54
|
-
# create a local file containing it
|
|
55
|
-
pem_db_path = temp_dir / "pem-db.json"
|
|
56
|
-
pem_db_path.write_text(requests.get(pem_db, verify=False).text)
|
|
57
|
-
args += ["--pem-db", pem_db_path]
|
|
58
|
-
run("ipsw", *args)
|
|
59
|
-
|
|
60
|
-
run("hdiutil", "attach", "-mountpoint", mnt, dmg)
|
|
61
|
-
|
|
62
|
-
try:
|
|
63
|
-
src = mnt if sub_path is None else mnt / sub_path
|
|
64
|
-
shutil.copytree(src, output, symlinks=True, dirs_exist_ok=True)
|
|
65
|
-
except shutil.Error:
|
|
66
|
-
# when overwriting the same files, some of them don't contain write permissions
|
|
67
|
-
pass
|
|
68
|
-
|
|
69
|
-
run("hdiutil", "detach", "-force", mnt)
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
def _decode_sandbox_profiles(kernel_output: Path, output: Path, profile_type: Optional[str] = None) -> None:
|
|
73
|
-
args: list[Union[str, Path]] = ["sb", "list", kernel_output]
|
|
74
|
-
if profile_type is not None:
|
|
75
|
-
args += ["--type", profile_type]
|
|
76
|
-
|
|
77
|
-
output.mkdir(exist_ok=True, parents=True)
|
|
78
|
-
profile_names = run("ipsw", *args).splitlines()
|
|
79
|
-
|
|
80
|
-
def decode_worker(profile_name: str) -> None:
|
|
81
|
-
# Not with_suffix(): it would cut a dotted name short, and com.apple.cloudd would share
|
|
82
|
-
# com.apple.sb with every other com.apple.* profile
|
|
83
|
-
profile_path = output / f"{profile_name}.sb"
|
|
84
|
-
decode_args: list[Union[str, Path]] = ["sb", "dec", kernel_output, profile_name]
|
|
85
|
-
if profile_type is not None:
|
|
86
|
-
decode_args += ["--type", profile_type]
|
|
87
|
-
try:
|
|
88
|
-
profile = run("ipsw", *decode_args)
|
|
89
|
-
except ProcessExecutionError as e:
|
|
90
|
-
logger.warning(f"failed to decode sandbox profile {profile_name}: {e}")
|
|
91
|
-
return
|
|
92
|
-
profile_path.write_text(profile)
|
|
93
|
-
|
|
94
|
-
with ThreadPoolExecutor(max_workers=os.cpu_count()) as executor:
|
|
95
|
-
futures = [
|
|
96
|
-
executor.submit(
|
|
97
|
-
decode_worker,
|
|
98
|
-
profile_name,
|
|
99
|
-
)
|
|
100
|
-
for profile_name in profile_names
|
|
101
|
-
]
|
|
102
|
-
for future in as_completed(futures):
|
|
103
|
-
future.result()
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
def _extract_kernelcache(build_identity: "BuildIdentity", output: Path) -> Path:
|
|
107
|
-
kernel_component = build_identity.get_component("KernelCache")
|
|
108
|
-
kernel_path = Path(kernel_component.path)
|
|
109
|
-
kernel_output = output / kernel_path.parts[-1]
|
|
110
|
-
output.mkdir(parents=True, exist_ok=True)
|
|
111
|
-
|
|
112
|
-
logger.info(f"extracting kernel into: {kernel_output}")
|
|
113
|
-
kernel_output.write_bytes(_im4p_payload(kernel_component.data))
|
|
114
|
-
try:
|
|
115
|
-
# In case the kernel is a FAT image, extract the arm64 macho
|
|
116
|
-
run("ipsw", "macho", "lipo", "-a", "arm64", kernel_output)
|
|
117
|
-
next(iter(kernel_output.parent.glob("*.arm64"))).rename(kernel_output)
|
|
118
|
-
except ProcessExecutionError:
|
|
119
|
-
pass
|
|
120
|
-
|
|
121
|
-
return kernel_output
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
def _im4p_payload(data: bytes) -> bytes:
|
|
125
|
-
"""Return the decompressed payload of an IM4P."""
|
|
126
|
-
payload = IM4P(data).payload
|
|
127
|
-
if payload is None:
|
|
128
|
-
raise ValueError("The IM4P carries no payload.")
|
|
129
|
-
payload.decompress()
|
|
130
|
-
return payload.output().data
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
class BuildIdentity(UserDict[str, Any]):
|
|
134
|
-
"""Dictionary-backed wrapper for a single build identity."""
|
|
135
|
-
|
|
136
|
-
def __init__(self, build_manifest: "BuildManifest", data: dict[str, Any]):
|
|
137
|
-
"""Wrap a single BuildIdentity entry from the manifest."""
|
|
138
|
-
super().__init__(data)
|
|
139
|
-
self.build_manifest = build_manifest
|
|
140
|
-
|
|
141
|
-
@cached_property
|
|
142
|
-
def device_class(self) -> str:
|
|
143
|
-
"""Return the normalized device class for this build identity."""
|
|
144
|
-
return self["Info"]["DeviceClass"].lower()
|
|
145
|
-
|
|
146
|
-
@cached_property
|
|
147
|
-
def restore_behavior(self) -> Optional[str]:
|
|
148
|
-
"""Return the restore behavior declared by the build identity."""
|
|
149
|
-
return self["Info"].get("RestoreBehavior")
|
|
150
|
-
|
|
151
|
-
@cached_property
|
|
152
|
-
def variant(self) -> Optional[str]:
|
|
153
|
-
"""Return the variant string for this build identity."""
|
|
154
|
-
return self["Info"].get("Variant")
|
|
155
|
-
|
|
156
|
-
@cached_property
|
|
157
|
-
def macos_variant(self) -> Optional[str]:
|
|
158
|
-
"""Return the macOS restore variant, if present."""
|
|
159
|
-
return self["Info"].get("MacOSVariant")
|
|
160
|
-
|
|
161
|
-
@cached_property
|
|
162
|
-
def manifest(self) -> dict[str, Any]:
|
|
163
|
-
"""Return the component manifest dictionary."""
|
|
164
|
-
return self["Manifest"]
|
|
165
|
-
|
|
166
|
-
@cached_property
|
|
167
|
-
def minimum_system_partition(self) -> Optional[int]:
|
|
168
|
-
"""Return the minimum system partition requirement, if present."""
|
|
169
|
-
return self["Info"].get("MinimumSystemPartition")
|
|
170
|
-
|
|
171
|
-
def get_component_path(self, component: str) -> str:
|
|
172
|
-
"""Return the archive path for a named component."""
|
|
173
|
-
return self.manifest[component]["Info"]["Path"]
|
|
174
|
-
|
|
175
|
-
def has_component(self, name: str) -> bool:
|
|
176
|
-
"""Return whether the build identity contains a named component."""
|
|
177
|
-
return name in self.manifest
|
|
178
|
-
|
|
179
|
-
def get_component(
|
|
180
|
-
self,
|
|
181
|
-
name: str,
|
|
182
|
-
tss: Optional[SupportsPathByEntry] = None,
|
|
183
|
-
data: Optional[bytes] = None,
|
|
184
|
-
path: Optional[str] = None,
|
|
185
|
-
) -> Component:
|
|
186
|
-
"""Return a component wrapper for a named manifest entry."""
|
|
187
|
-
return Component(self, name, tss=tss, data=data, path=path)
|
|
188
|
-
|
|
189
|
-
def extract_dsc(self, output: Path, pem_db: Optional[str] = None, split: bool = True) -> None:
|
|
190
|
-
"""Extract the system cryptex DSC payloads into ``output``."""
|
|
191
|
-
build_identity = self.build_manifest.build_identities[0]
|
|
192
|
-
if not build_identity.has_component("Cryptex1,SystemOS"):
|
|
193
|
-
return
|
|
194
|
-
|
|
195
|
-
device_support_symbols_path = output / "private/preboot/Cryptexes/OS/System"
|
|
196
|
-
device_support_symbols_path.mkdir(parents=True, exist_ok=True)
|
|
197
|
-
|
|
198
|
-
with TemporaryDirectory() as temp_dir:
|
|
199
|
-
system_os = Path(temp_dir) / "system_os.dmg"
|
|
200
|
-
system_os_component_path = build_identity.get_component_path("Cryptex1,SystemOS")
|
|
201
|
-
extract_as(self.build_manifest.ipsw.archive, system_os_component_path, system_os)
|
|
202
|
-
_extract_dmg(system_os, device_support_symbols_path, sub_path=Path("System"), pem_db=pem_db)
|
|
203
|
-
if split:
|
|
204
|
-
split_dsc(output)
|
|
205
|
-
|
|
206
|
-
def get_kernelcache_payload(self, arch: Optional[str] = None) -> bytes:
|
|
207
|
-
"""Return the decompressed kernelcache payload, optionally sliced by arch."""
|
|
208
|
-
payload = _im4p_payload(self.build_manifest.build_identities[0].get_component("KernelCache").data)
|
|
209
|
-
if arch is None:
|
|
210
|
-
return payload
|
|
211
|
-
|
|
212
|
-
with TemporaryDirectory() as temp_dir:
|
|
213
|
-
kernel_output = Path(temp_dir) / "kernel"
|
|
214
|
-
kernel_output.write_bytes(payload)
|
|
215
|
-
run("ipsw", "macho", "lipo", "-a", arch, kernel_output)
|
|
216
|
-
return Path(next(kernel_output.parent.glob(f"*.{arch}"))).read_bytes()
|
|
217
|
-
|
|
218
|
-
def extract_sandbox_profiles(self, output: Path) -> None:
|
|
219
|
-
"""Decode normal and protobox sandbox profiles into ``output``."""
|
|
220
|
-
output.mkdir(parents=True, exist_ok=True)
|
|
221
|
-
with TemporaryDirectory() as temp_dir:
|
|
222
|
-
kernel_output = _extract_kernelcache(self, Path(temp_dir))
|
|
223
|
-
_decode_sandbox_profiles(kernel_output, output)
|
|
224
|
-
_decode_sandbox_profiles(kernel_output, output / "protobox", profile_type="protobox")
|
|
225
|
-
|
|
226
|
-
def extract(self, output: Path, pem_db: Optional[str] = None) -> None:
|
|
227
|
-
"""Extract the build identity contents into a filesystem layout."""
|
|
228
|
-
logger.info(f"extracting into: {output}")
|
|
229
|
-
|
|
230
|
-
build_identity = self.build_manifest.build_identities[0]
|
|
231
|
-
|
|
232
|
-
logger.info(f"extracting OS into: {output}")
|
|
233
|
-
with TemporaryDirectory() as temp_dir:
|
|
234
|
-
os_dmg = Path(temp_dir) / "os.dmg"
|
|
235
|
-
os_component_path = build_identity.get_component_path("OS")
|
|
236
|
-
extract_as(self.build_manifest.ipsw.archive, os_component_path, os_dmg)
|
|
237
|
-
_extract_dmg(os_dmg, output, pem_db=pem_db)
|
|
238
|
-
|
|
239
|
-
kernel_output = _extract_kernelcache(self, output / "System/Library/Caches/com.apple.kernelcaches")
|
|
240
|
-
sandbox_profiles = output / "sandbox/profiles"
|
|
241
|
-
|
|
242
|
-
try:
|
|
243
|
-
_decode_sandbox_profiles(kernel_output, sandbox_profiles)
|
|
244
|
-
except ProcessExecutionError as e:
|
|
245
|
-
logger.error("Failed to extract sandbox profiles: %s", e)
|
|
246
|
-
try:
|
|
247
|
-
_decode_sandbox_profiles(kernel_output, sandbox_profiles / "protobox", profile_type="protobox")
|
|
248
|
-
except (ProcessExecutionError, FileNotFoundError, OSError) as e:
|
|
249
|
-
logger.error("Failed to extract sandbox profiles: %s", e)
|
|
250
|
-
|
|
251
|
-
for cryptex in ("App", "OS"):
|
|
252
|
-
name = {
|
|
253
|
-
"App": "Cryptex1,AppOS",
|
|
254
|
-
"OS": "Cryptex1,SystemOS",
|
|
255
|
-
}[cryptex]
|
|
256
|
-
|
|
257
|
-
if not build_identity.has_component(name):
|
|
258
|
-
continue
|
|
259
|
-
|
|
260
|
-
cryptex_path = output / "private/preboot/Cryptexes" / cryptex
|
|
261
|
-
cryptex_path.mkdir(parents=True, exist_ok=True)
|
|
262
|
-
|
|
263
|
-
logger.info(f"extracting {name} into: {cryptex_path}")
|
|
264
|
-
with TemporaryDirectory() as temp_dir:
|
|
265
|
-
temp_component = (Path(temp_dir) / name).with_suffix(".dmg")
|
|
266
|
-
component_path = build_identity.get_component_path(name)
|
|
267
|
-
extract_as(self.build_manifest.ipsw.archive, component_path, temp_component)
|
|
268
|
-
_extract_dmg(temp_component, cryptex_path, pem_db=pem_db)
|
|
269
|
-
|
|
270
|
-
split_dsc(output)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|