diff --git a/CHANGELOG.md b/CHANGELOG.md index 93f26adc7..fdfac92ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,31 @@ All notable changes to SideInstaller are documented here. +## Unreleased + +### Added +- **Tools › Pairing imports a pairing file** (#126). The page that generates and exports the + pairing file now has **Import pairing file** too, the same import as under the Install tab's + Advanced section. + +### Fixed +- **SideStore's certificate opens when SideStore sends the wrong password** (#130). SideStore + 0.6.4 sends a certificate it kept from SideStore 0.5.x with the certificate's machine identifier + as the password, while that certificate was written with the empty password, and SideInstaller + turned it down as "MAC tag mismatch". It now also tries the empty password, then the machine + identifiers and serial numbers of the team's certificates, as SideStore does with its own. +- **The certificate SideInstaller itself is signed with is marked** (#133). When Apple won't + issue another certificate, "Which certificate should be revoked?" now marks the one this copy + of SideInstaller was signed with, lists it last, and says that revoking it stops SideInstaller + from opening until it's installed again. Tools › Certificates marks it too. It's read from + SideInstaller's own code signature. +- **The developer disk image downloads when github.com doesn't answer** (#179). JIT and Location + spoofing stopped at "Downloading BuildManifest.plist failed (HTTP 504)"; each file now comes + from raw.githubusercontent.com, then jsDelivr, when github.com fails. +- **An IPA whose files carry setuid or setgid installs** (#119). Its extraction stopped at "Sign + the app" with "Operation not permitted", as iOS refuses those bits in an app's folder. They're + left out now, and a read-only file comes out writable, as signing needs. + ## 2.4.1 ### Fixed diff --git a/ios-app/CertManager.swift b/ios-app/CertManager.swift index 16fd6330f..45bdc20aa 100644 --- a/ios-app/CertManager.swift +++ b/ios-app/CertManager.swift @@ -56,6 +56,15 @@ struct DevCert: Identifiable, Decodable, Equatable { /// The certificate SideInstaller signs with: the only one whose private key /// is on this iPhone, so the only one it can export. var isSigning: Bool { signing == true } + + /// The certificate this copy of SideInstaller was signed with, by whatever + /// installed it: revoking it stops SideInstaller from opening. + var signedSideInstaller: Bool { signedSideInstaller(serials: InstalledSigner.certificateSerials) } + + /// `signedSideInstaller` against the serials of a signature's certificates. + func signedSideInstaller(serials: Set) -> Bool { + !serialNumber.isEmpty && serials.contains(CodeSignature.portalSerial(serialNumber)) + } } /// What `si_cert_import` reports: the team's certificate SideInstaller now signs diff --git a/ios-app/CertsView.swift b/ios-app/CertsView.swift index e0e11aab3..426872b36 100644 --- a/ios-app/CertsView.swift +++ b/ios-app/CertsView.swift @@ -63,7 +63,10 @@ struct CertsView: View { } message: { if let cert = pendingRevoke { Text(L("“%@” will be revoked. Apps already signed with it will stop launching on every device. This can't be undone.", - cert.displayName)) + cert.displayName) + + (cert.signedSideInstaller + ? " " + L("Revoking the certificate SideInstaller itself is signed with stops it from opening too, until it's installed again.") + : "")) } } } @@ -204,6 +207,12 @@ struct CertsView: View { .font(.caption.weight(.medium)) .foregroundStyle(Theme.positive) } + // Revoking this one stops SideInstaller from opening. + if cert.signedSideInstaller { + Label(L("SideInstaller itself is signed with this one"), systemImage: "exclamationmark.shield") + .font(.caption.weight(.medium)) + .foregroundStyle(Theme.warning) + } } Spacer() if cert.isExpired { diff --git a/ios-app/ChineseStrings.swift b/ios-app/ChineseStrings.swift index c5c8b528d..68f211d49 100644 --- a/ios-app/ChineseStrings.swift +++ b/ios-app/ChineseStrings.swift @@ -310,6 +310,7 @@ let chineseStrings: [String: String] = [ "SideInstaller can export only the certificate it signs with, and none of these is it: a certificate's private key stays on the device that asked Apple for it.": "SideInstaller 只能导出它用来签名的证书,而这里没有:证书的私钥只保存在向 Apple 申请它的设备上。", "SideInstaller signs with this one": "SideInstaller 用此证书签名", + "SideInstaller itself is signed with this one": "SideInstaller 本身由此证书签名", // MARK: - SideStore's certificate (sidestore://certificate) @@ -972,6 +973,9 @@ let chineseStrings: [String: String] = [ "Every app already signed with the certificate you pick will stop launching, on every device — including apps installed by AltStore, SideStore, or a computer. This can't be undone. The install retries straight afterwards.": "所有已用你选择的证书签名的 App 都将无法启动,在所有设备上都是如此——包括通过 AltStore、SideStore 或电脑安装的 App。此操作无法撤回。安装会紧接着重试。", " (expired)": "(已过期)", + " (signed SideInstaller)": "(SideInstaller 由它签名)", + "Revoking the certificate SideInstaller itself is signed with stops it from opening too, until it's installed again.": + "吊销 SideInstaller 自身所用的签名证书后,SideInstaller 也将无法打开,直到重新安装。", "Couldn't register this device": "无法注册此设备", "Your Apple ID has hit its limit of registered devices. Free accounts can only register a handful of devices per year and can't remove old ones until the year resets.": diff --git a/ios-app/ContentView.swift b/ios-app/ContentView.swift index 3957866f9..8494895f6 100644 --- a/ios-app/ContentView.swift +++ b/ios-app/ContentView.swift @@ -1352,7 +1352,7 @@ struct InstallPopup: View { .confirmationDialog(L("Which certificate should be revoked?"), isPresented: $showRevokeChooser, titleVisibility: .visible) { - ForEach(certManager.certs) { cert in + ForEach(revokeChoices) { cert in Button(revokeButtonLabel(for: cert), role: .destructive) { certManager.revoke(cert) { engine.log("Retrying the install after revoking \(cert.displayName).") @@ -1364,15 +1364,25 @@ struct InstallPopup: View { } message: { Text(certManager.certs.isEmpty ? L("Apple reports a certificate on this Apple ID, but none came back in the list. It may be a request that's still pending — wait a few minutes and tap Install again.") - : L("Every app already signed with the certificate you pick will stop launching, on every device — including apps installed by AltStore, SideStore, or a computer. This can't be undone. The install retries straight afterwards.")) + : L("Every app already signed with the certificate you pick will stop launching, on every device — including apps installed by AltStore, SideStore, or a computer. This can't be undone. The install retries straight afterwards.") + + (certManager.certs.contains(where: \.signedSideInstaller) + ? " " + L("Revoking the certificate SideInstaller itself is signed with stops it from opening too, until it's installed again.") + : "")) } } - /// Names a certificate in the chooser, with its machine and expiry. + /// The chooser's certificates, the one SideInstaller was signed with last. + private var revokeChoices: [DevCert] { + certManager.certs.filter { !$0.signedSideInstaller } + certManager.certs.filter(\.signedSideInstaller) + } + + /// Names a certificate in the chooser, with its machine and expiry, and + /// marks the one SideInstaller was signed with. private func revokeButtonLabel(for cert: DevCert) -> String { var label = cert.displayName if let machine = cert.machineLabel { label += " — \(machine)" } if cert.isExpired { label += L(" (expired)") } + if cert.signedSideInstaller { label += L(" (signed SideInstaller)") } return label } } diff --git a/ios-app/FrenchStrings.swift b/ios-app/FrenchStrings.swift index 8d1022088..ec1e06341 100644 --- a/ios-app/FrenchStrings.swift +++ b/ios-app/FrenchStrings.swift @@ -317,6 +317,7 @@ let frenchStrings: [String: String] = [ "SideInstaller can export only the certificate it signs with, and none of these is it: a certificate's private key stays on the device that asked Apple for it.": "SideInstaller ne peut exporter que le certificat avec lequel il signe, et aucun de ceux-ci ne l'est : la clé privée d'un certificat reste sur l'appareil qui l'a demandé à Apple.", "SideInstaller signs with this one": "SideInstaller signe avec celui-ci", + "SideInstaller itself is signed with this one": "SideInstaller lui-même est signé avec celui-ci", // MARK: - SideStore's certificate (sidestore://certificate) @@ -1009,6 +1010,9 @@ let frenchStrings: [String: String] = [ "Every app already signed with the certificate you pick will stop launching, on every device — including apps installed by AltStore, SideStore, or a computer. This can't be undone. The install retries straight afterwards.": "Toutes les apps déjà signées avec le certificat choisi cesseront de se lancer, sur tous les appareils — y compris celles installées par AltStore, SideStore ou depuis un ordinateur. C'est irréversible. L'installation reprend juste après.", " (expired)": " (expiré)", + " (signed SideInstaller)": " (a signé SideInstaller)", + "Revoking the certificate SideInstaller itself is signed with stops it from opening too, until it's installed again.": + "Révoquer le certificat avec lequel SideInstaller lui-même est signé l'empêche aussi de s'ouvrir, jusqu'à ce qu'il soit réinstallé.", "Couldn't register this device": "Impossible d'enregistrer cet appareil", "Your Apple ID has hit its limit of registered devices. Free accounts can only register a handful of devices per year and can't remove old ones until the year resets.": diff --git a/ios-app/ItalianStrings.swift b/ios-app/ItalianStrings.swift index b5312f43e..9e4de586d 100644 --- a/ios-app/ItalianStrings.swift +++ b/ios-app/ItalianStrings.swift @@ -316,6 +316,7 @@ let italianStrings: [String: String] = [ "SideInstaller can export only the certificate it signs with, and none of these is it: a certificate's private key stays on the device that asked Apple for it.": "SideInstaller può esportare solo il certificato con cui firma, e nessuno di questi lo è: la chiave privata di un certificato resta sul dispositivo che l'ha chiesto ad Apple.", "SideInstaller signs with this one": "SideInstaller firma con questo", + "SideInstaller itself is signed with this one": "SideInstaller stesso è firmato con questo", // MARK: - SideStore's certificate (sidestore://certificate) @@ -1002,6 +1003,9 @@ let italianStrings: [String: String] = [ "Every app already signed with the certificate you pick will stop launching, on every device — including apps installed by AltStore, SideStore, or a computer. This can't be undone. The install retries straight afterwards.": "Tutte le app già firmate con il certificato che scegli smetteranno di aprirsi, su qualsiasi dispositivo, comprese quelle installate con AltStore, SideStore o da un computer. L'operazione è irreversibile. L'installazione riparte subito dopo.", " (expired)": " (scaduto)", + " (signed SideInstaller)": " (ha firmato SideInstaller)", + "Revoking the certificate SideInstaller itself is signed with stops it from opening too, until it's installed again.": + "Revocare il certificato con cui è firmato SideInstaller stesso impedisce anche a SideInstaller di aprirsi, finché non viene reinstallato.", "Couldn't register this device": "Impossibile registrare questo dispositivo", "Your Apple ID has hit its limit of registered devices. Free accounts can only register a handful of devices per year and can't remove old ones until the year resets.": diff --git a/ios-app/JapaneseStrings.swift b/ios-app/JapaneseStrings.swift index 9ad233e9a..7f80d5510 100644 --- a/ios-app/JapaneseStrings.swift +++ b/ios-app/JapaneseStrings.swift @@ -312,6 +312,7 @@ let japaneseStrings: [String: String] = [ "SideInstaller can export only the certificate it signs with, and none of these is it: a certificate's private key stays on the device that asked Apple for it.": "SideInstaller が書き出せるのは署名に使っている証明書だけですが、この中にはありません。証明書の秘密鍵は、それを Apple に要求したデバイスにしかありません。", "SideInstaller signs with this one": "SideInstaller はこの証明書で署名します", + "SideInstaller itself is signed with this one": "SideInstaller 自体がこの証明書で署名されています", // MARK: - SideStore's certificate (sidestore://certificate) @@ -915,6 +916,9 @@ let japaneseStrings: [String: String] = [ "Every app already signed with the certificate you pick will stop launching, on every device — including apps installed by AltStore, SideStore, or a computer. This can't be undone. The install retries straight afterwards.": "選択した証明書で署名済みのすべてのアプリが、AltStore、SideStore、パソコンでインストールしたものも含め、すべてのデバイスで起動できなくなります。この操作は取り消せません。失効後、インストールは自動的に再試行されます。", " (expired)": "(期限切れ)", + " (signed SideInstaller)": "(SideInstaller の署名に使用)", + "Revoking the certificate SideInstaller itself is signed with stops it from opening too, until it's installed again.": + "SideInstaller 自体の署名に使われている証明書を失効させると、再インストールするまで SideInstaller も開けなくなります。", "Couldn't register this device": "このデバイスを登録できませんでした", "Your Apple ID has hit its limit of registered devices. Free accounts can only register a handful of devices per year and can't remove old ones until the year resets.": diff --git a/ios-app/KoreanStrings.swift b/ios-app/KoreanStrings.swift index 310eb8a59..296216c02 100644 --- a/ios-app/KoreanStrings.swift +++ b/ios-app/KoreanStrings.swift @@ -313,6 +313,7 @@ let koreanStrings: [String: String] = [ "SideInstaller can export only the certificate it signs with, and none of these is it: a certificate's private key stays on the device that asked Apple for it.": "SideInstaller는 서명에 사용하는 인증서만 내보낼 수 있는데, 이 목록에는 해당하는 인증서가 없습니다. 인증서의 개인 키는 Apple에 인증서를 요청한 기기에만 남아 있기 때문입니다.", "SideInstaller signs with this one": "SideInstaller가 이 인증서로 서명합니다", + "SideInstaller itself is signed with this one": "SideInstaller 자체가 이 인증서로 서명되었습니다", // MARK: - SideStore's certificate (sidestore://certificate) @@ -916,6 +917,9 @@ let koreanStrings: [String: String] = [ "Every app already signed with the certificate you pick will stop launching, on every device — including apps installed by AltStore, SideStore, or a computer. This can't be undone. The install retries straight afterwards.": "선택한 인증서로 서명된 모든 앱이 모든 기기에서 실행되지 않게 됩니다. AltStore, SideStore 또는 컴퓨터로 설치한 앱도 포함됩니다. 되돌릴 수 없습니다. 설치는 곧바로 다시 시도됩니다.", " (expired)": " (만료됨)", + " (signed SideInstaller)": " (SideInstaller 서명에 사용됨)", + "Revoking the certificate SideInstaller itself is signed with stops it from opening too, until it's installed again.": + "SideInstaller 자체가 서명된 인증서를 폐기하면 다시 설치할 때까지 SideInstaller도 열리지 않습니다.", "Couldn't register this device": "이 기기를 등록하지 못했습니다", "Your Apple ID has hit its limit of registered devices. Free accounts can only register a handful of devices per year and can't remove old ones until the year resets.": diff --git a/ios-app/LocationView.swift b/ios-app/LocationView.swift index bed1f3f3b..adb01f46e 100644 --- a/ios-app/LocationView.swift +++ b/ios-app/LocationView.swift @@ -116,17 +116,9 @@ enum DeveloperDiskImage { } guard !missing.isEmpty else { progress(1); return } - let baseURL = "https://github.com/doronz88/DeveloperDiskImage/raw/refs/heads/main/PersonalizedImages/\(variant.folder)" for (index, name) in missing.enumerated() { progress(Double(index) / Double(missing.count)) - guard let url = URL(string: "\(baseURL)/\(name)") else { - throw EngineError.message(L("Couldn't build the download URL for %@.", name)) - } - let (tmp, response) = try await URLSession.shared.download(from: url) - guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode) else { - let code = (response as? HTTPURLResponse)?.statusCode ?? 0 - throw EngineError.message(L("Downloading %@ failed (HTTP %d).", name, code)) - } + let tmp = try await download(name, from: sources(of: name, in: variant)) let destination = directory.appendingPathComponent(name) try? FileManager.default.removeItem(at: destination) try FileManager.default.moveItem(at: tmp, to: destination) @@ -134,6 +126,43 @@ enum DeveloperDiskImage { } progress(1) } + + /// Where a file of the mirror is fetched from, in order. github.com hands + /// each file on to raw.githubusercontent.com, so that is tried on its own + /// next; jsDelivr serves the same repository from its CDN (each file is + /// under its 20 MB limit) when GitHub doesn't answer, as with the HTTP 504 + /// in #179. + static func sources(of name: String, in variant: Variant) -> [URL] { + let path = "PersonalizedImages/\(variant.folder)/\(name)" + return [ + "https://github.com/doronz88/DeveloperDiskImage/raw/refs/heads/main/\(path)", + "https://raw.githubusercontent.com/doronz88/DeveloperDiskImage/refs/heads/main/\(path)", + "https://cdn.jsdelivr.net/gh/doronz88/DeveloperDiskImage@main/\(path)", + ].compactMap(URL.init(string:)) + } + + /// Downloads `name` from the first of `urls` that hands it over, to a + /// temporary file the caller moves. When none does, the error is the + /// first one's. + private static func download(_ name: String, from urls: [URL]) async throws -> URL { + var firstError: Error? + for url in urls { + do { + let (tmp, response) = try await URLSession.shared.download(from: url) + guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode) else { + try? FileManager.default.removeItem(at: tmp) + let code = (response as? HTTPURLResponse)?.statusCode ?? 0 + throw EngineError.message(L("Downloading %@ failed (HTTP %d).", name, code)) + } + return tmp + } catch { + if Task.isCancelled { throw CancellationError() } + Engine.shared.log("DDI: \(name) from \(url.host ?? "?") failed: \(error.localizedDescription)") + if firstError == nil { firstError = error } + } + } + throw firstError ?? EngineError.message(L("Couldn't build the download URL for %@.", name)) + } } // MARK: - Saved places diff --git a/ios-app/PairingManager.swift b/ios-app/PairingManager.swift index 0cef63c7d..41684bf47 100644 --- a/ios-app/PairingManager.swift +++ b/ios-app/PairingManager.swift @@ -40,7 +40,9 @@ final class PairingManager: ObservableObject { private var didAutoScan = false /// Any operation in flight, which disables the controls. - var isBusy: Bool { isGenerating || isScanning || isInstallingAll || installingTargetID != nil } + var isBusy: Bool { + isGenerating || isScanning || isInstallingAll || installingTargetID != nil || engine.isImportingPairing + } /// File for the Export share sheet. Prefers the merged file (readable by all /// supported apps), which exists only after a write has built it. @@ -85,6 +87,30 @@ final class PairingManager: ObservableObject { } } + /// Makes a pairing file made elsewhere (idevice_pair, iLoader, another + /// iPhone's export) the one in use, as the Install tab's import does, with + /// this page's popups. + func importFile(from url: URL) { + guard !isBusy, !engine.isRunning else { return } + lastError = nil + lastSuccess = nil + Task { + await engine.importPairingFile(from: url) + refresh() + if let error = engine.lastError { + // Shown here, and not left for the Install tab as well. + engine.lastError = nil + lastError = error + return + } + targets = [] + hasScanned = false + // Allow an auto-scan again for the new pairing file. + didAutoScan = false + lastSuccess = L("Pairing file ready. You can export it or install it into an app below.") + } + } + /// Generates the pairing file for another page that can't go on without /// one (JIT), with the same popups as Generate. That page reports how it /// went. Throws `CancellationError` when the popups are closed. diff --git a/ios-app/PairingView.swift b/ios-app/PairingView.swift index 1198c4f05..d1880cba1 100644 --- a/ios-app/PairingView.swift +++ b/ios-app/PairingView.swift @@ -1,9 +1,10 @@ import SwiftUI import UIKit +import UniformTypeIdentifiers -/// The Pairing page: generate the pairing file, export it, and write it into a -/// supported app installed on this iPhone over the loopback tunnel. Pushed from -/// Tools, whose `NavigationStack` this relies on. +/// The Pairing page: generate or import the pairing file, export it, and write +/// it into a supported app installed on this iPhone over the loopback tunnel. +/// Pushed from Tools, whose `NavigationStack` this relies on. struct PairingView: View { @Environment(Engine.self) private var engine /// Observed so labels redraw when the language changes. @@ -11,6 +12,7 @@ struct PairingView: View { @ObservedObject var manager: PairingManager @State private var showSettings = false + @State private var showImporter = false var body: some View { ScrollView { @@ -34,6 +36,13 @@ struct PairingView: View { .background(AppBackground()) .toolbar { settingsToolbarItem(isPresented: $showSettings) } .sheet(isPresented: $showSettings) { SettingsView() } + .sheet(isPresented: $showImporter) { + FileImporterRepresentableView(allowedContentTypes: UTType.pairingFileTypes) { urls in + guard let url = urls.first else { return } // empty means cancelled + manager.importFile(from: url) + } + .ignoresSafeArea() + } .onAppear { manager.refresh() manager.autoScan() @@ -71,7 +80,7 @@ struct PairingView: View { } } - // MARK: Pairing file (generate + export) + // MARK: Pairing file (generate, import, export) private var pairingFileCard: some View { PanelCard { @@ -95,6 +104,24 @@ struct PairingView: View { .buttonStyle(PrimaryButtonStyle()) .disabled(manager.isBusy || engine.isRunning) + // A file made elsewhere, as under the Install tab's Advanced. + Button { showImporter = true } label: { + HStack(spacing: 8) { + if engine.isImportingPairing { + ProgressView().controlSize(.small) + Text(L("Importing…")) + } else { + Image(systemName: "square.and.arrow.down") + Text(L("Import pairing file")) + } + } + .font(.subheadline.weight(.medium)) + .frame(maxWidth: .infinity) + } + .buttonStyle(SecondaryButtonStyle(), sound: .tap) + .controlSize(.regular) + .disabled(manager.isBusy || engine.isRunning) + if let url = manager.exportURL { ShareLink(item: url) { Label(L("Export pairing file"), systemImage: "square.and.arrow.up") diff --git a/ios-app/PortugueseStrings.swift b/ios-app/PortugueseStrings.swift index 9ef97320a..ab214215e 100644 --- a/ios-app/PortugueseStrings.swift +++ b/ios-app/PortugueseStrings.swift @@ -316,6 +316,7 @@ let portugueseStrings: [String: String] = [ "SideInstaller can export only the certificate it signs with, and none of these is it: a certificate's private key stays on the device that asked Apple for it.": "O SideInstaller só pode exportar o certificado com que assina, e nenhum destes é ele: a chave privada de um certificado fica no dispositivo que o pediu à Apple.", "SideInstaller signs with this one": "O SideInstaller assina com este", + "SideInstaller itself is signed with this one": "O próprio SideInstaller foi assinado com este", // MARK: - SideStore's certificate (sidestore://certificate) @@ -997,6 +998,9 @@ let portugueseStrings: [String: String] = [ "Every app already signed with the certificate you pick will stop launching, on every device — including apps installed by AltStore, SideStore, or a computer. This can't be undone. The install retries straight afterwards.": "Todo app já assinado com o certificado que você escolher vai parar de abrir, em todos os aparelhos — inclusive apps instalados pelo AltStore, pelo SideStore ou por um computador. Isso não pode ser desfeito. A instalação é repetida logo em seguida.", " (expired)": " (expirado)", + " (signed SideInstaller)": " (assinou o SideInstaller)", + "Revoking the certificate SideInstaller itself is signed with stops it from opening too, until it's installed again.": + "Revogar o certificado com que o próprio SideInstaller foi assinado também faz ele parar de abrir, até ser instalado de novo.", "Couldn't register this device": "Não foi possível registrar este dispositivo", "Your Apple ID has hit its limit of registered devices. Free accounts can only register a handful of devices per year and can't remove old ones until the year resets.": diff --git a/ios-app/SigningTeams.swift b/ios-app/SigningTeams.swift index f854201b9..cac2696ea 100644 --- a/ios-app/SigningTeams.swift +++ b/ios-app/SigningTeams.swift @@ -74,6 +74,188 @@ enum InstalledSigner { }() } +// MARK: - The certificate that signed SideInstaller + +extension InstalledSigner { + /// Serial numbers of the certificates in this copy's code signature, as the + /// developer portal writes them: the development certificate SideInstaller + /// was signed with, and Apple's above it, which no team lists. Revoking + /// that certificate stops SideInstaller from opening (`DevCert + /// .signedSideInstaller`). Read from the signature rather than the profile, + /// which names every certificate the team had when it was made. Empty when + /// the signature can't be read, as in the simulator. + static let certificateSerials: Set = { + guard let url = Bundle.main.executableURL, + let data = try? Data(contentsOf: url, options: .alwaysMapped) else { return [] } + return Set(CodeSignature.certificates(inExecutable: data) + .compactMap(CodeSignature.serialNumber(ofCertificate:))) + }() +} + +/// Reads the certificates out of a Mach-O file's code signature: the CMS blob +/// in its `LC_CODE_SIGNATURE` super blob holds the signing certificate and the +/// chain above it. +enum CodeSignature { + /// The DER certificates in the signature of the first slice that has one. + static func certificates(inExecutable data: Data) -> [Data] { + let bytes = Bytes(data: data) + for slice in slices(bytes) { + if let cms = cmsBlob(bytes, slice: slice) { + return certificates(inSignedData: bytes, cms) + } + } + return [] + } + + /// A certificate's serial number the way the developer portal lists it. + static func serialNumber(ofCertificate der: Data) -> String? { + let bytes = Bytes(data: der) + guard let cert = bytes.element(at: 0, end: bytes.count), cert.tag == 0x30, + let tbs = bytes.children(of: cert.content).first, tbs.tag == 0x30, + // A v3 certificate's [0] version comes first. + let serial = bytes.children(of: tbs.content).first(where: { $0.tag == 0x02 }), + !serial.content.isEmpty else { return nil } + return portalSerial(serial.content.map { String(format: "%02X", bytes[$0]) }.joined()) + } + + /// `serial` as the portal writes serials: uppercase hex, no leading zeros. + static func portalSerial(_ serial: String) -> String { + let trimmed = serial.uppercased().drop { $0 == "0" } + return trimmed.isEmpty ? "0" : String(trimmed) + } + + // MARK: Mach-O + + /// A fat file's slices, or the whole of a thin one. + private static func slices(_ bytes: Bytes) -> [Range] { + guard let magic = bytes.uint32(at: 0, bigEndian: true) else { return [] } + guard magic == 0xCAFE_BABE || magic == 0xCAFE_BABF else { return [0..) -> Range? { + let base = slice.lowerBound + let header: Int + switch bytes.uint32(at: base, bigEndian: false) { + case 0xFEED_FACF: header = 32 // MH_MAGIC_64 + case 0xFEED_FACE: header = 28 // MH_MAGIC + default: return nil + } + guard let commands = bytes.uint32(at: base + 16, bigEndian: false) else { return nil } + var at = base + header + for _ in 0..= 8 else { return nil } + if command == 0x1D { // LC_CODE_SIGNATURE + guard let offset = bytes.uint32(at: at + 8, bigEndian: false), + let length = bytes.uint32(at: at + 12, bigEndian: false) else { return nil } + return signatureSlot(bytes, superBlob: base + Int(offset), end: min(base + Int(offset) + Int(length), slice.upperBound)) + } + at += Int(size) + } + return nil + } + + /// The content of the super blob's CMS slot (`CSSLOT_SIGNATURESLOT`), a blob + /// wrapper around the DER signature. + private static func signatureSlot(_ bytes: Bytes, superBlob: Int, end: Int) -> Range? { + guard bytes.uint32(at: superBlob, bigEndian: true) == 0xFADE_0CC0, // CSMAGIC_EMBEDDED_SIGNATURE + let count = bytes.uint32(at: superBlob + 8, bigEndian: true) else { return nil } + for index in 0.. 8, + blob + Int(length) <= end else { return nil } + return blob + 8..) -> [Data] { + guard let info = bytes.element(at: cms.lowerBound, end: cms.upperBound), info.tag == 0x30, + let wrapper = bytes.children(of: info.content).dropFirst().first, wrapper.tag == 0xA0, + let signedData = bytes.children(of: wrapper.content).first, signedData.tag == 0x30, + let certificates = bytes.children(of: signedData.content).first(where: { $0.tag == 0xA0 }) + else { return [] } + return bytes.children(of: certificates.content) + .filter { $0.tag == 0x30 } + .map { bytes.data($0.whole) } + } + + /// `Data` read by offset from its start, with DER elements found by range. + private struct Bytes { + let data: Data + var count: Int { data.count } + + subscript(_ index: Int) -> UInt8 { data[data.startIndex + index] } + + func data(_ range: Range) -> Data { + data.subdata(in: data.startIndex + range.lowerBound.. UInt32? { + guard index >= 0, index <= count - 4 else { return nil } + return (0..<4).reduce(UInt32(0)) { $0 << 8 | UInt32(self[index + (bigEndian ? $1 : 3 - $1)]) } + } + + /// Big-endian, as a fat header writes it. + func uint64(at index: Int) -> UInt64? { + guard index >= 0, index <= count - 8 else { return nil } + return (0..<8).reduce(UInt64(0)) { $0 << 8 | UInt64(self[index + $1]) } + } + + struct Element { + let tag: UInt8 + let content: Range + let whole: Range + } + + /// The DER element at `start`, if it fits before `end`. + func element(at start: Int, end: Int) -> Element? { + guard start >= 0, start + 2 <= end, end <= count else { return nil } + let tag = self[start] + var at = start + 2 + var length = Int(self[start + 1]) + if length >= 0x80 { + // 0x80 alone is BER's indefinite length, which DER doesn't use. + let digits = length & 0x7F + guard (1...4).contains(digits), at + digits <= end else { return nil } + length = (0..) -> [Element] { + var elements: [Element] = [] + var at = range.lowerBound + while at < range.upperBound, let element = element(at: at, end: range.upperBound) { + elements.append(element) + at = element.whole.upperBound + } + return elements + } + } +} + // MARK: - The question /// The team sheet's state: the question it shows, and whose it is. diff --git a/ios-app/SpanishStrings.swift b/ios-app/SpanishStrings.swift index 5f474a547..1ba1b4c7e 100644 --- a/ios-app/SpanishStrings.swift +++ b/ios-app/SpanishStrings.swift @@ -318,6 +318,7 @@ let spanishStrings: [String: String] = [ "SideInstaller can export only the certificate it signs with, and none of these is it: a certificate's private key stays on the device that asked Apple for it.": "SideInstaller solo puede exportar el certificado con el que firma, y ninguno de estos lo es: la clave privada de un certificado se queda en el dispositivo que se lo pidió a Apple.", "SideInstaller signs with this one": "SideInstaller firma con este", + "SideInstaller itself is signed with this one": "El propio SideInstaller está firmado con este", // MARK: - SideStore's certificate (sidestore://certificate) @@ -1005,6 +1006,9 @@ let spanishStrings: [String: String] = [ "Every app already signed with the certificate you pick will stop launching, on every device — including apps installed by AltStore, SideStore, or a computer. This can't be undone. The install retries straight afterwards.": "Todas las apps ya firmadas con el certificado que elijas dejarán de abrirse, en todos los dispositivos, incluidas las instaladas con AltStore, SideStore o desde un ordenador. Esto no se puede deshacer. La instalación se reintenta justo después.", " (expired)": " (caducado)", + " (signed SideInstaller)": " (firmó SideInstaller)", + "Revoking the certificate SideInstaller itself is signed with stops it from opening too, until it's installed again.": + "Revocar el certificado con el que está firmado el propio SideInstaller hace que este tampoco se abra hasta que se vuelva a instalar.", "Couldn't register this device": "No se ha podido registrar este dispositivo", "Your Apple ID has hit its limit of registered devices. Free accounts can only register a handful of devices per year and can't remove old ones until the year resets.": diff --git a/ios-app/TurkishStrings.swift b/ios-app/TurkishStrings.swift index 4b1e17f02..2a20db6c1 100644 --- a/ios-app/TurkishStrings.swift +++ b/ios-app/TurkishStrings.swift @@ -285,6 +285,7 @@ let turkishStrings: [String: String] = [ "SideInstaller can export only the certificate it signs with, and none of these is it: a certificate's private key stays on the device that asked Apple for it.": "SideInstaller yalnızca imzaladığı sertifikayı dışa aktarabilir ve bunların hiçbiri o değil: bir sertifikanın özel anahtarı, Apple'dan onu isteyen cihazda kalır.", "SideInstaller signs with this one": "SideInstaller bununla imzalıyor", + "SideInstaller itself is signed with this one": "SideInstaller'ın kendisi bununla imzalanmış", // MARK: - SideStore's certificate (sidestore://certificate) @@ -890,6 +891,9 @@ let turkishStrings: [String: String] = [ "Every app already signed with the certificate you pick will stop launching, on every device — including apps installed by AltStore, SideStore, or a computer. This can't be undone. The install retries straight afterwards.": "Seçtiğin sertifikayla imzalanmış her uygulama, her cihazda açılmayı bırakır — AltStore, SideStore veya bilgisayarla yüklenenler dahil. Bu geri alınamaz. Yükleme hemen ardından yeniden dener.", " (expired)": " (süresi dolmuş)", + " (signed SideInstaller)": " (SideInstaller'ı imzaladı)", + "Revoking the certificate SideInstaller itself is signed with stops it from opening too, until it's installed again.": + "SideInstaller'ın kendisinin imzalandığı sertifikayı iptal etmek, yeniden yüklenene kadar onun da açılmasını engeller.", "Couldn't register this device": "Bu cihaz kaydedilemedi", "Your Apple ID has hit its limit of registered devices. Free accounts can only register a handful of devices per year and can't remove old ones until the year resets.": "Apple kimliğin kayıtlı cihaz sınırına ulaştı. Ücretsiz hesaplar yılda yalnızca birkaç cihaz kaydedebilir ve yıl sıfırlanana kadar eskileri kaldıramaz.", diff --git a/ios-app/VietnameseStrings.swift b/ios-app/VietnameseStrings.swift index 10aeca066..34e40a8d3 100644 --- a/ios-app/VietnameseStrings.swift +++ b/ios-app/VietnameseStrings.swift @@ -317,6 +317,7 @@ let vietnameseStrings: [String: String] = [ "SideInstaller can export only the certificate it signs with, and none of these is it: a certificate's private key stays on the device that asked Apple for it.": "SideInstaller chỉ có thể xuất chứng chỉ mà nó dùng để ký, và không chứng chỉ nào ở đây là nó: khóa riêng của một chứng chỉ nằm trên thiết bị đã yêu cầu nó từ Apple.", "SideInstaller signs with this one": "SideInstaller ký bằng chứng chỉ này", + "SideInstaller itself is signed with this one": "Chính SideInstaller được ký bằng chứng chỉ này", // MARK: - SideStore's certificate (sidestore://certificate) @@ -1001,6 +1002,9 @@ let vietnameseStrings: [String: String] = [ "Every app already signed with the certificate you pick will stop launching, on every device — including apps installed by AltStore, SideStore, or a computer. This can't be undone. The install retries straight afterwards.": "Mọi ứng dụng đã ký bằng chứng chỉ bạn chọn sẽ không mở được nữa, trên mọi thiết bị — kể cả ứng dụng cài bằng AltStore, SideStore hoặc từ máy tính. Không thể hoàn tác. Quá trình cài đặt sẽ thử lại ngay sau đó.", " (expired)": " (đã hết hạn)", + " (signed SideInstaller)": " (đã ký SideInstaller)", + "Revoking the certificate SideInstaller itself is signed with stops it from opening too, until it's installed again.": + "Thu hồi chứng chỉ đã dùng để ký chính SideInstaller sẽ khiến SideInstaller cũng không mở được nữa, cho đến khi được cài lại.", "Couldn't register this device": "Không thể đăng ký thiết bị này", "Your Apple ID has hit its limit of registered devices. Free accounts can only register a handful of devices per year and can't remove old ones until the year resets.": diff --git a/ios-tests/CodeSignatureTests.swift b/ios-tests/CodeSignatureTests.swift new file mode 100644 index 000000000..ad8ed0514 --- /dev/null +++ b/ios-tests/CodeSignatureTests.swift @@ -0,0 +1,109 @@ +import Foundation +import Testing +@testable import SideInstaller + +/// A PKCS#7 signature of nothing, made with LibreSSL 3.3.6 (`openssl smime +/// -sign -binary -noattr -nodetach -outform DER`) by rust-core's test +/// certificate (testdata/p12/cert.der, serial 5A3C9F01D2E4B6A8): the +/// `ContentInfo { signedData, [0] SignedData { …, [0] certificates } }` a code +/// signature's CMS blob is. +private let signature = Data(base64Encoded: """ +MIIFawYJKoZIhvcNAQcCoIIFXDCCBVgCAQExDzANBglghkgBZQMEAgEFADAPBgkqhkiG9w0BBwGg +AgQAoIIDdzCCA3MwggJbAghaPJ8B0uS2qDANBgkqhkiG9w0BAQsFADB8MRowGAYKCZImiZPyLGQB +AQwKVEVTVDAwMDAwMDEtMCsGA1UEAwwkQXBwbGUgRGV2ZWxvcG1lbnQ6IFRlc3QgKFRFU1QwMDAw +MDApMRMwEQYDVQQLDApURUFNMTIzNDU2MQ0wCwYDVQQKDARUZXN0MQswCQYDVQQGEwJVUzAeFw0y +NjEwMTcxNzU5MTJaFw0zNjEwMTQxNzU5MTJaMHwxGjAYBgoJkiaJk/IsZAEBDApURVNUMDAwMDAw +MS0wKwYDVQQDDCRBcHBsZSBEZXZlbG9wbWVudDogVGVzdCAoVEVTVDAwMDAwMCkxEzARBgNVBAsM +ClRFQU0xMjM0NTYxDTALBgNVBAoMBFRlc3QxCzAJBgNVBAYTAlVTMIIBIjANBgkqhkiG9w0BAQEF +AAOCAQ8AMIIBCgKCAQEAw9zWO90lDD8VPydqimHwUREy1doOKVJo+30L9EujDfd1V44+xPbp4d7Z +0Eamy2T4oRRjduZcCjKGwLezuwMyafl6WdDeHd3IGoM0wM/skJTnB2XVTe+J8XR5Yvs/ifYpNtD5 +Jekd6EKMJTvCxog64S7J7zhuLRzMxlxGjEfQCMUyL2AD23xprrGIsq3Aev7mFq9yXRuOTyZxLozy +C8d2ZqXuD256ZTkJyH56bieo1KaifWo1jLESPN3Th3ozwAmDHZ/oJHtFmOxjVedeqpIwVtX9f3Uw +BFZpu43/RCVmDldI1FDovg57IiQDt0Jus6OeMJE2nVPTAc9Bt8MaQVIAUQIDAQABMA0GCSqGSIb3 +DQEBCwUAA4IBAQCKz27az62lTFd7STpPLCoFUn5kQrTaxRIZJgGzNJ1WPJxPaRFvDvvlDhB/h0kS +uIwv8Q9YFruP8bg6+AKC5ZECSnN1062R5ySvfaoLHcyLFZn8p8f17oa+0TSKWZNisgmw/iMLUJMa +evLuQYFoYQocuqh2+N5yptmwoy8PMLctXbirctxIrsNN/oCAf3KkJMghgwAlQJcJMGLckk8BSm0a +JKvPNwr4TIdEeSyQOk4hVlYAmG2lH8AGTz0zJLBtuHL+4Z6vrm4YpP2+J2PSUZez/FI/DDfOqlJ5 +55SsnqmqbWQeTaBVFxs6kxzc7/XSgjC2YG90v7d/zM54FXdl3BevMYIBtDCCAbACAQEwgYgwfDEa +MBgGCgmSJomT8ixkAQEMClRFU1QwMDAwMDAxLTArBgNVBAMMJEFwcGxlIERldmVsb3BtZW50OiBU +ZXN0IChURVNUMDAwMDAwKTETMBEGA1UECwwKVEVBTTEyMzQ1NjENMAsGA1UECgwEVGVzdDELMAkG +A1UEBhMCVVMCCFo8nwHS5LaoMA0GCWCGSAFlAwQCAQUAMA0GCSqGSIb3DQEBAQUABIIBAAx6Ocxl +k9oPcsURbFezB3vlcTdqC7tjCYGsf8Wc9Xb9ETKY521ebNPQmcT4gSGlY9wm6UrknxDfYImYO6xP +5xnr0puCJ7ehvTBOHWmT/lJAai0WZFY4otHXqJddnLaGX0jlrickkd+pVOjBF1r5BFBcEibVAn69 +iuAUd9/l580amswcEUXaFXg7DmMtC1c+QqnhPnySqzK6jHhDwEfnQjZocPbpUCIfagvbAIrASlC0 +y27Poqv1Bd2wmMDc5zy3Jnb/0BQ5ofMXFd7Wgsr1ZAXebJKFWb/Wdd6zrZ1iVThdVcpR4ANY1r/T +v1EPRFkUr83TcRHb1w94DqGMo76eBEc= +""", options: .ignoreUnknownCharacters)! + +private let serial = "5A3C9F01D2E4B6A8" + +/// Big-endian, as code signature blobs and fat headers are written. +private func be32(_ value: UInt32) -> Data { withUnsafeBytes(of: value.bigEndian) { Data($0) } } +private func le32(_ value: UInt32) -> Data { withUnsafeBytes(of: value.littleEndian) { Data($0) } } + +/// A thin arm64 Mach-O with nothing but an `LC_CODE_SIGNATURE` whose super blob +/// holds a code directory slot and `cms` in the signature slot. +private func machO(cms: Data) -> Data { + let wrapper = be32(0xFADE_0B01) + be32(UInt32(8 + cms.count)) + cms + let directory = be32(0xFADE_0C02) + be32(8) // an empty CodeDirectory + let indexSize = 12 + 2 * 8 + let superBlob = be32(0xFADE_0CC0) + be32(UInt32(indexSize + directory.count + wrapper.count)) + be32(2) + + be32(0) + be32(UInt32(indexSize)) + + be32(0x10000) + be32(UInt32(indexSize + directory.count)) + + directory + wrapper + let headerSize = 32, commandSize = 16 + let dataOffset = UInt32(headerSize + commandSize) + let header = le32(0xFEED_FACF) + le32(0x0100_000C) + le32(0) + le32(2) // MH_EXECUTE + + le32(1) + le32(UInt32(commandSize)) + le32(0) + le32(0) + let command = le32(0x1D) + le32(UInt32(commandSize)) + le32(dataOffset) + le32(UInt32(superBlob.count)) + return header + command + superBlob +} + +@Suite("SideInstaller's own signing certificate") +struct CodeSignatureTests { + + @Test("The certificates come out of a thin Mach-O's code signature") + func thin() throws { + let certificates = CodeSignature.certificates(inExecutable: machO(cms: signature)) + #expect(certificates.count == 1) + #expect(certificates.compactMap(CodeSignature.serialNumber(ofCertificate:)) == [serial]) + } + + @Test("A fat file's first signed slice is read") + func fat() throws { + let slice = machO(cms: signature) + let offset = 4096 + var fat = be32(0xCAFE_BABE) + be32(1) + + be32(0x0100_000C) + be32(0) + be32(UInt32(offset)) + be32(UInt32(slice.count)) + be32(12) + fat += Data(count: offset - fat.count) + fat += slice + let certificates = CodeSignature.certificates(inExecutable: fat) + #expect(certificates.compactMap(CodeSignature.serialNumber(ofCertificate:)) == [serial]) + } + + @Test("A file without a readable signature gives no certificates") + func unreadable() { + #expect(CodeSignature.certificates(inExecutable: Data()).isEmpty) + #expect(CodeSignature.certificates(inExecutable: Data("not a Mach-O".utf8)).isEmpty) + // Ad hoc: a signature slot with no CMS in it. + #expect(CodeSignature.certificates(inExecutable: machO(cms: Data())).isEmpty) + // Cut short. + let whole = machO(cms: signature) + #expect(CodeSignature.certificates(inExecutable: whole.prefix(whole.count - 100)).isEmpty) + } + + @Test("Serials compare as the portal writes them") + func serials() { + #expect(CodeSignature.portalSerial("005a3c9f01d2e4b6a8") == serial) + #expect(CodeSignature.portalSerial("0") == "0") + let cert = { (serial: String) in + DevCert(name: "Apple Development: Test", serialNumber: serial, machineName: "siboot", + machineId: "", certificateId: "ID", platform: "ios", status: "Issued", + expiration: "", signing: nil) + } + #expect(cert("5A3C9F01D2E4B6A8").signedSideInstaller(serials: [serial])) + #expect(cert("05a3c9f01d2e4b6a8").signedSideInstaller(serials: [serial])) + #expect(!cert("6B4D").signedSideInstaller(serials: [serial])) + #expect(!cert("").signedSideInstaller(serials: ["0"])) + } +} diff --git a/rust-core/src/certs.rs b/rust-core/src/certs.rs index 220c29027..9465e3258 100644 --- a/rust-core/src/certs.rs +++ b/rust-core/src/certs.rs @@ -333,7 +333,7 @@ pub unsafe fn cert_import( let password = opt_str(password, ""); let result = catch_unwind(AssertUnwindSafe(|| { - let keys = crate::p12::signing_keys(&data, &password).map_err(|e| (1, e))?; + let keys = archive_keys(session, &data, &password).map_err(|e| (1, e))?; session.rt.block_on(async { for archived in &keys { let found = @@ -389,6 +389,52 @@ pub unsafe fn cert_import( } } +/// The keys in the archive `cert_import` was given, opened with the password +/// that came with it or, when that fails, with the ones SideStore may have +/// written it with (see `p12`): the empty password, then the machine +/// identifier and serial number of each of the team's certificates. The error, +/// when none opens it, is the given password's. +fn archive_keys( + session: &mut CertSession, + data: &[u8], + password: &str, +) -> Result, String> { + let first_error = match crate::p12::signing_keys_trying(data, [password, ""]) { + Ok((keys, used)) => { + if used != password { + tracing::info!("Certs: the archive opened with the empty password, not the one sent with it"); + } + return Ok(keys); + } + Err(e) => e, + }; + let certs = match session.rt.block_on(session.dev.list_ios_certs(&session.team)) { + Ok(certs) => certs, + Err(e) => { + tracing::warn!("Certs: couldn't list certificates to try their passwords: {}", report_text(&e)); + return Err(first_error); + } + }; + let mut others: Vec<&str> = Vec::new(); + for cert in &certs { + for other in [cert.machine_id.as_deref(), cert.serial_number.as_deref()].into_iter().flatten() { + if !other.is_empty() && other != password && !others.contains(&other) { + others.push(other); + } + } + } + match crate::p12::signing_keys_trying(data, others) { + Ok((keys, _)) => { + tracing::info!( + "Certs: the archive opened with a certificate's machine identifier or serial number, \ + not the password sent with it" + ); + Ok(keys) + } + Err(_) => Err(first_error), + } +} + /// Write the certificate with `serial_number` and SideInstaller's private key /// for it to `out_path` as a PKCS#12 archive encrypted with `password`, for /// another app or computer to sign with (see `p12::archive`). diff --git a/rust-core/src/p12.rs b/rust-core/src/p12.rs index 498b122d0..5357122e6 100644 --- a/rust-core/src/p12.rs +++ b/rust-core/src/p12.rs @@ -8,6 +8,13 @@ //! is OpenSSL's: encrypted bags, a MAC, and a `localKeyId` tying the key to its //! certificate. isideload's p12 reader opens the second but skips any key bag //! without a `localKeyId`, so the first is walked here. +//! +//! The password SideStore sends isn't always the one an AltSign archive was +//! written with: AltSign's `ALTCertificate.p12Data()` writes it with the empty +//! password, while SideStore 0.5.x saved the certificate's machine identifier +//! next to it as the password, and that is the one SideStore 0.6.4 sends ("MAC +//! tag mismatch", #130). `signing_keys_trying` takes the passwords to fall back +//! on, as SideStore tries several on an archive of its own. use der::{ asn1::{AnyRef, OctetString}, @@ -92,6 +99,24 @@ pub(crate) fn signing_keys(data: &[u8], password: &str) -> Result( + data: &[u8], + passwords: impl IntoIterator, +) -> Result<(Vec, &'a str), String> { + let mut first_error = None; + for password in passwords { + match signing_keys(data, password) { + Ok(keys) => return Ok((keys, password)), + Err(e) => { + first_error.get_or_insert(e); + } + } + } + Err(first_error.unwrap_or_else(|| "no password to open the archive with".into())) +} + /// Keys in unencrypted key bags, as SideSign writes them. An encrypted safe or /// a shrouded key bag is left for `linked_keys`. fn plain_keys(pfx: &Pfx) -> Result, String> { @@ -178,6 +203,10 @@ mod tests { /// defaults (RC2-40 certificate bag, 3DES key bag, SHA-1 MAC), password /// SERIAL. const OPENSSL: &[u8] = include_bytes!("../testdata/p12/openssl.p12"); + /// What AltSign's `ALTCertificate.p12Data()` writes, `PKCS12_create` with + /// the empty password: `openssl pkcs12 -export -passout pass:` with + /// LibreSSL's defaults. + const ALTSIGN: &[u8] = include_bytes!("../testdata/p12/altsign.p12"); fn expected_key() -> RsaPrivateKey { RsaPrivateKey::from_pkcs8_der(KEY_PKCS8).unwrap() @@ -202,6 +231,32 @@ mod tests { assert!(signing_keys(OPENSSL, "wrong").is_err()); } + /// #130: SideStore 0.6.4 sends a certificate kept from SideStore 0.5.x + /// with its machine identifier as the password, which fails the MAC; the + /// empty password opens it. + #[test] + fn falls_back_on_the_empty_password_for_an_altsign_archive() { + let machine_id = "3A1F2C4B-5D6E-4F70-8192-A3B4C5D6E7F8"; + assert!(signing_keys(ALTSIGN, machine_id).err().unwrap().contains("MAC")); + + let (keys, password) = signing_keys_trying(ALTSIGN, [machine_id, ""]).unwrap(); + assert_the_key(&keys); + assert_eq!(password, ""); + } + + #[test] + fn tries_the_passwords_in_turn_and_reports_the_first_failure() { + let (keys, password) = signing_keys_trying(OPENSSL, ["wrong", "", SERIAL, "unused"]).unwrap(); + assert_the_key(&keys); + assert_eq!(password, SERIAL); + + let first = signing_keys(OPENSSL, "wrong").err().unwrap(); + assert_eq!(signing_keys_trying(OPENSSL, ["wrong", "", "also wrong"]).err().unwrap(), first); + assert!(signing_keys_trying(OPENSSL, []).is_err()); + // An archive that needs no password opens with the first one tried. + assert_eq!(signing_keys_trying(SIDESIGN, ["sent", ""]).unwrap().1, "sent"); + } + /// The archive SideInstaller itself hands SideStore in `Account.sideconf` /// (isideload's `as_p12`: PBES2/AES-256, SHA-256 MAC), in case SideStore /// still holds that one as it was imported. diff --git a/rust-core/testdata/p12/altsign.p12 b/rust-core/testdata/p12/altsign.p12 new file mode 100644 index 000000000..e93cecd90 Binary files /dev/null and b/rust-core/testdata/p12/altsign.p12 differ diff --git a/rust-core/vendor/isideload/README.md b/rust-core/vendor/isideload/README.md index 1e57ac190..6f4e31554 100644 --- a/rust-core/vendor/isideload/README.md +++ b/rust-core/vendor/isideload/README.md @@ -827,6 +827,28 @@ an app given as a folder is left as it is. Tested by `leaves_out_the_watch_app_and_apple_double_files`. Upstream `main` (`a0742ec`, 2026-12-03) still keeps `Watch/`. +**17. `src/sideload/application.rs` — extract an IPA without setuid, setgid or +read-only modes.** + +`Application::new` extracted an IPA with `ZipArchive::extract`, which sets each +file's whole mode from the archive, setuid, setgid and sticky bits included. +iOS refuses those in an app's container: the likeliest cause of "Failed to +extract application archive … i/o error: Operation not permitted (os error 1)" +at "Sign the app" (SideInstaller#119, an imported IPA on an iPad, iOS 27.2), +since the extraction writes only into SideInstaller's own temporary folder and +setting a mode is the step there iOS can refuse. The IPA wasn't attached, so +that is unconfirmed. `extract_archive` now does the extraction: it keeps +only the read, write and execute bits of a file's mode and always lets its owner +read and write it, since signing rewrites files and a read-only one (what a +Windows zip's read-only attribute becomes) would stop it. Directories and links +come out as zip makes them. As zip refuses it, a path that would leave the +folder, by `..` or through a link extracted before it, is refused, now before +anything outside is created. Tested by +`extracts_without_setuid_setgid_or_read_only_modes` and +`refuses_to_write_through_a_link_out_of_the_app`; on the Mac those bits can be +set, so the first checks the modes that come out, not iOS's refusal. Upstream +`main` (`9816691`, 2026-12-05) still calls `extract`. + ## Re-vendoring Upstream's `sign_app` and `install_app` take `increased_memory_limit: bool`, and @@ -853,6 +875,10 @@ LosFarmosCTL ("Load app extensions from both supported directories", open since closed because Dadoum fixed it in the Tangled repository instead; crates.io still has only 0.1.0 (checked 2026-11-09). +A re-vendor has to keep changes 16 and 17, which upstream doesn't have, or apps +with an Apple Watch app, and IPAs whose files carry setuid or setgid, fail to +install again. + A re-vendor has to keep change 15 too, unless upstream gates those uses itself, or `rust-core/Cargo.toml` has to turn `install` back on. Upstream pull request nab138/isideload#33 (opened 2026-11-09 from FrizzleM's fork) does that on top of diff --git a/rust-core/vendor/isideload/src/sideload/application.rs b/rust-core/vendor/isideload/src/sideload/application.rs index f8fb6667d..c0b59df71 100644 --- a/rust-core/vendor/isideload/src/sideload/application.rs +++ b/rust-core/vendor/isideload/src/sideload/application.rs @@ -78,6 +78,93 @@ fn is_apple_double(path: &Path) -> bool { && head == APPLE_DOUBLE } +/// The bits of an entry's mode an extracted file keeps: read, write and +/// execute for its owner, group and others. Its setuid, setgid and sticky bits +/// are left out: iOS refuses them in an app's container, which stopped +/// `ZipArchive::extract` with "Operation not permitted" (SideInstaller#119), +/// and no app needs them. +const KEPT_MODE: u32 = 0o777; + +/// Extracts `archive` into `dir` as `ZipArchive::extract` does, setting only +/// `KEPT_MODE`'s bits of each file's mode, and always letting the owner read +/// and write it: signing rewrites files, and a read-only one (as a Windows +/// zip's read-only attribute comes out) would stop it. zip's own extract sets +/// the whole mode. As there, a path that would leave `dir`, by `..` or through +/// a symbolic link extracted before it, is refused. +fn extract_archive( + archive: &mut ZipArchive, + dir: &Path, +) -> Result<(), Report> { + use std::io::Read; + + let root = dir.canonicalize().context("Failed to find the extraction directory")?; + let mut modes = Vec::new(); + for index in 0..archive.len() { + let mut entry = archive.by_index(index).context("Failed to read the archive's entry")?; + let Some(name) = entry.enclosed_name() else { + bail!(SideloadError::InvalidBundle(format!( + "The archive's entry {} would land outside the app", + entry.name() + ))); + }; + let out = root.join(name); + let parent = out.parent().unwrap_or(&root).to_path_buf(); + if !stays_inside(&root, &parent) { + bail!(SideloadError::InvalidBundle(format!( + "The archive's entry {} goes through a link out of the app", + entry.name() + ))); + } + std::fs::create_dir_all(&parent).context("Failed to create a folder of the app")?; + // A link an earlier entry left under this name would take the write + // elsewhere. + if std::fs::symlink_metadata(&out).is_ok_and(|meta| meta.is_symlink()) { + std::fs::remove_file(&out).context("Failed to replace a link in the app")?; + } + if entry.is_dir() { + std::fs::create_dir_all(&out).context("Failed to create a folder of the app")?; + } else if entry.is_symlink() { + let mut target = String::new(); + entry + .read_to_string(&mut target) + .context("Failed to read a link in the archive")?; + #[cfg(unix)] + std::os::unix::fs::symlink(&target, &out).context("Failed to create a link in the app")?; + // Where links can't be made, the file holds its target, as zip does. + #[cfg(not(unix))] + std::fs::write(&out, target).context("Failed to write a file of the app")?; + } else { + let mut file = File::create(&out).context("Failed to create a file of the app")?; + std::io::copy(&mut entry, &mut file).context("Failed to write a file of the app")?; + if let Some(mode) = entry.unix_mode() { + modes.push((out, mode)); + } + } + } + #[cfg(unix)] + for (path, mode) in modes { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode & KEPT_MODE | 0o600)) + .context("Failed to set a file's permissions")?; + } + Ok(()) +} + +/// True when the deepest part of `path` that exists is inside `root` once its +/// links are followed, so creating the rest of it can't land outside. +fn stays_inside(root: &Path, path: &Path) -> bool { + let mut existing = path; + loop { + if let Ok(real) = existing.canonicalize() { + return real.starts_with(root); + } + match existing.parent() { + Some(parent) => existing = parent, + None => return false, + } + } +} + impl Application { pub fn new(path: PathBuf) -> Result { if !path.exists() { @@ -107,8 +194,7 @@ impl Application { let file = File::open(&path).context("Failed to open application archive")?; let mut archive = ZipArchive::new(file).context("Failed to open application archive")?; - archive - .extract(&temp_path) + extract_archive(&mut archive, &temp_path) .context("Failed to extract application archive")?; let payload_folder = temp_path.join("Payload"); @@ -572,6 +658,105 @@ mod tests { let _ = std::fs::remove_dir_all(&root); } + /// Writes `entries` to an IPA in a new temp directory, then ORs `extra` + /// into the mode the central directory gives the entry named `marked`, + /// which `SimpleFileOptions::unix_permissions` can't set. Returns the + /// directory and the IPA. + fn ipa_with(entries: &[(&str, &[u8], u32)], marked: &str, extra: u32) -> (PathBuf, PathBuf) { + use std::io::Write; + let root = std::env::temp_dir().join(format!("isideload-modes-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&root).unwrap(); + let ipa = root.join("Modes.ipa"); + let mut zip = zip::ZipWriter::new(File::create(&ipa).unwrap()); + for (name, data, mode) in entries { + let options = zip::write::SimpleFileOptions::default().unix_permissions(*mode); + zip.start_file(*name, options).unwrap(); + zip.write_all(data).unwrap(); + } + zip.finish().unwrap(); + + // Central directory header: signature, …, name length at 28, external + // attributes (mode << 16) at 38, name at 46. + let mut bytes = std::fs::read(&ipa).unwrap(); + let mut at = 0; + let mut patched = false; + while let Some(found) = bytes[at..].windows(4).position(|w| w == b"PK\x01\x02") { + let header = at + found; + let name_len = u16::from_le_bytes([bytes[header + 28], bytes[header + 29]]) as usize; + if &bytes[header + 46..header + 46 + name_len] == marked.as_bytes() { + let attrs = u32::from_le_bytes(bytes[header + 38..header + 42].try_into().unwrap()); + bytes[header + 38..header + 42].copy_from_slice(&(attrs | extra << 16).to_le_bytes()); + patched = true; + } + at = header + 4; + } + assert!(patched, "no central directory entry for {marked}"); + std::fs::write(&ipa, bytes).unwrap(); + (root, ipa) + } + + /// SideInstaller issue #119: an IPA whose binary carries setuid and setgid + /// stopped with "Operation not permitted", iOS refusing those bits in the + /// app's container. They're left out now, and a read-only file comes out + /// writable by its owner, as signing needs. + #[test] + fn extracts_without_setuid_setgid_or_read_only_modes() { + use std::os::unix::fs::PermissionsExt; + let info = { + let mut dict = plist::Dictionary::new(); + dict.insert("CFBundleIdentifier".into(), "com.example.t".into()); + let mut out = Vec::new(); + plist::to_writer_xml(&mut out, &dict).unwrap(); + out + }; + let (root, ipa) = ipa_with( + &[ + ("Payload/T.app/Info.plist", &info, 0o644), + ("Payload/T.app/T", b"binary", 0o755), + ("Payload/T.app/ReadOnly.txt", b"text", 0o444), + ], + "Payload/T.app/T", + 0o7000, + ); + let mut archive = zip::ZipArchive::new(File::open(&ipa).unwrap()).unwrap(); + let stored = archive.by_name("Payload/T.app/T").unwrap().unix_mode().unwrap(); + assert_eq!(stored & 0o7777, 0o7755); + drop(archive); + + let app = Application::new(ipa.clone()).unwrap(); + let dir = app.bundle.bundle_dir.clone(); + let mode = |name: &str| std::fs::metadata(dir.join(name)).unwrap().permissions().mode() & 0o7777; + assert_eq!(mode("T"), 0o755); + assert_eq!(mode("ReadOnly.txt"), 0o644); + assert_eq!(mode("Info.plist"), 0o644); + assert_eq!(std::fs::read(dir.join("T")).unwrap(), b"binary"); + let _ = std::fs::remove_dir_all(dir.parent().unwrap().parent().unwrap()); + let _ = std::fs::remove_dir_all(&root); + } + + /// A link in the archive can't take a later entry's write out of the app. + #[test] + fn refuses_to_write_through_a_link_out_of_the_app() { + use std::io::Write; + let root = std::env::temp_dir().join(format!("isideload-link-{}", uuid::Uuid::new_v4())); + let outside = root.join("outside"); + std::fs::create_dir_all(&outside).unwrap(); + let ipa = root.join("Link.ipa"); + let mut zip = zip::ZipWriter::new(File::create(&ipa).unwrap()); + let options = zip::write::SimpleFileOptions::default(); + zip.add_symlink("Payload/T.app/out", outside.to_string_lossy(), options).unwrap(); + // A link that stays inside works as before. + zip.add_symlink("Payload/T.app/Current", "Versions/A", options).unwrap(); + zip.start_file("Payload/T.app/out/Evil/evil.txt", options).unwrap(); + zip.write_all(b"evil").unwrap(); + zip.finish().unwrap(); + + assert!(Application::new(ipa.clone()).is_err()); + assert!(!outside.join("Evil").exists()); + let _ = std::fs::remove_dir_all(std::env::temp_dir().join("Link.ipa_extracted")); + let _ = std::fs::remove_dir_all(&root); + } + /// SideInstaller issue #110: the ExtensionKit extension in Extensions kept /// its bundle ID, which iOS refused as not under the app's new one. #[test]