// SPDX-License-Identifier: GPL-3.0-or-later import Foundation import Darwin import Security /// Private, authenticated, one-request-per-connection companion IPC. Both apps /// compile this exact source; no database, disk, or emulator commands live here. enum CompanionTransport { static var publisherTeamID: String { (Bundle.main.object(forInfoDictionaryKey: "VCCCompanionTeamIdentifier") as? String ?? "") .trimmingCharacters(in: .whitespacesAndNewlines) } static let protocolVersion = 1 static let maximumPayloadBytes = 24 * 1024 * 1024 private static let maximumFrameBytes = 32 * 1024 * 1024 + 4096 struct Configuration: Sendable { var directory: URL var timeout: TimeInterval = 120 var socketName = "service.sock" var teamID = CompanionTransport.publisherTeamID var serverBundleIDs: Set = ["com.brianholman.vccplus.oss.mac"] var clientBundleIDs: Set = ["com.brianholman.vccplus.oss.drivewire"] #if VCC_COMPANION_TESTING var allowUnsignedTestPeers = false #endif static var production: Configuration { Configuration(directory: URL(fileURLWithPath: "/private/tmp/vccplus-oss-companion-\(geteuid())", isDirectory: true)) } static var vccPlus: Configuration { .production } static var driveWire: Configuration { var configuration = production configuration.socketName = "drivewire.sock" configuration.serverBundleIDs = ["com.brianholman.vccplus.oss.drivewire"] configuration.clientBundleIDs = ["com.brianholman.vccplus.oss.mac"] return configuration } var expectedServerBundleIDs: Set { get { serverBundleIDs } set { serverBundleIDs = newValue } } var expectedClientBundleIDs: Set { get { clientBundleIDs } set { clientBundleIDs = newValue } } var socketPath: String { directory.appendingPathComponent(socketName).path } } enum Failure: LocalizedError { case unavailable, busy, untrustedPeer, unsafeEndpoint, unsupportedVersion, malformedFrame, tooLarge, timedOut case remote(String) var errorDescription: String? { switch self { case .unavailable: "VCC Plus's companion service is not available." case .busy: "Another VCC Plus companion service is already running." case .untrustedPeer: "The companion application's identity could not be verified." case .unsafeEndpoint: "The companion service location is not private or has changed." case .unsupportedVersion: "These application versions do not support the same companion protocol." case .malformedFrame: "The companion service returned an invalid response." case .tooLarge: "The companion request or response exceeds the supported size." case .timedOut: "The companion operation timed out." case .remote(let message): message } } } private struct Request: Codable { let version: Int let id: UUID let method: String let payload: Data } private struct Response: Codable { let version: Int let id: UUID let payload: Data? let error: String? } struct Client: Sendable { let configuration: Configuration init(configuration: Configuration = .production) { self.configuration = configuration } func request(method: String, payload: Data = Data()) async throws -> Data { guard !method.isEmpty, method.utf8.count <= 128 else { throw Failure.malformedFrame } guard payload.count <= maximumPayloadBytes else { throw Failure.tooLarge } let state = Connection() return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in DispatchQueue.global(qos: .userInitiated).async { defer { state.finish() } do { let fd = try makeSocket() try state.attach(fd) try checkDirectory(configuration.directory, create: false) try checkSocket(configuration.socketPath) let deadline = Date().addingTimeInterval(configuration.timeout) try connect(fd, path: configuration.socketPath, deadline: deadline, state: state) try authenticate(fd, configuration: configuration, permittedIDs: configuration.serverBundleIDs) let id = UUID() try writeFrame(JSONEncoder().encode(Request(version: protocolVersion, id: id, method: method, payload: payload)), fd: fd, deadline: deadline, state: state) let result = try JSONDecoder().decode(Response.self, from: readFrame(fd, deadline: deadline, state: state)) guard result.version == protocolVersion else { throw Failure.unsupportedVersion } guard result.id == id else { throw Failure.malformedFrame } if let error = result.error { throw Failure.remote(error) } guard let data = result.payload, data.count <= maximumPayloadBytes else { throw Failure.malformedFrame } continuation.resume(returning: data) } catch { continuation.resume(throwing: state.isCancelled ? CancellationError() : error) } } } } onCancel: { state.cancel() } } } final class Server: @unchecked Sendable { typealias Handler = @Sendable (String, Data) async throws -> Data let configuration: Configuration private let handler: Handler private let stateLock = NSLock() private let queue = DispatchQueue(label: "com.brianholman.vccplus.companion.accept") private let slots = DispatchSemaphore(value: 4) private var listener: DispatchSourceRead? private var lockFD: Int32 = -1 private var endpoint: (dev_t, ino_t)? private var connections: [UUID: Connection] = [:] private var stopped = false init(configuration: Configuration = .production, handler: @escaping Handler) throws { self.configuration = configuration; self.handler = handler try checkDirectory(configuration.directory, create: true) let lockPath = configuration.directory.appendingPathComponent(configuration.socketName + ".lock").path lockFD = open(lockPath, O_CREAT | O_RDWR | O_NOFOLLOW | O_CLOEXEC, 0o600) guard lockFD >= 0 else { throw Failure.unsafeEndpoint } var lockInfo = stat() guard fstat(lockFD, &lockInfo) == 0, lockInfo.st_uid == geteuid(), lockInfo.st_mode & S_IFMT == S_IFREG, lockInfo.st_mode & 0o777 == 0o600 else { close(lockFD); lockFD = -1; throw Failure.unsafeEndpoint } guard flock(lockFD, LOCK_EX | LOCK_NB) == 0 else { close(lockFD); lockFD = -1; throw Failure.busy } var fd: Int32 = -1 do { try removeStaleSocket(configuration.socketPath) fd = try makeSocket() var address = try unixAddress(configuration.socketPath) try checked(withUnsafePointer(to: &address) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { Darwin.bind(fd, $0, socklen_t(MemoryLayout.size)) } }) guard chmod(configuration.socketPath, 0o600) == 0 else { throw Failure.unsafeEndpoint } var info = stat(); guard lstat(configuration.socketPath, &info) == 0 else { throw Failure.unsafeEndpoint } endpoint = (info.st_dev, info.st_ino) try checked(Darwin.listen(fd, 8)) let source = DispatchSource.makeReadSource(fileDescriptor: fd, queue: queue) let socketFD = fd source.setEventHandler { [weak self] in self?.acceptConnection(socketFD) } source.setCancelHandler { close(socketFD) } listener = source; source.resume() } catch { if fd >= 0 { close(fd) } removeOwnedEndpoint() flock(lockFD, LOCK_UN); close(lockFD); lockFD = -1 throw error } } private func acceptConnection(_ fd: Int32) { while true { let peer = Darwin.accept(fd, nil, nil) guard peer >= 0 else { return } guard slots.wait(timeout: .now()) == .success else { close(peer); continue } let connection = Connection(), id = UUID() do { try configureSocket(peer); try connection.attach(peer) } catch { close(peer); slots.signal(); continue } stateLock.lock() let accepting = !stopped if accepting { connections[id] = connection } stateLock.unlock() guard accepting else { connection.finish(); slots.signal(); return } DispatchQueue.global(qos: .utility).async { [self] in do { try authenticate(peer, configuration: configuration, permittedIDs: configuration.clientBundleIDs) let deadline = Date().addingTimeInterval(configuration.timeout) let request = try JSONDecoder().decode(Request.self, from: readFrame(peer, deadline: deadline, state: connection)) guard request.version == protocolVersion else { throw Failure.unsupportedVersion } guard !request.method.isEmpty, request.method.utf8.count <= 128, request.payload.count <= maximumPayloadBytes else { throw Failure.malformedFrame } let task = Task { [self] in let response: Response do { let payload = try await withThrowingTaskGroup(of: Data.self) { group in group.addTask { try await self.handler(request.method, request.payload) } group.addTask { while true { try Task.checkCancellation() if Date() >= deadline { throw Failure.timedOut } if connection.isCancelled { throw CancellationError() } var byte: UInt8 = 0 let count = recv(peer, &byte, 1, MSG_PEEK | MSG_DONTWAIT) if count == 0 { throw CancellationError() } if count > 0 { throw Failure.malformedFrame } // exactly one request per connection if errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR { throw Failure.unavailable } try await Task.sleep(nanoseconds: 100_000_000) } } defer { group.cancelAll() } return try await group.next()! } guard payload.count <= maximumPayloadBytes else { throw Failure.tooLarge } response = Response(version: protocolVersion, id: request.id, payload: payload, error: nil) } catch { response = Response(version: protocolVersion, id: request.id, payload: nil, error: String(error.localizedDescription.prefix(2048))) } await withCheckedContinuation { (done: CheckedContinuation) in DispatchQueue.global(qos: .utility).async { [self] in defer { finish(id, connection: connection); done.resume() } if let bytes = try? JSONEncoder().encode(response) { try? writeFrame(bytes, fd: peer, deadline: deadline, state: connection) } } } } connection.setTask(task) } catch { finish(id, connection: connection) } } } } private func finish(_ id: UUID, connection: Connection) { connection.finish() stateLock.lock(); let removed = connections.removeValue(forKey: id); stateLock.unlock() if removed != nil { slots.signal() } } func stop() { stateLock.lock() guard !stopped else { stateLock.unlock(); return } stopped = true let source = listener; listener = nil let active = Array(connections.values) stateLock.unlock() source?.cancel() for connection in active { connection.cancel() } removeOwnedEndpoint() if lockFD >= 0 { flock(lockFD, LOCK_UN); close(lockFD); lockFD = -1 } } private func removeOwnedEndpoint() { guard let endpoint else { return } var info = stat() if lstat(configuration.socketPath, &info) == 0, info.st_uid == geteuid(), info.st_mode & S_IFMT == S_IFSOCK, info.st_dev == endpoint.0, info.st_ino == endpoint.1 { _ = unlink(configuration.socketPath) } self.endpoint = nil } deinit { stop() } } /// A descriptor is closed once, by its IO worker. Cancellation only shuts it /// down under a lock so a recycled descriptor can never be closed by a task. private final class Connection: @unchecked Sendable { private let lock = NSLock() private var fd: Int32 = -1 private var cancelled = false private var finished = false private var task: Task? var isCancelled: Bool { lock.lock(); defer { lock.unlock() }; return cancelled } func attach(_ value: Int32) throws { lock.lock(); defer { lock.unlock() } if cancelled { close(value); throw CancellationError() } fd = value } func setTask(_ value: Task) { lock.lock(); let cancel = cancelled || finished if !cancel { task = value } lock.unlock() if cancel { value.cancel() } } func cancel() { lock.lock(); cancelled = true if fd >= 0 { _ = shutdown(fd, SHUT_RDWR) } let running = task; lock.unlock(); running?.cancel() } func finish() { lock.lock(); let value = fd; fd = -1; task = nil; finished = true; lock.unlock() if value >= 0 { close(value) } } } private static func checked(_ value: Int32) throws { guard value >= 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } } private static func makeSocket() throws -> Int32 { let fd = socket(AF_UNIX, SOCK_STREAM, 0) guard fd >= 0 else { throw Failure.unavailable } do { try configureSocket(fd); return fd } catch { close(fd); throw error } } private static func configureSocket(_ fd: Int32) throws { try checked(fcntl(fd, F_SETFL, O_NONBLOCK)); try checked(fcntl(fd, F_SETFD, FD_CLOEXEC)) var yes: Int32 = 1 try checked(setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &yes, socklen_t(MemoryLayout.size(ofValue: yes)))) } private static func unixAddress(_ path: String) throws -> sockaddr_un { var address = sockaddr_un() address.sun_family = sa_family_t(AF_UNIX); address.sun_len = UInt8(MemoryLayout.size) let bytes = Array(path.utf8CString) guard bytes.count <= MemoryLayout.size(ofValue: address.sun_path) else { throw Failure.unsafeEndpoint } withUnsafeMutableBytes(of: &address.sun_path) { target in bytes.withUnsafeBytes { target.copyBytes(from: $0) } } return address } private static func checkDirectory(_ url: URL, create: Bool) throws { if create, mkdir(url.path, 0o700) != 0, errno != EEXIST { throw Failure.unsafeEndpoint } var info = stat() guard lstat(url.path, &info) == 0, info.st_uid == geteuid(), info.st_mode & S_IFMT == S_IFDIR, info.st_mode & 0o777 == 0o700 else { throw Failure.unsafeEndpoint } } private static func checkSocket(_ path: String) throws { var info = stat() guard lstat(path, &info) == 0 else { throw Failure.unavailable } guard info.st_uid == geteuid(), info.st_mode & S_IFMT == S_IFSOCK, info.st_mode & 0o777 == 0o600 else { throw Failure.unsafeEndpoint } } private static func removeStaleSocket(_ path: String) throws { var before = stat() guard lstat(path, &before) == 0 else { if errno == ENOENT { return }; throw Failure.unsafeEndpoint } try checkSocket(path) let fd = try makeSocket(); defer { close(fd) } var address = try unixAddress(path) let rc = withUnsafePointer(to: &address) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { Darwin.connect(fd, $0, socklen_t(MemoryLayout.size)) } } guard rc < 0, errno == ECONNREFUSED || errno == ENOENT else { throw Failure.busy } var after = stat() guard lstat(path, &after) == 0, after.st_uid == geteuid(), after.st_mode & S_IFMT == S_IFSOCK, before.st_dev == after.st_dev, before.st_ino == after.st_ino else { throw Failure.unsafeEndpoint } try checked(unlink(path)) } private static func connect(_ fd: Int32, path: String, deadline: Date, state: Connection) throws { var address = try unixAddress(path) let rc = withUnsafePointer(to: &address) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { Darwin.connect(fd, $0, socklen_t(MemoryLayout.size)) } } if rc < 0 { guard errno == EINPROGRESS || errno == EAGAIN else { throw Failure.unavailable } try wait(fd, events: Int16(POLLOUT), deadline: deadline, state: state) var error: Int32 = 0, length = socklen_t(MemoryLayout.size) guard getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &length) == 0, error == 0 else { throw Failure.unavailable } } } private static func wait(_ fd: Int32, events: Int16, deadline: Date, state: Connection) throws { while true { if state.isCancelled { throw CancellationError() } guard Date() < deadline else { throw Failure.timedOut } var descriptor = pollfd(fd: fd, events: events, revents: 0) let rc = poll(&descriptor, 1, 100) if rc > 0 { if descriptor.revents & events != 0 { return } throw Failure.unavailable } if rc < 0 && errno != EINTR { throw Failure.unavailable } } } private static func readBytes(_ count: Int, fd: Int32, deadline: Date, state: Connection) throws -> Data { var result = Data(count: count) try result.withUnsafeMutableBytes { buffer in var offset = 0 while offset < count { try wait(fd, events: Int16(POLLIN), deadline: deadline, state: state) let size = recv(fd, buffer.baseAddress! + offset, count - offset, 0) if size > 0 { offset += size } else if size == 0 { throw Failure.unavailable } else if errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK { throw Failure.unavailable } } } return result } private static func readFrame(_ fd: Int32, deadline: Date, state: Connection) throws -> Data { let prefix = try readBytes(4, fd: fd, deadline: deadline, state: state) let size = prefix.reduce(UInt32(0)) { ($0 << 8) | UInt32($1) } guard size > 0, size <= maximumFrameBytes else { throw Failure.tooLarge } return try readBytes(Int(size), fd: fd, deadline: deadline, state: state) } private static func writeFrame(_ data: Data, fd: Int32, deadline: Date, state: Connection) throws { guard data.count <= maximumFrameBytes else { throw Failure.tooLarge } var size = UInt32(data.count).bigEndian let frame = withUnsafeBytes(of: &size) { Data($0) } + data try frame.withUnsafeBytes { buffer in var offset = 0 while offset < frame.count { try wait(fd, events: Int16(POLLOUT), deadline: deadline, state: state) let sent = send(fd, buffer.baseAddress! + offset, frame.count - offset, 0) if sent > 0 { offset += sent } else if sent == 0 { throw Failure.unavailable } else if errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK { throw Failure.unavailable } } } } /// Validate a discovered/selected companion before asking Launch Services to /// run it. Bundle metadata alone is not authorization to execute an app. /// This reads and verifies code on disk; callers should run it off the main actor. static func validateApplication(at url: URL, permittedBundleIDs: Set, teamID: String = CompanionTransport.publisherTeamID) throws { guard !teamID.isEmpty, url.isFileURL, !permittedBundleIDs.isEmpty else { throw Failure.untrustedPeer } var code: SecStaticCode? guard SecStaticCodeCreateWithPath(url as CFURL, [], &code) == errSecSuccess, let code else { throw Failure.untrustedPeer } var info: CFDictionary? guard SecCodeCopySigningInformation(code, SecCSFlags(rawValue: kSecCSSigningInformation), &info) == errSecSuccess, let values = info as? [String: Any], let identifier = values[kSecCodeInfoIdentifier as String] as? String, permittedBundleIDs.contains(identifier), values[kSecCodeInfoTeamIdentifier as String] as? String == teamID else { throw Failure.untrustedPeer } var requirement: SecRequirement? guard SecRequirementCreateWithString("anchor apple generic" as CFString, [], &requirement) == errSecSuccess, SecStaticCodeCheckValidity(code, SecCSFlags(rawValue: kSecCSStrictValidate | kSecCSCheckAllArchitectures), requirement) == errSecSuccess else { throw Failure.untrustedPeer } } private static func authenticate(_ fd: Int32, configuration: Configuration, permittedIDs: Set) throws { var uid: uid_t = 0, gid: gid_t = 0 guard getpeereid(fd, &uid, &gid) == 0, uid == geteuid() else { throw Failure.untrustedPeer } #if VCC_COMPANION_TESTING if configuration.allowUnsignedTestPeers { return } #endif guard !configuration.teamID.isEmpty else { throw Failure.untrustedPeer } var pid: pid_t = 0, length = socklen_t(MemoryLayout.size) guard getsockopt(fd, SOL_LOCAL, LOCAL_PEERPID, &pid, &length) == 0, pid > 0 else { throw Failure.untrustedPeer } var guest: SecCode? let attributes = [kSecGuestAttributePid: NSNumber(value: pid)] as CFDictionary guard SecCodeCopyGuestWithAttributes(nil, attributes, [], &guest) == errSecSuccess, let guest else { throw Failure.untrustedPeer } var staticCode: SecStaticCode? guard SecCodeCopyStaticCode(guest, [], &staticCode) == errSecSuccess, let staticCode else { throw Failure.untrustedPeer } var info: CFDictionary? guard SecCodeCopySigningInformation(staticCode, SecCSFlags(rawValue: kSecCSSigningInformation), &info) == errSecSuccess, let values = info as? [String: Any], let identifier = values[kSecCodeInfoIdentifier as String] as? String, permittedIDs.contains(identifier), values[kSecCodeInfoTeamIdentifier as String] as? String == configuration.teamID else { throw Failure.untrustedPeer } // A matching string in an unsigned plist or an ad-hoc signature is not trust. var requirement: SecRequirement? guard SecRequirementCreateWithString("anchor apple generic" as CFString, [], &requirement) == errSecSuccess, SecCodeCheckValidity(guest, SecCSFlags(rawValue: kSecCSStrictValidate), requirement) == errSecSuccess else { throw Failure.untrustedPeer } } }