diff --git a/generate_keys/main.swift b/generate_keys/main.swift index cca1dca9..feb0350c 100644 --- a/generate_keys/main.swift +++ b/generate_keys/main.swift @@ -9,6 +9,8 @@ import Foundation import Security +let PRIVATE_KEY_LABEL = "Private key for signing Sparkle updates" + private func commonKeychainItemAttributes() -> [String: Any] { /// Attributes used for both adding a new item and matching an existing one. return [ @@ -37,7 +39,7 @@ private func failure(_ message: String) -> Never { exit(1) } -func findPublicKey() -> Data? { +func findKeyPair() -> Data? { var item: CFTypeRef? let res = SecItemCopyMatching(commonKeychainItemAttributes().merging([ /// Return a matched item's value as a CFData object. @@ -47,7 +49,7 @@ func findPublicKey() -> Data? { switch res { case errSecSuccess: if let keys = (item as? Data).flatMap({ Data(base64Encoded: $0) }) { - return keys[64...] + return keys } else { failure(""" Item found, but is corrupt or has been overwritten! @@ -86,7 +88,7 @@ func findPublicKey() -> Data? { exit(1) } -func generateKeyPair() -> Data { +func generateKeyPair() -> (publicEdKey: Data, privateEdKey: Data) { var seed = Array(repeating: 0, count: 32) var publicEdKey = Array(repeating: 0, count: 32) var privateEdKey = Array(repeating: 0, count: 64) @@ -95,7 +97,11 @@ func generateKeyPair() -> Data { failure("Unable to initialize random seed. Try restarting your computer.") } ed25519_create_keypair(&publicEdKey, &privateEdKey, seed) + + return (Data(publicEdKey), Data(privateEdKey)) +} +func storeKeyPair(publicEdKey: Data, privateEdKey: Data) { let query = commonKeychainItemAttributes().merging([ /// Mark the new item as sensitive (requires keychain password to export - e.g. a private key). kSecAttrIsSensitive as String: kCFBooleanTrue!, @@ -105,7 +111,7 @@ func generateKeyPair() -> Data { kSecAttrIsPermanent as String: kCFBooleanTrue!, /// The label of the new item (shown as its name/title in Keychain Access). - kSecAttrLabel as String: "Private key for signing Sparkle updates", + kSecAttrLabel as String: PRIVATE_KEY_LABEL, /// A comment regarding the item's content (can be viewed in Keychain Access; we give the public key here). kSecAttrComment as String: "Public key (SUPublicEDKey value) for this key is:\n\n\(Data(publicEdKey).base64EncodedString())", @@ -114,13 +120,13 @@ func generateKeyPair() -> Data { kSecAttrDescription as String: "private key", /// The actual data content of the new item. - kSecValueData as String: Data(privateEdKey + publicEdKey).base64EncodedData() as CFData + kSecValueData as String: (privateEdKey + publicEdKey).base64EncodedData() as CFData ], uniquingKeysWith: { $1 }) as CFDictionary switch SecItemAdd(query, nil) { case errSecSuccess: - return Data(publicEdKey) + break case errSecDuplicateItem: failure("You already have a conflicting key in your Keychain which was not found during lookup.") case errSecAuthFailed: @@ -135,36 +141,130 @@ func generateKeyPair() -> Data { You can look up this error at """) } - exit(1) +} + +func printNewPublicKeyUsage(_ publicKey: Data) { + print(""" + A key has been generated and saved in your keychain. Add the `SUPublicEDKey` key to + the Info.plist of each app for which you intend to use Sparkle for distributing + updates. It should appear like this: + + SUPublicEDKey + \(publicKey.base64EncodedString()) + + """) } /// Once it's safe to require Swift 5.3 and Xcode 12 for this code, rename this file to `generate_keys.swift` and /// replace this function with a class tagged with `@main`. func entryPoint() { - let isLookupMode = (CommandLine.arguments.dropFirst().first.map({ $0 == "-p" }) ?? false) + let arguments = CommandLine.arguments + let programName = arguments.first ?? "generate_keys" + + let mode = arguments.count > 1 ? arguments[1] : nil - /// If not in lookup-only mode, give an intro blurb. - if !isLookupMode { + /// If not in any mode, give an intro blurb. + if mode == nil { print(""" - This tool uses the macOS Keychain to store a private key for signing app updates which - will be distributed via Sparkle. The key will be associated with your user account. + Usage: \(programName) [-p] [-x private-key-file] [-f private-key-file] + + This tool generates a public & private keys and uses the macOS Keychain to store + the private key for signing app updates which will be distributed via Sparkle. + This key will be associated with your user account. Note: You only need one signing key, no matter how many apps you embed Sparkle in. The keychain may ask permission for this tool to access an existing key, if one exists, or for permission to save the new key. You must allow access in order to successfully proceed. + + Additional Options: + -p + Looks up and just prints the existing public key stored in the Keychain. + + -x private-key-file + Exports your private key from your login keychain and writes it to private-key-file. Note the contents of + this sensitive exported file are the same as the password to the \"\(PRIVATE_KEY_LABEL)\" item in + your keychain. + -f private-key-file + Imports the private key from private-key-file into your keychain instead of generating a new key. + This file has likely been exported via -x option from another machine. + Any existing \"\(PRIVATE_KEY_LABEL)\" items listed in Keychain Access may need to be removed manually first before proceeding. + + ---------------------------------------------------------------------------------------------------- + """) } - switch (findPublicKey(), isLookupMode) { - /// Existing key found, lookup mode - print just the pubkey and exit - case (.some(let pubKey), true): + switch mode { + case .some("-p"): + /// Lookup mode - print just the pubkey and exit + if let keyPair = findKeyPair() { + let pubKey = keyPair[64...] print(pubKey.base64EncodedString()) + } else { + failure("No existing signing key found!") + } + case .some("-f"): + /// Import mode - import the specifed key-pair file + guard arguments.count > 2 else { + failure("private-key-file was not specified") + } - /// Existing key found, normal mode - print instructions blurb and pubkey - case (.some(let pubKey), false): + let privateAndPublicBase64KeyFile = arguments[2] + let privateAndPublicBase64Key: String + do { + privateAndPublicBase64Key = try String(contentsOfFile: privateAndPublicBase64KeyFile) + } catch { + failure("Failed to read private-key-file: \(error)") + } + + guard let privateAndPublicKey = Data(base64Encoded: privateAndPublicBase64Key.trimmingCharacters(in: .whitespacesAndNewlines), options: .init()) else { + failure("Failed to decode base64 encoded key data from: \(privateAndPublicBase64Key)") + } + + guard privateAndPublicKey.count == 64 + 32 else { + failure("Imported key must be 96 bytes decoded. Instead it is \(privateAndPublicKey.count) bytes decoded.") + } + + print("Importing signing key..") + + let publicKey = privateAndPublicKey[64...] + let privateKey = privateAndPublicKey[0..<64] + + storeKeyPair(publicEdKey: publicKey, privateEdKey: privateKey) + + printNewPublicKeyUsage(publicKey) + + case .some("-x"): + /// Export mode - export the key-pair file from the user's keychain + guard arguments.count > 2 else { + failure("private-key-file was not specified") + } + + let exportURL = URL(fileURLWithPath: arguments[2]) + if let reachable = try? exportURL.checkResourceIsReachable(), reachable { + failure("private-key-file already exists: \(exportURL.path)") + } + + guard let keyPair = findKeyPair() else { + failure("No existing signing key found!") + } + + do { + try keyPair.base64EncodedString().write(to: exportURL, atomically: true, encoding: .utf8) + } catch { + failure("Failed to write exported file: \(error)") + } + + case .some(let unknownOption): + failure("Unknown option: \(unknownOption)") + + case nil: + /// Default mode - find an existing public key and print its usage, or generate new keys + if let keyPair = findKeyPair() { + let pubKey = keyPair[64...] print(""" A pre-existing signing key was found. This is how it should appear in your Info.plist: @@ -172,26 +272,14 @@ func entryPoint() { \(pubKey.base64EncodedString()) """) - - /// No existing key, lookup mode - error out - case (.none, true): - failure("No existing signing key found!") - - /// No existing key, normal mode - generate a new one - case (.none, false): + } else { print("Generating a new signing key. This may take a moment, depending on your machine.") - let pubKey = generateKeyPair() + let (pubKey, privKey) = generateKeyPair() + storeKeyPair(publicEdKey: pubKey, privateEdKey: privKey) - print(""" - A key has been generated and saved in your keychain. Add the `SUPublicEDKey` key to - the Info.plist of each app for which you intend to use Sparkle for distributing - updates. It should appear like this: - - SUPublicEDKey - \(pubKey.base64EncodedString()) - - """) + printNewPublicKeyUsage(pubKey) + } } }