ipsw-parser 1.5.0__tar.gz → 1.7.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.
Files changed (37) hide show
  1. {ipsw_parser-1.5.0 → ipsw_parser-1.7.0}/.github/workflows/python-app.yml +4 -0
  2. {ipsw_parser-1.5.0 → ipsw_parser-1.7.0}/PKG-INFO +4 -3
  3. {ipsw_parser-1.5.0 → ipsw_parser-1.7.0}/README.md +2 -0
  4. ipsw_parser-1.7.0/ipsw_parser/__main__.py +97 -0
  5. ipsw_parser-1.7.0/ipsw_parser/_version.py +24 -0
  6. ipsw_parser-1.7.0/ipsw_parser/archive.py +117 -0
  7. {ipsw_parser-1.5.0 → ipsw_parser-1.7.0}/ipsw_parser/build_identity.py +73 -20
  8. {ipsw_parser-1.5.0 → ipsw_parser-1.7.0}/ipsw_parser/build_manifest.py +10 -2
  9. {ipsw_parser-1.5.0 → ipsw_parser-1.7.0}/ipsw_parser/component.py +11 -2
  10. {ipsw_parser-1.5.0 → ipsw_parser-1.7.0}/ipsw_parser/dsc.py +3 -23
  11. ipsw_parser-1.7.0/ipsw_parser/exceptions.py +10 -0
  12. {ipsw_parser-1.5.0 → ipsw_parser-1.7.0}/ipsw_parser/firmware.py +6 -0
  13. {ipsw_parser-1.5.0 → ipsw_parser-1.7.0}/ipsw_parser/ipsw.py +31 -4
  14. {ipsw_parser-1.5.0 → ipsw_parser-1.7.0}/ipsw_parser.egg-info/PKG-INFO +4 -3
  15. {ipsw_parser-1.5.0 → ipsw_parser-1.7.0}/ipsw_parser.egg-info/SOURCES.txt +3 -1
  16. {ipsw_parser-1.5.0 → ipsw_parser-1.7.0}/ipsw_parser.egg-info/requires.txt +1 -2
  17. {ipsw_parser-1.5.0 → ipsw_parser-1.7.0}/requirements.txt +2 -3
  18. ipsw_parser-1.7.0/tests/test_archive_backends.py +70 -0
  19. ipsw_parser-1.5.0/ipsw_parser/__main__.py +0 -99
  20. ipsw_parser-1.5.0/ipsw_parser/_version.py +0 -34
  21. ipsw_parser-1.5.0/ipsw_parser/exceptions.py +0 -6
  22. {ipsw_parser-1.5.0 → ipsw_parser-1.7.0}/.gitattributes +0 -0
  23. {ipsw_parser-1.5.0 → ipsw_parser-1.7.0}/.github/ISSUE_TEMPLATE/bug_report.md +0 -0
  24. {ipsw_parser-1.5.0 → ipsw_parser-1.7.0}/.github/ISSUE_TEMPLATE/feature_request.md +0 -0
  25. {ipsw_parser-1.5.0 → ipsw_parser-1.7.0}/.github/workflows/codeql.yml +0 -0
  26. {ipsw_parser-1.5.0 → ipsw_parser-1.7.0}/.github/workflows/python-publish.yml +0 -0
  27. {ipsw_parser-1.5.0 → ipsw_parser-1.7.0}/.gitignore +0 -0
  28. {ipsw_parser-1.5.0 → ipsw_parser-1.7.0}/.pre-commit-config.yaml +0 -0
  29. {ipsw_parser-1.5.0 → ipsw_parser-1.7.0}/CODE_OF_CONDUCT.md +0 -0
  30. {ipsw_parser-1.5.0 → ipsw_parser-1.7.0}/LICENSE +0 -0
  31. {ipsw_parser-1.5.0 → ipsw_parser-1.7.0}/ipsw_parser/__init__.py +0 -0
  32. {ipsw_parser-1.5.0 → ipsw_parser-1.7.0}/ipsw_parser.egg-info/dependency_links.txt +0 -0
  33. {ipsw_parser-1.5.0 → ipsw_parser-1.7.0}/ipsw_parser.egg-info/entry_points.txt +0 -0
  34. {ipsw_parser-1.5.0 → ipsw_parser-1.7.0}/ipsw_parser.egg-info/top_level.txt +0 -0
  35. {ipsw_parser-1.5.0 → ipsw_parser-1.7.0}/pyproject.toml +0 -0
  36. {ipsw_parser-1.5.0 → ipsw_parser-1.7.0}/pytest.ini +0 -0
  37. {ipsw_parser-1.5.0 → ipsw_parser-1.7.0}/setup.cfg +0 -0
@@ -35,3 +35,7 @@ jobs:
35
35
  - name: Test show usage
36
36
  run: |
37
37
  python -m ipsw_parser --help
38
+ - name: Run tests
39
+ run: |
40
+ python -m pip install pytest
41
+ python -m pytest
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ipsw-parser
3
- Version: 1.5.0
3
+ Version: 1.7.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>
@@ -696,13 +696,12 @@ Requires-Python: >=3.9
696
696
  Description-Content-Type: text/markdown
697
697
  License-File: LICENSE
698
698
  Requires-Dist: construct>=2.9.29
699
- Requires-Dist: click
700
699
  Requires-Dist: coloredlogs
701
- Requires-Dist: cached_property
702
700
  Requires-Dist: plumbum
703
701
  Requires-Dist: pyimg4>=0.8.8
704
702
  Requires-Dist: requests
705
703
  Requires-Dist: remotezip2
704
+ Requires-Dist: typer
706
705
  Provides-Extra: test
707
706
  Requires-Dist: pytest; extra == "test"
708
707
  Dynamic: license-file
@@ -739,5 +738,7 @@ Options:
739
738
  Commands:
740
739
  device-support Create DeviceSupport directory
741
740
  extract Extract .ipsw into filesystem layout
741
+ extract-sandbox-profiles
742
+ Extract decoded sandbox profiles from the kernelcache
742
743
  info Parse given .ipsw basic info
