diff --git a/Supersign/DeveloperServices/App Groups/DeveloperServicesAssignAppGroupsOperation.swift b/Supersign/DeveloperServices/App Groups/DeveloperServicesAssignAppGroupsOperation.swift index fba52a9d..284c6059 100644 --- a/Supersign/DeveloperServices/App Groups/DeveloperServicesAssignAppGroupsOperation.swift +++ b/Supersign/DeveloperServices/App Groups/DeveloperServicesAssignAppGroupsOperation.swift @@ -45,7 +45,7 @@ public struct DeveloperServicesAssignAppGroupsOperation: DeveloperServicesOperat }) { assignAppGroup(group, appID: appID, completion: completion) } else { - let groupID = ProvisioningIdentifiers.groupID(fromSanitized: sanitized) + let groupID = ProvisioningIdentifiers.groupID(fromSanitized: sanitized, context: context) let name = ProvisioningIdentifiers.groupName(fromSanitized: sanitized) let request = DeveloperServicesAddAppGroupRequest( platform: context.platform, teamID: context.teamID, name: name, groupID: groupID diff --git a/Supersign/DeveloperServices/App IDs/DeveloperServicesAddAppOperation.swift b/Supersign/DeveloperServices/App IDs/DeveloperServicesAddAppOperation.swift index be4015fd..9acd8624 100644 --- a/Supersign/DeveloperServices/App IDs/DeveloperServicesAddAppOperation.swift +++ b/Supersign/DeveloperServices/App IDs/DeveloperServicesAddAppOperation.swift @@ -64,7 +64,7 @@ public struct DeveloperServicesAddAppOperation: DeveloperServicesOperation { ) self.context.client.send(request, completion: completion) } else { - let newBundleID = ProvisioningIdentifiers.identifier(fromSanitized: bundleID) + let newBundleID = ProvisioningIdentifiers.identifier(fromSanitized: bundleID, context: self.context) let name = ProvisioningIdentifiers.appName(fromSanitized: bundleID) let request = DeveloperServicesAddAppIDRequest( platform: self.context.platform, @@ -127,8 +127,10 @@ public struct DeveloperServicesAddAppOperation: DeveloperServicesOperation { 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) + if let getTaskAllow = ents.firstIndex(where: { $0 is GetTaskAllowEntitlement }) { + ents[getTaskAllow] = GetTaskAllowEntitlement(rawValue: true) + } else { + ents.append(GetTaskAllowEntitlement(rawValue: true)) } } } catch { diff --git a/Supersign/Installation/Connection.swift b/Supersign/Installation/Connection.swift index c447a28d..d7cba92f 100644 --- a/Supersign/Installation/Connection.swift +++ b/Supersign/Installation/Connection.swift @@ -118,7 +118,7 @@ public class Connection { } public func startClient(_ type: T.Type = T.self, sendEscrowBag: Bool = false) throws -> T { - try .init(device: device, service: .init(client: client, sendEscrowBag: sendEscrowBag)) + try .init(device: device, service: .init(client: client, type: type, sendEscrowBag: sendEscrowBag)) } } diff --git a/Supersign/Installation/DDIMounter.swift b/Supersign/Installation/DDIMounter.swift new file mode 100644 index 00000000..500391b5 --- /dev/null +++ b/Supersign/Installation/DDIMounter.swift @@ -0,0 +1,185 @@ +// +// DDIMounter.swift +// Supersign +// +// Created by Kabir Oberai on 25/03/21. +// Copyright © 2021 Kabir Oberai. All rights reserved. +// + +import Foundation +import SwiftyMobileDevice + +public final class DDIMounter { + + public struct DDILoc { + public let dmg: URL + public let signature: URL + + public init(dmg: URL, signature: URL) { + self.dmg = dmg + self.signature = signature + } + } + + private class RequestDelegate: NSObject, URLSessionTaskDelegate, URLSessionDataDelegate { + enum Verdict { + case streamData(size: Int) + case downloadFull(URL) + case failed(Swift.Error) + } + + private var verdict: Verdict? + private let cache: URL + private let fileStream: OutputStream + private let pipedStream: OutputStream + private let onVerdict: (Verdict) -> Void + init(stream: OutputStream, cache: URL, onVerdict: @escaping (Verdict) -> Void) { + self.pipedStream = stream + self.cache = cache + self.fileStream = OutputStream(url: cache, append: false)! + self.onVerdict = onVerdict + stream.open() + fileStream.open() + } + + func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didReceive response: URLResponse, + completionHandler: @escaping (URLSession.ResponseDisposition) -> Void + ) { + let len = response.expectedContentLength + completionHandler(.allow) + if len == -1 { + verdict = .downloadFull(cache) + } else { + let verdict: Verdict = .streamData(size: Int(len)) + self.verdict = verdict + onVerdict(verdict) + } + } + + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + data.withUnsafeBytes { bytes in + let buf = bytes.bindMemory(to: UInt8.self) + pipedStream.write(buf.baseAddress!, maxLength: buf.count) + fileStream.write(buf.baseAddress!, maxLength: buf.count) + } + } + + func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Swift.Error?) { + pipedStream.close() + fileStream.close() + if case let .downloadFull(url) = verdict { + onVerdict(error.map(Verdict.failed) ?? .downloadFull(url)) + } + } + } + + private enum MounterStatus: String, Decodable { + case complete = "Complete" + } + + private struct MountedImage: Decodable { + let status: MounterStatus + let signature: [Data]? + + private enum CodingKeys: String, CodingKey { + case signature = "ImageSignature" + case status = "Status" + } + } + + private struct MountResult: Decodable { + let status: MounterStatus? + let error: String? + + private enum CodingKeys: String, CodingKey { + case status = "Status" + case error = "Error" + } + } + + public struct Error: Swift.Error, LocalizedError { + public let message: String? + public var errorDescription: String? { message } + } + + private let client: MobileImageMounterClient + public init(connection: Connection) throws { + self.client = try connection.startClient() + } + + private func mount(file: InputStream, size: Int, signature: Data) throws { + file.open() + defer { file.close() } + + try client.upload(imageType: "Developer", file: file, size: size, signature: signature) + let result = try client.mount(imageType: "Developer", signature: signature, resultType: MountResult.self) + guard result.status == .complete else { + throw Error(message: result.error) + } + } + + public func mountIfNeeded(local: DDILoc, fetchRemote: () throws -> DDILoc) throws { + let mounted = try client.lookup(imageType: "Developer", resultType: MountedImage.self) + if mounted.signature != nil { return } + + if local.dmg.exists, + local.signature.exists, + let file = InputStream(url: local.dmg), + let fileSize = try? local.dmg.resourceValues(forKeys: [.fileSizeKey]).fileSize, + let signature = try? Data(contentsOf: local.signature) { + return try mount(file: file, size: fileSize, signature: signature) + } + + let remote = try fetchRemote() + + var istream: InputStream! + var ostream: OutputStream! + Stream.getBoundStreams(withBufferSize: 1024, inputStream: &istream, outputStream: &ostream) + + let group = DispatchGroup() + + var mode: RequestDelegate.Verdict! + group.enter() + let delegate = RequestDelegate(stream: ostream, cache: local.dmg) { m in + mode = m + group.leave() + } + + let dmgReq = URLRequest(url: remote.dmg) + let session = URLSession(configuration: .default, delegate: delegate, delegateQueue: nil) + session.dataTask(with: dmgReq).resume() + + let sigReq = URLRequest(url: remote.signature) + var sigRes: Result! + group.enter() + URLSession.shared.dataTask(with: sigReq) { data, _, err in + if let data = data { + sigRes = .success(data) + } else { + sigRes = .failure(err ?? Error(message: nil)) + } + group.leave() + try? data?.write(to: local.signature) + }.resume() + + group.wait() + let signature = try sigRes.get() + + switch mode! { + case .downloadFull(let url): + let file = InputStream(url: url)! + let size = try url.resourceValues(forKeys: [.fileSizeKey]).fileSize! + try mount(file: file, size: size, signature: signature) + case .streamData(let size): + try mount(file: istream, size: size, signature: signature) + case .failed(let error): + throw error + } + + _ = delegate + } + +} diff --git a/Supersign/Installation/Debugger.swift b/Supersign/Installation/Debugger.swift new file mode 100644 index 00000000..25024eb1 --- /dev/null +++ b/Supersign/Installation/Debugger.swift @@ -0,0 +1,43 @@ +// +// Debugger.swift +// Supersign +// +// Created by Kabir Oberai on 26/03/21. +// Copyright © 2021 Kabir Oberai. All rights reserved. +// + +import Foundation +import SwiftyMobileDevice + +public final class Debugger { + + private let client: DebugserverClient + public init(connection: Connection) throws { + client = try connection.startClient() + try client.send(command: "QSetMaxPacketSize:", arguments: ["1024"]) + } + + public enum Error: Swift.Error { + case userCancelled + } + + // if the receiver is released before the completion handler is called, the + // method will fail with `Debugger.Error.userCancelled` + public func attach(toProcess process: String, completion: @escaping (Result<(), Swift.Error>) -> Void) { + let queue = DispatchQueue(label: "debugger-attach-queue") + queue.async { [weak self] in + completion(Result { + var retainedSelf: Debugger? + var resp: Data + repeat { + retainedSelf = nil + guard let self = self else { throw Error.userCancelled } + retainedSelf = self + resp = try self.client.send(command: "vAttachWait;", arguments: [process]) + } while resp.isEmpty + try retainedSelf!.client.send(command: "D", arguments: []) + }) + } + } + +} diff --git a/Supersign/Installation/HeartbeatHandler.swift b/Supersign/Installation/HeartbeatHandler.swift index 45b22d7c..2ebddc1a 100644 --- a/Supersign/Installation/HeartbeatHandler.swift +++ b/Supersign/Installation/HeartbeatHandler.swift @@ -76,10 +76,14 @@ public final class HeartbeatHandler { Thread.sleep(forTimeInterval: .init(received.interval)) } + // TODO: Separate initial establishment phase (blocking) from loop + // (non-blocking) and throw during initial phase if too many failed + // attempts. Also maybe try to eliminate recursion to avoid relying + // on TCO which is not deterministically applied. private func start() { let heartbeatClient: HeartbeatClient do { - heartbeatClient = try HeartbeatClient(device: device, service: .init(client: client)) + heartbeatClient = try HeartbeatClient(device: device, service: .init(client: client, type: HeartbeatClient.self)) } catch { // we sleep instead of asyncAfter to allow the initial startHeartbeat // call to block until a connection is established @@ -103,7 +107,7 @@ public final class HeartbeatHandler { do { try self.beat(client: heartbeatClient, iteration: iteration) } catch { - print("Heartbeat failed: \(error)") + NSLog("%@", "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) { diff --git a/Supersign/Installation/IPAInstaller.swift b/Supersign/Installation/IPAInstaller.swift index 9c190ea0..62e6ffcc 100644 --- a/Supersign/Installation/IPAInstaller.swift +++ b/Supersign/Installation/IPAInstaller.swift @@ -18,7 +18,7 @@ public final class IPAInstaller { public func install( uploaded: IPAUploader.UploadedIPA, - progress: @escaping (InstallationProxyClient.InstallProgress) -> Void + progress: @escaping (InstallationProxyClient.RequestProgress) -> Void ) throws { var result: Result<(), Error>? let semaphore = DispatchSemaphore(value: 0) diff --git a/Supersign/Installation/ProfileManager.swift b/Supersign/Installation/ProfileManager.swift new file mode 100644 index 00000000..33267c38 --- /dev/null +++ b/Supersign/Installation/ProfileManager.swift @@ -0,0 +1,70 @@ +// +// ProfileManager.swift +// Supersign +// +// Created by Kabir Oberai on 25/03/21. +// Copyright © 2021 Kabir Oberai. All rights reserved. +// + +import Foundation +import SwiftyMobileDevice + +public final class ProfileManager { + + private let client: MISAgentClient + private let version: String + + private lazy var ge9_3: Bool = { + let components = version.split(separator: ".") + guard !components.isEmpty, let major = Int(components[0]) else { return false } + if major > 9 { + return true + } else if major < 9 { + return false + } + guard components.count >= 2, let minor = Int(components[1]) else { return false } + return minor >= 3 + }() + + public init(connection: Connection) throws { + self.client = try connection.startClient() + self.version = try connection.client.value(ofType: String.self, forDomain: nil, key: "ProductVersion") + } + + private func allProfiles() throws -> [Mobileprovision] { + try (ge9_3 ? client.profiles() : client.profilesLegacy()) + .map(Mobileprovision.init(data:)) + } + + private func parse(profiles: [Mobileprovision]) throws -> [String: [(Mobileprovision, Mobileprovision.Digest)]] { + let pairs = try profiles.compactMap { (p: Mobileprovision) -> (String, (Mobileprovision, Mobileprovision.Digest))? in + let d = try p.digest() + let ents = try d.entitlements.entitlements() + guard let appID = ents.lazy.compactMap({ $0 as? ApplicationIdentifierEntitlement }).first + else { return nil } + return (appID.rawValue, (p, d)) + } + return Dictionary(grouping: pairs) { $0.0 }.mapValues { $0.map { $0.1 } } + } + + public func install(profiles: [Mobileprovision]) throws { + let toInstall = try parse(profiles: profiles) + let installed = try parse(profiles: allProfiles()) + + for (bundleID, profiles) in toInstall { + guard profiles.count == 1 else { + print("Unexpected # of profiles for \(bundleID): \(profiles.count). Skipping.") + continue + } + let profile = profiles[0] + let installedProfiles = installed[bundleID] ?? [] + for installedProfile in installedProfiles { + print("Removing \(installedProfile.1.uuid) for \(bundleID)") + try client.removeProfile(withUUID: installedProfile.1.uuid) + } + print("Installing profile with UUID \(profile.1.uuid)") + try client.install(profile: profile.0.data()) + } + } + +} diff --git a/Supersign/Model/Entitlements/Entitlements.swift b/Supersign/Model/Entitlements/Entitlements.swift index 7b87d607..206d328f 100644 --- a/Supersign/Model/Entitlements/Entitlements.swift +++ b/Supersign/Model/Entitlements/Entitlements.swift @@ -17,8 +17,8 @@ public struct EntitlementContainer: ProtoCodableContainer { // allows access to a parsable entitlements list while not losing unparsed entitlements when it's modified public struct Entitlements { - private let decoder = PropertyListDecoder() - private let encoder = PropertyListEncoder() + private static let decoder = PropertyListDecoder() + private static let encoder = PropertyListEncoder() private var dict: [String: AnyEncodable] @@ -28,8 +28,8 @@ public struct Entitlements { } public func entitlements() throws -> [Entitlement] { - try decoder.decode( - ProtoCodableKeyValueContainer.self, from: encoder.encode(dict) + try Self.decoder.decode( + ProtoCodableKeyValueContainer.self, from: Self.encoder.encode(dict) ).values } diff --git a/Supersign/Utilities/ProvisioningIdentifiers.swift b/Supersign/Utilities/ProvisioningIdentifiers.swift index 5ec97fa5..d84dc327 100644 --- a/Supersign/Utilities/ProvisioningIdentifiers.swift +++ b/Supersign/Utilities/ProvisioningIdentifiers.swift @@ -21,8 +21,10 @@ extension ProvisioningIdentifiers { return identifier.split(separator: ".").dropFirst().joined(separator: ".") } - static func identifier(fromSanitized sanitized: String) -> String { - "\(Self.idPrefix)\(UUID().uuidString.split(separator: "-")[0]).\(sanitized)" + #warning("TODO: Remove context option; that's a temporary measure") + static func identifier(fromSanitized sanitized: String, context: SigningContext? = nil) -> String { + let uuid = context?.teamID.rawValue ?? String(UUID().uuidString.split(separator: "-")[0]) + return "\(Self.idPrefix)\(uuid).\(sanitized)" } static func safeify(identifier: String) -> String { @@ -35,8 +37,8 @@ extension ProvisioningIdentifiers { return sanitize(identifier: id) } - static func groupID(fromSanitized sanitized: String) -> DeveloperServicesAppGroup.GroupID { - .init(rawValue: "\(Self.groupPrefix)\(identifier(fromSanitized: sanitized))") + static func groupID(fromSanitized sanitized: String, context: SigningContext? = nil) -> DeveloperServicesAppGroup.GroupID { + .init(rawValue: "\(Self.groupPrefix)\(identifier(fromSanitized: sanitized, context: context))") } static func groupName(fromSanitized sanitized: String) -> String {