From c4c52142bc0e752a82b695bf9ca192f5bb189ca8 Mon Sep 17 00:00:00 2001 From: kabiroberai Date: Fri, 17 Jul 2020 04:27:01 +0530 Subject: [PATCH] Create Supercharge Installer, overhaul executable parser Also, - Fix crash when searching in FilesViewController - Make a lot of clang modules - Remove unnecessary CocoaPods dependencies - Fix OpenSSL memory leaks - Fix some provisioning (the dev center kind) bugs - Allow IPAInstaller to accept .app dirs, not just .ipa files --- Supercharge Installer/ConnectionManager.swift | 94 ++++ Supercharge Installer/Installer.swift | 404 ++++++++++++++++++ .../DeveloperServicesAddAppOperation.swift | 6 + .../DeveloperServicesLoginManager.swift | 2 +- .../AnisetteData.swift | 0 .../Anisette/AnisetteDataProvider.swift | 13 + .../Anisette/DeviceInfo+Fetching.swift | 84 ++++ Supersign/GrandSlam/Anisette/DeviceInfo.swift | 92 ++++ .../Anisette/LocalAnisetteDataProviders.swift | 250 +++++++++++ .../Supersette/SupersetteDataProvider.swift | 72 ++++ Supersign/GrandSlam/Crypto/AppTokens.swift | 15 +- Supersign/GrandSlam/Crypto/SRPClient.swift | 26 +- Supersign/GrandSlam/GrandSlamClient.swift | 6 +- .../GrandSlamFetchAppTokensOperation.swift | 2 +- ...ndSlamTwoFactorAuthenticateOperation.swift | 6 +- .../GrandSlamTrustedDeviceRequest.swift | 2 +- .../Requests/GrandSlamOperationRequest.swift | 6 +- Supersign/Installation/AppInstaller.swift | 21 +- Supersign/Installation/Connection.swift | 2 +- Supersign/Installation/HeartbeatHandler.swift | 40 +- Supersign/Installation/IPAInstaller.swift | 19 +- Supersign/Installation/IPAUploader.swift | 50 ++- .../Model/Entitlements/EntitlementTypes.swift | 5 +- Supersign/Signer/SigningContext.swift | 2 +- Supersign/Utilities/SigningInfo.swift | 14 + .../SupersignDeveloperServicesTests.swift | 5 +- .../Tests/SupersignGrandSlamTests.swift | 2 +- .../Tests/SupersignSigningTests.swift | 2 +- .../DeveloperServicesClient+Testing.swift | 20 +- 29 files changed, 1184 insertions(+), 78 deletions(-) create mode 100644 Supercharge Installer/ConnectionManager.swift create mode 100644 Supercharge Installer/Installer.swift rename Supersign/GrandSlam/{Fingerprint => Anisette}/AnisetteData.swift (100%) create mode 100644 Supersign/GrandSlam/Anisette/AnisetteDataProvider.swift create mode 100644 Supersign/GrandSlam/Anisette/DeviceInfo+Fetching.swift create mode 100644 Supersign/GrandSlam/Anisette/DeviceInfo.swift create mode 100644 Supersign/GrandSlam/Anisette/LocalAnisetteDataProviders.swift create mode 100644 Supersign/GrandSlam/Anisette/Supersette/SupersetteDataProvider.swift diff --git a/Supercharge Installer/ConnectionManager.swift b/Supercharge Installer/ConnectionManager.swift new file mode 100644 index 00000000..d23225c6 --- /dev/null +++ b/Supercharge Installer/ConnectionManager.swift @@ -0,0 +1,94 @@ +// +// ConnectionManager.swift +// Supercharge Installer +// +// Created by Kabir Oberai on 19/06/20. +// Copyright © 2020 Kabir Oberai. All rights reserved. +// + +import Foundation +import SwiftyMobileDevice + +protocol ConnectionManagerDelegate: class { + func connectionManager(_ manager: ConnectionManager, clientsDidChangeFrom oldValue: [ConnectionManager.Client]) +} + +class ConnectionManager { + + fileprivate struct ConnectionKey: Hashable, Equatable { + let udid: String + /* let connectionType: USBMux.ConnectionType */ + } + + fileprivate struct ConnectionValue { + let lockdownClient: LockdownClient + let deviceName: String + } + + struct Client { + let udid: String + let deviceName: String + + fileprivate init(key: ConnectionKey, value: ConnectionValue) { + self.udid = key.udid + self.deviceName = value.deviceName + } + + func isEquivalent(to other: Client) -> Bool { + udid == other.udid + } + } + + private var clientsDict: [ConnectionKey: ConnectionValue] = [:] { + didSet { + clientsDidChange() + } + } + + private(set) var clients: [Client] = [] { + didSet { + delegate?.connectionManager(self, clientsDidChangeFrom: oldValue) + } + } + + private var token: USBMux.SubscriptionToken? + + weak var delegate: ConnectionManagerDelegate? + + private func clientsDidChange() { + clients = clientsDict.sorted { $0.0.udid < $1.0.udid }.map(Client.init) + } + + init() throws { + self.token = try USBMux.subscribe { [weak self] event in + guard let self = self else { return } + self.handleEvent(event) + } + } + + private func handleEvent(_ event: USBMux.Event) { + // only handle USB. WiFi won't work because we can't re-pair over wifi afaik + guard event.device.connectionType == .usb else { return } + let udid = event.device.udid + let key = ConnectionKey(udid: udid) + switch event.kind { + case .removed: + clientsDict[key] = nil + case .paired: + return + case .added: + guard let device = try? Device(udid: udid), + let client = try? LockdownClient( + device: device, + label: LockdownClient.installerLabel, + performHandshake: false + ), + let deviceName = try? client.deviceName() + else { return } + clientsDict[key] = ConnectionValue(lockdownClient: client, deviceName: deviceName) + } + } + + deinit { try? token.map(USBMux.unsubscribe(withToken:)) } + +} diff --git a/Supercharge Installer/Installer.swift b/Supercharge Installer/Installer.swift new file mode 100644 index 00000000..3fcc04e9 --- /dev/null +++ b/Supercharge Installer/Installer.swift @@ -0,0 +1,404 @@ +// +// Installer.swift +// Supercharge Installer +// +// Created by Kabir Oberai on 19/06/20. +// Copyright © 2020 Kabir Oberai. All rights reserved. +// + +import Foundation +import Supersign +import SwiftyMobileDevice + +extension LockdownClient { + static let installerLabel = "supersign-installer" +} + +protocol InstallerDelegate: class { + func fetchCode(completion: @escaping (String?) -> Void) + func fetchTeam(fromTeams teams: [DeveloperServicesTeam], completion: @escaping (DeveloperServicesTeam?) -> Void) + func presentMessage(_ message: Installer.Message) + func dismissMessage() + func installerDidUpdate(toStage stage: String, progress: Double?) + func installerDidComplete(withResult result: Result<(), Error>) + + /// Decompress the zipped ipa file + /// + /// - Parameter ipa: The `ipa` file to decompress. + /// - Parameter directory: The directory into which `ipa` should be decompressed. + /// - Parameter progress: A closure to which the callee can provide progress updates. + /// - Parameter currentProgress: The current progress, or `nil` to indicate it is indeterminate. + /// - Parameter completion: A completion handler to call once decompression is finished. + /// - Parameter success: Whether or not extraction was successful. + func decompress( + ipa: URL, + in directory: URL, + progress: @escaping (_ currentProgress: Double?) -> Void, + completion: @escaping (_ success: Bool) -> Void + ) + + /// An opportunity for delegates to compress the app before installation. + /// + /// - Parameter payloadDir: The `Payload` directory which is to be compressed. + /// - Parameter progress: A closure to which the callee can provide progress updates. + /// - Parameter currentProgress: The current progress, or `nil` to indicate it is indeterminate. + /// - Parameter completion: A completion handler to call with the compressed file's URL. + /// - Parameter url: The URL of the compressed file. The caller is responsible for cleaning this + /// up once installation is complete. Pass `nil` to skip compression. + /// + /// - Note: The default implementation of this function simply calls `completion` with a + /// `nil` value for `url`. + func compressIfNeeded( + payloadDir: URL, + progress: @escaping (_ currentProgress: Double?) -> Void, + completion: @escaping (_ url: URL?) -> Void + ) +} + +extension InstallerDelegate { + func compressIfNeeded( + payloadDir: URL, + progress: @escaping (Double?) -> Void, + completion: @escaping (URL?) -> Void + ) { + completion(nil) + } +} + +final class Installer { + + enum Error: Swift.Error { + case alreadyInstalling + case deviceInfoFetchFailed + case noTeamFound + case userCancelled + case appExtractionFailed + case appCorrupted + case appPackagingFailed + } + + enum Message { + case pairDevice + case unlockDevice + } + + let udid: String + let appleID: String + let password: String + weak var delegate: InstallerDelegate? + + private var appInstaller: AppInstaller? + + private let tempDir = FileManager.default.temporaryDirectoryShim + .appendingPathComponent("com.kabiroberai.Supercharge-Installer.Staging") + private let installQueue = + DispatchQueue(label: "com.kabiroberai.Supercharge-Installer.install-queue", qos: .userInitiated, attributes: []) + + private enum ExecutionState { + case running + case complete + } + + private var executionStateLock = NSLock() + private var executionState: ExecutionState = .running + + private func shouldContinue() -> Bool { + executionStateLock.lock() + defer { executionStateLock.unlock() } + switch executionState { + case .running: + return true + case .complete: + return false + } + } + + private func completion(_ result: Result<(), Swift.Error>) { + executionStateLock.lock() + defer { executionStateLock.unlock() } + guard executionState != .complete else { return } + try? FileManager.default.removeItem(at: tempDir) + executionState = .complete + delegate?.installerDidComplete(withResult: result) + delegate = nil + } + + func cancel() { + completion(.failure(Error.userCancelled)) + } + + private var stage: String? + private func updateStage(to stage: String, ignoreCancellation: Bool = false) -> Bool { + guard ignoreCancellation || shouldContinue() else { return false } + self.stage = stage + delegate?.installerDidUpdate(toStage: stage, progress: 0) + return true + } + private func updateProgress(to progress: Double?, ignoreCancellation: Bool = false) -> Bool { + guard ignoreCancellation || shouldContinue() else { return false } + guard let stage = stage else { + preconditionFailure("Cannot change progress without setting stage at least once") + } + delegate?.installerDidUpdate(toStage: stage, progress: progress) + return true + } + + init( + udid: String, + appleID: String, + password: String, + delegate: InstallerDelegate + ) { + self.udid = udid + self.appleID = appleID + self.password = password + self.delegate = delegate + } + + private func performWithRecovery(hasPrompted: Bool = false, block: () throws -> T) throws -> T { + guard shouldContinue() else { throw Error.userCancelled } + + func recurse(_ message: Installer.Message) throws -> T { + if !hasPrompted { delegate?.presentMessage(message) } + // allow some time before recursing (even if TCO, we should probably not overdo it) + Thread.sleep(forTimeInterval: 0.5) + return try performWithRecovery(hasPrompted: true, block: block) + } + + do { + let result = try block() + if hasPrompted { delegate?.dismissMessage() } + return result + } catch let error as LockdownClient.Error where error == .pairingDialogResponsePending { + return try recurse(.pairDevice) + } catch let error as LockdownClient.Error where error == .passwordProtected { + return try recurse(.unlockDevice) + } catch { + if hasPrompted { delegate?.dismissMessage() } + throw error + } + } + + private func fetchPairingKeys() throws -> Data? { + let device = try Device(udid: udid) + + guard updateProgress(to: 1/3) else { return nil } + + // we can't reuse any previously created client because we need to perform a handshake this time + let lockdownClient = try performWithRecovery { + try LockdownClient(device: device, label: LockdownClient.installerLabel, performHandshake: true) + } + + try lockdownClient.setValue(udid, forDomain: "com.apple.mobile.wireless_lockdown", key: "WirelessBuddyID") + try lockdownClient.setValue(true, forDomain: "com.apple.mobile.wireless_lockdown", key: "EnableWifiConnections") + + guard updateProgress(to: 2/3) else { return nil } + + // now create a new pair record, temporarily removing the existing one. This is necessary + // because if two machines try accessing lockdown with the same device wirelessly, it'll + // fail during the heartbeat + let oldRecord = try USBMux.pairRecord(forUDID: udid) + try USBMux.deletePairRecord(forUDID: udid) + defer { try? USBMux.savePairRecord(oldRecord, forUDID: udid) } + + try performWithRecovery { try lockdownClient.pair() } + return try USBMux.pairRecord(forUDID: udid) + } + + private func install( + deviceInfo: DeviceInfo, + token: DeveloperServicesLoginToken, + client: DeveloperServicesClient, + team: DeveloperServicesTeam, + possiblyCompressedApp: URL + ) { + guard shouldContinue() else { return } + executionStateLock.lock() + defer { executionStateLock.unlock() } + let appInstaller = AppInstaller(app: possiblyCompressedApp, udid: udid, pairingKeys: ()) + self.appInstaller = appInstaller + appInstaller.install( + progress: { stage in + _ = self.updateStage(to: stage.displayName, ignoreCancellation: true) + _ = self.updateProgress(to: stage.displayProgress, ignoreCancellation: true) + }, + completion: completion + ) + } + + private func packageAndInstall( + deviceInfo: DeviceInfo, + token: DeveloperServicesLoginToken, + client: DeveloperServicesClient, + team: DeveloperServicesTeam, + appDir: URL + ) { + guard self.updateStage(to: "Packaging app"), + self.updateProgress(to: nil) + else { return } + + delegate?.compressIfNeeded( + payloadDir: appDir.deletingLastPathComponent(), + progress: { progress in + _ = self.updateProgress(to: progress, ignoreCancellation: true) + }, + completion: { url in + self.installQueue.async { + self.install( + deviceInfo: deviceInfo, + token: token, + client: client, + team: team, + possiblyCompressedApp: url ?? appDir + ) + } + } + ) + } + + private func install( + deviceInfo: DeviceInfo, + token: DeveloperServicesLoginToken, + client: DeveloperServicesClient, + team: DeveloperServicesTeam, + appDir: URL + ) { + guard self.updateStage(to: "Preparing device") else { return } + + do { + guard let pairingKeys = try fetchPairingKeys() + else { return } // nil: user cancelled + try Superconfig( + udid: udid, + pairingKeys: pairingKeys, + deviceInfo: deviceInfo, + preferredTeamID: team.id.rawValue, + appleID: appleID, + token: token + ).save(inAppDir: appDir) + } catch { + return completion(.failure(error)) + } + + let context: SigningContext + do { + context = try SigningContext( + udid: udid, + teamID: team.id, + client: client, + signingInfoManager: MemoryBackedSigningInfoManager(), + platform: .iOS + ) + } catch { + return completion(.failure(error)) + } + let signer = Signer(context: context) + signer.sign( + app: appDir, + status: { status in + _ = self.updateStage(to: status, ignoreCancellation: true) + }, + progress: { progress in + _ = self.updateProgress(to: progress, ignoreCancellation: true) + }, completion: { result in + guard result.get(withErrorHandler: self.completion) != nil else { return } + self.packageAndInstall( + deviceInfo: deviceInfo, + token: token, + client: client, + team: team, + appDir: appDir + ) + } + ) + } + + private func install(deviceInfo: DeviceInfo, token: DeveloperServicesLoginToken, appDir: URL) { + let client = DeveloperServicesClient(loginToken: token, deviceInfo: deviceInfo) + client.send(DeveloperServicesListTeamsRequest()) { result in + guard let teams = result.get(withErrorHandler: self.completion) else { return } + guard self.updateProgress(to: 1) else { return } + switch teams.count { + case 0: + return self.completion(.failure(Error.noTeamFound)) + case 1: + self.install(deviceInfo: deviceInfo, token: token, client: client, team: teams[0], appDir: appDir) + default: + self.delegate?.fetchTeam(fromTeams: teams) { team in + self.installQueue.async { + guard let team = team else { return self.completion(.failure(Error.userCancelled)) } + self.install(deviceInfo: deviceInfo, token: token, client: client, team: team, appDir: appDir) + } + } + } + } + } + + private func install(decompressionDidSucceed: Bool) { + let payload = self.tempDir.appendingPathComponent("Payload") + guard decompressionDidSucceed, + let appDir = payload.implicitContents.first(where: { $0.pathExtension == "app" }) + else { return self.completion(.failure(Error.appExtractionFailed)) } + + guard let deviceInfo = DeviceInfo.current() else { + return completion(.failure(Error.deviceInfoFetchFailed)) + } + + guard updateStage(to: "Logging in") else { return } + DeveloperServicesLoginManager(deviceInfo: deviceInfo).logIn( + withUsername: self.appleID, + password: self.password, + twoFactorDelegate: self + ) { result in + guard let token = result.get(withErrorHandler: self.completion) else { return } + guard self.updateProgress(to: 1/2) else { return } + self.install(deviceInfo: deviceInfo, token: token, appDir: appDir) + } + } + + private func installOnQueue() { + guard self.updateStage(to: "Unpacking app") else { return } + + let ipa = Bundle.main.url(forResource: "Supercharge", withExtension: "ipa")! + if FileManager.default.fileExists(atPath: tempDir.path) { + try? FileManager.default.removeItem(at: tempDir) + } + + do { + try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true) + } catch { + return completion(.failure(error)) + } + + delegate?.decompress( + ipa: ipa, + in: tempDir, + progress: { progress in + _ = self.updateProgress(to: progress, ignoreCancellation: true) + }, + completion: { success in + guard self.shouldContinue() else { return self.completion(.failure(Error.userCancelled)) } + self.installQueue.async { + self.install(decompressionDidSucceed: success) + } + } + ) + } + + func install() { + installQueue.async { + self.installOnQueue() + } + } + +} + +extension Installer: TwoFactorAuthDelegate { + func fetchCode(completion: @escaping (String?) -> Void) { + delegate?.fetchCode { code in + self.installQueue.async { + completion(code) + } + } + } +} diff --git a/Supersign/DeveloperServices/App IDs/DeveloperServicesAddAppOperation.swift b/Supersign/DeveloperServices/App IDs/DeveloperServicesAddAppOperation.swift index 6ebbf470..be4015fd 100644 --- a/Supersign/DeveloperServices/App IDs/DeveloperServicesAddAppOperation.swift +++ b/Supersign/DeveloperServices/App IDs/DeveloperServicesAddAppOperation.swift @@ -125,6 +125,12 @@ public struct DeveloperServicesAddAppOperation: DeveloperServicesOperation { do { try entitlements.update(teamID: self.context.teamID, bundleID: appID.bundleID) + // set get-task-allow to YES, required for dev certs + try entitlements.updateEntitlements { ents in + ents.firstIndex { $0 is GetTaskAllowEntitlement }.map { idx in + ents[idx] = GetTaskAllowEntitlement(rawValue: true) + } + } } catch { return completion(.failure(error)) } diff --git a/Supersign/DeveloperServices/DeveloperServicesLoginManager.swift b/Supersign/DeveloperServices/DeveloperServicesLoginManager.swift index c12818a4..f3e6d6f1 100644 --- a/Supersign/DeveloperServices/DeveloperServicesLoginManager.swift +++ b/Supersign/DeveloperServices/DeveloperServicesLoginManager.swift @@ -35,7 +35,7 @@ public struct DeveloperServicesLoginManager { customAnisetteProvider: AnisetteDataProvider? = nil ) { self.deviceInfo = deviceInfo - self.anisetteProvider = customAnisetteProvider ?? ComputedAnisetteDataProvider(deviceInfo: deviceInfo) + self.anisetteProvider = customAnisetteProvider ?? SupersetteDataProvider(deviceInfo: deviceInfo) self.client = GrandSlamClient(deviceInfo: deviceInfo, customAnisetteDataProvider: anisetteProvider) } diff --git a/Supersign/GrandSlam/Fingerprint/AnisetteData.swift b/Supersign/GrandSlam/Anisette/AnisetteData.swift similarity index 100% rename from Supersign/GrandSlam/Fingerprint/AnisetteData.swift rename to Supersign/GrandSlam/Anisette/AnisetteData.swift diff --git a/Supersign/GrandSlam/Anisette/AnisetteDataProvider.swift b/Supersign/GrandSlam/Anisette/AnisetteDataProvider.swift new file mode 100644 index 00000000..ae708da9 --- /dev/null +++ b/Supersign/GrandSlam/Anisette/AnisetteDataProvider.swift @@ -0,0 +1,13 @@ +// +// AnisetteDataProvider.swift +// Supersign +// +// Created by Kabir Oberai on 19/11/19. +// Copyright © 2019 Kabir Oberai. All rights reserved. +// + +import Foundation + +public protocol AnisetteDataProvider { + func fetchAnisetteData(completion: @escaping (Result) -> Void) +} diff --git a/Supersign/GrandSlam/Anisette/DeviceInfo+Fetching.swift b/Supersign/GrandSlam/Anisette/DeviceInfo+Fetching.swift new file mode 100644 index 00000000..036e3df3 --- /dev/null +++ b/Supersign/GrandSlam/Anisette/DeviceInfo+Fetching.swift @@ -0,0 +1,84 @@ +// +// DeviceInfo+Fetching.swift +// Supersign +// +// Created by Kabir Oberai on 18/06/20. +// Copyright © 2020 Kabir Oberai. All rights reserved. +// + +import Foundation + +#if os(macOS) +extension DeviceInfo { + + private static func fetchDeviceID() -> String? { + var waitTime = timespec(tv_sec: 0, tv_nsec: 0) // wait indefinitely + let bytes = [UInt8](unsafeUninitializedCapacity: MemoryLayout.size) { buf, count in + count = (gethostuuid(buf.baseAddress!, &waitTime) == 0) ? buf.count : 0 + } + guard !bytes.isEmpty else { return nil } + return bytes.withUnsafeBufferPointer { buf in + UUID(uuid: UnsafeRawPointer(buf.baseAddress!).load(as: uuid_t.self)).uuidString + } + } + + private static func hardwareProperty(forKey key: String) -> Data? { + let entry = IORegistryEntryFromPath(kIOMasterPortDefault, "IODeviceTree:/options") + guard entry != 0 else { return nil } + defer { IOObjectRelease(entry) } + + return IORegistryEntryCreateCFProperty( + entry, key as CFString, kCFAllocatorDefault, 0 + )?.takeRetainedValue() as? Data + } + + private static func fetchROMAddress() -> String? { + hardwareProperty(forKey: "4D1EDE05-38C7-4a6a-9CC6-4BCCA8B38C14:ROM")? + .map { String(format: "%02hhx", $0) } + .joined() + } + + private static func fetchMLBSerialNumber() -> String? { + hardwareProperty(forKey: "4D1EDE05-38C7-4a6a-9CC6-4BCCA8B38C14:MLB")? + .map { String(format: isprint(Int32($0)) != 0 ? "%c" : "%02hhx", $0) } + .joined() + } + + private static func fetchSerialNumber() -> String? { + let service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice")) + guard service != 0 else { return nil } + defer { IOObjectRelease(service) } + return IORegistryEntryCreateCFProperty( + service, "IOPlatformSerialNumber" as CFString, kCFAllocatorDefault, 0 + )?.takeRetainedValue() as? String + } + + private static func fetchHardwareModel() -> String? { + var modelSize = 0 + guard sysctlbyname("hw.model", nil, &modelSize, nil, 0) == 0 else { return nil } + guard let rawString = malloc(modelSize) else { return nil } + guard sysctlbyname("hw.model", rawString, &modelSize, nil, 0) == 0 else { + free(rawString) + return nil + } + return String(bytesNoCopy: rawString, length: modelSize - 1, encoding: .utf8, freeWhenDone: true) + } + + public static func current() -> DeviceInfo? { + guard let deviceID = fetchDeviceID(), + let romAddress = fetchROMAddress(), + let mlbSerialNumber = fetchMLBSerialNumber(), + let serialNumber = fetchSerialNumber(), + let modelID = fetchHardwareModel() + else { return nil } + return DeviceInfo( + deviceID: deviceID, + romAddress: romAddress, + mlbSerialNumber: mlbSerialNumber, + serialNumber: serialNumber, + modelID: modelID + ) + } + +} +#endif diff --git a/Supersign/GrandSlam/Anisette/DeviceInfo.swift b/Supersign/GrandSlam/Anisette/DeviceInfo.swift new file mode 100644 index 00000000..d63b7aec --- /dev/null +++ b/Supersign/GrandSlam/Anisette/DeviceInfo.swift @@ -0,0 +1,92 @@ +// +// DeviceInfo.swift +// Supersign +// +// Created by Kabir Oberai on 19/11/19. +// Copyright © 2019 Kabir Oberai. All rights reserved. +// + +import Foundation + +public struct DeviceInfo: Codable { + + /// `X-Xcode-Version` + static let xcodeVersionKey = "X-Xcode-Version" + /// Not included in `dictionary` + public static let xcodeVersion = "11.2 (11B41)" + + public struct ClientInfo: Codable { + public static let macOSVersion = "10.14.6" + public static let macOSBuild = "18G103" + + public static let authKitVersion = "1" + public static let akdVersion = "1.0" + public static let cfNetworkVersion = "978.0.7" + public static let darwinVersion = "18.7.0" + + public let modelID: String // e.g. MacBookPro11,5 + + // TODO: Do we need to replace com.apple.akd with com.apple.dt.Xcode? See AltStore + var clientString: String { + """ + <\(modelID)> \ + + """ + } + + var userAgent: String { + "akd/\(Self.akdVersion) CFNetwork/\(Self.cfNetworkVersion) Darwin/\(Self.darwinVersion)" + } + + public init(modelID: String) { + self.modelID = modelID + } + } + + /// `X-Mme-Device-Id` + static let deviceIDKey = "X-Mme-Device-Id" + public let deviceID: String + + /// `X-Apple-I-ROM` + static let romAddressKey = "X-Apple-I-ROM" + public let romAddress: String + + /// `X-Apple-I-MLB` + static let mlbSerialNumberKey = "X-Apple-I-MLB" + /// main logic board serial number + public let mlbSerialNumber: String + + /// `X-Apple-I-SRL-NO` + static let serialNumberKey = "X-Apple-I-SRL-NO" + public let serialNumber: String + + public let modelID: String + + /// `X-MMe-Client-Info` + static let clientInfoKey = "X-MMe-Client-Info" + public var clientInfo: ClientInfo { .init(modelID: modelID) } + + public init( + deviceID: String, + romAddress: String, + mlbSerialNumber: String, + serialNumber: String, + modelID: String + ) { + self.deviceID = deviceID + self.romAddress = romAddress + self.mlbSerialNumber = mlbSerialNumber + self.serialNumber = serialNumber + self.modelID = modelID + } + + var dictionary: [String: String] { + [ + Self.deviceIDKey: deviceID, + Self.romAddressKey: romAddress, + Self.mlbSerialNumberKey: mlbSerialNumber, + Self.serialNumberKey: serialNumber + ] + } + +} diff --git a/Supersign/GrandSlam/Anisette/LocalAnisetteDataProviders.swift b/Supersign/GrandSlam/Anisette/LocalAnisetteDataProviders.swift new file mode 100644 index 00000000..cabae3c8 --- /dev/null +++ b/Supersign/GrandSlam/Anisette/LocalAnisetteDataProviders.swift @@ -0,0 +1,250 @@ +// +// LocalAnisetteDataProviders.swift +// Supersign +// +// Created by Kabir Oberai on 29/06/20. +// Copyright © 2020 Kabir Oberai. All rights reserved. +// + +import Foundation + +/// Creates a socket connected to `ip` on `port`. +/// +/// - Returns: A connected socket file descriptor, or `nil` if +/// the connection failed. The caller is responsible for closing +/// the returned file descriptor. +private func connect(toIP ip: String, port: UInt16) -> Int32? { + var addr = sockaddr_in() + addr.sin_family = .init(AF_INET) + addr.sin_port = CFSwapInt16HostToBig(port) + addr.sin_addr.s_addr = inet_addr(ip) + + // we can't do this inside withUnsafePointer due to memory exclusivity rules + let addrSize = MemoryLayout.size(ofValue: addr) + + let socketFd = socket(AF_INET, SOCK_STREAM, 0) + guard socketFd != -1 else { return nil } + guard withUnsafePointer(to: &addr, { + connect( + socketFd, + UnsafeRawPointer($0).assumingMemoryBound(to: sockaddr.self), + .init(addrSize) + ) + }) == 0 else { return nil } + + return socketFd +} + +public class NetcatAnisetteDataProvider: AnisetteDataProvider { + + private struct RawAnisetteData { + let machineID: String + let localUserID: String + let routingInfo: String + let oneTimePassword: String + } + + private class ConnectionInfo { + let socketFd: Int32 + let machineID: String + let localUserID: String + let routingInfo: String + let firstOTP: String + + init(socketFd: Int32, machineID: String, localUserID: String, routingInfo: String, firstOTP: String) { + self.socketFd = socketFd + self.machineID = machineID + self.localUserID = localUserID + self.routingInfo = routingInfo + self.firstOTP = firstOTP + } + + deinit { close(socketFd) } + } + + public enum Error: Swift.Error { + /// The user is probably not running anisettehelperd on the host machine + case helperUnreachable + case invalidAnisetteData + case networkError(errno: Int32) + } + + public let ip: String + public let port: UInt16 + public let deviceInfo: DeviceInfo + private var _connectionInfo: ConnectionInfo? + private var hasUsedFirstOTP = false + + public init(ip: String, port: UInt16, deviceInfo: DeviceInfo) { + self.ip = ip + self.port = port + self.deviceInfo = deviceInfo + } + + public convenience init(localPort port: UInt16, deviceInfo: DeviceInfo) { + self.init(ip: "0.0.0.0", port: port, deviceInfo: deviceInfo) + } + + private func readAll(fromSocket sock: Int32) throws -> Data { + let capacity = 1024 + let buf = UnsafeMutablePointer.allocate(capacity: capacity) + defer { buf.deallocate() } + var data = Data() + while true { + let count = recv(sock, buf, capacity, 0) + guard count != -1 else { + throw Error.networkError(errno: errno) + } + data.append(buf, count: count) + if count < capacity { + break + } + } + return data + } + + private func connectionInfo() throws -> ConnectionInfo { + if let connectionInfo = _connectionInfo { return connectionInfo } + + guard let socketFd = connect(toIP: ip, port: port) else { throw Error.helperUnreachable } + + let id = deviceInfo.deviceID + write(socketFd, id, strlen(id) + 1) // include null + let clientInfo = deviceInfo.clientInfo.clientString + write(socketFd, clientInfo, strlen(clientInfo) + 1) + + let initialData = try readAll(fromSocket: socketFd) + guard let string = String(data: initialData, encoding: .utf8) + else { throw Error.invalidAnisetteData } + + let components = string.split(separator: "\r\n") + guard components.count == 4 else { throw Error.invalidAnisetteData } + + let connectionInfo = ConnectionInfo( + socketFd: socketFd, + machineID: String(components[0]), + localUserID: String(components[1]), + routingInfo: String(components[2]), + firstOTP: String(components[3]) + ) + _connectionInfo = connectionInfo + return connectionInfo + } + + private func rawAnisetteData() throws -> RawAnisetteData { + let info = try connectionInfo() + if !hasUsedFirstOTP { + return RawAnisetteData( + machineID: info.machineID, + localUserID: info.localUserID, + routingInfo: info.routingInfo, + oneTimePassword: info.firstOTP + ) + } + + write(info.socketFd, "a\n", 3) + let response = try readAll(fromSocket: info.socketFd) + guard let otp = String(data: response, encoding: .utf8) + else { throw Error.invalidAnisetteData } + return RawAnisetteData( + machineID: info.machineID, + localUserID: info.localUserID, + routingInfo: info.routingInfo, + oneTimePassword: otp + ) + } + + public func fetchAnisetteData(completion: @escaping (Result) -> Void) { + let time = Date() + + let raw: RawAnisetteData + let routingInfo: UInt64 + do { + raw = try rawAnisetteData() + guard let rinfo = UInt64(raw.routingInfo) + else { throw Error.invalidAnisetteData } + routingInfo = rinfo + } catch { + return completion(.failure(error)) + } + + let anisette = AnisetteData( + clientTime: time, + routingInfo: routingInfo, + machineID: raw.machineID, + localUserID: raw.localUserID, + oneTimePassword: raw.oneTimePassword + ) + + completion(.success(anisette)) + } + +} + +/// Provides Anisette Data by making a request to a TCP server +public class TCPAnisetteDataProvider: AnisetteDataProvider { + + public enum Error: Swift.Error { + /// The user is probably not running anisettehelperd on the host machine + case helperUnreachable + case invalidAnisetteData + } + + public let ip: String + public let port: UInt16 + + public init(ip: String, port: UInt16) { + self.ip = ip + self.port = port + } + + public convenience init(localPort port: UInt16) { + self.init(ip: "0.0.0.0", port: port) + } + + private func rawAnisetteData() throws -> Data { + guard let socketFd = connect(toIP: ip, port: port) else { throw Error.helperUnreachable } + + let capacity = 1024 + let buf = UnsafeMutablePointer.allocate(capacity: capacity) + defer { buf.deallocate() } + var data = Data() + while true { + let count = recv(socketFd, buf, capacity, 0) + // swiftlint:disable:next empty_count + guard count != 0 else { break } + data.append(buf, count: count) + } + + return data + } + + public func fetchAnisetteData(completion: @escaping (Result) -> Void) { + let time = Date() + + let rawDeserialized: Any + do { + let raw = try rawAnisetteData() + rawDeserialized = try PropertyListSerialization.propertyList(from: raw, format: nil) + } catch { + return completion(.failure(error)) + } + + guard let data = rawDeserialized as? [String: Any], + let rinfoString = data[AnisetteData.routingInfoKey] as? String, + let rinfo = UInt64(rinfoString), + let machineID = data[AnisetteData.machineIDKey] as? String, + let localUserID = data[AnisetteData.localUserIDKey] as? String, + let oneTimePassword = data[AnisetteData.oneTimePasswordKey] as? String + else { return completion(.failure(Error.invalidAnisetteData)) } + + completion(.success(AnisetteData( + clientTime: time, + routingInfo: rinfo, + machineID: machineID, + localUserID: localUserID, + oneTimePassword: oneTimePassword + ))) + } + +} diff --git a/Supersign/GrandSlam/Anisette/Supersette/SupersetteDataProvider.swift b/Supersign/GrandSlam/Anisette/Supersette/SupersetteDataProvider.swift new file mode 100644 index 00000000..f63d18d6 --- /dev/null +++ b/Supersign/GrandSlam/Anisette/Supersette/SupersetteDataProvider.swift @@ -0,0 +1,72 @@ +// +// SupersetteDataProvider.swift +// Supersign +// +// Created by Kabir Oberai on 14/06/20. +// Copyright © 2020 Kabir Oberai. All rights reserved. +// + +import Foundation + +public class SupersetteDataProvider: AnisetteDataProvider { + + private static let gateway = URL(string: "https://anisette.supercharge.app:8443/v1/generate")! + + private static let encoder = JSONEncoder() + private static let decoder = JSONDecoder() + + public enum Error: Swift.Error { + case networkError + case invalidAnisetteData + } + + public let deviceInfo: DeviceInfo + + public init(deviceInfo: DeviceInfo) { + self.deviceInfo = deviceInfo + } + + private struct AnisetteRequestBody: Encodable { + let deviceID: String + let clientInfo: String + } + + private struct AnisetteResponse: Decodable { + let routingInfo: UInt64 + let machineID: String + let localUserID: String + let oneTimePassword: String + } + + public func fetchAnisetteData(completion: @escaping (Result) -> Void) { + let clientTime = Date() + var request = URLRequest(url: Self.gateway) + request.httpMethod = "POST" + request.addValue("application/json", forHTTPHeaderField: "Content-Type") + request.addValue("application/json", forHTTPHeaderField: "Accept") + request.addValue("BF95B548-3C87-4BBD-8B96-534421368416", forHTTPHeaderField: "Superpass") + do { + request.httpBody = try Self.encoder.encode(AnisetteRequestBody( + deviceID: deviceInfo.deviceID, + clientInfo: deviceInfo.clientInfo.clientString + )) + } catch { + return completion(.failure(error)) + } + URLSession.shared.dataTask(with: request) { data, _, error in + completion(Result { + if let error = error { throw error } + let data = try data.orThrow(Error.invalidAnisetteData) + let anisetteResponse = try Self.decoder.decode(AnisetteResponse.self, from: data) + return AnisetteData( + clientTime: clientTime, + routingInfo: anisetteResponse.routingInfo, + machineID: anisetteResponse.machineID, + localUserID: anisetteResponse.localUserID, + oneTimePassword: anisetteResponse.oneTimePassword + ) + }) + }.resume() + } + +} diff --git a/Supersign/GrandSlam/Crypto/AppTokens.swift b/Supersign/GrandSlam/Crypto/AppTokens.swift index b5d66ab3..74fa7e91 100644 --- a/Supersign/GrandSlam/Crypto/AppTokens.swift +++ b/Supersign/GrandSlam/Crypto/AppTokens.swift @@ -11,30 +11,27 @@ import Foundation enum AppTokens { static func checksum(withSK sk: Data, adsid: String, apps: [String]) -> Data { - sk.withUnsafeBytes { buf in - let bound = buf.bindMemory(to: Int8.self) + sk.withUnsafeBytes { skBuf in let ptrArray = apps.map { strdup($0)! } defer { ptrArray.forEach { free($0) } } let immutablePtrArray = ptrArray.map { UnsafePointer($0) } - return immutablePtrArray.withUnsafeBufferPointer { buf in + return immutablePtrArray.withUnsafeBufferPointer { ptrBuf in var length = 0 let bytes = app_tokens_create_checksum( - bound.baseAddress!, bound.count, adsid, buf.baseAddress!, buf.count, &length + skBuf.baseAddress!, skBuf.count, adsid, ptrBuf.baseAddress!, ptrBuf.count, &length ) return Data(bytesNoCopy: bytes, count: length, deallocator: .free) } } } - static func decrypt(gcm: Data, sk: Data) -> Data? { + static func decrypt(gcm: Data, withSK sk: Data) -> Data? { gcm.withUnsafeBytes { gcmBuf in sk.withUnsafeBytes { skBuf in - let gcmBound = gcmBuf.bindMemory(to: Int8.self) - let skBound = skBuf.bindMemory(to: Int8.self) var length = 0 return app_tokens_decrypt_gcm( - gcmBound.baseAddress!, gcmBound.count, - skBound.baseAddress!, skBound.count, + gcmBuf.baseAddress!, gcmBuf.count, + skBuf.baseAddress!, skBuf.count, &length ).map { Data(bytesNoCopy: $0, count: length, deallocator: .free) } } diff --git a/Supersign/GrandSlam/Crypto/SRPClient.swift b/Supersign/GrandSlam/Crypto/SRPClient.swift index 4f3cbeb3..34c628b1 100644 --- a/Supersign/GrandSlam/Crypto/SRPClient.swift +++ b/Supersign/GrandSlam/Crypto/SRPClient.swift @@ -20,17 +20,13 @@ class SRPClient { } func add(data: Data) { - data.withUnsafeBytes { buf in - let bound = buf.bindMemory(to: Int8.self) - srp_client_add_data(raw, bound.baseAddress!, bound.count) - } + data.withUnsafeBytes { srp_client_add_data(raw, $0.baseAddress!, $0.count) } } func decrypt(cbc: Data) -> Data? { cbc.withUnsafeBytes { buf in - let bound = buf.bindMemory(to: Int8.self) var length = 0 - return srp_client_decrypt_cbc(raw, bound.baseAddress!, bound.count, &length) + return srp_client_decrypt_cbc(raw, buf.baseAddress!, buf.count, &length) .map { Data(bytesNoCopy: $0, count: length, deallocator: .free) } } } @@ -52,16 +48,14 @@ class SRPClient { ) -> Data? { salt.withUnsafeBytes { saltBuf in key.withUnsafeBytes { keyBuf in - let saltBound = saltBuf.bindMemory(to: Int8.self) - let keyBound = keyBuf.bindMemory(to: Int8.self) var length = 0 return srp_client_process_challenge( raw, username, password, - saltBound.baseAddress!, saltBound.count, + saltBuf.baseAddress!, saltBuf.count, .init(iterations), - keyBound.baseAddress!, - keyBound.count, + keyBuf.baseAddress!, + keyBuf.count, isS2K, &length ).map { Data(bytesNoCopy: $0, count: length, deallocator: .free) } @@ -70,17 +64,11 @@ class SRPClient { } func verify(hamk: Data) -> Bool { - hamk.withUnsafeBytes { buf in - let bound = buf.bindMemory(to: Int8.self) - return srp_client_verify_session_HAMK(raw, bound.baseAddress!, bound.count) - } + hamk.withUnsafeBytes { srp_client_verify_session_HAMK(raw, $0.baseAddress!, $0.count) } } func verify(negProto: Data) -> Bool { - negProto.withUnsafeBytes { buf in - let bound = buf.bindMemory(to: Int8.self) - return srp_client_verify_neg_proto(raw, bound.baseAddress!, bound.count) - } + negProto.withUnsafeBytes { srp_client_verify_neg_proto(raw, $0.baseAddress!, $0.count) } } } diff --git a/Supersign/GrandSlam/GrandSlamClient.swift b/Supersign/GrandSlam/GrandSlamClient.swift index b8d37aae..d5294009 100644 --- a/Supersign/GrandSlam/GrandSlamClient.swift +++ b/Supersign/GrandSlam/GrandSlamClient.swift @@ -22,7 +22,7 @@ class GrandSlamClient { ) { self.deviceInfo = deviceInfo self.anisetteDataProvider = customAnisetteDataProvider - ?? ComputedAnisetteDataProvider(deviceInfo: deviceInfo) + ?? SupersetteDataProvider(deviceInfo: deviceInfo) self.lookupManager = .init(deviceInfo: deviceInfo) } @@ -52,8 +52,8 @@ class GrandSlamClient { } request.configure(request: &urlRequest, deviceInfo: deviceInfo, anisetteData: anisetteData) - URLSession.shared.dataTask(with: urlRequest) { data, response, error in - print(response.map(String.init(describing:)) ?? "NO RESPONSE") + URLSession.shared.dataTask(with: urlRequest) { data, _, error in +// print(response.map(String.init(describing:)) ?? "NO RESPONSE") if let error = error { return completion(.failure(error)) } diff --git a/Supersign/GrandSlam/Operations/GrandSlamFetchAppTokensOperation.swift b/Supersign/GrandSlam/Operations/GrandSlamFetchAppTokensOperation.swift index 70527177..80e0b20f 100644 --- a/Supersign/GrandSlam/Operations/GrandSlamFetchAppTokensOperation.swift +++ b/Supersign/GrandSlam/Operations/GrandSlamFetchAppTokensOperation.swift @@ -61,7 +61,7 @@ class GrandSlamFetchAppTokensOperation { response: GrandSlamAppTokensRequest.Decoder.Value, completion: @escaping (Result<[AppTokenKey: Token], Swift.Error>) -> Void ) { - guard let decrypted = AppTokens.decrypt(gcm: response.encryptedToken, sk: self.loginData.sk) + guard let decrypted = AppTokens.decrypt(gcm: response.encryptedToken, withSK: loginData.sk) else { return completion(.failure(Error.invalidResponse)) } completion(Result { let pairs = try decoder diff --git a/Supersign/GrandSlam/Operations/GrandSlamTwoFactorAuthenticateOperation.swift b/Supersign/GrandSlam/Operations/GrandSlamTwoFactorAuthenticateOperation.swift index ea6401b2..b95f8cfe 100644 --- a/Supersign/GrandSlam/Operations/GrandSlamTwoFactorAuthenticateOperation.swift +++ b/Supersign/GrandSlam/Operations/GrandSlamTwoFactorAuthenticateOperation.swift @@ -9,13 +9,14 @@ import Foundation public protocol TwoFactorAuthDelegate: class { - func fetchCode(completion: @escaping (String) -> Void) + func fetchCode(completion: @escaping (String?) -> Void) } class GrandSlamTwoFactorAuthenticateOperation { enum Error: Swift.Error { case incorrectVerificationCode + case userCancelled } let client: GrandSlamClient @@ -42,7 +43,8 @@ class GrandSlamTwoFactorAuthenticateOperation { } } - private func validate(code: String, completion: @escaping (Result<(), Swift.Error>) -> Void) { + private func validate(code: String?, completion: @escaping (Result<(), Swift.Error>) -> Void) { + guard let code = code else { return completion(.failure(Error.userCancelled)) } let request = GrandSlamValidateRequest(loginData: loginData, verificationCode: code) client.send(request) { result in switch result { diff --git a/Supersign/GrandSlam/Requests/Concrete/GrandSlamTrustedDeviceRequest.swift b/Supersign/GrandSlam/Requests/Concrete/GrandSlamTrustedDeviceRequest.swift index 4efc6f43..36121d61 100644 --- a/Supersign/GrandSlam/Requests/Concrete/GrandSlamTrustedDeviceRequest.swift +++ b/Supersign/GrandSlam/Requests/Concrete/GrandSlamTrustedDeviceRequest.swift @@ -21,7 +21,7 @@ struct GrandSlamTrustedDeviceRequest: GrandSlamTwoFactorRequest { struct GrandSlamSecondaryAuthRequest: GrandSlamTwoFactorRequest { struct Decoder: GrandSlamDataDecoder { static func decode(data: Data) throws { - print(String(data: data, encoding: .utf8) ?? "NO DATA") +// print(String(data: data, encoding: .utf8) ?? "NO DATA") } } diff --git a/Supersign/GrandSlam/Requests/GrandSlamOperationRequest.swift b/Supersign/GrandSlam/Requests/GrandSlamOperationRequest.swift index 96cd0e5f..d30b7e75 100644 --- a/Supersign/GrandSlam/Requests/GrandSlamOperationRequest.swift +++ b/Supersign/GrandSlam/Requests/GrandSlamOperationRequest.swift @@ -8,9 +8,13 @@ import Foundation -struct GrandSlamOperationError: Error { +struct GrandSlamOperationError: Error, LocalizedError { let code: Int let message: String + + var errorDescription: String? { + "\(message) (\(code))" + } } struct GrandSlamOperationResponseStatusWrapper: Decodable { diff --git a/Supersign/Installation/AppInstaller.swift b/Supersign/Installation/AppInstaller.swift index c0ef14e4..fdb727d9 100644 --- a/Supersign/Installation/AppInstaller.swift +++ b/Supersign/Installation/AppInstaller.swift @@ -86,26 +86,19 @@ public class AppInstaller { } } - public let ipa: URL - public let bundleID: String + public let app: URL public let udid: String - public let pairingKeys: Data + public let pairingKeys: PairingKeys public init( - ipa: URL, - bundleID: String, + app: URL, udid: String, - pairingKeys: Data + pairingKeys: PairingKeys ) { - self.ipa = ipa - self.bundleID = bundleID + self.app = app self.udid = udid self.pairingKeys = pairingKeys } - #warning("We should have some sort of `static` queue/lock") - // because if two connections are attempted simultaneously, - // the heartbeat will fail. - // synchronous private func installSync( progress: @escaping (Stage) -> Void @@ -132,14 +125,14 @@ public class AppInstaller { try cancelPoint() - let uploaded = try uploader.upload(ipa: ipa, withBundleID: bundleID) { currentProgress in + let uploaded = try uploader.upload(app: app) { currentProgress in progress(.uploading(currentProgress)) } defer { uploaded.delete() } try cancelPoint() - try installer.install(uploaded: uploaded, bundleID: bundleID) { currentProgress in + try installer.install(uploaded: uploaded) { currentProgress in progress(.installing(currentProgress.details, currentProgress.progress)) } } diff --git a/Supersign/Installation/Connection.swift b/Supersign/Installation/Connection.swift index 28ef7311..0e21cbc6 100644 --- a/Supersign/Installation/Connection.swift +++ b/Supersign/Installation/Connection.swift @@ -20,7 +20,7 @@ public class Connection { public let client: LockdownClient private let heartbeatHandler: HeartbeatHandler - public init(udid: String, pairingKeys: Data, progress: (Double) -> Void) throws { + public init(udid: String, pairingKeys: PairingKeys, progress: (Double) -> Void) throws { progress(0/4) usbmuxHandler = try USBMuxHandler(udid: udid, pairingKeys: pairingKeys) diff --git a/Supersign/Installation/HeartbeatHandler.swift b/Supersign/Installation/HeartbeatHandler.swift index 795a05dc..723d1d2b 100644 --- a/Supersign/Installation/HeartbeatHandler.swift +++ b/Supersign/Installation/HeartbeatHandler.swift @@ -9,6 +9,21 @@ import Foundation import SwiftyMobileDevice +#warning("We should have a shared heartbeat internally") +// because otherwise if two connections are attempted simultaneously, +// the concurrent heartbeats will fail. Basically, let the interface +// continue to look like you have multiple HeartbeatHandlers, but +// internally maintain a refcount to a shared structure that maintains +// a common heartbeat while the refcount > 0. +// +// Or maybe take the abstraction up a layer to `Connection`, or somehow +// put it in USBMuxHandler? Since in fact that probably needs to be +// common too. In fact both of those things seem to basically be what +// the usbmuxd daemon does, so maybe refactor them into a single +// USBMuxDaemonShim or something, which internally has a single connection +// for each device. Alternatively, refactor `Connection` to behave like that? + +#if os(iOS) public class HeartbeatHandler { private struct Error: Swift.Error {} @@ -50,10 +65,11 @@ public class HeartbeatHandler { private let heartbeatQueue = DispatchQueue( label: "com.kabiroberai.Supersign.heartbeat-queue" ) - public private(set) var isStopped = false + private let stopLock = NSLock() + private var isStopped = false - public let device: Device - public let client: LockdownClient + private let device: Device + private let client: LockdownClient public init(device: Device, client: LockdownClient) { self.device = device self.client = client @@ -92,10 +108,18 @@ public class HeartbeatHandler { for iteration in 0... { // only retains `self` for this iteration. This way, if the reference to // the handler is dropped, the heartbeat stops - guard let self = self, !self.isStopped else { break } + guard let self = self else { break } + + do { + self.stopLock.lock() + defer { self.stopLock.unlock() } + guard !self.isStopped else { break } + } + do { try self.beat(client: heartbeatClient, iteration: iteration) } catch { + print("Heartbeat failed: \(error)") // dispatching async should prevent stack overflows. // We return to break out of the current loop. return self.heartbeatQueue.asyncAfter(deadline: .now() + Self.restartInterval) { @@ -107,7 +131,15 @@ public class HeartbeatHandler { } public func stop() { + stopLock.lock() + defer { stopLock.unlock() } isStopped = true } } +#else +public class HeartbeatHandler { + public init(device: Device, client: LockdownClient) {} + public func stop() {} +} +#endif diff --git a/Supersign/Installation/IPAInstaller.swift b/Supersign/Installation/IPAInstaller.swift index 591aac37..a8817cae 100644 --- a/Supersign/Installation/IPAInstaller.swift +++ b/Supersign/Installation/IPAInstaller.swift @@ -18,20 +18,21 @@ public class IPAInstaller { public func install( uploaded: IPAUploader.UploadedIPA, - bundleID: String, progress: @escaping (InstallationProxyClient.InstallProgress) -> Void ) throws { - let options = InstallationProxyClient.Options(additionalOptions: ["CFBundleIdentifier": bundleID]) - - var error: Error? + var result: Result<(), Error>? let semaphore = DispatchSemaphore(value: 0) - client.install(package: uploaded.location, options: options, progress: progress) { result in - defer { semaphore.signal() } - if case let .failure(e) = result { error = e } - } + client.install( + package: uploaded.location, + progress: progress, + completion: { res in + defer { semaphore.signal() } + result = res + } + ) semaphore.wait() - if let error = error { throw error } + try result!.get() } } diff --git a/Supersign/Installation/IPAUploader.swift b/Supersign/Installation/IPAUploader.swift index de50822a..12c9d6d7 100644 --- a/Supersign/Installation/IPAUploader.swift +++ b/Supersign/Installation/IPAUploader.swift @@ -11,6 +11,10 @@ import SwiftyMobileDevice public final class IPAUploader { + public enum Error: Swift.Error { + case unexpectedSymlink(at: URL) + } + private static let packagePath = URL(fileURLWithPath: "PublicStaging") private static let bufferSize = 1 << 20 // 1 MB @@ -27,7 +31,7 @@ public final class IPAUploader { deinit { delete() } public func delete() { guard !isDeleted else { return } - try? uploader.client.removeItem(at: location) + try? uploader.client.removeItemAndContents(at: location) } } @@ -36,7 +40,25 @@ public final class IPAUploader { self.client = try connection.startClient() } - private func upload(_ src: URL, to dest: URL, progress: (Double) -> Void) throws { + private func uploadSymlink(_ src: URL, to dest: URL, progress: (Double) -> Void) throws { + let symlinkDest = try FileManager.default.destinationOfSymbolicLink(atPath: src.path) + try client.linkItem(at: URL(fileURLWithPath: symlinkDest), to: dest, type: .symlink) + } + + private func uploadDir(_ src: URL, to dest: URL, progress: (Double) -> Void) throws { + try client.createDirectory(at: dest) + let contents = try src.contents() + let numFiles = contents.count + let progressPerFile = 1 / Double(numFiles) + var baseProgress: Double = 0 + for file in contents { + let fileDest = dest.appendingPathComponent(file.lastPathComponent) + try upload(file, to: fileDest) { progress(baseProgress + $0 * progressPerFile) } + baseProgress += progressPerFile + } + } + + private func uploadFile(_ src: URL, to dest: URL, progress: (Double) -> Void) throws { let srcData = try Data(contentsOf: src) let size = srcData.count let sizeDouble = Double(size) @@ -59,13 +81,31 @@ public final class IPAUploader { } } - public func upload(ipa: URL, withBundleID bundleID: String, progress: (Double) -> Void) throws -> UploadedIPA { + private func upload(_ src: URL, to dest: URL, allowSymlinks: Bool = true, progress: (Double) -> Void) throws { + progress(0) + let resources = try src.resourceValues(forKeys: [.isSymbolicLinkKey, .isDirectoryKey]) + if resources.isSymbolicLink == true { + guard allowSymlinks else { throw Error.unexpectedSymlink(at: src) } + try uploadSymlink(src, to: dest, progress: progress) + } else if resources.isDirectory == true { + try uploadDir(src, to: dest, progress: progress) + } else { + try uploadFile(src, to: dest, progress: progress) + } + progress(1) + } + + public func upload(app: URL, progress: (Double) -> Void) throws -> UploadedIPA { if try !client.fileExists(at: Self.packagePath) { try client.createDirectory(at: Self.packagePath) } - let dest = Self.packagePath.appendingPathComponent(bundleID) - try upload(ipa, to: dest, progress: progress) + let dest = Self.packagePath.appendingPathComponent("Supercharge-App") + if try client.fileExists(at: dest) { + try client.removeItemAndContents(at: dest) + } + + try upload(app, to: dest, allowSymlinks: false, progress: progress) return UploadedIPA(uploader: self, location: dest) } diff --git a/Supersign/Model/Entitlements/EntitlementTypes.swift b/Supersign/Model/Entitlements/EntitlementTypes.swift index 4d937437..d1055bcd 100644 --- a/Supersign/Model/Entitlements/EntitlementTypes.swift +++ b/Supersign/Model/Entitlements/EntitlementTypes.swift @@ -66,7 +66,10 @@ public struct KeychainAccessGroupsEntitlement: Entitlement, RawRepresentable { public struct AppGroupEntitlement: Entitlement, RawRepresentable { public static let identifier = "com.apple.security.application-groups" - public static let isFree = true + #warning("Enable app groups on free accounts") + // but first we need to fix the bug where it only assigns one + // app group even if the ents say there are multiple + public static let isFree = false public var rawValue: [DeveloperServicesAppGroup.GroupID] public init(rawValue: [DeveloperServicesAppGroup.GroupID]) { self.rawValue = rawValue } diff --git a/Supersign/Signer/SigningContext.swift b/Supersign/Signer/SigningContext.swift index 2f902963..13b16f1c 100644 --- a/Supersign/Signer/SigningContext.swift +++ b/Supersign/Signer/SigningContext.swift @@ -45,7 +45,7 @@ extension SigningContext { #elseif canImport(UIKit) return UIDevice.current.name #elseif os(macOS) - return Host.current.localizedName ?? "Mac" + return Host.current().localizedName ?? "Mac" #else return "Supercharge Client" #endif diff --git a/Supersign/Utilities/SigningInfo.swift b/Supersign/Utilities/SigningInfo.swift index f3b4313d..e342bf9d 100644 --- a/Supersign/Utilities/SigningInfo.swift +++ b/Supersign/Utilities/SigningInfo.swift @@ -29,6 +29,20 @@ extension SigningInfoManager { } } +public class MemoryBackedSigningInfoManager: SigningInfoManager { + private var infos: [String: SigningInfo] = [:] + + public init() {} + + public func info(forTeamID teamID: DeveloperServicesTeam.ID) throws -> SigningInfo? { + infos[teamID.rawValue] + } + + public func setInfo(_ info: SigningInfo?, forTeamID teamID: DeveloperServicesTeam.ID) throws { + infos[teamID.rawValue] = info + } +} + public struct KeyValueSigningInfoManager: SigningInfoManager { private enum KeyType: String { case certificate diff --git a/SupersignTests/Tests/SupersignDeveloperServicesTests.swift b/SupersignTests/Tests/SupersignDeveloperServicesTests.swift index de5ad87b..375925ff 100644 --- a/SupersignTests/Tests/SupersignDeveloperServicesTests.swift +++ b/SupersignTests/Tests/SupersignDeveloperServicesTests.swift @@ -36,11 +36,12 @@ class SupersignDeveloperServicesTests: XCTestCase { udid: Config.current.udid, teamID: team.id, client: client, - signingInfoManager: TestSigningInfoManager() + signingInfoManager: MemoryBackedSigningInfoManager() )) let waiter = ResultWaiter(description: "Failed to provision") - DeveloperServicesProvisioningOperation(context: context, app: source).perform(completion: waiter.completion) + DeveloperServicesProvisioningOperation(context: context, app: source) { _ in } + .perform(completion: waiter.completion) let response = try XCTTry(waiter.wait(timeout: 10000)) print(response) diff --git a/SupersignTests/Tests/SupersignGrandSlamTests.swift b/SupersignTests/Tests/SupersignGrandSlamTests.swift index 01aee357..45176351 100644 --- a/SupersignTests/Tests/SupersignGrandSlamTests.swift +++ b/SupersignTests/Tests/SupersignGrandSlamTests.swift @@ -10,7 +10,7 @@ import XCTest @testable import Supersign class TwoFactorAuthenticator: TwoFactorAuthDelegate { - func fetchCode(completion: @escaping (String) -> Void) { + func fetchCode(completion: @escaping (String?) -> Void) { print("Code: ", terminator: "") completion(readLine() ?? "") } diff --git a/SupersignTests/Tests/SupersignSigningTests.swift b/SupersignTests/Tests/SupersignSigningTests.swift index ed774f66..4d0db389 100644 --- a/SupersignTests/Tests/SupersignSigningTests.swift +++ b/SupersignTests/Tests/SupersignSigningTests.swift @@ -50,7 +50,7 @@ class SupersignSigningTests: XCTestCase { udid: Config.current.udid, teamID: team.id, client: client, - signingInfoManager: TestSigningInfoManager(), + signingInfoManager: MemoryBackedSigningInfoManager(), signerImpl: signerImpl )) let signer = Signer(context: context) diff --git a/SupersignTests/Utilities/DeveloperServicesClient+Testing.swift b/SupersignTests/Utilities/DeveloperServicesClient+Testing.swift index ff551e3b..838a24d4 100644 --- a/SupersignTests/Utilities/DeveloperServicesClient+Testing.swift +++ b/SupersignTests/Utilities/DeveloperServicesClient+Testing.swift @@ -18,12 +18,28 @@ extension TCPAnisetteDataProvider { } +extension NetcatAnisetteDataProvider { + + static func test() -> NetcatAnisetteDataProvider { + NetcatAnisetteDataProvider(localPort: 4322, deviceInfo: Config.current.deviceInfo) + } + +} + +extension SupersetteDataProvider { + + static func test() -> SupersetteDataProvider { + SupersetteDataProvider(deviceInfo: Config.current.deviceInfo) + } + +} + extension GrandSlamClient { static func test() -> GrandSlamClient { GrandSlamClient( deviceInfo: Config.current.deviceInfo, - customAnisetteDataProvider: TCPAnisetteDataProvider.test() + customAnisetteDataProvider: SupersetteDataProvider.test() ) } @@ -35,7 +51,7 @@ extension DeveloperServicesClient { DeveloperServicesClient( loginToken: Config.current.appleID.token, deviceInfo: Config.current.deviceInfo, - customAnisetteDataProvider: TCPAnisetteDataProvider.test() + customAnisetteDataProvider: SupersetteDataProvider.test() ) }