743
744
  ```
@@ -30,5 +30,7 @@ Options:
30
30
  Commands:
31
31
  device-support Create DeviceSupport directory
32
32
  extract Extract .ipsw into filesystem layout
33
+ extract-sandbox-profiles
34
+ Extract decoded sandbox profiles from the kernelcache
33
35
  info Parse given .ipsw basic info
34
36
  ```
@@ -0,0 +1,97 @@
1
+ #!/usr/bin/env python3
2
+ import logging
3
+ from pathlib import Path
4
+ from typing import Annotated, Optional
5
+
6
+ import coloredlogs
7
+ import typer
8
+
9
+ from ipsw_parser.ipsw import IPSW
10
+
11
+ coloredlogs.install(level=logging.DEBUG)
12
+
13
+ logging.getLogger("asyncio").disabled = True
14
+ logging.getLogger("parso.cache").disabled = True
15
+ logging.getLogger("parso.cache.pickle").disabled = True
16
+ logging.getLogger("parso.python.diff").disabled = True
17
+ logging.getLogger("humanfriendly.prompts").disabled = True
18
+ logging.getLogger("blib2to3.pgen2.driver").disabled = True
19
+ logging.getLogger("urllib3.connectionpool").disabled = True
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+ PEM_DB_ENV_VAR = "IPSW_PARSER_PEM_DB"
24
+
25
+ cli = typer.Typer(
26
+ help="CLI utility for extracting info from IPSW files",
27
+ )
28
+
29
+ IpswArgument = Annotated[str, typer.Argument(help="Path to an IPSW zip, extracted IPSW directory, or HTTP URL.")]
30
+ OutputArgument = Annotated[Path, typer.Argument(help="Output path.", exists=False)]
31
+ PemDbOption = Annotated[
32
+ Optional[str],
33
+ typer.Option(
34
+ "--pem-db",
35
+ envvar=PEM_DB_ENV_VAR,
36
+ help="Path DB file url (can be either a filesystem path or an HTTP URL). "
37
+ "Alternatively, use the IPSW_PARSER_PEM_DB envvar.",
38
+ ),
39
+ ]
40
+ ArchOption = Annotated[Optional[str], typer.Option(help="Arch name to extract using lipo")]
41
+
42
+
43
+ @cli.command("info")
44
+ def info(ipsw: IpswArgument) -> None:
45
+ """Print basic metadata for an IPSW."""
46
+ parsed_ipsw = IPSW.create_from_path(ipsw)
47
+ print(f"SupportedProductTypes: {parsed_ipsw.build_manifest.supported_product_types}")
48
+ print(f"ProductVersion: {parsed_ipsw.build_manifest.product_version}")
49
+ print(f"ProductBuildVersion: {parsed_ipsw.build_manifest.product_build_version}")
50
+
51
+ development_files = parsed_ipsw.get_development_files()
52
+ if development_files:
53
+ print("DevelopmentFiles:")
54
+ for file in development_files:
55
+ print(f"- {file}")
56
+
57
+
58
+ @cli.command("extract")
59
+ def extract(ipsw: IpswArgument, output: OutputArgument, pem_db: PemDbOption = None) -> None:
60
+ """Extract an IPSW into the project filesystem layout."""
61
+ parsed_ipsw = IPSW.create_from_path(ipsw)
62
+
63
+ if not output.exists():
64
+ output.mkdir(parents=True, exist_ok=True)
65
+
66
+ parsed_ipsw.build_manifest.build_identities[0].extract(output, pem_db=pem_db)
67
+ parsed_ipsw.archive.extractall(
68
+ path=output, members=[f for f in parsed_ipsw.archive.filelist if f.filename.startswith("Firmware")]
69
+ )
70
+
71
+
72
+ @cli.command("extract-kernel")
73
+ def extract_kernel(ipsw: IpswArgument, output: OutputArgument, arch: ArchOption = None) -> None:
74
+ """Extract the kernelcache payload into a single output file."""
75
+ parsed_ipsw = IPSW.create_from_path(ipsw)
76
+ output.write_bytes(parsed_ipsw.build_manifest.build_identities[0].get_kernelcache_payload(arch=arch))
77
+
78
+
79
+ @cli.command("extract-sandbox-profiles")
80
+ def extract_sandbox_profiles(ipsw: IpswArgument, output: OutputArgument) -> None:
81
+ """Extract decoded sandbox profiles into the output directory."""
82
+ parsed_ipsw = IPSW.create_from_path(ipsw)
83
+
84
+ if not output.exists():
85
+ output.mkdir(parents=True, exist_ok=True)
86
+
87
+ parsed_ipsw.build_manifest.build_identities[0].extract_sandbox_profiles(output)
88
+
89
+
90
+ @cli.command("device-support")
91
+ def device_support(ipsw: IpswArgument, pem_db: PemDbOption = None) -> None:
92
+ """Create an Xcode DeviceSupport directory for an IPSW."""
93
+ IPSW.create_from_path(ipsw).create_device_support(pem_db=pem_db)
94
+
95
+
96
+ if __name__ == "__main__":
97
+ cli()
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '1.7.0'
22
+ __version_tuple__ = version_tuple = (1, 7, 0)
23
+
24
+ __commit_id__ = commit_id = 'g1f720c17d'
@@ -0,0 +1,117 @@
1
+ import shutil
2
+ import stat
3
+ from collections.abc import Iterable
4
+ from dataclasses import dataclass
5
+ from functools import cached_property
6
+ from pathlib import Path
7
+ from typing import BinaryIO, Protocol, Union
8
+ from zipfile import ZipFile, ZipInfo
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class ArchiveMember:
13
+ """Metadata describing a single archive entry."""
14
+
15
+ filename: str
16
+ file_size: int
17
+ external_attr: int
18
+
19
+
20
+ class Archive(Protocol):
21
+ """Protocol implemented by supported IPSW archive backends."""
22
+
23
+ @property
24
+ def filelist(self) -> list[ArchiveMember]:
25
+ """Return archive members with metadata."""
26
+ ...
27
+
28
+ def namelist(self) -> list[str]:
29
+ """Return archive member names."""
30
+ ...
31
+
32
+ def open(self, path: str) -> BinaryIO:
33
+ """Open an archive member for binary reading."""
34
+ ...
35
+
36
+ def read(self, path: str) -> bytes:
37
+ """Read an archive member into memory."""
38
+ ...
39
+
40
+ def extractall(self, path: Path, members: Iterable[Union[ArchiveMember, ZipInfo, str]]) -> None:
41
+ """Extract the selected archive members into ``path``."""
42
+ ...
43
+
44
+
45
+ class ZipArchive:
46
+ """Archive adapter backed by ``zipfile.ZipFile``."""
47
+
48
+ def __init__(self, archive: ZipFile):
49
+ """Wrap an existing ZIP archive object."""
50
+ self._archive = archive
51
+
52
+ @property
53
+ def filelist(self) -> list[ZipInfo]:
54
+ """Return ZIP member metadata."""
55
+ return self._archive.filelist
56
+
57
+ def namelist(self) -> list[str]:
58
+ """Return ZIP member names."""
59
+ return self._archive.namelist()
60
+
61
+ def open(self, path: str) -> BinaryIO:
62
+ """Open a ZIP member for binary reading."""
63
+ return self._archive.open(path)
64
+
65
+ def read(self, path: str) -> bytes:
66
+ """Read a ZIP member into memory."""
67
+ return self._archive.read(path)
68
+
69
+ def extractall(self, path: Path, members: Iterable[Union[ArchiveMember, ZipInfo, str]]) -> None:
70
+ """Extract the selected ZIP members into ``path``."""
71
+ self._archive.extractall(path=path, members=members)
72
+
73
+
74
+ class DirectoryArchive:
75
+ """Archive adapter that exposes a directory tree like an IPSW archive."""
76
+
77
+ def __init__(self, root: Path):
78
+ """Wrap an extracted IPSW directory."""
79
+ self._root = root
80
+
81
+ @cached_property
82
+ def filelist(self) -> list[ArchiveMember]:
83
+ """Return filesystem entries as archive-style metadata."""
84
+ result = []
85
+ for file_path in sorted(path for path in self._root.rglob("*") if path.is_file()):
86
+ file_stat = file_path.stat()
87
+ relative_path = file_path.relative_to(self._root).as_posix()
88
+ mode = stat.S_IFREG | stat.S_IMODE(file_stat.st_mode)
89
+ result.append(
90
+ ArchiveMember(
91
+ filename=relative_path,
92
+ file_size=file_stat.st_size,
93
+ external_attr=mode << 16,
94
+ )
95
+ )
96
+ return result
97
+
98
+ def namelist(self) -> list[str]:
99
+ """Return relative file paths under the archive root."""
100
+ return [member.filename for member in self.filelist]
101
+
102
+ def open(self, path: str) -> BinaryIO:
103
+ """Open a file relative to the archive root."""
104
+ return (self._root / path).open("rb")
105
+
106
+ def read(self, path: str) -> bytes:
107
+ """Read a file relative to the archive root."""
108
+ return (self._root / path).read_bytes()
109
+
110
+ def extractall(self, path: Path, members: Iterable[Union[ArchiveMember, ZipInfo, str]]) -> None:
111
+ """Copy the selected members into ``path``."""
112
+ for member in members:
113
+ filename = member if isinstance(member, str) else member.filename
114
+ source = self._root / filename
115
+ destination = path / filename
116
+ destination.parent.mkdir(parents=True, exist_ok=True)
117
+ shutil.copyfile(source, destination)
@@ -2,16 +2,16 @@ import logging
2
2
  import os
