import CryptoKit import Foundation import Security struct UpdateCrypto { static func canonical(_ text: String, count: Int, message: String) throws -> Data { guard let data = Data(base64Encoded: text), data.count == count, data.base64EncodedString() == text else { throw DevError(message) } return data } static func digest(_ url: URL) throws -> String { let handle = try FileHandle(forReadingFrom: url) defer { do { try handle.close() } catch { FileHandle.standardError.write(Data("Could not close archive: \(error)\n".utf8)) } } var hash = SHA256() while let chunk = try handle.read(upToCount: 1024 * 1024), !chunk.isEmpty { hash.update(data: chunk) } return hash.finalize().map { String(format: "%02x", $0) }.joined() } static func verify(_ archive: URL, signature: String, publicKey: String) throws { let signatureData = try canonical(signature, count: 64, message: "Invalid signature or public key encoding") let bytes = try canonical(publicKey, count: 32, message: "Invalid signature or public key encoding") let key = try Curve25519.Signing.PublicKey(rawRepresentation: bytes) guard key.isValidSignature(signatureData, for: try Data(contentsOf: archive, options: .mappedIfSafe)) else { throw DevError("The update signature does not match the downloaded archive and public key") } } static func run(_ args: [String]) throws { do { switch args.first { case "temporary-key" where args.count == 2: let key = Curve25519.Signing.PrivateKey() let path = args[1] guard !FileManager.default.fileExists(atPath: path), FileManager.default.createFile( atPath: path, contents: key.rawRepresentation.base64EncodedData(), attributes: [.posixPermissions: 0o600]) else { throw DevError("Could not write the temporary signing key") } print(key.publicKey.rawRepresentation.base64EncodedString()) case "sign" where args.count == 2: let input = FileHandle.standardInput.readDataToEndOfFile() guard let text = String(data: input, encoding: .utf8) else { throw DevError("Expected a canonical base64 Ed25519 seed on stdin") } let seed = try canonical(text, count: 32, message: "Expected a canonical base64 Ed25519 seed on stdin") let key = try Curve25519.Signing.PrivateKey(rawRepresentation: seed) print( try key.signature(for: Data(contentsOf: URL(fileURLWithPath: args[1]), options: .mappedIfSafe)) .base64EncodedString()) case "verify" where args.count == 4: try verify(URL(fileURLWithPath: args[1]), signature: args[2], publicKey: args[3]) default: throw DevError( "Usage: update-crypto temporary-key FILE | sign ARCHIVE < SEED | verify ARCHIVE SIGNATURE PUBLIC_KEY" ) } } catch { throw DevError("Update signing: \(error)") } } } struct UpdateKey { struct Generated: Equatable { let seed: Data let publicKey: String } static func generate() -> Generated { let key = Curve25519.Signing.PrivateKey() return Generated( seed: key.rawRepresentation.base64EncodedData(), publicKey: key.publicKey.rawRepresentation.base64EncodedString()) } static func create( path: URL, account: String, generate: () throws -> Generated = { Self.generate() }, store: (URL, String, Data, String) throws -> Void = Self.store ) throws -> String { guard !account.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, !account.contains("\0") else { throw DevError("A nonempty account is required") } guard try ReleaseFiles.regular(path) else { throw DevError("Keychain not found: \(path.path)") } let key = try generate() try store(path, account, key.seed, key.publicKey) return key.publicKey } static func quoted(_ value: String) throws -> String { guard !value.contains("\n"), !value.contains("\r"), !value.contains("\0") else { throw DevError("Keychain fields cannot contain control characters") } return "\"" + value.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" } static func store(_ path: URL, _ account: String, _ seed: Data, _ publicKey: String) throws { try store(path, account, seed, publicKey) { executable, arguments, input in try DevProcess.run(executable, arguments, input: input) } } static func store( _ path: URL, _ account: String, _ seed: Data, _ publicKey: String, process: (String, [String], Data?) throws -> DevProcessResult ) throws { // The frontend selects a legacy keychain without deprecated APIs or changing the owner's search list. let lookup = ["find-generic-password", "-a", account, "-s", "https://sparkle-project.org", "-w", path.path] let existing = try process("/usr/bin/security", lookup, nil) if existing.status == 0 { throw DevError("A key already exists for this account; refusing to rotate it") } guard existing.status == 44 else { throw DevError("Could not read the selected keychain (status \(existing.status))") } guard let text = String(data: seed, encoding: .utf8) else { throw DevError("Invalid signing key") } let arguments = [ "add-generic-password", "-a", account, "-s", "https://sparkle-project.org", "-l", "Parcel Update Signing Key", "-j", "SUPublicEDKey: " + publicKey, "-w", text, path.path, ] let command = try arguments.map(quoted).joined(separator: " ") + "\n" let added = try process("/usr/bin/security", ["-i"], Data(command.utf8)) if added.status == 45 { throw DevError("A key already exists for this account; refusing to rotate it") } guard added.status == 0 else { throw DevError("Could not store the signing key (status \(added.status))") } let stored = try process("/usr/bin/security", lookup, nil) var storedBytes = stored.stdout if storedBytes.last == 10 { storedBytes.removeLast() } guard stored.status == 0, storedBytes == seed else { throw DevError("Could not verify the signing key in the selected keychain") } } static func run(_ args: [String]) throws { do { var account = "dev.vinnymac.parcel" var path = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent( "Library/Keychains/login.keychain-db") var dry = false var index = 0 while index < args.count { switch args[index] { case "--dry-run": dry = true case "--account", "--keychain": guard index + 1 < args.count else { throw DevError("Missing update key option value") } if args[index] == "--account" { account = args[index + 1] } else { path = URL(fileURLWithPath: args[index + 1]) } index += 1 default: throw DevError("Usage: generate-update-key [--account ACCOUNT] [--keychain PATH] [--dry-run]") } index += 1 } guard !account.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, !account.contains("\0") else { throw DevError("A nonempty account is required") } if dry { print("Would create an Ed25519 key for \(account) in \(path.path); no keychain was opened.") } else { print(try create(path: path, account: account)) } } catch { throw DevError("Update key: \(error)") } } }