ipsw-parser 1.4.3__tar.gz → 1.5.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.4.3 → ipsw_parser-1.5.0}/.github/workflows/python-app.yml +1 -1
  2. {ipsw_parser-1.4.3 → ipsw_parser-1.5.0}/.github/workflows/python-publish.yml +2 -2
  3. ipsw_parser-1.5.0/.pre-commit-config.yaml +9 -0
  4. {ipsw_parser-1.4.3 → ipsw_parser-1.5.0}/PKG-INFO +2 -1
  5. ipsw_parser-1.5.0/ipsw_parser/__main__.py +99 -0
  6. {ipsw_parser-1.4.3 → ipsw_parser-1.5.0}/ipsw_parser/_version.py +16 -3
  7. ipsw_parser-1.5.0/ipsw_parser/build_identity.py +181 -0
  8. {ipsw_parser-1.4.3 → ipsw_parser-1.5.0}/ipsw_parser/build_manifest.py +21 -20
  9. {ipsw_parser-1.4.3 → ipsw_parser-1.5.0}/ipsw_parser/component.py +16 -8
  10. ipsw_parser-1.5.0/ipsw_parser/dsc.py +83 -0
  11. ipsw_parser-1.5.0/ipsw_parser/firmware.py +39 -0
  12. ipsw_parser-1.5.0/ipsw_parser/ipsw.py +147 -0
  13. {ipsw_parser-1.4.3 → ipsw_parser-1.5.0}/ipsw_parser.egg-info/PKG-INFO +2 -1
  14. {ipsw_parser-1.4.3 → ipsw_parser-1.5.0}/ipsw_parser.egg-info/SOURCES.txt +1 -0
  15. {ipsw_parser-1.4.3 → ipsw_parser-1.5.0}/pyproject.toml +50 -0
  16. ipsw_parser-1.4.3/.pre-commit-config.yaml +0 -14
  17. ipsw_parser-1.4.3/ipsw_parser/__main__.py +0 -95
  18. ipsw_parser-1.4.3/ipsw_parser/build_identity.py +0 -176
  19. ipsw_parser-1.4.3/ipsw_parser/firmware.py +0 -39
  20. ipsw_parser-1.4.3/ipsw_parser/ipsw.py +0 -132
  21. {ipsw_parser-1.4.3 → ipsw_parser-1.5.0}/.gitattributes +0 -0
  22. {ipsw_parser-1.4.3 → ipsw_parser-1.5.0}/.github/ISSUE_TEMPLATE/bug_report.md +0 -0
  23. {ipsw_parser-1.4.3 → ipsw_parser-1.5.0}/.github/ISSUE_TEMPLATE/feature_request.md +0 -0
  24. {ipsw_parser-1.4.3 → ipsw_parser-1.5.0}/.github/workflows/codeql.yml +0 -0
  25. {ipsw_parser-1.4.3 → ipsw_parser-1.5.0}/.gitignore +0 -0
  26. {ipsw_parser-1.4.3 → ipsw_parser-1.5.0}/CODE_OF_CONDUCT.md +0 -0
  27. {ipsw_parser-1.4.3 → ipsw_parser-1.5.0}/LICENSE +0 -0
  28. {ipsw_parser-1.4.3 → ipsw_parser-1.5.0}/README.md +0 -0
  29. {ipsw_parser-1.4.3 → ipsw_parser-1.5.0}/ipsw_parser/__init__.py +0 -0
  30. {ipsw_parser-1.4.3 → ipsw_parser-1.5.0}/ipsw_parser/exceptions.py +0 -0
  31. {ipsw_parser-1.4.3 → ipsw_parser-1.5.0}/ipsw_parser.egg-info/dependency_links.txt +0 -0
  32. {ipsw_parser-1.4.3 → ipsw_parser-1.5.0}/ipsw_parser.egg-info/entry_points.txt +0 -0
  33. {ipsw_parser-1.4.3 → ipsw_parser-1.5.0}/ipsw_parser.egg-info/requires.txt +0 -0
  34. {ipsw_parser-1.4.3 → ipsw_parser-1.5.0}/ipsw_parser.egg-info/top_level.txt +0 -0
  35. {ipsw_parser-1.4.3 → ipsw_parser-1.5.0}/pytest.ini +0 -0
  36. {ipsw_parser-1.4.3 → ipsw_parser-1.5.0}/requirements.txt +0 -0
  37. {ipsw_parser-1.4.3 → ipsw_parser-1.5.0}/setup.cfg +0 -0