3
3
  import shutil
4
4
  from collections import UserDict
5
+ from functools import cached_property
5
6
  from pathlib import Path
6
7
  from tempfile import TemporaryDirectory
7
8
  from typing import Optional
8
- from zipfile import ZipFile
9
9
 
10
10
  import requests
11
- from cached_property import cached_property
12
11
  from plumbum import ProcessExecutionError, local
13
12
  from pyimg4 import IM4P
14
13
 
14
+ from ipsw_parser.archive import Archive
15
15
  from ipsw_parser.component import Component
16
16
  from ipsw_parser.dsc import split_dsc
17
17
 
@@ -20,10 +20,10 @@ logger = logging.getLogger(__name__)
20
20
  AEA_MAGIC = b"AEA1"
21
21
 
22
22
 
23
- def extract_as(zipf: ZipFile, member_name, output_path, chunk_size=64 * 1024):
24
- """Extract a single member from a ZIP archive to a custom output path"""
23
+ def extract_as(archive: Archive, member_name, output_path, chunk_size=64 * 1024):
24
+ """Extract one archive member into a caller-provided path."""
25
25
  os.makedirs(os.path.dirname(output_path), exist_ok=True)
26
- with zipf.open(member_name) as source, open(output_path, "wb") as target:
26
+ with archive.open(member_name) as source, open(output_path, "wb") as target:
27
27
  shutil.copyfileobj(source, target, length=chunk_size)
28
28
 
29
29
 
