diff --git a/.github/build_github.sh b/.github/build_github.sh index 87dc7c8c9..613191d6a 100644 --- a/.github/build_github.sh +++ b/.github/build_github.sh @@ -86,5 +86,13 @@ find Payload -type d -name "_CodeSignature" -exec rm -r {} + ldid -S.github/sidelc/LiveWidgetExtension_adhoc.xml ./Payload/LiveContainer.app/PlugIns/LiveWidgetExtension.appex/LiveWidgetExtension -# package +# Preserve the usual integrated build for Apple accounts that cannot +# obtain the Increased Memory Limit entitlement. zip -r "$scheme+SideStore.ipa" "Payload" -x "._*" -x ".DS_Store" -x "__MACOSX" + +# A separate *host* Extra Memory variant. SideStore must use its Apple +# Developer Portal session to enable the capability, verify the downloaded +# profile, and sign the LC+ main process with the granted entitlement. +# This marker is in the extra variant ONLY, not the normal integrated IPA. +python3 scripts/prepare_host_memory_request.py ./Payload/LiveContainer.app --entitlements entitlements.xml +zip -r "$scheme+SideStore-ExtraMemory.ipa" "Payload" -x "._*" -x ".DS_Store" -x "__MACOSX" diff --git a/.github/workflows/increased-memory-preflight.yml b/.github/workflows/increased-memory-preflight.yml index 4cca13aad..c912e184b 100644 --- a/.github/workflows/increased-memory-preflight.yml +++ b/.github/workflows/increased-memory-preflight.yml @@ -1,7 +1,7 @@ name: Increased Memory Limit - Signing Preflight on: push: - branches: ['feature/sidestore-advanced-increased-memory'] + branches: ['feature/sidestore-advanced-increased-memory', 'feature/lcplus-host-extra-memory'] pull_request: paths: - 'scripts/prepare_sidestore_source.py' @@ -21,7 +21,9 @@ jobs: - name: Test fail-closed signer overlay run: | python3 -m unittest discover -s Tests -p 'test_increased_memory_signer.py' -v - python3 -m py_compile scripts/prepare_sidestore_source.py scripts/patch_sidestore_memory_signer.py scripts/verify_sidestore_source.py + python3 -m unittest discover -s Tests -p 'test_host_memory_request.py' -v + python3 -m unittest discover -s Tests -p 'test_verify_ipa.py' -v + python3 -m py_compile scripts/prepare_host_memory_request.py scripts/verify_ipa.py scripts/prepare_sidestore_source.py scripts/patch_sidestore_memory_signer.py scripts/verify_sidestore_source.py - uses: actions/checkout@v4 with: repository: LiveContainer/SideStore @@ -44,5 +46,10 @@ jobs: assert '!(key == memoryKey && increasedMemoryRequested)' in sign assert 'profile.entitlements[.increasedMemoryLimit] as? Bool == true' in profile assert 'targetFeatures[.increasedMemoryLimit] = "true"' in profile - print('Pinned signer and Apple portal preflight are wired; no Apple account used.') + assert 'entitlements[ALTEntitlement.increasedMemoryLimit.rawValue] as? Bool == true' in profile + resign=(root/'SideStore/Core/Operations/PipelineOperations/ResignAppOperation.swift').read_text() + assert 'lcosMemoryRequested' in resign + assert 'SigningIncreasedMemory.writeRequest' in resign + assert 'prepared.bundleIdentifier' in resign + print('Host memory request is rebound to final app ID and retained across refreshes. No Apple account used.') PY diff --git a/.github/workflows/livecontainer-os.yml b/.github/workflows/livecontainer-os.yml index bbe6aed05..e9f51a5ad 100644 --- a/.github/workflows/livecontainer-os.yml +++ b/.github/workflows/livecontainer-os.yml @@ -78,9 +78,11 @@ jobs: - name: Verify integrated IPA and record provenance run: | mv LiveContainer+SideStore.ipa LifeContainer+SideStore.ipa + mv LiveContainer+SideStore-ExtraMemory.ipa LifeContainer+SideStore-ExtraMemory.ipa mv LiveContainer.ipa LifeContainer+-Standalone.ipa python3 scripts/verify_ipa.py LifeContainer+SideStore.ipa --integrated --signing-injection --automations --builtin-jit --source-commit "$GITHUB_SHA" --output build-evidence.json - shasum -a 256 LifeContainer+SideStore.ipa LifeContainer+-Standalone.ipa > SHA256SUMS + python3 scripts/verify_ipa.py LifeContainer+SideStore-ExtraMemory.ipa --integrated --signing-injection --automations --builtin-jit --host-memory-request --source-commit "$GITHUB_SHA" --output build-evidence-extra-memory.json + shasum -a 256 LifeContainer+SideStore.ipa LifeContainer+SideStore-ExtraMemory.ipa LifeContainer+-Standalone.ipa > SHA256SUMS git rev-parse HEAD > SOURCE_COMMIT git submodule status > SUBMODULES printenv SIDESTORE_BUILD_RUN > SIDESTORE_BUILD_RUN @@ -89,11 +91,13 @@ jobs: name: LifeContainer+SideStore.ipa path: | LifeContainer+SideStore.ipa + LifeContainer+SideStore-ExtraMemory.ipa SHA256SUMS SOURCE_COMMIT SUBMODULES SIDESTORE_BUILD_RUN build-evidence.json + build-evidence-extra-memory.json artifacts/signing-bridge/signing-bridge-evidence.json artifacts/sidestore-source/SIDESTORE_SOURCE.json artifacts/device-probe/LCOSProbe.ipa diff --git a/Integrations/SideStore/README.md b/Integrations/SideStore/README.md index b00f17e89..814af8bb0 100644 --- a/Integrations/SideStore/README.md +++ b/Integrations/SideStore/README.md @@ -94,3 +94,35 @@ App Groups entitlement even when a profile contains it. The result is the purple not start” screen. Both the source IPA and final integrated IPA now reject a missing declaration. This check does not grant entitlements: the final device installation still needs a valid provisioning profile granting the shared app group. + + +## Extra Memory for the LC+ host (not just guest IPA installs) + +The dedicated **`LifeContainer+SideStore-ExtraMemory.ipa`** now carries a +validated `LCOSIncreasedMemoryRequest.plist` for the **main +`LiveContainer.app`**. The ordinary `LifeContainer+SideStore.ipa` and +standalone build remain unchanged and do not request the capability, so +Apple accounts without Increased Memory permission can still install LC+. + +This marker is **not an entitlement**. When LC+ itself is signed through the +updated embedded SideStore/SideSign pipeline (PR #9 and the host follow-up), +SideStore requests the Increased Memory Limit capability on the actual Apple +App ID, verifies the returned provisioning profile, and SideSign signs +`com.apple.developer.kernel.increased-memory-limit` only if Apple granted it. +The request is rebound to the final signed bundle identifier and consumed +before signing. Later refreshes preserve an already authorized capability. + +To verify an installed device: open **LC+ → Settings → Extra Memory · LC+**. +This reads the real `SecTaskCopyValueForEntitlement` value of LC+'s running +process. `Yes` means the installed host has the entitlement; `No` means it +does not. This does **not** guarantee a specific amount of memory on a device. + +Important: existing installed copies cannot gain extra memory by updating an +IPA setting or installing a guest app. Re-sign/reinstall **the host itself** +with the appropriate authorized Apple account and a profile granting the +capability. Preserve the existing bundle identity where possible and **back +up LC+ user containers before any replacement**, especially if the installer +proposes deleting the previous app. Apple's portal can refuse the capability; +then the signing flow must fail visibly rather than silently install LC+ +without the entitlement. Other sideloading services that ignore the marker +cannot be treated as supporting this automatic request. diff --git a/LiveContainerSwiftUI/Views/Settings/LCJITLessDiagnoseView.swift b/LiveContainerSwiftUI/Views/Settings/LCJITLessDiagnoseView.swift index df9026609..c1667b513 100644 --- a/LiveContainerSwiftUI/Views/Settings/LCJITLessDiagnoseView.swift +++ b/LiveContainerSwiftUI/Views/Settings/LCJITLessDiagnoseView.swift @@ -10,6 +10,7 @@ struct LCEntitlementView : View { @State var isLiveProcess: Bool @State var loaded = false @State var entitlementReadSuccess = false + @State private var hostIncreasedMemory: Bool? = nil @State var teamId : String? @State var getTaskAllow = false @@ -54,6 +55,17 @@ struct LCEntitlementView : View { Text(getTaskAllow ? "lc.common.yes".loc : "lc.common.no".loc) .foregroundStyle(getTaskAllow ? .green : .red) } + if !isLiveProcess { + HStack { + Text("lcos.memory.hostStatus".loc) + Spacer() + Text(hostIncreasedMemory == true ? "lc.common.yes".loc : "lc.common.no".loc) + .foregroundStyle(hostIncreasedMemory == true ? .green : .red) + } + Text("lcos.memory.hostStatusHelp".loc) + .font(.footnote) + .foregroundStyle(.secondary) + } HStack { Text("com.apple.security.application-groups \("lc.common.correct".loc)") Spacer() @@ -154,6 +166,16 @@ struct LCEntitlementView : View { } getTaskAllow = entitlementDict["get-task-allow"] as? Bool ?? false + if !isLiveProcess { + // Read the *running LC+ process*, not a build-time XML declaration + // or a guest IPA. Only Apple's installed code signature can grant + // the kernel entitlement used by apps executing in this process. + let task = SecTaskCreateFromSelf(nil) + hostIncreasedMemory = + (SecTaskCopyValueForEntitlement(task, + "com.apple.developer.kernel.increased-memory-limit" as CFString, + nil)?.takeRetainedValue() as? Bool) == true + } } diff --git a/LiveContainerSwiftUI/Views/Settings/LCSettingsView.swift b/LiveContainerSwiftUI/Views/Settings/LCSettingsView.swift index 85dff9e80..e7f02f579 100644 --- a/LiveContainerSwiftUI/Views/Settings/LCSettingsView.swift +++ b/LiveContainerSwiftUI/Views/Settings/LCSettingsView.swift @@ -76,6 +76,13 @@ struct LCSettingsView: View { @State private var isViewAppeared = false let storeName = LCUtils.getStoreName() + + private var hostExtraMemoryEntitled: Bool { + let task = SecTaskCreateFromSelf(nil) + return (SecTaskCopyValueForEntitlement(task, + "com.apple.developer.kernel.increased-memory-limit" as CFString, + nil)?.takeRetainedValue() as? Bool) == true + } init() { _certificateDataFound = State(initialValue: LCSharedUtils.certificatePassword() != nil) @@ -92,6 +99,22 @@ struct LCSettingsView: View { Label("lcos.logs.title".loc, systemImage: "waveform.path.ecg") } } + Section { + NavigationLink { + LCEntitlementView(isLiveProcess: false) + } label: { + HStack(spacing: 12) { + Label("lcos.memory.title".loc, systemImage: "memorychip") + Spacer() + Text(hostExtraMemoryEntitled + ? "lc.common.yes".loc : "lc.common.no".loc) + .font(.subheadline) + .foregroundStyle(hostExtraMemoryEntitled ? Color.green : Color.secondary) + } + } + } footer: { + Text("lcos.memory.signingHelp".loc) + } if sharedModel.multiLCStatus != 2 { Section{ if !certificateDataFound { diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index 0f2fa380b..e4f13b8b1 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -1,6 +1,10 @@ { "sourceLanguage" : "en", "strings" : { + "lcos.memory.hostStatus" : {"extractionState":"manual","localizations":{"en":{"stringUnit":{"state":"translated","value":"LC+ Extra Memory"}},"ru":{"stringUnit":{"state":"translated","value":"Extra Memory для LC+"}}}}, + "lcos.memory.hostStatusHelp" : {"extractionState":"manual","localizations":{"en":{"stringUnit":{"state":"translated","value":"This status reads the entitlement in the installed LC+ process, not the IPA or Developer Portal. Signing LC+ with an Apple-granted profile and reinstalling it are required."}},"ru":{"stringUnit":{"state":"translated","value":"Статус проверяет право запущенного процесса LC+, а не IPA или Apple Developer Portal. Нужно подписать LC+ профилем с разрешением Apple и переустановить."}}}}, + "lcos.memory.title" : {"extractionState":"manual","localizations":{"en":{"stringUnit":{"state":"translated","value":"Extra Memory · LC+"}},"ru":{"stringUnit":{"state":"translated","value":"Extra Memory · LC+"}}}}, + "lcos.memory.signingHelp" : {"extractionState":"manual","localizations":{"en":{"stringUnit":{"state":"translated","value":"For guest apps inside LC+, Extra Memory must be granted to the LC+ host. If the status is No, sign and reinstall LC+ with Increased Memory Limit enabled for its App ID."}},"ru":{"stringUnit":{"state":"translated","value":"Для гостевых приложений внутри LC+ право Extra Memory должно быть у основного приложения LC+. Если статус «Нет», подпишите и переустановите LC+ с Increased Memory Limit для его App ID."}}}}, "lcos.install.increasedMemory" : {"extractionState":"manual","localizations":{"en":{"stringUnit":{"state":"translated","value":"Increased Memory Limit"}},"ru":{"stringUnit":{"state":"translated","value":"Увеличенный лимит памяти"}}}}, "lcos.install.increasedMemorySubtitle" : {"extractionState":"manual","localizations":{"en":{"stringUnit":{"state":"translated","value":"Request additional app memory from Apple when signing"}},"ru":{"stringUnit":{"state":"translated","value":"Запросить дополнительную память через Apple при подписи"}}}}, "lcos.install.increasedMemoryHelp" : {"extractionState":"manual","localizations":{"en":{"stringUnit":{"state":"translated","value":"Requires an Apple-granted capability and a provisioning profile that contains the entitlement. Only applies after SideStore signs and reinstalls the app. Not all Apple accounts or devices are supported."}},"ru":{"stringUnit":{"state":"translated","value":"Нужны разрешённая Apple возможность App ID и профиль подписи с соответствующим правом. Действует только после подписи и переустановки через SideStore. Поддерживается не всеми аккаунтами и устройствами."}}}}, diff --git a/Tests/test_host_memory_request.py b/Tests/test_host_memory_request.py new file mode 100644 index 000000000..3b223aabe --- /dev/null +++ b/Tests/test_host_memory_request.py @@ -0,0 +1,64 @@ +"""LC+ host-only Extra Memory preparation: no Apple login or signing in these tests.""" +import pathlib +import plistlib +import sys +import tempfile +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1] / "scripts")) +from prepare_host_memory_request import prepare_host, MARKER, ENTITLEMENT + + +class HostExtraMemoryRequestTests(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory() + self.addCleanup(self.temporary.cleanup) + root = pathlib.Path(self.temporary.name) + self.app = root / "Payload" / "LiveContainer.app" + self.app.mkdir(parents=True) + self.app.joinpath("LiveContainer").write_bytes(b"test executable") + self.app.joinpath("Info.plist").write_bytes(plistlib.dumps({ + "CFBundleIdentifier": "com.kdt.livecontainer", + "CFBundleExecutable": "LiveContainer", + })) + self.entitlements = root / "entitlements.xml" + self.entitlements.write_bytes(plistlib.dumps({ENTITLEMENT: True})) + + def test_host_request_matches_real_bundle(self): + evidence = prepare_host(self.app, self.entitlements) + payload = plistlib.loads((self.app / MARKER).read_bytes()) + self.assertEqual(payload, { + "schema": 1, "requested": True, + "bundleIdentifier": "com.kdt.livecontainer", + }) + self.assertEqual(evidence["bundle"], payload["bundleIdentifier"]) + self.assertFalse(evidence["apple_profile_granted"]) + self.assertFalse(evidence["installed_signature_verified"]) + + def test_declared_entitlement_is_required(self): + self.entitlements.write_bytes(plistlib.dumps({})) + with self.assertRaisesRegex(ValueError, "host entitlement"): + prepare_host(self.app, self.entitlements) + self.assertFalse((self.app / MARKER).exists()) + + def test_does_not_write_to_wrong_host(self): + self.app.joinpath("Info.plist").write_bytes(plistlib.dumps({ + "CFBundleIdentifier": "com.example.other", + "CFBundleExecutable": "OtherApp", + })) + with self.assertRaisesRegex(ValueError, "real LC"): + prepare_host(self.app, self.entitlements) + self.assertFalse((self.app / MARKER).exists()) + + def test_rejects_malformed_bundle_identifier(self): + self.app.joinpath("Info.plist").write_bytes(plistlib.dumps({ + "CFBundleIdentifier": "../escape", + "CFBundleExecutable": "LiveContainer", + })) + with self.assertRaisesRegex(ValueError, "bundle identifier"): + prepare_host(self.app, self.entitlements) + self.assertFalse((self.app / MARKER).exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/Tests/test_verify_ipa.py b/Tests/test_verify_ipa.py index 2a5315529..6a9a8f4c4 100644 --- a/Tests/test_verify_ipa.py +++ b/Tests/test_verify_ipa.py @@ -6,7 +6,7 @@ import zipfile sys.path.insert(0, str(pathlib.Path(__file__).parents[1] / 'scripts')) -from verify_ipa import verify_frameworks +from verify_ipa import verify_frameworks, verify_host_memory_request class EmbeddedFrameworkTests(unittest.TestCase): @@ -26,6 +26,27 @@ def framework(self, folder, **overrides): return {folder + 'Info.plist': plistlib.dumps(info), folder + 'Runtime': bytes.fromhex('cffaedfe')} + def test_integrated_host_request_is_real_lc_app_not_guest(self): + root = 'Payload/LiveContainer.app/' + info = {'CFBundleIdentifier': 'com.kdt.livecontainer'} + marker = root + 'LCOSIncreasedMemoryRequest.plist' + payload = {'schema': 1, 'requested': True, + 'bundleIdentifier': 'com.kdt.livecontainer'} + with self.archive({marker: plistlib.dumps(payload)}) as archive: + report = verify_host_memory_request(archive, root, info) + self.assertTrue(report['host_requested']) + self.assertFalse(report['apple_profile_granted']) + self.assertFalse(report['installed_memory_entitlement_verified']) + + with self.archive({}) as archive: + with self.assertRaisesRegex(ValueError, 'host lacks Increased'): + verify_host_memory_request(archive, root, info) + + payload['bundleIdentifier'] = 'com.example.guest' + with self.archive({marker: plistlib.dumps(payload)}) as archive: + with self.assertRaisesRegex(ValueError, 'does not match'): + verify_host_memory_request(archive, root, info) + def test_missing_stikjit_plist_reproduces_install_failure(self): folder = 'Payload/App.app/Frameworks/StikJIT.framework/' with self.archive({folder + 'StikJIT': bytes.fromhex('cffaedfe')}) as archive: diff --git a/scripts/prepare_host_memory_request.py b/scripts/prepare_host_memory_request.py new file mode 100644 index 000000000..486641a0f --- /dev/null +++ b/scripts/prepare_host_memory_request.py @@ -0,0 +1,54 @@ +"""Prepare a *host* Increased Memory Limit request for the final integrated LC+ IPA. + +SideStore must use its Apple Developer Portal session and real provisioning +profile to grant the entitlement when the user installs/re-signs LC+. +This file does NOT grant any entitlement, sign the app or allocate memory. +""" +import argparse +import json +import pathlib +import plistlib +import re + +ENTITLEMENT = "com.apple.developer.kernel.increased-memory-limit" +MARKER = "LCOSIncreasedMemoryRequest.plist" + + +def prepare_host(app: pathlib.Path, entitlements: pathlib.Path) -> dict: + app = pathlib.Path(app) + with (app / "Info.plist").open("rb") as source: + info = plistlib.load(source) + with pathlib.Path(entitlements).open("rb") as source: + declared = plistlib.load(source) + + identifier = info.get("CFBundleIdentifier") + executable = info.get("CFBundleExecutable") + if not isinstance(identifier, str) or re.fullmatch( + r"[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z0-9_-]+)+", identifier + ) is None: + raise ValueError("Invalid LC+ bundle identifier; no memory request produced") + if executable != "LiveContainer" or not (app / executable).is_file(): + raise ValueError("Expected the real LC+ host executable") + if declared.get(ENTITLEMENT) is not True: + raise ValueError("LC+ host entitlement was not declared by the Xcode project") + + payload = {"schema": 1, "requested": True, "bundleIdentifier": identifier} + marker = app / MARKER + marker.write_bytes(plistlib.dumps(payload, fmt=plistlib.FMT_XML, sort_keys=True)) + if plistlib.loads(marker.read_bytes()) != payload: + raise ValueError("Host memory request marker verification failed") + return { + "bundle": identifier, + "requested_entitlement": ENTITLEMENT, + "marker": MARKER, + "apple_profile_granted": False, + "installed_signature_verified": False, + } + + +if __name__ == "__main__": + cli = argparse.ArgumentParser() + cli.add_argument("app", type=pathlib.Path) + cli.add_argument("--entitlements", required=True, type=pathlib.Path) + args = cli.parse_args() + print(json.dumps(prepare_host(args.app, args.entitlements), indent=2)) diff --git a/scripts/prepare_sidestore_source.py b/scripts/prepare_sidestore_source.py index 66b8c7f4f..e62f83666 100644 --- a/scripts/prepare_sidestore_source.py +++ b/scripts/prepare_sidestore_source.py @@ -16,7 +16,23 @@ s=operation.read_text(encoding='utf-8') anchor=' let appBundleURL = try await self.prepareAppBundle(for: appBundle, profiles: profiles, appexBundleIds: context.appexBundleIds ?? [:])' assert s.count(anchor)==1 -s=s.replace(anchor, ' let lcosOriginalBundleIdentifier = self.context.bundleIdentifier\n'+anchor+'\n try SigningBundleIdentifiers.validateBundle(at: appBundleURL)\n try LCOSSigningInjection.prepare(at: appBundleURL, bundleIdentifier: lcosOriginalBundleIdentifier)') +s=s.replace(anchor, ''' let lcosOriginalBundleIdentifier = self.context.bundleIdentifier + let lcosMemoryRequested = try SigningIncreasedMemory.requested( + in: appBundle.fileURL, bundleIdentifier: appBundle.bundleIdentifier) +'''+anchor+''' + if lcosMemoryRequested { + // SideStore may add a team suffix/change the final app identity. + // The marker is bound to the original IPA during provisioning; + // rebind it to the *actual* prepared bundle ID before SideSign + // enforces the same request at the final signature step. + guard let prepared = ALTApplication(fileURL: appBundleURL) else { + throw OperationError.invalidApp(reason: "Cannot inspect prepared app for Increased Memory Limit") + } + try SigningIncreasedMemory.writeRequest( + in: appBundleURL, bundleIdentifier: prepared.bundleIdentifier) + } + try SigningBundleIdentifiers.validateBundle(at: appBundleURL) + try LCOSSigningInjection.prepare(at: appBundleURL, bundleIdentifier: lcosOriginalBundleIdentifier)''') anchor=' let newBundleID = appexBundleIds[identifier] ?? profile.bundleIdentifier' assert s.count(anchor)==1 s=s.replace(anchor, ''' if context.useMainProfile, identifier != context.targetBundleIdentifier, appexBundleIds[identifier] == nil { @@ -40,6 +56,12 @@ // explicitly opted-in request is sent to Apple and may be denied. targetFeatures[.increasedMemoryLimit] = "true" SigningDiagnostics.record("memory.capability.requested", appID.bundleIdentifier) + } else if appID.features[.increasedMemoryLimit] == "true", + entitlements[ALTEntitlement.increasedMemoryLimit.rawValue] as? Bool == true { + // Preserve a previously authorized host entitlement when + // refreshing a signed LC+ installation. A consumed one-time + // marker must not cause Apple to disable the capability later. + targetFeatures[.increasedMemoryLimit] = "true" } '''+anchor) diff --git a/scripts/verify_ipa.py b/scripts/verify_ipa.py index 1983ddf1f..8b3303786 100644 --- a/scripts/verify_ipa.py +++ b/scripts/verify_ipa.py @@ -42,7 +42,39 @@ def verify_frameworks(archive): return len(frameworks) -def verify(path, integrated=False, source_commit=None, signing_injection=False, automations=False, builtin_jit=False): + +def verify_host_memory_request(archive, root, info): + """Assert LC+ host will explicitly request Apple capability when re-signed. + + This is preparation evidence; an IPA's unsigned metadata cannot prove that + an actual Apple provisioning profile or installed signature grants memory. + """ + entry = root + "LCOSIncreasedMemoryRequest.plist" + try: + blob = archive.read(entry) + except KeyError as error: + raise ValueError("Integrated LC+ host lacks Increased Memory Limit request") from error + if len(blob) > 4096: + raise ValueError("Host Increased Memory Limit request exceeds size limit") + try: + payload = plistlib.loads(blob) + except (ValueError, plistlib.InvalidFileException) as error: + raise ValueError("Invalid LC+ host memory request plist") from error + if payload != { + "schema": 1, + "requested": True, + "bundleIdentifier": info["CFBundleIdentifier"], + }: + raise ValueError("LC+ host memory request does not match final app identity") + return { + "host_requested": True, + "installed_memory_entitlement_verified": False, + "apple_profile_granted": False, + } + + +def verify(path, integrated=False, source_commit=None, signing_injection=False, automations=False, + builtin_jit=False, host_memory_request=False): path = pathlib.Path(path) if not path.is_file() or path.stat().st_size == 0: raise ValueError('IPA is absent or empty') @@ -84,6 +116,10 @@ def verify(path, integrated=False, source_commit=None, signing_injection=False, raise ValueError('Missing integrated component: ' + suffix) if 'group.com.SideStore.SideStore' not in info.get('ALTAppGroups', []): raise ValueError('Missing SideStore app group declaration') + if host_memory_request: + host_memory_evidence = verify_host_memory_request(archive, root, info) + elif root + "LCOSIncreasedMemoryRequest.plist" in names: + raise ValueError("Standard LC+ IPA unexpectedly requests Extra Memory") if signing_injection: side = root + 'Frameworks/SideStoreApp.framework/' manifest = json.loads(archive.read(side + 'LCOSSigningIntegration.json')) @@ -129,7 +165,8 @@ def verify(path, integrated=False, source_commit=None, signing_injection=False, 'bundle': info['CFBundleIdentifier'], 'signing_injection': signing_injection, 'integrated': integrated, 'entries': len(names), 'frameworks_checked': framework_count, 'source_commit': source_commit, 'automation_metadata': automations, - 'verification': 'ZIP integrity and expected components only', 'device_tested': False} + 'verification': 'ZIP integrity and expected components only', 'device_tested': False, + 'host_memory_request': host_memory_evidence if integrated and host_memory_request else None} if __name__ == '__main__': parser = argparse.ArgumentParser() @@ -138,10 +175,12 @@ def verify(path, integrated=False, source_commit=None, signing_injection=False, parser.add_argument('--signing-injection', action='store_true') parser.add_argument('--automations', action='store_true') parser.add_argument('--builtin-jit', action='store_true') + parser.add_argument('--host-memory-request', action='store_true') parser.add_argument('--output') parser.add_argument('--source-commit') args = parser.parse_args() - evidence = verify(args.ipa, args.integrated, args.source_commit, args.signing_injection, args.automations, args.builtin_jit) + evidence = verify(args.ipa, args.integrated, args.source_commit, args.signing_injection, + args.automations, args.builtin_jit, args.host_memory_request) result = json.dumps(evidence, indent=2) if args.output: pathlib.Path(args.output).write_text(result + '\n', encoding='utf-8')