@@ -13,7 +13,7 @@ jobs:
13
13
 
14
14
  strategy:
15
15
  matrix:
16
- python-version: [ "3.9", "3.10", "3.11", "3.12", "3.13" ]
16
+ python-version: [ "3.9", "3.10", "3.11", "3.12", "3.13", "3.14" ]
17
17
  os: [ ubuntu-latest, macos-latest, windows-latest ]
18
18
 
19
19
  steps:
@@ -13,9 +13,9 @@ jobs:
13
13
  runs-on: ubuntu-latest
14
14
 
15
15
  steps:
16
- - uses: actions/checkout@v2
16
+ - uses: actions/checkout@v4
17
17
  - name: Set up Python
18
- uses: actions/setup-python@v2
18
+ uses: actions/setup-python@v4
19
19
  with:
20
20
  python-version: '3.x'
21
21
  - name: Install dependencies
@@ -0,0 +1,9 @@
1
+ repos:
2
+ - repo: https://github.com/astral-sh/ruff-pre-commit
3
+ # Ruff version.
4
+ rev: v0.14.2
5
+ hooks:
6
+ # Run the linter.
7
+ - id: ruff-check
8
+ # Run the formatter.
9
+ - id: ruff-format
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ipsw-parser
3
- Version: 1.4.3
3
+ Version: 1.5.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>
@@ -690,6 +690,7 @@ Classifier: Programming Language :: Python :: 3.10
690
690
  Classifier: Programming Language :: Python :: 3.11
691
691
  Classifier: Programming Language :: Python :: 3.12
692
692
  Classifier: Programming Language :: Python :: 3.13
693
+ Classifier: Programming Language :: Python :: 3.14
693
694
  Classifier: Programming Language :: Python :: 3 :: Only
694
695
  Requires-Python: >=3.9
695
696
  Description-Content-Type: text/markdown
@@ -0,0 +1,99 @@
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,7 +1,14 @@
1
1
  # file generated by setuptools-scm
2
2
  # don't change, don't track in version control
3
3
 
4
- __all__ = ["__version__", "__version_tuple__", "version", "version_tuple"]
4
+ __all__ = [
5
+ "__version__",
6
+ "__version_tuple__",
7
+ "version",
8
+ "version_tuple",
9
+ "__commit_id__",
10
+ "commit_id",
11
+ ]
5
12
 
6
13
  TYPE_CHECKING = False
7
14
  if TYPE_CHECKING:
@@ -9,13 +16,19 @@ if TYPE_CHECKING:
9
16
  from typing import Union
10
17
 
11
18
  VERSION_TUPLE = Tuple[Union[int, str], ...]
19
+ COMMIT_ID = Union[str, None]
12
20
  else:
13
21
  VERSION_TUPLE = object
22
+ COMMIT_ID = object
14
23
 
15
24
  version: str
16
25
  __version__: str
17
26
  __version_tuple__: VERSION_TUPLE
18
27
  version_tuple: VERSION_TUPLE
28
+ commit_id: COMMIT_ID
29
+ __commit_id__: COMMIT_ID
19
30
 
20
- __version__ = version = '1.4.3'
21
- __version_tuple__ = version_tuple = (1, 4, 3)
31
+ __version__ = version = '1.5.0'
32
+ __version_tuple__ = version_tuple = (1, 5, 0)
33
+
34
+ __commit_id__ = commit_id = 'gd02ef0cd1'
@@ -0,0 +1,181 @@
1
+ import logging
2
+ import os
3
+ import shutil
4
+ from collections import UserDict
5
+ from pathlib import Path
6
+ from tempfile import TemporaryDirectory
7
+ from typing import Optional
8
+ from zipfile import ZipFile
9
+
10
+ import requests
11
+ from cached_property import cached_property
12
+ from plumbum import ProcessExecutionError, local
13
+ from pyimg4 import IM4P
14
+
15
+ from ipsw_parser.component import Component
16
+ from ipsw_parser.dsc import split_dsc
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+ AEA_MAGIC = b"AEA1"
21
+
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"""
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:
27
+ shutil.copyfileobj(source, target, length=chunk_size)
28
+
29
+
30
+ def _extract_dmg(dmg: Path, output: Path, sub_path: Optional[Path] = None, pem_db: Optional[str] = None) -> None:
31
+ ipsw = local["ipsw"]
32
+ hdiutil = local["hdiutil"]
33
+ # darwin system statistically have problems cleaning up after detaching the mountpoint
34
+ with TemporaryDirectory() as temp_dir:
35
+ temp_dir = Path(temp_dir)
36
+ mnt = temp_dir / "mnt"
37
+ mnt.mkdir()
38
+
39
+ with dmg.open("rb") as f:
40
+ magic = f.read(len(AEA_MAGIC))
41
+ if magic == AEA_MAGIC:
42
+ logger.debug("Found Apple Encrypted Archive. Decrypting...")
43
+ aea_dmg = str(dmg.absolute()) + ".aea"
44
+ dmg.rename(aea_dmg)
45
+ dmg = temp_dir / Path(aea_dmg).name.rsplit(".", 1)[0]
46
+ args = ["fw", "aea", aea_dmg, "-o", temp_dir]
47
+ if pem_db is not None:
48
+ if "://" in pem_db:
49
+ # create a local file containing it
50
+ temp_pem_db = temp_dir / "pem-db.json"
51
+ temp_pem_db.write_text(requests.get(pem_db, verify=False).text)
52
+ pem_db = temp_pem_db
53
+ args += ["--pem-db", pem_db]
54
+ ipsw(args)
55
+
56
+ hdiutil("attach", "-mountpoint", mnt, dmg)
57
+
58
+ try:
59
+ src = mnt if sub_path is None else mnt / sub_path
60
+ shutil.copytree(src, output, symlinks=True, dirs_exist_ok=True)
61
+ except shutil.Error:
62
+ # when overwriting the same files, some of them don't contain write permissions
63
+ pass
64
+
65
+ hdiutil("detach", "-force", mnt)
66
+
67
+
68
+ class BuildIdentity(UserDict):
69
+ def __init__(self, build_manifest, data):
70
+ super().__init__(data)
71
+ self.build_manifest = build_manifest
72
+
73
+ @cached_property
74
+ def device_class(self) -> str:
75
+ return self["Info"]["DeviceClass"].lower()
76
+
77
+ @cached_property
78
+ def restore_behavior(self) -> str:
79
+ return self["Info"].get("RestoreBehavior")
80
+
81
+ @cached_property
82
+ def variant(self):
83
+ return self["Info"].get("Variant")
84
+
85
+ @cached_property
86
+ def macos_variant(self) -> str:
87
+ return self["Info"].get("MacOSVariant")
88
+
89
+ @cached_property
90
+ def manifest(self) -> dict:
91
+ return self["Manifest"]
92
+
93
+ @cached_property
94
+ def minimum_system_partition(self):
95
+ return self["Info"].get("MinimumSystemPartition")
96
+
97
+ def get_component_path(self, component: str) -> str:
98
+ return self.manifest[component]["Info"]["Path"]
99
+
100
+ def has_component(self, name: str) -> bool:
101
+ return name in self.manifest
102
+
103
+ def get_component(self, name: str, **args) -> Component:
104
+ return Component(self, name, **args)
105
+
106
+ def extract_dsc(self, output: Path, pem_db: Optional[str] = None, split: bool = True) -> None:
107
+ build_identity = self.build_manifest.build_identities[0]
108
+ if not build_identity.has_component("Cryptex1,SystemOS"):
109
+ return
110
+
111
+ device_support_symbols_path = output / "private/preboot/Cryptexes/OS/System"
112
+ device_support_symbols_path.mkdir(parents=True, exist_ok=True)
113
+
114
+ with TemporaryDirectory() as temp_dir:
115
+ system_os = Path(temp_dir) / "system_os.dmg"
116
+ system_os_component_path = build_identity.get_component_path("Cryptex1,SystemOS")
117
+ extract_as(self.build_manifest.ipsw.archive, system_os_component_path, system_os)
118
+ _extract_dmg(system_os, device_support_symbols_path, sub_path=Path("System"), pem_db=pem_db)
119
+ if split:
120
+ split_dsc(output)
121
+
122
+ def get_kernelcache_payload(self, arch: Optional[str] = None) -> bytes:
123
+ im4p = IM4P(self.build_manifest.build_identities[0].get_component("KernelCache").data)
124
+ im4p.payload.decompress()
125
+ payload = im4p.payload.output().data
126
+ if arch is None:
127
+ return payload
128
+
129
+ with TemporaryDirectory() as temp_dir:
130
+ kernel_output = Path(temp_dir) / "kernel"
131
+ local["ipsw"]("macho", "lipo", "-a", arch, kernel_output)
132
+ return Path(next(kernel_output.parent.glob(f"*.{arch}"))).read_bytes()
133
+
134
+ def extract(self, output: Path, pem_db: Optional[str] = None) -> None:
135
+ logger.info(f"extracting into: {output}")
136
+
137
+ build_identity = self.build_manifest.build_identities[0]
138
+
139
+ logger.info(f"extracting OS into: {output}")
140
+ with TemporaryDirectory() as temp_dir:
141
+ os_dmg = Path(temp_dir) / "os.dmg"
142
+ os_component_path = build_identity.get_component_path("OS")
143
+ extract_as(self.build_manifest.ipsw.archive, os_component_path, os_dmg)
144
+ _extract_dmg(os_dmg, output, pem_db=pem_db)
145
+
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
161
+
162
+ for cryptex in ("App", "OS"):
163
+ name = {
164
+ "App": "Cryptex1,AppOS",
165
+ "OS": "Cryptex1,SystemOS",
166
+ }[cryptex]
167
+
168
+ if not build_identity.has_component(name):
169
+ continue
170
+
171
+ cryptex_path = output / "private/preboot/Cryptexes" / cryptex
172
+ cryptex_path.mkdir(parents=True, exist_ok=True)
173
+
174
+ logger.info(f"extracting {name} into: {cryptex_path}")
175
+ with TemporaryDirectory() as temp_dir:
176
+ temp_component = (Path(temp_dir) / name).with_suffix(".dmg")
177
+ component_path = build_identity.get_component_path(name)
178
+ extract_as(self.build_manifest.ipsw.archive, component_path, temp_component)
179
+ _extract_dmg(temp_component, cryptex_path, pem_db=pem_db)
180
+
181
+ split_dsc(output)
@@ -1,4 +1,5 @@
1
1
  import plistlib
2
+ from typing import Optional
2
3
 
3
4
  from cached_property import cached_property
4
5
 
@@ -14,8 +15,8 @@ class BuildManifest:
14
15
 
15
16
  @cached_property
16
17
  def build_major(self) -> int:
17
- build_major = ''
18
- for i in self._manifest['ProductBuildVersion']:
18
+ build_major = ""
19
+ for i in self._manifest["ProductBuildVersion"]:
19
20
  if i.isdigit():
20
21
  build_major += i
21
22
  else:
@@ -25,45 +26,45 @@ class BuildManifest:
25
26
 
26
27
  @cached_property
27
28
  def supported_product_types(self) -> list[str]:
28
- return self._manifest['SupportedProductTypes']
29
+ return self._manifest["SupportedProductTypes"]
29
30
 
30
31
  @cached_property
31
32
  def supported_product_types_family(self) -> str:
32
33
  product = self.supported_product_types[0]
33
- if product.startswith('iBridge'):
34
- return 'iBridge'
35
- elif product.startswith('iPhone'):
36
- return 'iPhone'
37
- elif 'Mac' in product:
38
- return 'Mac'
34
+ if product.startswith("iBridge"):
35
+ return "iBridge"
36
+ elif product.startswith("iPhone"):
37
+ return "iPhone"
38
+ elif "Mac" in product:
39
+ return "Mac"
39
40
  else:
40
41
  raise ValueError()
41
42
 
42
43
  @cached_property
43
44
  def product_version(self) -> str:
44
- return self._manifest['ProductVersion']
45
+ return self._manifest["ProductVersion"]
45
46
 
46
47
  @cached_property
47
48
  def product_build_version(self) -> str:
48
- return self._manifest['ProductBuildVersion']
49
+ return self._manifest["ProductBuildVersion"]
49
50
 
50
- def get_build_identity(self, device_class: str, restore_behavior: str = None, variant: str = None) -> BuildIdentity:
51
+ def get_build_identity(
52
+ self, device_class: str, restore_behavior: Optional[str] = None, variant: Optional[str] = None
53
+ ) -> BuildIdentity:
51
54
  for build_identity in self.build_identities:
52
- if variant is not None:
53
- if variant not in build_identity.variant:
54
- continue
55
+ if variant is not None and variant not in build_identity.variant:
56
+ continue
55
57
 
56
58
  if build_identity.device_class != device_class:
57
59
  continue
58
60
 
59
- if restore_behavior is not None:
60
- if build_identity.restore_behavior != restore_behavior:
61
- continue
61
+ if restore_behavior is not None and build_identity.restore_behavior != restore_behavior:
62
+ continue
62
63
 
63
64
  return build_identity
64
- raise NoSuchBuildIdentityError('failed to find the correct BuildIdentity from the BuildManifest')
65
+ raise NoSuchBuildIdentityError("failed to find the correct BuildIdentity from the BuildManifest")
65
66
 
66
67
  def _parse_build_identities(self) -> None:
67
68
  self.build_identities = []
68
- for build_identity in self._manifest['BuildIdentities']:
69
+ for build_identity in self._manifest["BuildIdentities"]:
69
70
  self.build_identities.append(BuildIdentity(self, build_identity))
@@ -1,5 +1,6 @@
1
1
  import logging
2
2
  import os.path
3
+ from typing import Optional
3
4
 
4
5
  from cached_property import cached_property
5
6
 
@@ -9,27 +10,34 @@ from ipsw_parser.exceptions import IpswException
9
10
  class TSSResponse(dict):
10
11
  @property
11
12
  def ap_img4_ticket(self):
12
- ticket = self.get('ApImg4Ticket')
13
+ ticket = self.get("ApImg4Ticket")
13
14
 
14
15
  if ticket is None:
15
- raise IpswException('TSS response doesn\'t contain a ApImg4Ticket')
16
+ raise IpswException("TSS response doesn't contain a ApImg4Ticket")
16
17
 
17
18
  return ticket
18
19
 
19
20
  @property
20
21
  def bb_ticket(self):
21
- return self.get('BBTicket')
22
+ return self.get("BBTicket")
22
23
 
23
24
  def get_path_by_entry(self, component: str):
24
25
  node = self.get(component)
25
26
  if node is not None:
26
- return node.get('Path')
27
+ return node.get("Path")
27
28
 
28
29
  return None
29
30
 
30
31
 
31
32
  class Component:
32
- def __init__(self, build_identity, name: str, tss: TSSResponse = None, data: bytes = None, path: str = None):
33
+ def __init__(
34
+ self,
35
+ build_identity,
36
+ name: str,
37
+ tss: TSSResponse = None,
38
+ data: Optional[bytes] = None,
39
+ path: Optional[str] = None,
40
+ ):
33
41
  self.logger = logging.getLogger(__name__)
34
42
  self._tss = tss
35
43
  self.build_identity = build_identity
@@ -47,19 +55,19 @@ class Component:
47
55
  path = self._tss.get_path_by_entry(self.name)
48
56
 
49
57
  if path is None:
50
- self.logger.debug(f'NOTE: No path for component {self.name} in TSS, will fetch from build_identity')
58
+ self.logger.debug(f"NOTE: No path for component {self.name} in TSS, will fetch from build_identity")
51
59
 
52
60
  if path is None:
53
61
  path = self.build_identity.get_component_path(self.name)
54
62
 
55
63
  if path is None:
56
- raise IpswException(f'Failed to find component path for: {self.name}')
64
+ raise IpswException(f"Failed to find component path for: {self.name}")
57
65
 
58
66
  return path
59
67
 
60
68
  @cached_property
61
69
  def data(self) -> bytes:
62
70
  if self._data is None:
63
- self.logger.debug(f'Extracting {os.path.basename(self.path)} ({self.path})')
71
+ self.logger.debug(f"Extracting {os.path.basename(self.path)} ({self.path})")
64
72
  return self.build_identity.build_manifest.ipsw.read(self.path)
65
73
  return self._data
@@ -0,0 +1,83 @@
1
+ import logging
2
+ import plistlib
3
+ from datetime import datetime
4
+ from pathlib import Path
5
+
6
+ from plumbum import local
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ def split_dsc(root: Path) -> None:
12
+ ipsw = local["ipsw"]
13
+ dsc_paths = [
14
+ root / "System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64",
15
+ root / "System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64e",
16
+ root / "private/preboot/Cryptexes/OS/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64",
17
+ root / "private/preboot/Cryptexes/OS/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64e",
18
+ ]
19
+
20
+ for dsc in dsc_paths:
21
+ if not dsc.exists():
22
+ continue
23
+
24
+ logger.info(f"splitting DSC: {dsc}")
25
+ ipsw("dyld", "split", dsc, "-o", root)
26
+
27
+
28
+ 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
+ """
40
+ device_support_path = Path("~/Library/Developer/Xcode/iOS DeviceSupport").expanduser()
41
+ device_support_path /= f"{product_type} {product_version} ({product_build_version})"
42
+ return device_support_path
43
+
44
+
45
+ def create_device_support_layout(
46
+ product_type: str, product_version: str, product_build_version: str, root_path: Path
47
+ ) -> 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
+ """
60
+ device_support_path = get_device_support_path(product_type, product_version, product_build_version)
61
+
62
+ # Split DSC files
63
+ split_dsc(root_path)
64
+
65
+ # Clean up the cryptex DSC files after splitting
66
+ cryptex_dsc_dir = root_path / "private/preboot/Cryptexes/OS/System/Library/Caches/com.apple.dyld"
67
+ if cryptex_dsc_dir.exists():
68
+ for file in cryptex_dsc_dir.iterdir():
69
+ file.unlink()
70
+
71
+ # Create the device support metadata files
72
+ (device_support_path / "Info.plist").write_bytes(
73
+ plistlib.dumps({
74
+ "DSC Extractor Version": "1228.0.0.0.0",
75
+ "DateCollected": datetime.now(),
76
+ "Version": "16.0",
77
+ })
78
+ )
79
+ (device_support_path / ".finalized").write_bytes(plistlib.dumps({}))
80
+ (device_support_path / ".processed_dyld_shared_cache_arm64e").touch()
81
+ (device_support_path / ".processing_lock").touch()
82
+
83
+ return device_support_path
@@ -0,0 +1,39 @@
1
+ class Firmware:
2
+ def __init__(self, firmware_path: str, ipsw):
3
+ self._ipsw = ipsw
4
+ self._firmware_path = firmware_path
5
+ self._manifest_data = self._ipsw.read(self.get_relative_path("manifest"))
6
+ self._firmware_files = {}
7
+ for filename in self._manifest_data.splitlines():
8
+ filename = filename.strip()
9
+ component_name = self.get_component_name(filename)
10
+ self._firmware_files[component_name] = f"{firmware_path}/{filename}"
11
+
12
+ def get_relative_path(self, path: str):
13
+ return f"{self._firmware_path}/{path}"
14
+
15
+ def get_files(self):
16
+ return self._firmware_files
17
+
18
+ @staticmethod
19
+ def get_component_name(filename):
20
+ names = {
21
+ "LLB": "LLB",
22
+ "iBoot": "iBoot",
23
+ "DeviceTree": "DeviceTree",
24
+ "applelogo": "AppleLogo",
25
+ "liquiddetect": "Liquid",
26
+ "lowpowermode": "LowPowerWallet0",
27
+ "recoverymode": "RecoveryMode",
28
+ "batterylow0": "BatteryLow0",
29
+ "batterylow1": "BatteryLow1",
30
+ "glyphcharging": "BatteryCharging",
31
+ "glyphplugin": "BatteryPlugin",
32
+ "batterycharging0": "BatteryCharging0",
33
+ "batterycharging1": "BatteryCharging1",
34
+ "batteryfull": "BatteryFull",
35
+ "needservice": "NeedService",
36
+ "SCAB": "SCAB",
37
+ "sep-firmware": "RestoreSEP",
38
+ }
39
+ return names.get(filename)