@@ -65,45 +65,99 @@ def _extract_dmg(dmg: Path, output: Path, sub_path: Optional[Path] = None, pem_d
65
65
  hdiutil("detach", "-force", mnt)
66
66
 
67
67
 
68
+ def _decode_sandbox_profiles(kernel_output: Path, output: Path, profile_type: Optional[str] = None) -> None:
69
+ ipsw = local["ipsw"]
70
+ args = ["sb", "list", kernel_output]
71
+ if profile_type is not None:
72
+ args += ["--type", profile_type]
73
+
74
+ output.mkdir(exist_ok=True, parents=True)
75
+
76
+ for profile_name in ipsw(*args).splitlines():
77
+ profile_path = (output / profile_name).with_suffix(".sb")
78
+ decode_args = ["sb", "dec", kernel_output, profile_name]
79
+ if profile_type is not None:
80
+ decode_args += ["--type", profile_type]
81
+ try:
82
+ profile = ipsw(*decode_args)
83
+ except ProcessExecutionError as e:
84
+ logger.warning(f"failed to decode sandbox profile {profile_name}: {e}")
85
+ continue
86
+ profile_path.write_text(profile)
87
+
88
+
89
+ def _extract_kernelcache(build_identity: "BuildIdentity", output: Path) -> Path:
90
+ kernel_component = build_identity.get_component("KernelCache")
91
+ kernel_path = Path(kernel_component.path)
92
+ kernel_output = output / kernel_path.parts[-1]
93
+ output.mkdir(parents=True, exist_ok=True)
94
+
95
+ logger.info(f"extracting kernel into: {kernel_output}")
96
+ im4p = IM4P(kernel_component.data)
97
+ im4p.payload.decompress()
98
+ kernel_output.write_bytes(im4p.payload.output().data)
99
+ try:
100
+ # In case the kernel is a FAT image, extract the arm64 macho
101
+ local["ipsw"]("macho", "lipo", "-a", "arm64", kernel_output)
102
+ next(iter(kernel_output.parent.glob("*.arm64"))).rename(kernel_output)
103
+ except ProcessExecutionError:
104
+ pass
105
+
106
+ return kernel_output
107
+
108
+
68
109
  class BuildIdentity(UserDict):
110
+ """Dictionary-backed wrapper for a single build identity."""
111
+
69
112
  def __init__(self, build_manifest, data):
113
+ """Wrap a single BuildIdentity entry from the manifest."""
70
114
  super().__init__(data)
71
115
  self.build_manifest = build_manifest
72
116
 
73
117
  @cached_property
74
118
  def device_class(self) -> str:
119
+ """Return the normalized device class for this build identity."""
75
120
  return self["Info"]["DeviceClass"].lower()
76
121
 
77
122
  @cached_property
78
123
  def restore_behavior(self) -> str:
124
+ """Return the restore behavior declared by the build identity."""
79
125
  return self["Info"].get("RestoreBehavior")
80
126
 
81
127
  @cached_property
82
128
  def variant(self):
129
+ """Return the variant string for this build identity."""
83
130
  return self["Info"].get("Variant")
84
131
 
85
132
  @cached_property
86
133
  def macos_variant(self) -> str:
134
+ """Return the macOS restore variant, if present."""
87
135
  return self["Info"].get("MacOSVariant")
88
136
 
89
137
  @cached_property
90
138
  def manifest(self) -> dict:
139
+ """Return the component manifest dictionary."""
91
140
  return self["Manifest"]
92
141
 
93
142
  @cached_property
94
143
  def minimum_system_partition(self):
144
+ """Return the minimum system partition requirement, if present."""
95
145
  return self["Info"].get("MinimumSystemPartition")
96
146
 
97
147
  def get_component_path(self, component: str) -> str:
148
+ """Return the archive path for a named component."""
98
149
  return self.manifest[component]["Info"]["Path"]
99
150
 
100
151
  def has_component(self, name: str) -> bool:
152
+ """Return whether the build identity contains a named component."""
101
153
  return name in self.manifest
102
154
 
103
155
  def get_component(self, name: str, **args) -> Component:
156
+ """Return a component wrapper for a named manifest entry."""
104
157
  return Component(self, name, **args)
105
158
 
106
159
  def extract_dsc(self, output: Path, pem_db: Optional[str] = None, split: bool = True) -> None:
160
+ """Extract the system cryptex DSC payloads into ``output``."""
107
161
  build_identity = self.build_manifest.build_identities[0]
108
162
  if not build_identity.has_component("Cryptex1,SystemOS"):
109
163
  return
@@ -120,6 +174,7 @@ class BuildIdentity(UserDict):
120
174
  split_dsc(output)
121
175
 
122
176
  def get_kernelcache_payload(self, arch: Optional[str] = None) -> bytes:
177
+ """Return the decompressed kernelcache payload, optionally sliced by arch."""
123
178
  im4p = IM4P(self.build_manifest.build_identities[0].get_component("KernelCache").data)
124
179
  im4p.payload.decompress()
125
180
  payload = im4p.payload.output().data
@@ -131,7 +186,16 @@ class BuildIdentity(UserDict):
131
186
  local["ipsw"]("macho", "lipo", "-a", arch, kernel_output)
132
187
  return Path(next(kernel_output.parent.glob(f"*.{arch}"))).read_bytes()
133
188
 
189
+ def extract_sandbox_profiles(self, output: Path) -> None:
190
+ """Decode normal and protobox sandbox profiles into ``output``."""
191
+ output.mkdir(parents=True, exist_ok=True)
192
+ with TemporaryDirectory() as temp_dir:
193
+ kernel_output = _extract_kernelcache(self, Path(temp_dir))
194
+ _decode_sandbox_profiles(kernel_output, output)
195
+ _decode_sandbox_profiles(kernel_output, output / "protobox", profile_type="protobox")
196
+
134
197
  def extract(self, output: Path, pem_db: Optional[str] = None) -> None:
198
+ """Extract the build identity contents into a filesystem layout."""
135
199
  logger.info(f"extracting into: {output}")
136
200
 
137
201
  build_identity = self.build_manifest.build_identities[0]
@@ -143,21 +207,10 @@ class BuildIdentity(UserDict):
143
207
  extract_as(self.build_manifest.ipsw.archive, os_component_path, os_dmg)
144
208
  _extract_dmg(os_dmg, output, pem_db=pem_db)
145
209
 
146
- kernel_component = build_identity.get_component("KernelCache")
147
- kernel_path = Path(kernel_component.path)
148
- kernel_output = output / "System/Library/Caches/com.apple.kernelcaches" / kernel_path.parts[-1]
149
- kernel_output.parent.mkdir(parents=True, exist_ok=True)
150
-
151
- logger.info(f"extracting kernel into: {kernel_output}")
152
- im4p = IM4P(kernel_component.data)
153
- im4p.payload.decompress()
154
- kernel_output.write_bytes(im4p.payload.output().data)
155
- try:
156
- # In case the kernel is a FAT image, extract the arm64 macho
157
- local["ipsw"]("macho", "lipo", "-a", "arm64", kernel_output)
158
- next(iter(kernel_output.parent.glob("*.arm64"))).rename(kernel_output)
159
- except ProcessExecutionError:
160
- pass
210
+ kernel_output = _extract_kernelcache(self, output / "System/Library/Caches/com.apple.kernelcaches")
211
+ sandbox_profiles = output / "sandbox/profiles"
212
+ _decode_sandbox_profiles(kernel_output, sandbox_profiles)
213
+ _decode_sandbox_profiles(kernel_output, sandbox_profiles / "protobox", profile_type="protobox")
161
214
 
162
215
  for cryptex in ("App", "OS"):
163
216
  name = {
@@ -1,20 +1,23 @@
1
1
  import plistlib
2
+ from functools import cached_property
2
3
  from typing import Optional
3
4
 
4
- from cached_property import cached_property
5
-
6
5
  from ipsw_parser.build_identity import BuildIdentity
7
6
  from ipsw_parser.exceptions import NoSuchBuildIdentityError
8
7
 
9
8
 
10
9
  class BuildManifest:
10
+ """Parsed ``BuildManifest.plist`` wrapper with lookup helpers."""
11
+
11
12
  def __init__(self, ipsw, manifest: bytes):
13
+ """Parse a BuildManifest plist for the given IPSW."""
12
14
  self.ipsw = ipsw
13
15
  self._manifest = plistlib.loads(manifest)
14
16
  self._parse_build_identities()
15
17
 
16
18
  @cached_property
17
19
  def build_major(self) -> int:
20
+ """Return the numeric major portion of the build version."""
18
21
  build_major = ""
19
22
  for i in self._manifest["ProductBuildVersion"]:
20
23
  if i.isdigit():
@@ -26,10 +29,12 @@ class BuildManifest:
26
29
 
27
30
  @cached_property
28
31
  def supported_product_types(self) -> list[str]:
32
+ """Return supported product identifiers from the manifest."""
29
33
  return self._manifest["SupportedProductTypes"]
30
34
 
31
35
  @cached_property
32
36
  def supported_product_types_family(self) -> str:
37
+ """Return the broad device family inferred from the first product type."""
33
38
  product = self.supported_product_types[0]
34
39
  if product.startswith("iBridge"):
35
40
  return "iBridge"
@@ -42,15 +47,18 @@ class BuildManifest:
42
47
 
43
48
  @cached_property
44
49
  def product_version(self) -> str:
50
+ """Return the product version from the manifest."""
45
51
  return self._manifest["ProductVersion"]
46
52
 
47
53
  @cached_property
48
54
  def product_build_version(self) -> str:
55
+ """Return the product build version from the manifest."""
49
56
  return self._manifest["ProductBuildVersion"]
50
57
 
51
58
  def get_build_identity(
52
59
  self, device_class: str, restore_behavior: Optional[str] = None, variant: Optional[str] = None
53
60
  ) -> BuildIdentity:
61
+ """Return the first build identity matching the requested filters."""
54
62
  for build_identity in self.build_identities:
55
63
  if variant is not None and variant not in build_identity.variant:
56
64
  continue
@@ -1,15 +1,17 @@
1
1
  import logging
2
2
  import os.path
3
+ from functools import cached_property
3
4
  from typing import Optional
4
5
 
5
- from cached_property import cached_property
6
-
7
6
  from ipsw_parser.exceptions import IpswException
8
7
 
9
8
 
10
9
  class TSSResponse(dict):
10
+ """Dictionary wrapper for TSS response payloads."""
11
+
11
12
  @property
12
13
  def ap_img4_ticket(self):
14
+ """Return the AP IMG4 ticket from the TSS response."""
13
15
  ticket = self.get("ApImg4Ticket")
14
16
 
15
17
  if ticket is None:
@@ -19,9 +21,11 @@ class TSSResponse(dict):
19
21
 
20
22
  @property
21
23
  def bb_ticket(self):
24
+ """Return the baseband ticket from the TSS response, if present."""
22
25
  return self.get("BBTicket")
23
26
 
24
27
  def get_path_by_entry(self, component: str):
28
+ """Return the path for a component entry in the TSS response."""
25
29
  node = self.get(component)
26
30
  if node is not None:
27
31
  return node.get("Path")
@@ -30,6 +34,8 @@ class TSSResponse(dict):
30
34
 
31
35
 
32
36
  class Component:
37
+ """Resolved view of a build identity component."""
38
+
33
39
  def __init__(
34
40
  self,
35
41
  build_identity,
@@ -38,6 +44,7 @@ class Component:
38
44
  data: Optional[bytes] = None,
39
45
  path: Optional[str] = None,
40
46
  ):
47
+ """Create a component view for a build identity entry."""
41
48
  self.logger = logging.getLogger(__name__)
42
49
  self._tss = tss
43
50
  self.build_identity = build_identity
@@ -47,6 +54,7 @@ class Component:
47
54
 
48
55
  @cached_property
49
56
  def path(self) -> str:
57
+ """Resolve the component path from TSS data or the build manifest."""
50
58
  if self._path:
51
59
  return self._path
52
60
 
@@ -67,6 +75,7 @@ class Component:
67
75
 
68
76
  @cached_property
69
77
  def data(self) -> bytes:
78
+ """Return the component payload bytes."""
70
79
  if self._data is None:
71
80
  self.logger.debug(f"Extracting {os.path.basename(self.path)} ({self.path})")
72
81
  return self.build_identity.build_manifest.ipsw.read(self.path)
@@ -9,6 +9,7 @@ logger = logging.getLogger(__name__)
9
9
 
10
10
 
11
11
  def split_dsc(root: Path) -> None:
12
+ """Split dyld shared caches found under ``root`` using ``ipsw dyld split``."""
12
13
  ipsw = local["ipsw"]
13
14
  dsc_paths = [
14
15
  root / "System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64",
@@ -26,17 +27,7 @@ def split_dsc(root: Path) -> None:
26
27
 
27
28
 
28
29
  def get_device_support_path(product_type: str, product_version: str, product_build_version: str) -> Path:
29
- """
30
- Construct the device support directory path.
31
-
32
- Args:
33
- product_type: Product type (e.g., 'iPhone15,2')
34
- product_version: Product version (e.g., '16.0')
35
- product_build_version: Product build version (e.g., '20A362')
36
-
37
- Returns:
38
- Path to the device support directory
39
- """
30
+ """Return the Xcode DeviceSupport path for the given product metadata."""
40
31
  device_support_path = Path("~/Library/Developer/Xcode/iOS DeviceSupport").expanduser()
41
32
  device_support_path /= f"{product_type} {product_version} ({product_build_version})"
42
33
  return device_support_path
@@ -45,18 +36,7 @@ def get_device_support_path(product_type: str, product_version: str, product_bui
45
36
  def create_device_support_layout(
46
37
  product_type: str, product_version: str, product_build_version: str, root_path: Path
47
38
  ) -> Path:
48
- """
49
- Split DSC and create the "device support" directory layout.
50
-
51
- Args:
52
- product_type: Product type (e.g., 'iPhone15,2')
53
- product_version: Product version (e.g., '16.0')
54
- product_build_version: Product build version (e.g., '20A362')
55
- root_path: System root path containing the extracted DSC symbols
56
-
57
- Returns:
58
- Path to the created device support directory
59
- """
39
+ """Create the Xcode DeviceSupport layout for extracted symbol files."""
60
40
  device_support_path = get_device_support_path(product_type, product_version, product_build_version)
61
41
 
62
42
  # Split DSC files
@@ -0,0 +1,10 @@
1
+ class IpswException(Exception):
2
+ """Base exception for IPSW parser failures."""
3
+
4
+ pass
5
+
6
+
7
+ class NoSuchBuildIdentityError(IpswException):
8
+ """Raised when a matching build identity cannot be found."""
9
+
10
+ pass
@@ -1,5 +1,8 @@
1
1
  class Firmware:
2
+ """Helper for firmware manifests and component file mapping."""
3
+
2
4
  def __init__(self, firmware_path: str, ipsw):
5
+ """Index firmware manifest entries under a firmware directory."""
3
6
  self._ipsw = ipsw
4
7
  self._firmware_path = firmware_path
5
8
  self._manifest_data = self._ipsw.read(self.get_relative_path("manifest"))
@@ -10,13 +13,16 @@ class Firmware:
10
13
  self._firmware_files[component_name] = f"{firmware_path}/{filename}"
11
14
 
12
15
  def get_relative_path(self, path: str):
16
+ """Return a firmware-relative archive path."""
13
17
  return f"{self._firmware_path}/{path}"
14
18
 
15
19
  def get_files(self):
20
+ """Return the indexed firmware component mapping."""
16
21
  return self._firmware_files
17
22
 
18
23
  @staticmethod
19
24
  def get_component_name(filename):
25
+ """Map a firmware filename to its logical component name."""
20
26
  names = {
21
27
  "LLB": "LLB",
22
28
  "iBoot": "iBoot",
@@ -1,12 +1,14 @@
1
1
  import logging
2
- import zipfile
3
2
  from contextlib import contextmanager
3
+ from functools import cached_property
4
4
  from pathlib import Path
5
5
  from typing import Optional
6
+ from zipfile import ZipFile
6
7
 
7
- from cached_property import cached_property
8
8
  from construct import Const, Default, PaddedString, Struct
9
+ from remotezip2 import RemoteZip
9
10
 
11
+ from ipsw_parser.archive import Archive, ArchiveMember, DirectoryArchive, ZipArchive
10
12
  from ipsw_parser.build_manifest import BuildManifest
11
13
  from ipsw_parser.dsc import create_device_support_layout
12
14
  from ipsw_parser.firmware import Firmware
@@ -33,7 +35,22 @@ cpio_odc_header = Struct(
33
35
 
34
36
 
35
37
  class IPSW:
36
- def __init__(self, archive: zipfile.ZipFile):
38
+ """High-level interface for reading and extracting IPSW contents."""
39
+
40
+ @classmethod
41
+ def create_from_path(cls, value: str) -> "IPSW":
42
+ """Create an ``IPSW`` from a local path, extracted directory, or URL."""
43
+ if value.startswith("http://") or value.startswith("https://"):
44
+ return cls(ZipArchive(RemoteZip(value)))
45
+
46
+ path = Path(value).expanduser()
47
+ if path.is_dir():
48
+ return cls(DirectoryArchive(path))
49
+
50
+ return cls(ZipArchive(ZipFile(path)))
51
+
52
+ def __init__(self, archive: Archive):
53
+ """Create an IPSW wrapper around an archive backend."""
37
54
  self.archive = archive
38
55
  self._logger = logging.getLogger(__file__)
39
56
  self.build_manifest = BuildManifest(
@@ -45,18 +62,22 @@ class IPSW:
45
62
 
46
63
  @cached_property
47
64
  def restore_version(self) -> bytes:
65
+ """Return the raw ``RestoreVersion.plist`` payload."""
48
66
  return self.read("RestoreVersion.plist")
49
67
 
50
68
  @cached_property
51
69
  def system_version(self) -> bytes:
70
+ """Return the raw ``SystemVersion.plist`` payload."""
52
71
  return self.read("SystemVersion.plist")
53
72
 
54
73
  @cached_property
55
- def filelist(self) -> list[zipfile.ZipInfo]:
74
+ def filelist(self) -> list[ArchiveMember]:
75
+ """Return archive members for the IPSW."""
56
76
  return self.archive.filelist
57
77
 
58
78
  @contextmanager
59
79
  def open_path(self, path: str):
80
+ """Open an IPSW member and close it automatically on exit."""
60
81
  file = self.archive.open(path)
61
82
  try:
62
83
  yield file
@@ -65,6 +86,7 @@ class IPSW:
65
86
 
66
87
  @property
67
88
  def bootability(self) -> bytes:
89
+ """Build a cpio archive containing bootability bundle payloads."""
68
90
  result = b""
69
91
  prefix = "BootabilityBundle/Restore/Bootability/"
70
92
  inode = 1
@@ -113,16 +135,20 @@ class IPSW:
113
135
  return result
114
136
 
115
137
  def read(self, path: str) -> bytes:
138
+ """Read an IPSW member into memory."""
116
139
  return self.archive.read(path)
117
140
 
118
141
  def get_global_manifest(self, macos_variant: str, device_class: str) -> bytes:
142
+ """Return the restore manifest for a macOS variant and device class."""
119
143
  manifest_path = f"Firmware/Manifests/restore/{macos_variant}/apticket.{device_class}.im4m"
120
144
  return self.read(manifest_path)
121
145
 
122
146
  def get_firmware(self, firmware_path: str) -> Firmware:
147
+ """Return a firmware helper rooted at ``firmware_path``."""
123
148
  return Firmware(firmware_path, self)
124
149
 
125
150
  def get_development_files(self) -> list[str]:
151
+ """Return archive entries associated with development builds."""
126
152
  result = []
127
153
  for entry in self.archive.namelist():
128
154
  for release in ("devel", "kasan", "research"):
@@ -131,6 +157,7 @@ class IPSW:
131
157
  return result
132
158
 
133
159
  def create_device_support(self, pem_db: Optional[str] = None) -> None:
160
+ """Create an Xcode DeviceSupport directory for this IPSW."""
134
161
  device_support_path = Path("~/Library/Developer/Xcode/iOS DeviceSupport").expanduser()
135
162
  device_support_path /= (
136
163
  f"{self.build_manifest.supported_product_types[0]} "
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ipsw-parser
3
- Version: 1.5.0
3
+ Version: 1.7.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>
@@ -696,13 +696,12 @@ Requires-Python: >=3.9
696
696
  Description-Content-Type: text/markdown
697
697
  License-File: LICENSE
698
698
  Requires-Dist: construct>=2.9.29
699
- Requires-Dist: click
700
699
  Requires-Dist: coloredlogs
701
- Requires-Dist: cached_property
702
700
  Requires-Dist: plumbum
703
701
  Requires-Dist: pyimg4>=0.8.8
704
702
  Requires-Dist: requests
705
703
  Requires-Dist: remotezip2
704
+ Requires-Dist: typer
706
705
  Provides-Extra: test
707
706
  Requires-Dist: pytest; extra == "test"
708
707
  Dynamic: license-file
@@ -739,5 +738,7 @@ Options:
739
738
  Commands:
740
739
  device-support Create DeviceSupport directory
741
740
  extract Extract .ipsw into filesystem layout
741
+ extract-sandbox-profiles
742
+ Extract decoded sandbox profiles from the kernelcache
742
743
  info Parse given .ipsw basic info
743
744
  ```
@@ -15,6 +15,7 @@ requirements.txt
15
15
  ipsw_parser/__init__.py
16
16
  ipsw_parser/__main__.py
17
17
  ipsw_parser/_version.py
18
+ ipsw_parser/archive.py
18
19
  ipsw_parser/build_identity.py
19
20
  ipsw_parser/build_manifest.py
20
21
  ipsw_parser/component.py
@@ -27,4 +28,5 @@ ipsw_parser.egg-info/SOURCES.txt
27
28
  ipsw_parser.egg-info/dependency_links.txt
28
29
  ipsw_parser.egg-info/entry_points.txt
29
30
  ipsw_parser.egg-info/requires.txt
30
- ipsw_parser.egg-info/top_level.txt
31
+ ipsw_parser.egg-info/top_level.txt
32
+ tests/test_archive_backends.py
@@ -1,11 +1,10 @@
1
1
  construct>=2.9.29
2
- click
3
2
  coloredlogs
4
- cached_property
5
3
  plumbum
6
4
  pyimg4>=0.8.8
7
5
  requests
8
6
  remotezip2
7
+ typer
9
8
 
10
9
  [test]
11
10
  pytest
@@ -1,8 +1,7 @@
1
1
  construct>=2.9.29
2
- click
3
2
  coloredlogs
4
- cached_property
5
3
  plumbum
6
4
  pyimg4>=0.8.8
7
5
  requests
8
- remotezip2
6
+ remotezip2
7
+ typer
@@ -0,0 +1,70 @@
1
+ import plistlib
2
+ from pathlib import Path
3
+ from zipfile import ZipFile
4
+
5
+ from ipsw_parser.archive import DirectoryArchive, ZipArchive
6
+ from ipsw_parser.ipsw import IPSW
7
+
8
+
9
+ def _build_manifest() -> bytes:
10
+ return plistlib.dumps({
11
+ "SupportedProductTypes": ["iPhone1,1"],
12
+ "ProductVersion": "1.0",
13
+ "ProductBuildVersion": "1A1",
14
+ "BuildIdentities": [],
15
+ })
16
+
17
+
18
+ def _write_ipsw_layout(root: Path) -> None:
19
+ (root / "BuildManifest.plist").write_bytes(_build_manifest())
20
+ (root / "RestoreVersion.plist").write_bytes(b"restore-version")
21
+ (root / "SystemVersion.plist").write_bytes(b"system-version")
22
+ firmware = root / "Firmware"
23
+ firmware.mkdir()
24
+ (firmware / "devel-file.bin").write_bytes(b"dev")
25
+ release = root / "Release"
26
+ release.mkdir()
27
+ (release / "normal-file.bin").write_bytes(b"release")
28
+
29
+
30
+ def test_directory_archive_supports_ipsw_loading(tmp_path: Path) -> None:
31
+ _write_ipsw_layout(tmp_path)
32
+
33
+ ipsw = IPSW(DirectoryArchive(tmp_path))
34
+
35
+ assert ipsw.build_manifest.product_version == "1.0"
36
+ assert ipsw.restore_version == b"restore-version"
37
+ assert ipsw.system_version == b"system-version"
38
+ assert ipsw.get_development_files() == ["Firmware/devel-file.bin"]
39
+
40
+
41
+ def test_zip_archive_supports_same_ipsw_behavior(tmp_path: Path) -> None:
42
+ source = tmp_path / "source"
43
+ source.mkdir()
44
+ _write_ipsw_layout(source)
45
+
46
+ archive_path = tmp_path / "sample.ipsw"
47
+ with ZipFile(archive_path, "w") as archive:
48
+ for file_path in sorted(path for path in source.rglob("*") if path.is_file()):
49
+ archive.write(file_path, arcname=file_path.relative_to(source).as_posix())
50
+
51
+ with ZipFile(archive_path) as archive:
52
+ ipsw = IPSW(ZipArchive(archive))
53
+
54
+ assert ipsw.build_manifest.product_build_version == "1A1"
55
+ assert ipsw.restore_version == b"restore-version"
56
+ assert ipsw.get_development_files() == ["Firmware/devel-file.bin"]
57
+
58
+
59
+ def test_directory_extractall_copies_requested_members(tmp_path: Path) -> None:
60
+ source = tmp_path / "source"
61
+ source.mkdir()
62
+ _write_ipsw_layout(source)
63
+ archive = DirectoryArchive(source)
64
+
65
+ output = tmp_path / "output"
66
+ members = [member for member in archive.filelist if member.filename.startswith("Firmware")]
67
+ archive.extractall(output, members)
68
+
69
+ assert (output / "Firmware" / "devel-file.bin").read_bytes() == b"dev"
70
+ assert not (output / "Release" / "normal-file.bin").exists()
@@ -1,99 +0,0 @@
1
- #!/usr/bin/env python3
2
- import logging
3
- from pathlib import Path
4
- from typing import Optional
5
- from zipfile import ZipFile
6
-
7
- import click
8
- import coloredlogs
9
- from remotezip2 import RemoteZip
10
-
11
- from ipsw_parser.ipsw import IPSW
12
-
13
- coloredlogs.install(level=logging.DEBUG)
14
-
15
- logging.getLogger("asyncio").disabled = True
16
- logging.getLogger("parso.cache").disabled = True
17
- logging.getLogger("parso.cache.pickle").disabled = True
18
- logging.getLogger("parso.python.diff").disabled = True
19
- logging.getLogger("humanfriendly.prompts").disabled = True
20
- logging.getLogger("blib2to3.pgen2.driver").disabled = True
21
- logging.getLogger("urllib3.connectionpool").disabled = True
22
-
23
- logger = logging.getLogger(__name__)
24
-
25
- PEM_DB_ENV_VAR = "IPSW_PARSER_PEM_DB"
26
-
27
-
28
- def handle_ipsw_argument(ctx: click.Context, param: click.Argument, value: str) -> IPSW:
29
- if value.startswith("http://") or value.startswith("https://"):
30
- return IPSW(RemoteZip(value))
31
- return IPSW(ZipFile(Path(value).expanduser()))
32
-
33
-
34
- ipsw_argument = click.argument("ipsw", callback=handle_ipsw_argument)
35
- pem_db_option = click.option(
36
- "--pem-db",
37
- envvar=PEM_DB_ENV_VAR,
38
- help="Path DB file url (can be either a filesystem path or an HTTP URL). "
39
- "Alternatively, use the IPSW_PARSER_PEM_DB envvar.",
40
- )
41
-
42
-
43
- @click.group()
44
- def cli() -> None:
45
- """CLI utility for extracting info from IPSW files"""
46
- pass
47
-
48
-
49
- @cli.command("info")
50
- @ipsw_argument
51
- def info(ipsw) -> None:
52
- """Parse given .ipsw basic info"""
53
- print(f"SupportedProductTypes: {ipsw.build_manifest.supported_product_types}")
54
- print(f"ProductVersion: {ipsw.build_manifest.product_version}")
55
- print(f"ProductBuildVersion: {ipsw.build_manifest.product_build_version}")
56
-
57
- development_files = ipsw.get_development_files()
58
- if development_files:
59
- print("DevelopmentFiles:")
60
- for file in development_files:
61
- print(f"- {file}")
62
-
63
-
64
- @cli.command("extract")
65
- @ipsw_argument
66
- @click.argument("output", type=click.Path(exists=False))
67
- @pem_db_option
68
- def extract(ipsw: IPSW, output: str, pem_db: Optional[str]) -> None:
69
- """Extract .ipsw into filesystem layout"""
70
- output = Path(output)
71
-
72
- if not output.exists():
73
- output.mkdir(parents=True, exist_ok=True)
74
-
75
- ipsw.build_manifest.build_identities[0].extract(output, pem_db=pem_db)
76
- ipsw.archive.extractall(
77
- path=output, members=[f for f in ipsw.archive.filelist if f.filename.startswith("Firmware")]
78
- )
79
-
80
-
81
- @cli.command("extract-kernel")
82
- @ipsw_argument
83
- @click.argument("output", type=click.Path(exists=False))
84
- @click.option("--arch", help="Arch name to extract using lipo")
85
- def extract_kernel(ipsw: IPSW, output: str, arch: Optional[str]) -> None:
86
- """Extract kernelcache from given .ipsw into given output filename"""
87
- Path(output).write_bytes(ipsw.build_manifest.build_identities[0].get_kernelcache_payload(arch=arch))
88
-
89
-
90
- @cli.command("device-support")
91
- @ipsw_argument
92
- @pem_db_option
93
- def device_support(ipsw: IPSW, pem_db: Optional[str]) -> None:
94
- """Create DeviceSupport directory"""
95
- ipsw.create_device_support(pem_db=pem_db)
96
-
97
-
98
- if __name__ == "__main__":
99
- cli()
@@ -1,34 +0,0 @@
1
- # file generated by setuptools-scm
2
- # don't change, don't track in version control
3
-
4
- __all__ = [
5
- "__version__",
6
- "__version_tuple__",
7
- "version",
8
- "version_tuple",
9
- "__commit_id__",
10
- "commit_id",
11
- ]
12
-
13
- TYPE_CHECKING = False
14
- if TYPE_CHECKING:
15
- from typing import Tuple
16
- from typing import Union
17
-
18
- VERSION_TUPLE = Tuple[Union[int, str], ...]
19
- COMMIT_ID = Union[str, None]
20
- else:
21
- VERSION_TUPLE = object
22
- COMMIT_ID = object
23
-
24
- version: str
25
- __version__: str
26
- __version_tuple__: VERSION_TUPLE
27
- version_tuple: VERSION_TUPLE
28
- commit_id: COMMIT_ID
29
- __commit_id__: COMMIT_ID
30
-
31
- __version__ = version = '1.5.0'
32
- __version_tuple__ = version_tuple = (1, 5, 0)
33
-
34
- __commit_id__ = commit_id = 'gd02ef0cd1'
@@ -1,6 +0,0 @@
1
- class IpswException(Exception):
2
- pass
3
-
4
-
5
- class NoSuchBuildIdentityError(IpswException):
6
- pass
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes