ipasign 1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ipasign/signer.py ADDED
@@ -0,0 +1,275 @@
1
+ """Per-file code signing.
2
+
3
+ Ties the blob builders, the CMS builder and the Mach-O writer together for a
4
+ single binary. A ``Signer`` holds the credential-derived material that is the
5
+ same for every file in a run; a ``FileContext`` holds what differs per file
6
+ (bundle id, info plist hash, CodeResources hash).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import datetime
12
+ import hashlib
13
+ import os
14
+ from dataclasses import dataclass, field
15
+ from pathlib import Path
16
+
17
+ from . import _plist, blobs, macho
18
+ from .cms import CmsParts, build_cms
19
+ from .credentials import Identity
20
+ from .errors import BundleError, MachOError
21
+
22
+ EMPTY_ENTITLEMENTS_PLIST = (
23
+ b'<?xml version="1.0" encoding="UTF-8"?>\n'
24
+ b'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" '
25
+ b'"http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n'
26
+ b'<plist version="1.0">\n'
27
+ b"<dict/>\n"
28
+ b"</plist>\n"
29
+ )
30
+
31
+
32
+ @dataclass(slots=True)
33
+ class Signer:
34
+ """Credential-derived material shared by every file in one signing run."""
35
+
36
+ identity: Identity | None = None
37
+ adhoc: bool = False
38
+ entitlements: dict = field(default_factory=dict)
39
+ entitlements_plist: bytes = b""
40
+ team_id: str = ""
41
+ subject_cn: str = ""
42
+ signing_time: datetime.datetime | None = None
43
+
44
+ @property
45
+ def get_task_allow(self) -> bool:
46
+ value = self.entitlements.get("get-task-allow")
47
+ return value is True
48
+
49
+ def entitlements_for(self, is_execute: bool) -> tuple[bytes, bytes]:
50
+ """(XML blob, DER blob) for a slice, empty when nothing applies."""
51
+ if not is_execute:
52
+ return blobs.entitlements_xml(EMPTY_ENTITLEMENTS_PLIST), b""
53
+ if not self.entitlements_plist:
54
+ return b"", b""
55
+ return (
56
+ blobs.entitlements_xml(self.entitlements_plist),
57
+ blobs.entitlements_der(self.entitlements),
58
+ )
59
+
60
+ def build_leaf_code_directory(self, slc: macho.Slice, ctx: "FileContext", code_length: int) -> bytes:
61
+ """The SHA-256 CodeDirectory for one slice at ``code_length``."""
62
+ req = blobs.requirements(ctx.bundle_id, self.subject_cn)
63
+ ent_xml, ent_der = self.entitlements_for(slc.is_execute)
64
+
65
+ spec = blobs.CodeDirectorySpec(
66
+ bundle_id=ctx.bundle_id,
67
+ team_id=self.team_id,
68
+ code_limit=code_length,
69
+ exec_seg_limit=slc.exec_seg_limit,
70
+ is_execute=slc.is_execute,
71
+ adhoc=self.adhoc,
72
+ info_plist_hash=ctx.info_plist_hash,
73
+ requirements_hash=hashlib.sha256(req).digest() if req else b"",
74
+ code_resources_hash=ctx.code_resources_hash,
75
+ entitlements_hash=hashlib.sha256(ent_xml).digest() if ent_xml else b"",
76
+ der_entitlements_hash=hashlib.sha256(ent_der).digest() if ent_der else b"",
77
+ get_task_allow=self.get_task_allow,
78
+ code_slots=blobs.hash_pages(slc.view, code_length),
79
+ )
80
+ return blobs.code_directory(spec)
81
+
82
+ def build_signature(self, slc: macho.Slice, ctx: "FileContext") -> bytes:
83
+ """The whole SuperBlob for one slice."""
84
+ code_length = slc.code_length
85
+ cd = self.build_leaf_code_directory(slc, ctx, code_length)
86
+
87
+ req = blobs.requirements(ctx.bundle_id, self.subject_cn)
88
+ ent_xml, ent_der = self.entitlements_for(slc.is_execute)
89
+
90
+ if self.adhoc:
91
+ # Ad-hoc has no CMS blob at all: the slot is left out of the
92
+ # SuperBlob rather than written as an empty wrapper.
93
+ cms_blob = b""
94
+ else:
95
+ if self.identity is None:
96
+ raise BundleError("a non-ad-hoc signature needs an identity")
97
+ cd_hash = hashlib.sha256(cd).digest()
98
+ cdhashes = _plist.dumps({"cdhashes": [cd_hash[:20]]})
99
+ payload = build_cms(
100
+ self.identity,
101
+ CmsParts(
102
+ code_directory=cd,
103
+ cdhashes_plist=cdhashes,
104
+ apple_hash=cd_hash,
105
+ signing_time=self.signing_time,
106
+ ),
107
+ )
108
+ cms_blob = blobs.blob_wrapper(payload)
109
+
110
+ return blobs.superblob(
111
+ [
112
+ (blobs.CSSLOT_CODEDIRECTORY, cd),
113
+ (blobs.CSSLOT_REQUIREMENTS, req),
114
+ (blobs.CSSLOT_ENTITLEMENTS, ent_xml),
115
+ (blobs.CSSLOT_DER_ENTITLEMENTS, ent_der),
116
+ (blobs.CSSLOT_SIGNATURESLOT, cms_blob),
117
+ ]
118
+ )
119
+
120
+
121
+ @dataclass(slots=True)
122
+ class FileContext:
123
+ """What differs per signed file."""
124
+
125
+ bundle_id: str
126
+ info_plist_hash: bytes = b""
127
+ code_resources_hash: bytes = b""
128
+
129
+
130
+ def _temp_path(target: Path) -> Path:
131
+ """A sibling temp name that keeps the target's basename.
132
+
133
+ ``Runner`` becomes ``Runner.is_tmp``; two binaries in one directory cannot
134
+ collide because their target names differ.
135
+ """
136
+ return target.with_name(target.name + ".is_tmp")
137
+
138
+
139
+ def write_atomic(target: Path, data: bytes) -> None:
140
+ """Write ``data`` next to ``target`` and rename over it.
141
+
142
+ A crash leaves the original file untouched rather than a truncated binary.
143
+ """
144
+ temp = _temp_path(target)
145
+ try:
146
+ with open(temp, "wb") as handle:
147
+ handle.write(data)
148
+ handle.flush()
149
+ os.fsync(handle.fileno())
150
+ os.replace(temp, target)
151
+ except OSError:
152
+ try:
153
+ temp.unlink()
154
+ except OSError:
155
+ pass
156
+ raise
157
+
158
+
159
+ def sign_slice(signer: Signer, slc: macho.Slice, ctx: FileContext) -> bytes:
160
+ """Sign one slice, growing the file when the current region is too small.
161
+
162
+ An unsigned slice has no region to reuse, so it grows first and the blob is
163
+ built once against the final layout. A slice that already carries a
164
+ signature is signed in place when the existing region can hold the new blob,
165
+ and regrown when it cannot.
166
+ """
167
+ code_length = slc.code_length
168
+
169
+ if slc.code_signature is not None:
170
+ signature = signer.build_signature(slc, ctx)
171
+ if slc.size - code_length >= len(signature):
172
+ return macho.place_signature(slc, slc.view.tobytes(), code_length, signature)
173
+
174
+ new_length = code_length + macho.signature_region_size(code_length)
175
+ if new_length <= slc.size:
176
+ raise MachOError(
177
+ f"cannot fit a signature for {slc.size} bytes at {code_length} in {slc.size} bytes"
178
+ )
179
+
180
+ grown = macho.grow_slice(slc, new_length)
181
+ grown_slice = macho.MachOFile.parse(grown).slices[0]
182
+ signature = signer.build_signature(grown_slice, ctx)
183
+ if code_length + len(signature) > new_length:
184
+ raise MachOError("signature region is smaller than the signature it must hold")
185
+ return macho.place_signature(grown_slice, grown, code_length, signature)
186
+
187
+
188
+ def _needs_growth(slc: macho.Slice, signer: Signer, ctx: FileContext) -> bool:
189
+ """Whether the existing signature region is too small for the new blob."""
190
+ if slc.code_signature is None:
191
+ return True
192
+ return slc.size - slc.code_length < len(signer.build_signature(slc, ctx))
193
+
194
+
195
+ def sign_file_data(signer: Signer, data: bytes, ctx: FileContext) -> tuple[bytes, int]:
196
+ """Sign every slice of an in-memory Mach-O file.
197
+
198
+ A file whose existing signature regions all have room is patched in place,
199
+ so the container layout, alignment and trailing padding are left exactly as
200
+ they were. Only a slice that must grow triggers a re-layout, and then the
201
+ fat container is rebuilt with every slice aligned.
202
+ """
203
+ parsed = macho.MachOFile.parse(data)
204
+
205
+ if not any(_needs_growth(slc, signer, ctx) for slc in parsed.slices):
206
+ out = bytearray(data)
207
+ for slc in parsed.slices:
208
+ signed = sign_slice(signer, slc, ctx)
209
+ if len(signed) != slc.size:
210
+ raise MachOError("in-place signing changed a slice's length")
211
+ out[slc.base : slc.base + slc.size] = signed
212
+ return bytes(out), len(parsed.slices)
213
+
214
+ signed_slices = [sign_slice(signer, slc, ctx) for slc in parsed.slices]
215
+ if not parsed.is_fat:
216
+ return signed_slices[0], 1
217
+ return macho.build_fat(signed_slices, parsed.archs, parsed.fat_big_endian), len(signed_slices)
218
+
219
+
220
+ def bundle_id_fallback(slc: macho.Slice, path: Path) -> str:
221
+ """Bundle id for a file signed outside a bundle.
222
+
223
+ The embedded ``__info_plist`` section wins; the file's own name, extension
224
+ included, is the last resort.
225
+ """
226
+ if slc.info_plist:
227
+ try:
228
+ parsed = _plist.loads(slc.info_plist)
229
+ if isinstance(parsed, dict) and parsed.get("CFBundleIdentifier"):
230
+ return str(parsed["CFBundleIdentifier"])
231
+ except Exception:
232
+ pass
233
+ return path.name
234
+
235
+
236
+ def embedded_info_plist_hash(slc: macho.Slice) -> bytes:
237
+ """SHA-256 of the embedded ``__info_plist`` section, zeros when absent."""
238
+ if not slc.info_plist:
239
+ return b"\0" * 32
240
+ return hashlib.sha256(slc.info_plist).digest()
241
+
242
+
243
+ def sign_macho_file(signer: Signer, path: Path, ctx: FileContext | None = None) -> int:
244
+ """Sign a Mach-O file in place and return the number of slices signed."""
245
+ try:
246
+ data = path.read_bytes()
247
+ except OSError as exc:
248
+ raise MachOError(f"cannot read {path}: {exc}") from exc
249
+
250
+ parsed = macho.MachOFile.parse(data)
251
+ if ctx is None:
252
+ bundle_id = ""
253
+ info_hash = b""
254
+ for slc in parsed.slices:
255
+ bundle_id = bundle_id or bundle_id_fallback(slc, path)
256
+ info_hash = info_hash or embedded_info_plist_hash(slc)
257
+ break
258
+ ctx = FileContext(bundle_id=bundle_id, info_plist_hash=info_hash)
259
+
260
+ signed, count = sign_file_data(signer, data, ctx)
261
+ write_atomic(path, signed)
262
+ return count
263
+
264
+
265
+ __all__ = [
266
+ "Signer",
267
+ "FileContext",
268
+ "sign_slice",
269
+ "sign_file_data",
270
+ "sign_macho_file",
271
+ "write_atomic",
272
+ "bundle_id_fallback",
273
+ "embedded_info_plist_hash",
274
+ "EMPTY_ENTITLEMENTS_PLIST",
275
+ ]
@@ -0,0 +1,96 @@
1
+ Metadata-Version: 2.4
2
+ Name: ipasign
3
+ Version: 1.0
4
+ Summary: iOS code signing in Python
5
+ Author-email: Senophyx <contact@senophyx.id>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/Senophyx/ipasign
8
+ Project-URL: Repository, https://github.com/Senophyx/ipasign
9
+ Project-URL: Issue tracker, https://github.com/Senophyx/ipasign/issues
10
+ Keywords: ios,ipa,codesign,code signing,macho,mobileprovision,p12
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Software Development :: Libraries
20
+ Classifier: Topic :: System :: Software Distribution
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: asn1crypto>=1.5.1
25
+ Requires-Dist: cryptography>=50.0.1
26
+ Dynamic: license-file
27
+
28
+ [![Views](https://api.visitorbadge.io/api/visitors?path=Senophyx%2Fipasign&label=Views&countColor=%23002fff)](https://github.com/Senophyx/ipasign)
29
+ [![PyPI](https://img.shields.io/pypi/v/ipasign?style=for-the-badge&logo=pypi&logoColor=FFD43B)](https://pypi.org/project/ipasign)
30
+
31
+ # ipasign
32
+
33
+ iOS code signing written in Python. Re-sign `.ipa` archives, `.app` bundles,
34
+ frameworks, dylibs and bare Mach-O executables with a `.p12` identity and a
35
+ `.mobileprovision` profile, producing a signature that iOS and Apple's
36
+ `codesign` accept.
37
+
38
+ ## Install
39
+
40
+ Via PyPI:
41
+
42
+ ```bash
43
+ pip install ipasign
44
+ ```
45
+
46
+ With uv:
47
+
48
+ ```bash
49
+ uv add ipasign
50
+ ```
51
+
52
+ Requires Python 3.10 or later. The only dependencies are `cryptography` and
53
+ `asn1crypto`, both installed automatically.
54
+
55
+ ## Quick Example
56
+
57
+ ```python
58
+ import ipasign
59
+
60
+ key = ipasign.Key("identity.p12", "profile.mobileprovision", "password")
61
+ out = key.sign("input.ipa", "output.ipa")
62
+
63
+ print(f"Successfully signed: {out.output_path}")
64
+ print(f"{out.app_name} {out.app_version} ({out.bundle_id})")
65
+ ```
66
+
67
+ `sign()` returns a result object, not a boolean:
68
+
69
+ | Attribute | Meaning |
70
+ |-----------|---------|
71
+ | `output_path` | Where the signed artifact actually landed |
72
+ | `bundle_id` | The identifier sealed into the CodeDirectory |
73
+ | `signed_count` | How many Mach-O files were signed |
74
+ | `app_name` | The app's display name, read from `Info.plist` |
75
+ | `app_version` | The release version, read from `Info.plist` |
76
+
77
+ Failures raise. Every exception derives from `ipasign.IpasignError`.
78
+
79
+ ### Ad-hoc signing
80
+
81
+ No credentials needed:
82
+
83
+ ```python
84
+ ipasign.Key(adhoc=True).sign("input.ipa", "output.ipa")
85
+ ```
86
+
87
+ ## Changelog
88
+
89
+ Release notes are available in
90
+ [CHANGELOG.md](https://github.com/Senophyx/ipasign/blob/main/CHANGELOG.md).
91
+
92
+ ## License
93
+ ```
94
+ This Project under MIT License
95
+ Copyright (c) 2026 Senophyx
96
+ ```
@@ -0,0 +1,17 @@
1
+ ipasign/__init__.py,sha256=7yRz_OfY6JLl_awhnjbO2FU8rwwChQBXZS7IfoV7Sro,849
2
+ ipasign/_apple_ca.py,sha256=x_T6uKjogNHW7TTtqKA_R6yZzHeW9F1-gcX4CfRoJ90,16639
3
+ ipasign/_plist.py,sha256=HTX6XIvBqaoh24qqim-cb22XWAZYwqQvK4wHpkgSjD4,850
4
+ ipasign/archive.py,sha256=cD9BTjCpJqqNvsORHBVDvBCUWepn4zGC7n94dgaK7LQ,5823
5
+ ipasign/blobs.py,sha256=vpSKpIyh6G9YpmxfM3QWDlaeNXGprvdT4IhhVDglTts,11552
6
+ ipasign/bundle.py,sha256=J5ROCGH73TdwWK5iUUU7vjctRH_4AKCH7cJqBOLL9zY,9164
7
+ ipasign/cms.py,sha256=PtHe2QoeYiR6RK2k8w5tNtUbwf_PcOISuCSi1hve1wQ,5841
8
+ ipasign/credentials.py,sha256=MPKiM-ZcDMS6pgK7GshPt4HCz5CktMKNChwpCu9CMVg,9200
9
+ ipasign/errors.py,sha256=O5imf-TfVNvyeE1ylaMe5GmYEcBwNCsXvtefUuZXAK0,1353
10
+ ipasign/key.py,sha256=b6gpA_1mA7ELxL9Fqadpcac3Ei4CLoNhdb0He_eCW7Y,8912
11
+ ipasign/macho.py,sha256=sWL402l64FV34gd_5vhFODxlfTF6YRaHqkbgXZqXARc,16561
12
+ ipasign/signer.py,sha256=7UhO5MjDCvqU7x4Ku1pMxxs86LyH391zoSlOe8gpsD4,9907
13
+ ipasign-1.0.dist-info/licenses/LICENSE,sha256=9QjCWhLLGVXxlAvG5oHfOvfs8v0Ord22Klqm9e_vnyo,1065
14
+ ipasign-1.0.dist-info/METADATA,sha256=Sphk3JvtRiATd_i1RruDSS2V-JpMc9Sr3mwTxTYZUFQ,2906
15
+ ipasign-1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
16
+ ipasign-1.0.dist-info/top_level.txt,sha256=BxqnjHigbq2c6W0khgnzkMpA66mDMI8_ykeULsId0KA,8
17
+ ipasign-1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Senophyx
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ ipasign